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>
27 static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
28 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
29 [_id] = & _name ## _verifier_ops,
30 #define BPF_MAP_TYPE(_id, _ops)
31 #define BPF_LINK_TYPE(_id, _name)
32 #include <linux/bpf_types.h>
38 /* bpf_check() is a static code analyzer that walks eBPF program
39 * instruction by instruction and updates register/stack state.
40 * All paths of conditional branches are analyzed until 'bpf_exit' insn.
42 * The first pass is depth-first-search to check that the program is a DAG.
43 * It rejects the following programs:
44 * - larger than BPF_MAXINSNS insns
45 * - if loop is present (detected via back-edge)
46 * - unreachable insns exist (shouldn't be a forest. program = one function)
47 * - out of bounds or malformed jumps
48 * The second pass is all possible path descent from the 1st insn.
49 * Since it's analyzing all pathes through the program, the length of the
50 * analysis is limited to 64k insn, which may be hit even if total number of
51 * insn is less then 4K, but there are too many branches that change stack/regs.
52 * Number of 'branches to be analyzed' is limited to 1k
54 * On entry to each instruction, each register has a type, and the instruction
55 * changes the types of the registers depending on instruction semantics.
56 * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
59 * All registers are 64-bit.
60 * R0 - return register
61 * R1-R5 argument passing registers
62 * R6-R9 callee saved registers
63 * R10 - frame pointer read-only
65 * At the start of BPF program the register R1 contains a pointer to bpf_context
66 * and has type PTR_TO_CTX.
68 * Verifier tracks arithmetic operations on pointers in case:
69 * BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
70 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
71 * 1st insn copies R10 (which has FRAME_PTR) type into R1
72 * and 2nd arithmetic instruction is pattern matched to recognize
73 * that it wants to construct a pointer to some element within stack.
74 * So after 2nd insn, the register R1 has type PTR_TO_STACK
75 * (and -20 constant is saved for further stack bounds checking).
76 * Meaning that this reg is a pointer to stack plus known immediate constant.
78 * Most of the time the registers have SCALAR_VALUE type, which
79 * means the register has some value, but it's not a valid pointer.
80 * (like pointer plus pointer becomes SCALAR_VALUE type)
82 * When verifier sees load or store instructions the type of base register
83 * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are
84 * four pointer types recognized by check_mem_access() function.
86 * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
87 * and the range of [ptr, ptr + map's value_size) is accessible.
89 * registers used to pass values to function calls are checked against
90 * function argument constraints.
92 * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
93 * It means that the register type passed to this function must be
94 * PTR_TO_STACK and it will be used inside the function as
95 * 'pointer to map element key'
97 * For example the argument constraints for bpf_map_lookup_elem():
98 * .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
99 * .arg1_type = ARG_CONST_MAP_PTR,
100 * .arg2_type = ARG_PTR_TO_MAP_KEY,
102 * ret_type says that this function returns 'pointer to map elem value or null'
103 * function expects 1st argument to be a const pointer to 'struct bpf_map' and
104 * 2nd argument should be a pointer to stack, which will be used inside
105 * the helper function as a pointer to map element key.
107 * On the kernel side the helper function looks like:
108 * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
110 * struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
111 * void *key = (void *) (unsigned long) r2;
114 * here kernel can access 'key' and 'map' pointers safely, knowing that
115 * [key, key + map->key_size) bytes are valid and were initialized on
116 * the stack of eBPF program.
119 * Corresponding eBPF program may look like:
120 * BPF_MOV64_REG(BPF_REG_2, BPF_REG_10), // after this insn R2 type is FRAME_PTR
121 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
122 * BPF_LD_MAP_FD(BPF_REG_1, map_fd), // after this insn R1 type is CONST_PTR_TO_MAP
123 * BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
124 * here verifier looks at prototype of map_lookup_elem() and sees:
125 * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
126 * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
128 * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
129 * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
130 * and were initialized prior to this call.
131 * If it's ok, then verifier allows this BPF_CALL insn and looks at
132 * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
133 * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
134 * returns ether pointer to map value or NULL.
136 * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
137 * insn, the register holding that pointer in the true branch changes state to
138 * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
139 * branch. See check_cond_jmp_op().
141 * After the call R0 is set to return type of the function and registers R1-R5
142 * are set to NOT_INIT to indicate that they are no longer readable.
144 * The following reference types represent a potential reference to a kernel
145 * resource which, after first being allocated, must be checked and freed by
147 * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET
149 * When the verifier sees a helper call return a reference type, it allocates a
150 * pointer id for the reference and stores it in the current function state.
151 * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into
152 * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type
153 * passes through a NULL-check conditional. For the branch wherein the state is
154 * changed to CONST_IMM, the verifier releases the reference.
156 * For each helper function that allocates a reference, such as
157 * bpf_sk_lookup_tcp(), there is a corresponding release function, such as
158 * bpf_sk_release(). When a reference type passes into the release function,
159 * the verifier also releases the reference. If any unchecked or unreleased
160 * reference remains at the end of the program, the verifier rejects it.
163 /* verifier_state + insn_idx are pushed to stack when branch is encountered */
164 struct bpf_verifier_stack_elem {
165 /* verifer state is 'st'
166 * before processing instruction 'insn_idx'
167 * and after processing instruction 'prev_insn_idx'
169 struct bpf_verifier_state st;
172 struct bpf_verifier_stack_elem *next;
173 /* length of verifier log at the time this state was pushed on stack */
177 #define BPF_COMPLEXITY_LIMIT_JMP_SEQ 8192
178 #define BPF_COMPLEXITY_LIMIT_STATES 64
180 #define BPF_MAP_KEY_POISON (1ULL << 63)
181 #define BPF_MAP_KEY_SEEN (1ULL << 62)
183 #define BPF_MAP_PTR_UNPRIV 1UL
184 #define BPF_MAP_PTR_POISON ((void *)((0xeB9FUL << 1) + \
185 POISON_POINTER_DELTA))
186 #define BPF_MAP_PTR(X) ((struct bpf_map *)((X) & ~BPF_MAP_PTR_UNPRIV))
188 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux)
190 return BPF_MAP_PTR(aux->map_ptr_state) == BPF_MAP_PTR_POISON;
193 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux)
195 return aux->map_ptr_state & BPF_MAP_PTR_UNPRIV;
198 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
199 const struct bpf_map *map, bool unpriv)
201 BUILD_BUG_ON((unsigned long)BPF_MAP_PTR_POISON & BPF_MAP_PTR_UNPRIV);
202 unpriv |= bpf_map_ptr_unpriv(aux);
203 aux->map_ptr_state = (unsigned long)map |
204 (unpriv ? BPF_MAP_PTR_UNPRIV : 0UL);
207 static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux)
209 return aux->map_key_state & BPF_MAP_KEY_POISON;
212 static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux)
214 return !(aux->map_key_state & BPF_MAP_KEY_SEEN);
217 static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux)
219 return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON);
222 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state)
224 bool poisoned = bpf_map_key_poisoned(aux);
226 aux->map_key_state = state | BPF_MAP_KEY_SEEN |
227 (poisoned ? BPF_MAP_KEY_POISON : 0ULL);
230 struct bpf_call_arg_meta {
231 struct bpf_map *map_ptr;
243 struct btf *btf_vmlinux;
245 static DEFINE_MUTEX(bpf_verifier_lock);
247 static const struct bpf_line_info *
248 find_linfo(const struct bpf_verifier_env *env, u32 insn_off)
250 const struct bpf_line_info *linfo;
251 const struct bpf_prog *prog;
255 nr_linfo = prog->aux->nr_linfo;
257 if (!nr_linfo || insn_off >= prog->len)
260 linfo = prog->aux->linfo;
261 for (i = 1; i < nr_linfo; i++)
262 if (insn_off < linfo[i].insn_off)
265 return &linfo[i - 1];
268 void bpf_verifier_vlog(struct bpf_verifier_log *log, const char *fmt,
273 n = vscnprintf(log->kbuf, BPF_VERIFIER_TMP_LOG_SIZE, fmt, args);
275 WARN_ONCE(n >= BPF_VERIFIER_TMP_LOG_SIZE - 1,
276 "verifier log line truncated - local buffer too short\n");
278 n = min(log->len_total - log->len_used - 1, n);
281 if (log->level == BPF_LOG_KERNEL) {
282 pr_err("BPF:%s\n", log->kbuf);
285 if (!copy_to_user(log->ubuf + log->len_used, log->kbuf, n + 1))
291 static void bpf_vlog_reset(struct bpf_verifier_log *log, u32 new_pos)
295 if (!bpf_verifier_log_needed(log))
298 log->len_used = new_pos;
299 if (put_user(zero, log->ubuf + new_pos))
303 /* log_level controls verbosity level of eBPF verifier.
304 * bpf_verifier_log_write() is used to dump the verification trace to the log,
305 * so the user can figure out what's wrong with the program
307 __printf(2, 3) void bpf_verifier_log_write(struct bpf_verifier_env *env,
308 const char *fmt, ...)
312 if (!bpf_verifier_log_needed(&env->log))
316 bpf_verifier_vlog(&env->log, fmt, args);
319 EXPORT_SYMBOL_GPL(bpf_verifier_log_write);
321 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
323 struct bpf_verifier_env *env = private_data;
326 if (!bpf_verifier_log_needed(&env->log))
330 bpf_verifier_vlog(&env->log, fmt, args);
334 __printf(2, 3) void bpf_log(struct bpf_verifier_log *log,
335 const char *fmt, ...)
339 if (!bpf_verifier_log_needed(log))
343 bpf_verifier_vlog(log, fmt, args);
347 static const char *ltrim(const char *s)
355 __printf(3, 4) static void verbose_linfo(struct bpf_verifier_env *env,
357 const char *prefix_fmt, ...)
359 const struct bpf_line_info *linfo;
361 if (!bpf_verifier_log_needed(&env->log))
364 linfo = find_linfo(env, insn_off);
365 if (!linfo || linfo == env->prev_linfo)
371 va_start(args, prefix_fmt);
372 bpf_verifier_vlog(&env->log, prefix_fmt, args);
377 ltrim(btf_name_by_offset(env->prog->aux->btf,
380 env->prev_linfo = linfo;
383 static bool type_is_pkt_pointer(enum bpf_reg_type type)
385 return type == PTR_TO_PACKET ||
386 type == PTR_TO_PACKET_META;
389 static bool type_is_sk_pointer(enum bpf_reg_type type)
391 return type == PTR_TO_SOCKET ||
392 type == PTR_TO_SOCK_COMMON ||
393 type == PTR_TO_TCP_SOCK ||
394 type == PTR_TO_XDP_SOCK;
397 static bool reg_type_not_null(enum bpf_reg_type type)
399 return type == PTR_TO_SOCKET ||
400 type == PTR_TO_TCP_SOCK ||
401 type == PTR_TO_MAP_VALUE ||
402 type == PTR_TO_SOCK_COMMON;
405 static bool reg_type_may_be_null(enum bpf_reg_type type)
407 return type == PTR_TO_MAP_VALUE_OR_NULL ||
408 type == PTR_TO_SOCKET_OR_NULL ||
409 type == PTR_TO_SOCK_COMMON_OR_NULL ||
410 type == PTR_TO_TCP_SOCK_OR_NULL ||
411 type == PTR_TO_BTF_ID_OR_NULL ||
412 type == PTR_TO_MEM_OR_NULL;
415 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
417 return reg->type == PTR_TO_MAP_VALUE &&
418 map_value_has_spin_lock(reg->map_ptr);
421 static bool reg_type_may_be_refcounted_or_null(enum bpf_reg_type type)
423 return type == PTR_TO_SOCKET ||
424 type == PTR_TO_SOCKET_OR_NULL ||
425 type == PTR_TO_TCP_SOCK ||
426 type == PTR_TO_TCP_SOCK_OR_NULL ||
427 type == PTR_TO_MEM ||
428 type == PTR_TO_MEM_OR_NULL;
431 static bool arg_type_may_be_refcounted(enum bpf_arg_type type)
433 return type == ARG_PTR_TO_SOCK_COMMON;
436 /* Determine whether the function releases some resources allocated by another
437 * function call. The first reference type argument will be assumed to be
438 * released by release_reference().
440 static bool is_release_function(enum bpf_func_id func_id)
442 return func_id == BPF_FUNC_sk_release ||
443 func_id == BPF_FUNC_ringbuf_submit ||
444 func_id == BPF_FUNC_ringbuf_discard;
447 static bool may_be_acquire_function(enum bpf_func_id func_id)
449 return func_id == BPF_FUNC_sk_lookup_tcp ||
450 func_id == BPF_FUNC_sk_lookup_udp ||
451 func_id == BPF_FUNC_skc_lookup_tcp ||
452 func_id == BPF_FUNC_map_lookup_elem ||
453 func_id == BPF_FUNC_ringbuf_reserve;
456 static bool is_acquire_function(enum bpf_func_id func_id,
457 const struct bpf_map *map)
459 enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
461 if (func_id == BPF_FUNC_sk_lookup_tcp ||
462 func_id == BPF_FUNC_sk_lookup_udp ||
463 func_id == BPF_FUNC_skc_lookup_tcp ||
464 func_id == BPF_FUNC_ringbuf_reserve)
467 if (func_id == BPF_FUNC_map_lookup_elem &&
468 (map_type == BPF_MAP_TYPE_SOCKMAP ||
469 map_type == BPF_MAP_TYPE_SOCKHASH))
475 static bool is_ptr_cast_function(enum bpf_func_id func_id)
477 return func_id == BPF_FUNC_tcp_sock ||
478 func_id == BPF_FUNC_sk_fullsock;
481 /* string representation of 'enum bpf_reg_type' */
482 static const char * const reg_type_str[] = {
484 [SCALAR_VALUE] = "inv",
485 [PTR_TO_CTX] = "ctx",
486 [CONST_PTR_TO_MAP] = "map_ptr",
487 [PTR_TO_MAP_VALUE] = "map_value",
488 [PTR_TO_MAP_VALUE_OR_NULL] = "map_value_or_null",
489 [PTR_TO_STACK] = "fp",
490 [PTR_TO_PACKET] = "pkt",
491 [PTR_TO_PACKET_META] = "pkt_meta",
492 [PTR_TO_PACKET_END] = "pkt_end",
493 [PTR_TO_FLOW_KEYS] = "flow_keys",
494 [PTR_TO_SOCKET] = "sock",
495 [PTR_TO_SOCKET_OR_NULL] = "sock_or_null",
496 [PTR_TO_SOCK_COMMON] = "sock_common",
497 [PTR_TO_SOCK_COMMON_OR_NULL] = "sock_common_or_null",
498 [PTR_TO_TCP_SOCK] = "tcp_sock",
499 [PTR_TO_TCP_SOCK_OR_NULL] = "tcp_sock_or_null",
500 [PTR_TO_TP_BUFFER] = "tp_buffer",
501 [PTR_TO_XDP_SOCK] = "xdp_sock",
502 [PTR_TO_BTF_ID] = "ptr_",
503 [PTR_TO_BTF_ID_OR_NULL] = "ptr_or_null_",
504 [PTR_TO_MEM] = "mem",
505 [PTR_TO_MEM_OR_NULL] = "mem_or_null",
508 static char slot_type_char[] = {
509 [STACK_INVALID] = '?',
515 static void print_liveness(struct bpf_verifier_env *env,
516 enum bpf_reg_liveness live)
518 if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE))
520 if (live & REG_LIVE_READ)
522 if (live & REG_LIVE_WRITTEN)
524 if (live & REG_LIVE_DONE)
528 static struct bpf_func_state *func(struct bpf_verifier_env *env,
529 const struct bpf_reg_state *reg)
531 struct bpf_verifier_state *cur = env->cur_state;
533 return cur->frame[reg->frameno];
536 const char *kernel_type_name(u32 id)
538 return btf_name_by_offset(btf_vmlinux,
539 btf_type_by_id(btf_vmlinux, id)->name_off);
542 static void print_verifier_state(struct bpf_verifier_env *env,
543 const struct bpf_func_state *state)
545 const struct bpf_reg_state *reg;
550 verbose(env, " frame%d:", state->frameno);
551 for (i = 0; i < MAX_BPF_REG; i++) {
552 reg = &state->regs[i];
556 verbose(env, " R%d", i);
557 print_liveness(env, reg->live);
558 verbose(env, "=%s", reg_type_str[t]);
559 if (t == SCALAR_VALUE && reg->precise)
561 if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
562 tnum_is_const(reg->var_off)) {
563 /* reg->off should be 0 for SCALAR_VALUE */
564 verbose(env, "%lld", reg->var_off.value + reg->off);
566 if (t == PTR_TO_BTF_ID || t == PTR_TO_BTF_ID_OR_NULL)
567 verbose(env, "%s", kernel_type_name(reg->btf_id));
568 verbose(env, "(id=%d", reg->id);
569 if (reg_type_may_be_refcounted_or_null(t))
570 verbose(env, ",ref_obj_id=%d", reg->ref_obj_id);
571 if (t != SCALAR_VALUE)
572 verbose(env, ",off=%d", reg->off);
573 if (type_is_pkt_pointer(t))
574 verbose(env, ",r=%d", reg->range);
575 else if (t == CONST_PTR_TO_MAP ||
576 t == PTR_TO_MAP_VALUE ||
577 t == PTR_TO_MAP_VALUE_OR_NULL)
578 verbose(env, ",ks=%d,vs=%d",
579 reg->map_ptr->key_size,
580 reg->map_ptr->value_size);
581 if (tnum_is_const(reg->var_off)) {
582 /* Typically an immediate SCALAR_VALUE, but
583 * could be a pointer whose offset is too big
586 verbose(env, ",imm=%llx", reg->var_off.value);
588 if (reg->smin_value != reg->umin_value &&
589 reg->smin_value != S64_MIN)
590 verbose(env, ",smin_value=%lld",
591 (long long)reg->smin_value);
592 if (reg->smax_value != reg->umax_value &&
593 reg->smax_value != S64_MAX)
594 verbose(env, ",smax_value=%lld",
595 (long long)reg->smax_value);
596 if (reg->umin_value != 0)
597 verbose(env, ",umin_value=%llu",
598 (unsigned long long)reg->umin_value);
599 if (reg->umax_value != U64_MAX)
600 verbose(env, ",umax_value=%llu",
601 (unsigned long long)reg->umax_value);
602 if (!tnum_is_unknown(reg->var_off)) {
605 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
606 verbose(env, ",var_off=%s", tn_buf);
608 if (reg->s32_min_value != reg->smin_value &&
609 reg->s32_min_value != S32_MIN)
610 verbose(env, ",s32_min_value=%d",
611 (int)(reg->s32_min_value));
612 if (reg->s32_max_value != reg->smax_value &&
613 reg->s32_max_value != S32_MAX)
614 verbose(env, ",s32_max_value=%d",
615 (int)(reg->s32_max_value));
616 if (reg->u32_min_value != reg->umin_value &&
617 reg->u32_min_value != U32_MIN)
618 verbose(env, ",u32_min_value=%d",
619 (int)(reg->u32_min_value));
620 if (reg->u32_max_value != reg->umax_value &&
621 reg->u32_max_value != U32_MAX)
622 verbose(env, ",u32_max_value=%d",
623 (int)(reg->u32_max_value));
628 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
629 char types_buf[BPF_REG_SIZE + 1];
633 for (j = 0; j < BPF_REG_SIZE; j++) {
634 if (state->stack[i].slot_type[j] != STACK_INVALID)
636 types_buf[j] = slot_type_char[
637 state->stack[i].slot_type[j]];
639 types_buf[BPF_REG_SIZE] = 0;
642 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
643 print_liveness(env, state->stack[i].spilled_ptr.live);
644 if (state->stack[i].slot_type[0] == STACK_SPILL) {
645 reg = &state->stack[i].spilled_ptr;
647 verbose(env, "=%s", reg_type_str[t]);
648 if (t == SCALAR_VALUE && reg->precise)
650 if (t == SCALAR_VALUE && tnum_is_const(reg->var_off))
651 verbose(env, "%lld", reg->var_off.value + reg->off);
653 verbose(env, "=%s", types_buf);
656 if (state->acquired_refs && state->refs[0].id) {
657 verbose(env, " refs=%d", state->refs[0].id);
658 for (i = 1; i < state->acquired_refs; i++)
659 if (state->refs[i].id)
660 verbose(env, ",%d", state->refs[i].id);
665 #define COPY_STATE_FN(NAME, COUNT, FIELD, SIZE) \
666 static int copy_##NAME##_state(struct bpf_func_state *dst, \
667 const struct bpf_func_state *src) \
671 if (WARN_ON_ONCE(dst->COUNT < src->COUNT)) { \
672 /* internal bug, make state invalid to reject the program */ \
673 memset(dst, 0, sizeof(*dst)); \
676 memcpy(dst->FIELD, src->FIELD, \
677 sizeof(*src->FIELD) * (src->COUNT / SIZE)); \
680 /* copy_reference_state() */
681 COPY_STATE_FN(reference, acquired_refs, refs, 1)
682 /* copy_stack_state() */
683 COPY_STATE_FN(stack, allocated_stack, stack, BPF_REG_SIZE)
686 #define REALLOC_STATE_FN(NAME, COUNT, FIELD, SIZE) \
687 static int realloc_##NAME##_state(struct bpf_func_state *state, int size, \
690 u32 old_size = state->COUNT; \
691 struct bpf_##NAME##_state *new_##FIELD; \
692 int slot = size / SIZE; \
694 if (size <= old_size || !size) { \
697 state->COUNT = slot * SIZE; \
698 if (!size && old_size) { \
699 kfree(state->FIELD); \
700 state->FIELD = NULL; \
704 new_##FIELD = kmalloc_array(slot, sizeof(struct bpf_##NAME##_state), \
710 memcpy(new_##FIELD, state->FIELD, \
711 sizeof(*new_##FIELD) * (old_size / SIZE)); \
712 memset(new_##FIELD + old_size / SIZE, 0, \
713 sizeof(*new_##FIELD) * (size - old_size) / SIZE); \
715 state->COUNT = slot * SIZE; \
716 kfree(state->FIELD); \
717 state->FIELD = new_##FIELD; \
720 /* realloc_reference_state() */
721 REALLOC_STATE_FN(reference, acquired_refs, refs, 1)
722 /* realloc_stack_state() */
723 REALLOC_STATE_FN(stack, allocated_stack, stack, BPF_REG_SIZE)
724 #undef REALLOC_STATE_FN
726 /* do_check() starts with zero-sized stack in struct bpf_verifier_state to
727 * make it consume minimal amount of memory. check_stack_write() access from
728 * the program calls into realloc_func_state() to grow the stack size.
729 * Note there is a non-zero 'parent' pointer inside bpf_verifier_state
730 * which realloc_stack_state() copies over. It points to previous
731 * bpf_verifier_state which is never reallocated.
733 static int realloc_func_state(struct bpf_func_state *state, int stack_size,
734 int refs_size, bool copy_old)
736 int err = realloc_reference_state(state, refs_size, copy_old);
739 return realloc_stack_state(state, stack_size, copy_old);
742 /* Acquire a pointer id from the env and update the state->refs to include
743 * this new pointer reference.
744 * On success, returns a valid pointer id to associate with the register
745 * On failure, returns a negative errno.
747 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
749 struct bpf_func_state *state = cur_func(env);
750 int new_ofs = state->acquired_refs;
753 err = realloc_reference_state(state, state->acquired_refs + 1, true);
757 state->refs[new_ofs].id = id;
758 state->refs[new_ofs].insn_idx = insn_idx;
763 /* release function corresponding to acquire_reference_state(). Idempotent. */
764 static int release_reference_state(struct bpf_func_state *state, int ptr_id)
768 last_idx = state->acquired_refs - 1;
769 for (i = 0; i < state->acquired_refs; i++) {
770 if (state->refs[i].id == ptr_id) {
771 if (last_idx && i != last_idx)
772 memcpy(&state->refs[i], &state->refs[last_idx],
773 sizeof(*state->refs));
774 memset(&state->refs[last_idx], 0, sizeof(*state->refs));
775 state->acquired_refs--;
782 static int transfer_reference_state(struct bpf_func_state *dst,
783 struct bpf_func_state *src)
785 int err = realloc_reference_state(dst, src->acquired_refs, false);
788 err = copy_reference_state(dst, src);
794 static void free_func_state(struct bpf_func_state *state)
803 static void clear_jmp_history(struct bpf_verifier_state *state)
805 kfree(state->jmp_history);
806 state->jmp_history = NULL;
807 state->jmp_history_cnt = 0;
810 static void free_verifier_state(struct bpf_verifier_state *state,
815 for (i = 0; i <= state->curframe; i++) {
816 free_func_state(state->frame[i]);
817 state->frame[i] = NULL;
819 clear_jmp_history(state);
824 /* copy verifier state from src to dst growing dst stack space
825 * when necessary to accommodate larger src stack
827 static int copy_func_state(struct bpf_func_state *dst,
828 const struct bpf_func_state *src)
832 err = realloc_func_state(dst, src->allocated_stack, src->acquired_refs,
836 memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
837 err = copy_reference_state(dst, src);
840 return copy_stack_state(dst, src);
843 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
844 const struct bpf_verifier_state *src)
846 struct bpf_func_state *dst;
847 u32 jmp_sz = sizeof(struct bpf_idx_pair) * src->jmp_history_cnt;
850 if (dst_state->jmp_history_cnt < src->jmp_history_cnt) {
851 kfree(dst_state->jmp_history);
852 dst_state->jmp_history = kmalloc(jmp_sz, GFP_USER);
853 if (!dst_state->jmp_history)
856 memcpy(dst_state->jmp_history, src->jmp_history, jmp_sz);
857 dst_state->jmp_history_cnt = src->jmp_history_cnt;
859 /* if dst has more stack frames then src frame, free them */
860 for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
861 free_func_state(dst_state->frame[i]);
862 dst_state->frame[i] = NULL;
864 dst_state->speculative = src->speculative;
865 dst_state->curframe = src->curframe;
866 dst_state->active_spin_lock = src->active_spin_lock;
867 dst_state->branches = src->branches;
868 dst_state->parent = src->parent;
869 dst_state->first_insn_idx = src->first_insn_idx;
870 dst_state->last_insn_idx = src->last_insn_idx;
871 for (i = 0; i <= src->curframe; i++) {
872 dst = dst_state->frame[i];
874 dst = kzalloc(sizeof(*dst), GFP_KERNEL);
877 dst_state->frame[i] = dst;
879 err = copy_func_state(dst, src->frame[i]);
886 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
889 u32 br = --st->branches;
891 /* WARN_ON(br > 1) technically makes sense here,
892 * but see comment in push_stack(), hence:
894 WARN_ONCE((int)br < 0,
895 "BUG update_branch_counts:branches_to_explore=%d\n",
903 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
904 int *insn_idx, bool pop_log)
906 struct bpf_verifier_state *cur = env->cur_state;
907 struct bpf_verifier_stack_elem *elem, *head = env->head;
910 if (env->head == NULL)
914 err = copy_verifier_state(cur, &head->st);
919 bpf_vlog_reset(&env->log, head->log_pos);
921 *insn_idx = head->insn_idx;
923 *prev_insn_idx = head->prev_insn_idx;
925 free_verifier_state(&head->st, false);
932 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
933 int insn_idx, int prev_insn_idx,
936 struct bpf_verifier_state *cur = env->cur_state;
937 struct bpf_verifier_stack_elem *elem;
940 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
944 elem->insn_idx = insn_idx;
945 elem->prev_insn_idx = prev_insn_idx;
946 elem->next = env->head;
947 elem->log_pos = env->log.len_used;
950 err = copy_verifier_state(&elem->st, cur);
953 elem->st.speculative |= speculative;
954 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
955 verbose(env, "The sequence of %d jumps is too complex.\n",
959 if (elem->st.parent) {
960 ++elem->st.parent->branches;
961 /* WARN_ON(branches > 2) technically makes sense here,
963 * 1. speculative states will bump 'branches' for non-branch
965 * 2. is_state_visited() heuristics may decide not to create
966 * a new state for a sequence of branches and all such current
967 * and cloned states will be pointing to a single parent state
968 * which might have large 'branches' count.
973 free_verifier_state(env->cur_state, true);
974 env->cur_state = NULL;
975 /* pop all elements and return */
976 while (!pop_stack(env, NULL, NULL, false));
980 #define CALLER_SAVED_REGS 6
981 static const int caller_saved[CALLER_SAVED_REGS] = {
982 BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
985 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
986 struct bpf_reg_state *reg);
988 /* Mark the unknown part of a register (variable offset or scalar value) as
989 * known to have the value @imm.
991 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
993 /* Clear id, off, and union(map_ptr, range) */
994 memset(((u8 *)reg) + sizeof(reg->type), 0,
995 offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
996 reg->var_off = tnum_const(imm);
997 reg->smin_value = (s64)imm;
998 reg->smax_value = (s64)imm;
999 reg->umin_value = imm;
1000 reg->umax_value = imm;
1002 reg->s32_min_value = (s32)imm;
1003 reg->s32_max_value = (s32)imm;
1004 reg->u32_min_value = (u32)imm;
1005 reg->u32_max_value = (u32)imm;
1008 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1010 reg->var_off = tnum_const_subreg(reg->var_off, imm);
1011 reg->s32_min_value = (s32)imm;
1012 reg->s32_max_value = (s32)imm;
1013 reg->u32_min_value = (u32)imm;
1014 reg->u32_max_value = (u32)imm;
1017 /* Mark the 'variable offset' part of a register as zero. This should be
1018 * used only on registers holding a pointer type.
1020 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
1022 __mark_reg_known(reg, 0);
1025 static void __mark_reg_const_zero(struct bpf_reg_state *reg)
1027 __mark_reg_known(reg, 0);
1028 reg->type = SCALAR_VALUE;
1031 static void mark_reg_known_zero(struct bpf_verifier_env *env,
1032 struct bpf_reg_state *regs, u32 regno)
1034 if (WARN_ON(regno >= MAX_BPF_REG)) {
1035 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
1036 /* Something bad happened, let's kill all regs */
1037 for (regno = 0; regno < MAX_BPF_REG; regno++)
1038 __mark_reg_not_init(env, regs + regno);
1041 __mark_reg_known_zero(regs + regno);
1044 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1046 return type_is_pkt_pointer(reg->type);
1049 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
1051 return reg_is_pkt_pointer(reg) ||
1052 reg->type == PTR_TO_PACKET_END;
1055 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
1056 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
1057 enum bpf_reg_type which)
1059 /* The register can already have a range from prior markings.
1060 * This is fine as long as it hasn't been advanced from its
1063 return reg->type == which &&
1066 tnum_equals_const(reg->var_off, 0);
1069 /* Reset the min/max bounds of a register */
1070 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
1072 reg->smin_value = S64_MIN;
1073 reg->smax_value = S64_MAX;
1074 reg->umin_value = 0;
1075 reg->umax_value = U64_MAX;
1077 reg->s32_min_value = S32_MIN;
1078 reg->s32_max_value = S32_MAX;
1079 reg->u32_min_value = 0;
1080 reg->u32_max_value = U32_MAX;
1083 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
1085 reg->smin_value = S64_MIN;
1086 reg->smax_value = S64_MAX;
1087 reg->umin_value = 0;
1088 reg->umax_value = U64_MAX;
1091 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
1093 reg->s32_min_value = S32_MIN;
1094 reg->s32_max_value = S32_MAX;
1095 reg->u32_min_value = 0;
1096 reg->u32_max_value = U32_MAX;
1099 static void __update_reg32_bounds(struct bpf_reg_state *reg)
1101 struct tnum var32_off = tnum_subreg(reg->var_off);
1103 /* min signed is max(sign bit) | min(other bits) */
1104 reg->s32_min_value = max_t(s32, reg->s32_min_value,
1105 var32_off.value | (var32_off.mask & S32_MIN));
1106 /* max signed is min(sign bit) | max(other bits) */
1107 reg->s32_max_value = min_t(s32, reg->s32_max_value,
1108 var32_off.value | (var32_off.mask & S32_MAX));
1109 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
1110 reg->u32_max_value = min(reg->u32_max_value,
1111 (u32)(var32_off.value | var32_off.mask));
1114 static void __update_reg64_bounds(struct bpf_reg_state *reg)
1116 /* min signed is max(sign bit) | min(other bits) */
1117 reg->smin_value = max_t(s64, reg->smin_value,
1118 reg->var_off.value | (reg->var_off.mask & S64_MIN));
1119 /* max signed is min(sign bit) | max(other bits) */
1120 reg->smax_value = min_t(s64, reg->smax_value,
1121 reg->var_off.value | (reg->var_off.mask & S64_MAX));
1122 reg->umin_value = max(reg->umin_value, reg->var_off.value);
1123 reg->umax_value = min(reg->umax_value,
1124 reg->var_off.value | reg->var_off.mask);
1127 static void __update_reg_bounds(struct bpf_reg_state *reg)
1129 __update_reg32_bounds(reg);
1130 __update_reg64_bounds(reg);
1133 /* Uses signed min/max values to inform unsigned, and vice-versa */
1134 static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
1136 /* Learn sign from signed bounds.
1137 * If we cannot cross the sign boundary, then signed and unsigned bounds
1138 * are the same, so combine. This works even in the negative case, e.g.
1139 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1141 if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) {
1142 reg->s32_min_value = reg->u32_min_value =
1143 max_t(u32, reg->s32_min_value, reg->u32_min_value);
1144 reg->s32_max_value = reg->u32_max_value =
1145 min_t(u32, reg->s32_max_value, reg->u32_max_value);
1148 /* Learn sign from unsigned bounds. Signed bounds cross the sign
1149 * boundary, so we must be careful.
1151 if ((s32)reg->u32_max_value >= 0) {
1152 /* Positive. We can't learn anything from the smin, but smax
1153 * is positive, hence safe.
1155 reg->s32_min_value = reg->u32_min_value;
1156 reg->s32_max_value = reg->u32_max_value =
1157 min_t(u32, reg->s32_max_value, reg->u32_max_value);
1158 } else if ((s32)reg->u32_min_value < 0) {
1159 /* Negative. We can't learn anything from the smax, but smin
1160 * is negative, hence safe.
1162 reg->s32_min_value = reg->u32_min_value =
1163 max_t(u32, reg->s32_min_value, reg->u32_min_value);
1164 reg->s32_max_value = reg->u32_max_value;
1168 static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
1170 /* Learn sign from signed bounds.
1171 * If we cannot cross the sign boundary, then signed and unsigned bounds
1172 * are the same, so combine. This works even in the negative case, e.g.
1173 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1175 if (reg->smin_value >= 0 || reg->smax_value < 0) {
1176 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1178 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1182 /* Learn sign from unsigned bounds. Signed bounds cross the sign
1183 * boundary, so we must be careful.
1185 if ((s64)reg->umax_value >= 0) {
1186 /* Positive. We can't learn anything from the smin, but smax
1187 * is positive, hence safe.
1189 reg->smin_value = reg->umin_value;
1190 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1192 } else if ((s64)reg->umin_value < 0) {
1193 /* Negative. We can't learn anything from the smax, but smin
1194 * is negative, hence safe.
1196 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1198 reg->smax_value = reg->umax_value;
1202 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
1204 __reg32_deduce_bounds(reg);
1205 __reg64_deduce_bounds(reg);
1208 /* Attempts to improve var_off based on unsigned min/max information */
1209 static void __reg_bound_offset(struct bpf_reg_state *reg)
1211 struct tnum var64_off = tnum_intersect(reg->var_off,
1212 tnum_range(reg->umin_value,
1214 struct tnum var32_off = tnum_intersect(tnum_subreg(reg->var_off),
1215 tnum_range(reg->u32_min_value,
1216 reg->u32_max_value));
1218 reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
1221 static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
1223 reg->umin_value = reg->u32_min_value;
1224 reg->umax_value = reg->u32_max_value;
1225 /* Attempt to pull 32-bit signed bounds into 64-bit bounds
1226 * but must be positive otherwise set to worse case bounds
1227 * and refine later from tnum.
1229 if (reg->s32_min_value >= 0 && reg->s32_max_value >= 0)
1230 reg->smax_value = reg->s32_max_value;
1232 reg->smax_value = U32_MAX;
1233 if (reg->s32_min_value >= 0)
1234 reg->smin_value = reg->s32_min_value;
1236 reg->smin_value = 0;
1239 static void __reg_combine_32_into_64(struct bpf_reg_state *reg)
1241 /* special case when 64-bit register has upper 32-bit register
1242 * zeroed. Typically happens after zext or <<32, >>32 sequence
1243 * allowing us to use 32-bit bounds directly,
1245 if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) {
1246 __reg_assign_32_into_64(reg);
1248 /* Otherwise the best we can do is push lower 32bit known and
1249 * unknown bits into register (var_off set from jmp logic)
1250 * then learn as much as possible from the 64-bit tnum
1251 * known and unknown bits. The previous smin/smax bounds are
1252 * invalid here because of jmp32 compare so mark them unknown
1253 * so they do not impact tnum bounds calculation.
1255 __mark_reg64_unbounded(reg);
1256 __update_reg_bounds(reg);
1259 /* Intersecting with the old var_off might have improved our bounds
1260 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1261 * then new var_off is (0; 0x7f...fc) which improves our umax.
1263 __reg_deduce_bounds(reg);
1264 __reg_bound_offset(reg);
1265 __update_reg_bounds(reg);
1268 static bool __reg64_bound_s32(s64 a)
1270 if (a > S32_MIN && a < S32_MAX)
1275 static bool __reg64_bound_u32(u64 a)
1277 if (a > U32_MIN && a < U32_MAX)
1282 static void __reg_combine_64_into_32(struct bpf_reg_state *reg)
1284 __mark_reg32_unbounded(reg);
1286 if (__reg64_bound_s32(reg->smin_value))
1287 reg->s32_min_value = (s32)reg->smin_value;
1288 if (__reg64_bound_s32(reg->smax_value))
1289 reg->s32_max_value = (s32)reg->smax_value;
1290 if (__reg64_bound_u32(reg->umin_value))
1291 reg->u32_min_value = (u32)reg->umin_value;
1292 if (__reg64_bound_u32(reg->umax_value))
1293 reg->u32_max_value = (u32)reg->umax_value;
1295 /* Intersecting with the old var_off might have improved our bounds
1296 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1297 * then new var_off is (0; 0x7f...fc) which improves our umax.
1299 __reg_deduce_bounds(reg);
1300 __reg_bound_offset(reg);
1301 __update_reg_bounds(reg);
1304 /* Mark a register as having a completely unknown (scalar) value. */
1305 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
1306 struct bpf_reg_state *reg)
1309 * Clear type, id, off, and union(map_ptr, range) and
1310 * padding between 'type' and union
1312 memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
1313 reg->type = SCALAR_VALUE;
1314 reg->var_off = tnum_unknown;
1316 reg->precise = env->subprog_cnt > 1 || !env->bpf_capable;
1317 __mark_reg_unbounded(reg);
1320 static void mark_reg_unknown(struct bpf_verifier_env *env,
1321 struct bpf_reg_state *regs, u32 regno)
1323 if (WARN_ON(regno >= MAX_BPF_REG)) {
1324 verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
1325 /* Something bad happened, let's kill all regs except FP */
1326 for (regno = 0; regno < BPF_REG_FP; regno++)
1327 __mark_reg_not_init(env, regs + regno);
1330 __mark_reg_unknown(env, regs + regno);
1333 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1334 struct bpf_reg_state *reg)
1336 __mark_reg_unknown(env, reg);
1337 reg->type = NOT_INIT;
1340 static void mark_reg_not_init(struct bpf_verifier_env *env,
1341 struct bpf_reg_state *regs, u32 regno)
1343 if (WARN_ON(regno >= MAX_BPF_REG)) {
1344 verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
1345 /* Something bad happened, let's kill all regs except FP */
1346 for (regno = 0; regno < BPF_REG_FP; regno++)
1347 __mark_reg_not_init(env, regs + regno);
1350 __mark_reg_not_init(env, regs + regno);
1353 #define DEF_NOT_SUBREG (0)
1354 static void init_reg_state(struct bpf_verifier_env *env,
1355 struct bpf_func_state *state)
1357 struct bpf_reg_state *regs = state->regs;
1360 for (i = 0; i < MAX_BPF_REG; i++) {
1361 mark_reg_not_init(env, regs, i);
1362 regs[i].live = REG_LIVE_NONE;
1363 regs[i].parent = NULL;
1364 regs[i].subreg_def = DEF_NOT_SUBREG;
1368 regs[BPF_REG_FP].type = PTR_TO_STACK;
1369 mark_reg_known_zero(env, regs, BPF_REG_FP);
1370 regs[BPF_REG_FP].frameno = state->frameno;
1373 #define BPF_MAIN_FUNC (-1)
1374 static void init_func_state(struct bpf_verifier_env *env,
1375 struct bpf_func_state *state,
1376 int callsite, int frameno, int subprogno)
1378 state->callsite = callsite;
1379 state->frameno = frameno;
1380 state->subprogno = subprogno;
1381 init_reg_state(env, state);
1385 SRC_OP, /* register is used as source operand */
1386 DST_OP, /* register is used as destination operand */
1387 DST_OP_NO_MARK /* same as above, check only, don't mark */
1390 static int cmp_subprogs(const void *a, const void *b)
1392 return ((struct bpf_subprog_info *)a)->start -
1393 ((struct bpf_subprog_info *)b)->start;
1396 static int find_subprog(struct bpf_verifier_env *env, int off)
1398 struct bpf_subprog_info *p;
1400 p = bsearch(&off, env->subprog_info, env->subprog_cnt,
1401 sizeof(env->subprog_info[0]), cmp_subprogs);
1404 return p - env->subprog_info;
1408 static int add_subprog(struct bpf_verifier_env *env, int off)
1410 int insn_cnt = env->prog->len;
1413 if (off >= insn_cnt || off < 0) {
1414 verbose(env, "call to invalid destination\n");
1417 ret = find_subprog(env, off);
1420 if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
1421 verbose(env, "too many subprograms\n");
1424 env->subprog_info[env->subprog_cnt++].start = off;
1425 sort(env->subprog_info, env->subprog_cnt,
1426 sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
1430 static int check_subprogs(struct bpf_verifier_env *env)
1432 int i, ret, subprog_start, subprog_end, off, cur_subprog = 0;
1433 struct bpf_subprog_info *subprog = env->subprog_info;
1434 struct bpf_insn *insn = env->prog->insnsi;
1435 int insn_cnt = env->prog->len;
1437 /* Add entry function. */
1438 ret = add_subprog(env, 0);
1442 /* determine subprog starts. The end is one before the next starts */
1443 for (i = 0; i < insn_cnt; i++) {
1444 if (insn[i].code != (BPF_JMP | BPF_CALL))
1446 if (insn[i].src_reg != BPF_PSEUDO_CALL)
1448 if (!env->bpf_capable) {
1450 "function calls to other bpf functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
1453 ret = add_subprog(env, i + insn[i].imm + 1);
1458 /* Add a fake 'exit' subprog which could simplify subprog iteration
1459 * logic. 'subprog_cnt' should not be increased.
1461 subprog[env->subprog_cnt].start = insn_cnt;
1463 if (env->log.level & BPF_LOG_LEVEL2)
1464 for (i = 0; i < env->subprog_cnt; i++)
1465 verbose(env, "func#%d @%d\n", i, subprog[i].start);
1467 /* now check that all jumps are within the same subprog */
1468 subprog_start = subprog[cur_subprog].start;
1469 subprog_end = subprog[cur_subprog + 1].start;
1470 for (i = 0; i < insn_cnt; i++) {
1471 u8 code = insn[i].code;
1473 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
1475 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
1477 off = i + insn[i].off + 1;
1478 if (off < subprog_start || off >= subprog_end) {
1479 verbose(env, "jump out of range from insn %d to %d\n", i, off);
1483 if (i == subprog_end - 1) {
1484 /* to avoid fall-through from one subprog into another
1485 * the last insn of the subprog should be either exit
1486 * or unconditional jump back
1488 if (code != (BPF_JMP | BPF_EXIT) &&
1489 code != (BPF_JMP | BPF_JA)) {
1490 verbose(env, "last insn is not an exit or jmp\n");
1493 subprog_start = subprog_end;
1495 if (cur_subprog < env->subprog_cnt)
1496 subprog_end = subprog[cur_subprog + 1].start;
1502 /* Parentage chain of this register (or stack slot) should take care of all
1503 * issues like callee-saved registers, stack slot allocation time, etc.
1505 static int mark_reg_read(struct bpf_verifier_env *env,
1506 const struct bpf_reg_state *state,
1507 struct bpf_reg_state *parent, u8 flag)
1509 bool writes = parent == state->parent; /* Observe write marks */
1513 /* if read wasn't screened by an earlier write ... */
1514 if (writes && state->live & REG_LIVE_WRITTEN)
1516 if (parent->live & REG_LIVE_DONE) {
1517 verbose(env, "verifier BUG type %s var_off %lld off %d\n",
1518 reg_type_str[parent->type],
1519 parent->var_off.value, parent->off);
1522 /* The first condition is more likely to be true than the
1523 * second, checked it first.
1525 if ((parent->live & REG_LIVE_READ) == flag ||
1526 parent->live & REG_LIVE_READ64)
1527 /* The parentage chain never changes and
1528 * this parent was already marked as LIVE_READ.
1529 * There is no need to keep walking the chain again and
1530 * keep re-marking all parents as LIVE_READ.
1531 * This case happens when the same register is read
1532 * multiple times without writes into it in-between.
1533 * Also, if parent has the stronger REG_LIVE_READ64 set,
1534 * then no need to set the weak REG_LIVE_READ32.
1537 /* ... then we depend on parent's value */
1538 parent->live |= flag;
1539 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
1540 if (flag == REG_LIVE_READ64)
1541 parent->live &= ~REG_LIVE_READ32;
1543 parent = state->parent;
1548 if (env->longest_mark_read_walk < cnt)
1549 env->longest_mark_read_walk = cnt;
1553 /* This function is supposed to be used by the following 32-bit optimization
1554 * code only. It returns TRUE if the source or destination register operates
1555 * on 64-bit, otherwise return FALSE.
1557 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
1558 u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
1563 class = BPF_CLASS(code);
1565 if (class == BPF_JMP) {
1566 /* BPF_EXIT for "main" will reach here. Return TRUE
1571 if (op == BPF_CALL) {
1572 /* BPF to BPF call will reach here because of marking
1573 * caller saved clobber with DST_OP_NO_MARK for which we
1574 * don't care the register def because they are anyway
1575 * marked as NOT_INIT already.
1577 if (insn->src_reg == BPF_PSEUDO_CALL)
1579 /* Helper call will reach here because of arg type
1580 * check, conservatively return TRUE.
1589 if (class == BPF_ALU64 || class == BPF_JMP ||
1590 /* BPF_END always use BPF_ALU class. */
1591 (class == BPF_ALU && op == BPF_END && insn->imm == 64))
1594 if (class == BPF_ALU || class == BPF_JMP32)
1597 if (class == BPF_LDX) {
1599 return BPF_SIZE(code) == BPF_DW;
1600 /* LDX source must be ptr. */
1604 if (class == BPF_STX) {
1605 if (reg->type != SCALAR_VALUE)
1607 return BPF_SIZE(code) == BPF_DW;
1610 if (class == BPF_LD) {
1611 u8 mode = BPF_MODE(code);
1614 if (mode == BPF_IMM)
1617 /* Both LD_IND and LD_ABS return 32-bit data. */
1621 /* Implicit ctx ptr. */
1622 if (regno == BPF_REG_6)
1625 /* Explicit source could be any width. */
1629 if (class == BPF_ST)
1630 /* The only source register for BPF_ST is a ptr. */
1633 /* Conservatively return true at default. */
1637 /* Return TRUE if INSN doesn't have explicit value define. */
1638 static bool insn_no_def(struct bpf_insn *insn)
1640 u8 class = BPF_CLASS(insn->code);
1642 return (class == BPF_JMP || class == BPF_JMP32 ||
1643 class == BPF_STX || class == BPF_ST);
1646 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
1647 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
1649 if (insn_no_def(insn))
1652 return !is_reg64(env, insn, insn->dst_reg, NULL, DST_OP);
1655 static void mark_insn_zext(struct bpf_verifier_env *env,
1656 struct bpf_reg_state *reg)
1658 s32 def_idx = reg->subreg_def;
1660 if (def_idx == DEF_NOT_SUBREG)
1663 env->insn_aux_data[def_idx - 1].zext_dst = true;
1664 /* The dst will be zero extended, so won't be sub-register anymore. */
1665 reg->subreg_def = DEF_NOT_SUBREG;
1668 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
1669 enum reg_arg_type t)
1671 struct bpf_verifier_state *vstate = env->cur_state;
1672 struct bpf_func_state *state = vstate->frame[vstate->curframe];
1673 struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
1674 struct bpf_reg_state *reg, *regs = state->regs;
1677 if (regno >= MAX_BPF_REG) {
1678 verbose(env, "R%d is invalid\n", regno);
1683 rw64 = is_reg64(env, insn, regno, reg, t);
1685 /* check whether register used as source operand can be read */
1686 if (reg->type == NOT_INIT) {
1687 verbose(env, "R%d !read_ok\n", regno);
1690 /* We don't need to worry about FP liveness because it's read-only */
1691 if (regno == BPF_REG_FP)
1695 mark_insn_zext(env, reg);
1697 return mark_reg_read(env, reg, reg->parent,
1698 rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
1700 /* check whether register used as dest operand can be written to */
1701 if (regno == BPF_REG_FP) {
1702 verbose(env, "frame pointer is read only\n");
1705 reg->live |= REG_LIVE_WRITTEN;
1706 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
1708 mark_reg_unknown(env, regs, regno);
1713 /* for any branch, call, exit record the history of jmps in the given state */
1714 static int push_jmp_history(struct bpf_verifier_env *env,
1715 struct bpf_verifier_state *cur)
1717 u32 cnt = cur->jmp_history_cnt;
1718 struct bpf_idx_pair *p;
1721 p = krealloc(cur->jmp_history, cnt * sizeof(*p), GFP_USER);
1724 p[cnt - 1].idx = env->insn_idx;
1725 p[cnt - 1].prev_idx = env->prev_insn_idx;
1726 cur->jmp_history = p;
1727 cur->jmp_history_cnt = cnt;
1731 /* Backtrack one insn at a time. If idx is not at the top of recorded
1732 * history then previous instruction came from straight line execution.
1734 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
1739 if (cnt && st->jmp_history[cnt - 1].idx == i) {
1740 i = st->jmp_history[cnt - 1].prev_idx;
1748 /* For given verifier state backtrack_insn() is called from the last insn to
1749 * the first insn. Its purpose is to compute a bitmask of registers and
1750 * stack slots that needs precision in the parent verifier state.
1752 static int backtrack_insn(struct bpf_verifier_env *env, int idx,
1753 u32 *reg_mask, u64 *stack_mask)
1755 const struct bpf_insn_cbs cbs = {
1756 .cb_print = verbose,
1757 .private_data = env,
1759 struct bpf_insn *insn = env->prog->insnsi + idx;
1760 u8 class = BPF_CLASS(insn->code);
1761 u8 opcode = BPF_OP(insn->code);
1762 u8 mode = BPF_MODE(insn->code);
1763 u32 dreg = 1u << insn->dst_reg;
1764 u32 sreg = 1u << insn->src_reg;
1767 if (insn->code == 0)
1769 if (env->log.level & BPF_LOG_LEVEL) {
1770 verbose(env, "regs=%x stack=%llx before ", *reg_mask, *stack_mask);
1771 verbose(env, "%d: ", idx);
1772 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
1775 if (class == BPF_ALU || class == BPF_ALU64) {
1776 if (!(*reg_mask & dreg))
1778 if (opcode == BPF_MOV) {
1779 if (BPF_SRC(insn->code) == BPF_X) {
1781 * dreg needs precision after this insn
1782 * sreg needs precision before this insn
1788 * dreg needs precision after this insn.
1789 * Corresponding register is already marked
1790 * as precise=true in this verifier state.
1791 * No further markings in parent are necessary
1796 if (BPF_SRC(insn->code) == BPF_X) {
1798 * both dreg and sreg need precision
1803 * dreg still needs precision before this insn
1806 } else if (class == BPF_LDX) {
1807 if (!(*reg_mask & dreg))
1811 /* scalars can only be spilled into stack w/o losing precision.
1812 * Load from any other memory can be zero extended.
1813 * The desire to keep that precision is already indicated
1814 * by 'precise' mark in corresponding register of this state.
1815 * No further tracking necessary.
1817 if (insn->src_reg != BPF_REG_FP)
1819 if (BPF_SIZE(insn->code) != BPF_DW)
1822 /* dreg = *(u64 *)[fp - off] was a fill from the stack.
1823 * that [fp - off] slot contains scalar that needs to be
1824 * tracked with precision
1826 spi = (-insn->off - 1) / BPF_REG_SIZE;
1828 verbose(env, "BUG spi %d\n", spi);
1829 WARN_ONCE(1, "verifier backtracking bug");
1832 *stack_mask |= 1ull << spi;
1833 } else if (class == BPF_STX || class == BPF_ST) {
1834 if (*reg_mask & dreg)
1835 /* stx & st shouldn't be using _scalar_ dst_reg
1836 * to access memory. It means backtracking
1837 * encountered a case of pointer subtraction.
1840 /* scalars can only be spilled into stack */
1841 if (insn->dst_reg != BPF_REG_FP)
1843 if (BPF_SIZE(insn->code) != BPF_DW)
1845 spi = (-insn->off - 1) / BPF_REG_SIZE;
1847 verbose(env, "BUG spi %d\n", spi);
1848 WARN_ONCE(1, "verifier backtracking bug");
1851 if (!(*stack_mask & (1ull << spi)))
1853 *stack_mask &= ~(1ull << spi);
1854 if (class == BPF_STX)
1856 } else if (class == BPF_JMP || class == BPF_JMP32) {
1857 if (opcode == BPF_CALL) {
1858 if (insn->src_reg == BPF_PSEUDO_CALL)
1860 /* regular helper call sets R0 */
1862 if (*reg_mask & 0x3f) {
1863 /* if backtracing was looking for registers R1-R5
1864 * they should have been found already.
1866 verbose(env, "BUG regs %x\n", *reg_mask);
1867 WARN_ONCE(1, "verifier backtracking bug");
1870 } else if (opcode == BPF_EXIT) {
1873 } else if (class == BPF_LD) {
1874 if (!(*reg_mask & dreg))
1877 /* It's ld_imm64 or ld_abs or ld_ind.
1878 * For ld_imm64 no further tracking of precision
1879 * into parent is necessary
1881 if (mode == BPF_IND || mode == BPF_ABS)
1882 /* to be analyzed */
1888 /* the scalar precision tracking algorithm:
1889 * . at the start all registers have precise=false.
1890 * . scalar ranges are tracked as normal through alu and jmp insns.
1891 * . once precise value of the scalar register is used in:
1892 * . ptr + scalar alu
1893 * . if (scalar cond K|scalar)
1894 * . helper_call(.., scalar, ...) where ARG_CONST is expected
1895 * backtrack through the verifier states and mark all registers and
1896 * stack slots with spilled constants that these scalar regisers
1897 * should be precise.
1898 * . during state pruning two registers (or spilled stack slots)
1899 * are equivalent if both are not precise.
1901 * Note the verifier cannot simply walk register parentage chain,
1902 * since many different registers and stack slots could have been
1903 * used to compute single precise scalar.
1905 * The approach of starting with precise=true for all registers and then
1906 * backtrack to mark a register as not precise when the verifier detects
1907 * that program doesn't care about specific value (e.g., when helper
1908 * takes register as ARG_ANYTHING parameter) is not safe.
1910 * It's ok to walk single parentage chain of the verifier states.
1911 * It's possible that this backtracking will go all the way till 1st insn.
1912 * All other branches will be explored for needing precision later.
1914 * The backtracking needs to deal with cases like:
1915 * 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)
1918 * if r5 > 0x79f goto pc+7
1919 * R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
1922 * call bpf_perf_event_output#25
1923 * where .arg5_type = ARG_CONST_SIZE_OR_ZERO
1927 * call foo // uses callee's r6 inside to compute r0
1931 * to track above reg_mask/stack_mask needs to be independent for each frame.
1933 * Also if parent's curframe > frame where backtracking started,
1934 * the verifier need to mark registers in both frames, otherwise callees
1935 * may incorrectly prune callers. This is similar to
1936 * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
1938 * For now backtracking falls back into conservative marking.
1940 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
1941 struct bpf_verifier_state *st)
1943 struct bpf_func_state *func;
1944 struct bpf_reg_state *reg;
1947 /* big hammer: mark all scalars precise in this path.
1948 * pop_stack may still get !precise scalars.
1950 for (; st; st = st->parent)
1951 for (i = 0; i <= st->curframe; i++) {
1952 func = st->frame[i];
1953 for (j = 0; j < BPF_REG_FP; j++) {
1954 reg = &func->regs[j];
1955 if (reg->type != SCALAR_VALUE)
1957 reg->precise = true;
1959 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
1960 if (func->stack[j].slot_type[0] != STACK_SPILL)
1962 reg = &func->stack[j].spilled_ptr;
1963 if (reg->type != SCALAR_VALUE)
1965 reg->precise = true;
1970 static int __mark_chain_precision(struct bpf_verifier_env *env, int regno,
1973 struct bpf_verifier_state *st = env->cur_state;
1974 int first_idx = st->first_insn_idx;
1975 int last_idx = env->insn_idx;
1976 struct bpf_func_state *func;
1977 struct bpf_reg_state *reg;
1978 u32 reg_mask = regno >= 0 ? 1u << regno : 0;
1979 u64 stack_mask = spi >= 0 ? 1ull << spi : 0;
1980 bool skip_first = true;
1981 bool new_marks = false;
1984 if (!env->bpf_capable)
1987 func = st->frame[st->curframe];
1989 reg = &func->regs[regno];
1990 if (reg->type != SCALAR_VALUE) {
1991 WARN_ONCE(1, "backtracing misuse");
1998 reg->precise = true;
2002 if (func->stack[spi].slot_type[0] != STACK_SPILL) {
2006 reg = &func->stack[spi].spilled_ptr;
2007 if (reg->type != SCALAR_VALUE) {
2015 reg->precise = true;
2021 if (!reg_mask && !stack_mask)
2024 DECLARE_BITMAP(mask, 64);
2025 u32 history = st->jmp_history_cnt;
2027 if (env->log.level & BPF_LOG_LEVEL)
2028 verbose(env, "last_idx %d first_idx %d\n", last_idx, first_idx);
2029 for (i = last_idx;;) {
2034 err = backtrack_insn(env, i, ®_mask, &stack_mask);
2036 if (err == -ENOTSUPP) {
2037 mark_all_scalars_precise(env, st);
2042 if (!reg_mask && !stack_mask)
2043 /* Found assignment(s) into tracked register in this state.
2044 * Since this state is already marked, just return.
2045 * Nothing to be tracked further in the parent state.
2050 i = get_prev_insn_idx(st, i, &history);
2051 if (i >= env->prog->len) {
2052 /* This can happen if backtracking reached insn 0
2053 * and there are still reg_mask or stack_mask
2055 * It means the backtracking missed the spot where
2056 * particular register was initialized with a constant.
2058 verbose(env, "BUG backtracking idx %d\n", i);
2059 WARN_ONCE(1, "verifier backtracking bug");
2068 func = st->frame[st->curframe];
2069 bitmap_from_u64(mask, reg_mask);
2070 for_each_set_bit(i, mask, 32) {
2071 reg = &func->regs[i];
2072 if (reg->type != SCALAR_VALUE) {
2073 reg_mask &= ~(1u << i);
2078 reg->precise = true;
2081 bitmap_from_u64(mask, stack_mask);
2082 for_each_set_bit(i, mask, 64) {
2083 if (i >= func->allocated_stack / BPF_REG_SIZE) {
2084 /* the sequence of instructions:
2086 * 3: (7b) *(u64 *)(r3 -8) = r0
2087 * 4: (79) r4 = *(u64 *)(r10 -8)
2088 * doesn't contain jmps. It's backtracked
2089 * as a single block.
2090 * During backtracking insn 3 is not recognized as
2091 * stack access, so at the end of backtracking
2092 * stack slot fp-8 is still marked in stack_mask.
2093 * However the parent state may not have accessed
2094 * fp-8 and it's "unallocated" stack space.
2095 * In such case fallback to conservative.
2097 mark_all_scalars_precise(env, st);
2101 if (func->stack[i].slot_type[0] != STACK_SPILL) {
2102 stack_mask &= ~(1ull << i);
2105 reg = &func->stack[i].spilled_ptr;
2106 if (reg->type != SCALAR_VALUE) {
2107 stack_mask &= ~(1ull << i);
2112 reg->precise = true;
2114 if (env->log.level & BPF_LOG_LEVEL) {
2115 print_verifier_state(env, func);
2116 verbose(env, "parent %s regs=%x stack=%llx marks\n",
2117 new_marks ? "didn't have" : "already had",
2118 reg_mask, stack_mask);
2121 if (!reg_mask && !stack_mask)
2126 last_idx = st->last_insn_idx;
2127 first_idx = st->first_insn_idx;
2132 static int mark_chain_precision(struct bpf_verifier_env *env, int regno)
2134 return __mark_chain_precision(env, regno, -1);
2137 static int mark_chain_precision_stack(struct bpf_verifier_env *env, int spi)
2139 return __mark_chain_precision(env, -1, spi);
2142 static bool is_spillable_regtype(enum bpf_reg_type type)
2145 case PTR_TO_MAP_VALUE:
2146 case PTR_TO_MAP_VALUE_OR_NULL:
2150 case PTR_TO_PACKET_META:
2151 case PTR_TO_PACKET_END:
2152 case PTR_TO_FLOW_KEYS:
2153 case CONST_PTR_TO_MAP:
2155 case PTR_TO_SOCKET_OR_NULL:
2156 case PTR_TO_SOCK_COMMON:
2157 case PTR_TO_SOCK_COMMON_OR_NULL:
2158 case PTR_TO_TCP_SOCK:
2159 case PTR_TO_TCP_SOCK_OR_NULL:
2160 case PTR_TO_XDP_SOCK:
2162 case PTR_TO_BTF_ID_OR_NULL:
2169 /* Does this register contain a constant zero? */
2170 static bool register_is_null(struct bpf_reg_state *reg)
2172 return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
2175 static bool register_is_const(struct bpf_reg_state *reg)
2177 return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
2180 static bool __is_pointer_value(bool allow_ptr_leaks,
2181 const struct bpf_reg_state *reg)
2183 if (allow_ptr_leaks)
2186 return reg->type != SCALAR_VALUE;
2189 static void save_register_state(struct bpf_func_state *state,
2190 int spi, struct bpf_reg_state *reg)
2194 state->stack[spi].spilled_ptr = *reg;
2195 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
2197 for (i = 0; i < BPF_REG_SIZE; i++)
2198 state->stack[spi].slot_type[i] = STACK_SPILL;
2201 /* check_stack_read/write functions track spill/fill of registers,
2202 * stack boundary and alignment are checked in check_mem_access()
2204 static int check_stack_write(struct bpf_verifier_env *env,
2205 struct bpf_func_state *state, /* func where register points to */
2206 int off, int size, int value_regno, int insn_idx)
2208 struct bpf_func_state *cur; /* state of the current function */
2209 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
2210 u32 dst_reg = env->prog->insnsi[insn_idx].dst_reg;
2211 struct bpf_reg_state *reg = NULL;
2213 err = realloc_func_state(state, round_up(slot + 1, BPF_REG_SIZE),
2214 state->acquired_refs, true);
2217 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
2218 * so it's aligned access and [off, off + size) are within stack limits
2220 if (!env->allow_ptr_leaks &&
2221 state->stack[spi].slot_type[0] == STACK_SPILL &&
2222 size != BPF_REG_SIZE) {
2223 verbose(env, "attempt to corrupt spilled pointer on stack\n");
2227 cur = env->cur_state->frame[env->cur_state->curframe];
2228 if (value_regno >= 0)
2229 reg = &cur->regs[value_regno];
2231 if (reg && size == BPF_REG_SIZE && register_is_const(reg) &&
2232 !register_is_null(reg) && env->bpf_capable) {
2233 if (dst_reg != BPF_REG_FP) {
2234 /* The backtracking logic can only recognize explicit
2235 * stack slot address like [fp - 8]. Other spill of
2236 * scalar via different register has to be conervative.
2237 * Backtrack from here and mark all registers as precise
2238 * that contributed into 'reg' being a constant.
2240 err = mark_chain_precision(env, value_regno);
2244 save_register_state(state, spi, reg);
2245 } else if (reg && is_spillable_regtype(reg->type)) {
2246 /* register containing pointer is being spilled into stack */
2247 if (size != BPF_REG_SIZE) {
2248 verbose_linfo(env, insn_idx, "; ");
2249 verbose(env, "invalid size of register spill\n");
2253 if (state != cur && reg->type == PTR_TO_STACK) {
2254 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
2258 if (!env->bypass_spec_v4) {
2259 bool sanitize = false;
2261 if (state->stack[spi].slot_type[0] == STACK_SPILL &&
2262 register_is_const(&state->stack[spi].spilled_ptr))
2264 for (i = 0; i < BPF_REG_SIZE; i++)
2265 if (state->stack[spi].slot_type[i] == STACK_MISC) {
2270 int *poff = &env->insn_aux_data[insn_idx].sanitize_stack_off;
2271 int soff = (-spi - 1) * BPF_REG_SIZE;
2273 /* detected reuse of integer stack slot with a pointer
2274 * which means either llvm is reusing stack slot or
2275 * an attacker is trying to exploit CVE-2018-3639
2276 * (speculative store bypass)
2277 * Have to sanitize that slot with preemptive
2280 if (*poff && *poff != soff) {
2281 /* disallow programs where single insn stores
2282 * into two different stack slots, since verifier
2283 * cannot sanitize them
2286 "insn %d cannot access two stack slots fp%d and fp%d",
2287 insn_idx, *poff, soff);
2293 save_register_state(state, spi, reg);
2295 u8 type = STACK_MISC;
2297 /* regular write of data into stack destroys any spilled ptr */
2298 state->stack[spi].spilled_ptr.type = NOT_INIT;
2299 /* Mark slots as STACK_MISC if they belonged to spilled ptr. */
2300 if (state->stack[spi].slot_type[0] == STACK_SPILL)
2301 for (i = 0; i < BPF_REG_SIZE; i++)
2302 state->stack[spi].slot_type[i] = STACK_MISC;
2304 /* only mark the slot as written if all 8 bytes were written
2305 * otherwise read propagation may incorrectly stop too soon
2306 * when stack slots are partially written.
2307 * This heuristic means that read propagation will be
2308 * conservative, since it will add reg_live_read marks
2309 * to stack slots all the way to first state when programs
2310 * writes+reads less than 8 bytes
2312 if (size == BPF_REG_SIZE)
2313 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
2315 /* when we zero initialize stack slots mark them as such */
2316 if (reg && register_is_null(reg)) {
2317 /* backtracking doesn't work for STACK_ZERO yet. */
2318 err = mark_chain_precision(env, value_regno);
2324 /* Mark slots affected by this stack write. */
2325 for (i = 0; i < size; i++)
2326 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
2332 static int check_stack_read(struct bpf_verifier_env *env,
2333 struct bpf_func_state *reg_state /* func where register points to */,
2334 int off, int size, int value_regno)
2336 struct bpf_verifier_state *vstate = env->cur_state;
2337 struct bpf_func_state *state = vstate->frame[vstate->curframe];
2338 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
2339 struct bpf_reg_state *reg;
2342 if (reg_state->allocated_stack <= slot) {
2343 verbose(env, "invalid read from stack off %d+0 size %d\n",
2347 stype = reg_state->stack[spi].slot_type;
2348 reg = ®_state->stack[spi].spilled_ptr;
2350 if (stype[0] == STACK_SPILL) {
2351 if (size != BPF_REG_SIZE) {
2352 if (reg->type != SCALAR_VALUE) {
2353 verbose_linfo(env, env->insn_idx, "; ");
2354 verbose(env, "invalid size of register fill\n");
2357 if (value_regno >= 0) {
2358 mark_reg_unknown(env, state->regs, value_regno);
2359 state->regs[value_regno].live |= REG_LIVE_WRITTEN;
2361 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
2364 for (i = 1; i < BPF_REG_SIZE; i++) {
2365 if (stype[(slot - i) % BPF_REG_SIZE] != STACK_SPILL) {
2366 verbose(env, "corrupted spill memory\n");
2371 if (value_regno >= 0) {
2372 /* restore register state from stack */
2373 state->regs[value_regno] = *reg;
2374 /* mark reg as written since spilled pointer state likely
2375 * has its liveness marks cleared by is_state_visited()
2376 * which resets stack/reg liveness for state transitions
2378 state->regs[value_regno].live |= REG_LIVE_WRITTEN;
2379 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
2380 /* If value_regno==-1, the caller is asking us whether
2381 * it is acceptable to use this value as a SCALAR_VALUE
2383 * We must not allow unprivileged callers to do that
2384 * with spilled pointers.
2386 verbose(env, "leaking pointer from stack off %d\n",
2390 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
2394 for (i = 0; i < size; i++) {
2395 if (stype[(slot - i) % BPF_REG_SIZE] == STACK_MISC)
2397 if (stype[(slot - i) % BPF_REG_SIZE] == STACK_ZERO) {
2401 verbose(env, "invalid read from stack off %d+%d size %d\n",
2405 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
2406 if (value_regno >= 0) {
2407 if (zeros == size) {
2408 /* any size read into register is zero extended,
2409 * so the whole register == const_zero
2411 __mark_reg_const_zero(&state->regs[value_regno]);
2412 /* backtracking doesn't support STACK_ZERO yet,
2413 * so mark it precise here, so that later
2414 * backtracking can stop here.
2415 * Backtracking may not need this if this register
2416 * doesn't participate in pointer adjustment.
2417 * Forward propagation of precise flag is not
2418 * necessary either. This mark is only to stop
2419 * backtracking. Any register that contributed
2420 * to const 0 was marked precise before spill.
2422 state->regs[value_regno].precise = true;
2424 /* have read misc data from the stack */
2425 mark_reg_unknown(env, state->regs, value_regno);
2427 state->regs[value_regno].live |= REG_LIVE_WRITTEN;
2433 static int check_stack_access(struct bpf_verifier_env *env,
2434 const struct bpf_reg_state *reg,
2437 /* Stack accesses must be at a fixed offset, so that we
2438 * can determine what type of data were returned. See
2439 * check_stack_read().
2441 if (!tnum_is_const(reg->var_off)) {
2444 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
2445 verbose(env, "variable stack access var_off=%s off=%d size=%d\n",
2450 if (off >= 0 || off < -MAX_BPF_STACK) {
2451 verbose(env, "invalid stack off=%d size=%d\n", off, size);
2458 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
2459 int off, int size, enum bpf_access_type type)
2461 struct bpf_reg_state *regs = cur_regs(env);
2462 struct bpf_map *map = regs[regno].map_ptr;
2463 u32 cap = bpf_map_flags_to_cap(map);
2465 if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
2466 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
2467 map->value_size, off, size);
2471 if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
2472 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
2473 map->value_size, off, size);
2480 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
2481 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
2482 int off, int size, u32 mem_size,
2483 bool zero_size_allowed)
2485 bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
2486 struct bpf_reg_state *reg;
2488 if (off >= 0 && size_ok && (u64)off + size <= mem_size)
2491 reg = &cur_regs(env)[regno];
2492 switch (reg->type) {
2493 case PTR_TO_MAP_VALUE:
2494 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
2495 mem_size, off, size);
2498 case PTR_TO_PACKET_META:
2499 case PTR_TO_PACKET_END:
2500 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
2501 off, size, regno, reg->id, off, mem_size);
2505 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
2506 mem_size, off, size);
2512 /* check read/write into a memory region with possible variable offset */
2513 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
2514 int off, int size, u32 mem_size,
2515 bool zero_size_allowed)
2517 struct bpf_verifier_state *vstate = env->cur_state;
2518 struct bpf_func_state *state = vstate->frame[vstate->curframe];
2519 struct bpf_reg_state *reg = &state->regs[regno];
2522 /* We may have adjusted the register pointing to memory region, so we
2523 * need to try adding each of min_value and max_value to off
2524 * to make sure our theoretical access will be safe.
2526 if (env->log.level & BPF_LOG_LEVEL)
2527 print_verifier_state(env, state);
2529 /* The minimum value is only important with signed
2530 * comparisons where we can't assume the floor of a
2531 * value is 0. If we are using signed variables for our
2532 * index'es we need to make sure that whatever we use
2533 * will have a set floor within our range.
2535 if (reg->smin_value < 0 &&
2536 (reg->smin_value == S64_MIN ||
2537 (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
2538 reg->smin_value + off < 0)) {
2539 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
2543 err = __check_mem_access(env, regno, reg->smin_value + off, size,
2544 mem_size, zero_size_allowed);
2546 verbose(env, "R%d min value is outside of the allowed memory range\n",
2551 /* If we haven't set a max value then we need to bail since we can't be
2552 * sure we won't do bad things.
2553 * If reg->umax_value + off could overflow, treat that as unbounded too.
2555 if (reg->umax_value >= BPF_MAX_VAR_OFF) {
2556 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
2560 err = __check_mem_access(env, regno, reg->umax_value + off, size,
2561 mem_size, zero_size_allowed);
2563 verbose(env, "R%d max value is outside of the allowed memory range\n",
2571 /* check read/write into a map element with possible variable offset */
2572 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
2573 int off, int size, bool zero_size_allowed)
2575 struct bpf_verifier_state *vstate = env->cur_state;
2576 struct bpf_func_state *state = vstate->frame[vstate->curframe];
2577 struct bpf_reg_state *reg = &state->regs[regno];
2578 struct bpf_map *map = reg->map_ptr;
2581 err = check_mem_region_access(env, regno, off, size, map->value_size,
2586 if (map_value_has_spin_lock(map)) {
2587 u32 lock = map->spin_lock_off;
2589 /* if any part of struct bpf_spin_lock can be touched by
2590 * load/store reject this program.
2591 * To check that [x1, x2) overlaps with [y1, y2)
2592 * it is sufficient to check x1 < y2 && y1 < x2.
2594 if (reg->smin_value + off < lock + sizeof(struct bpf_spin_lock) &&
2595 lock < reg->umax_value + off + size) {
2596 verbose(env, "bpf_spin_lock cannot be accessed directly by load/store\n");
2603 #define MAX_PACKET_OFF 0xffff
2605 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
2606 const struct bpf_call_arg_meta *meta,
2607 enum bpf_access_type t)
2609 switch (env->prog->type) {
2610 /* Program types only with direct read access go here! */
2611 case BPF_PROG_TYPE_LWT_IN:
2612 case BPF_PROG_TYPE_LWT_OUT:
2613 case BPF_PROG_TYPE_LWT_SEG6LOCAL:
2614 case BPF_PROG_TYPE_SK_REUSEPORT:
2615 case BPF_PROG_TYPE_FLOW_DISSECTOR:
2616 case BPF_PROG_TYPE_CGROUP_SKB:
2621 /* Program types with direct read + write access go here! */
2622 case BPF_PROG_TYPE_SCHED_CLS:
2623 case BPF_PROG_TYPE_SCHED_ACT:
2624 case BPF_PROG_TYPE_XDP:
2625 case BPF_PROG_TYPE_LWT_XMIT:
2626 case BPF_PROG_TYPE_SK_SKB:
2627 case BPF_PROG_TYPE_SK_MSG:
2629 return meta->pkt_access;
2631 env->seen_direct_write = true;
2634 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
2636 env->seen_direct_write = true;
2645 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
2646 int size, bool zero_size_allowed)
2648 struct bpf_reg_state *regs = cur_regs(env);
2649 struct bpf_reg_state *reg = ®s[regno];
2652 /* We may have added a variable offset to the packet pointer; but any
2653 * reg->range we have comes after that. We are only checking the fixed
2657 /* We don't allow negative numbers, because we aren't tracking enough
2658 * detail to prove they're safe.
2660 if (reg->smin_value < 0) {
2661 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
2665 err = __check_mem_access(env, regno, off, size, reg->range,
2668 verbose(env, "R%d offset is outside of the packet\n", regno);
2672 /* __check_mem_access has made sure "off + size - 1" is within u16.
2673 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
2674 * otherwise find_good_pkt_pointers would have refused to set range info
2675 * that __check_mem_access would have rejected this pkt access.
2676 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
2678 env->prog->aux->max_pkt_offset =
2679 max_t(u32, env->prog->aux->max_pkt_offset,
2680 off + reg->umax_value + size - 1);
2685 /* check access to 'struct bpf_context' fields. Supports fixed offsets only */
2686 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
2687 enum bpf_access_type t, enum bpf_reg_type *reg_type,
2690 struct bpf_insn_access_aux info = {
2691 .reg_type = *reg_type,
2695 if (env->ops->is_valid_access &&
2696 env->ops->is_valid_access(off, size, t, env->prog, &info)) {
2697 /* A non zero info.ctx_field_size indicates that this field is a
2698 * candidate for later verifier transformation to load the whole
2699 * field and then apply a mask when accessed with a narrower
2700 * access than actual ctx access size. A zero info.ctx_field_size
2701 * will only allow for whole field access and rejects any other
2702 * type of narrower access.
2704 *reg_type = info.reg_type;
2706 if (*reg_type == PTR_TO_BTF_ID || *reg_type == PTR_TO_BTF_ID_OR_NULL)
2707 *btf_id = info.btf_id;
2709 env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
2710 /* remember the offset of last byte accessed in ctx */
2711 if (env->prog->aux->max_ctx_offset < off + size)
2712 env->prog->aux->max_ctx_offset = off + size;
2716 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
2720 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
2723 if (size < 0 || off < 0 ||
2724 (u64)off + size > sizeof(struct bpf_flow_keys)) {
2725 verbose(env, "invalid access to flow keys off=%d size=%d\n",
2732 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
2733 u32 regno, int off, int size,
2734 enum bpf_access_type t)
2736 struct bpf_reg_state *regs = cur_regs(env);
2737 struct bpf_reg_state *reg = ®s[regno];
2738 struct bpf_insn_access_aux info = {};
2741 if (reg->smin_value < 0) {
2742 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
2747 switch (reg->type) {
2748 case PTR_TO_SOCK_COMMON:
2749 valid = bpf_sock_common_is_valid_access(off, size, t, &info);
2752 valid = bpf_sock_is_valid_access(off, size, t, &info);
2754 case PTR_TO_TCP_SOCK:
2755 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
2757 case PTR_TO_XDP_SOCK:
2758 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
2766 env->insn_aux_data[insn_idx].ctx_field_size =
2767 info.ctx_field_size;
2771 verbose(env, "R%d invalid %s access off=%d size=%d\n",
2772 regno, reg_type_str[reg->type], off, size);
2777 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
2779 return cur_regs(env) + regno;
2782 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
2784 return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
2787 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
2789 const struct bpf_reg_state *reg = reg_state(env, regno);
2791 return reg->type == PTR_TO_CTX;
2794 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
2796 const struct bpf_reg_state *reg = reg_state(env, regno);
2798 return type_is_sk_pointer(reg->type);
2801 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
2803 const struct bpf_reg_state *reg = reg_state(env, regno);
2805 return type_is_pkt_pointer(reg->type);
2808 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
2810 const struct bpf_reg_state *reg = reg_state(env, regno);
2812 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
2813 return reg->type == PTR_TO_FLOW_KEYS;
2816 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
2817 const struct bpf_reg_state *reg,
2818 int off, int size, bool strict)
2820 struct tnum reg_off;
2823 /* Byte size accesses are always allowed. */
2824 if (!strict || size == 1)
2827 /* For platforms that do not have a Kconfig enabling
2828 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
2829 * NET_IP_ALIGN is universally set to '2'. And on platforms
2830 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
2831 * to this code only in strict mode where we want to emulate
2832 * the NET_IP_ALIGN==2 checking. Therefore use an
2833 * unconditional IP align value of '2'.
2837 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
2838 if (!tnum_is_aligned(reg_off, size)) {
2841 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
2843 "misaligned packet access off %d+%s+%d+%d size %d\n",
2844 ip_align, tn_buf, reg->off, off, size);
2851 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
2852 const struct bpf_reg_state *reg,
2853 const char *pointer_desc,
2854 int off, int size, bool strict)
2856 struct tnum reg_off;
2858 /* Byte size accesses are always allowed. */
2859 if (!strict || size == 1)
2862 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
2863 if (!tnum_is_aligned(reg_off, size)) {
2866 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
2867 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
2868 pointer_desc, tn_buf, reg->off, off, size);
2875 static int check_ptr_alignment(struct bpf_verifier_env *env,
2876 const struct bpf_reg_state *reg, int off,
2877 int size, bool strict_alignment_once)
2879 bool strict = env->strict_alignment || strict_alignment_once;
2880 const char *pointer_desc = "";
2882 switch (reg->type) {
2884 case PTR_TO_PACKET_META:
2885 /* Special case, because of NET_IP_ALIGN. Given metadata sits
2886 * right in front, treat it the very same way.
2888 return check_pkt_ptr_alignment(env, reg, off, size, strict);
2889 case PTR_TO_FLOW_KEYS:
2890 pointer_desc = "flow keys ";
2892 case PTR_TO_MAP_VALUE:
2893 pointer_desc = "value ";
2896 pointer_desc = "context ";
2899 pointer_desc = "stack ";
2900 /* The stack spill tracking logic in check_stack_write()
2901 * and check_stack_read() relies on stack accesses being
2907 pointer_desc = "sock ";
2909 case PTR_TO_SOCK_COMMON:
2910 pointer_desc = "sock_common ";
2912 case PTR_TO_TCP_SOCK:
2913 pointer_desc = "tcp_sock ";
2915 case PTR_TO_XDP_SOCK:
2916 pointer_desc = "xdp_sock ";
2921 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
2925 static int update_stack_depth(struct bpf_verifier_env *env,
2926 const struct bpf_func_state *func,
2929 u16 stack = env->subprog_info[func->subprogno].stack_depth;
2934 /* update known max for given subprogram */
2935 env->subprog_info[func->subprogno].stack_depth = -off;
2939 /* starting from main bpf function walk all instructions of the function
2940 * and recursively walk all callees that given function can call.
2941 * Ignore jump and exit insns.
2942 * Since recursion is prevented by check_cfg() this algorithm
2943 * only needs a local stack of MAX_CALL_FRAMES to remember callsites
2945 static int check_max_stack_depth(struct bpf_verifier_env *env)
2947 int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
2948 struct bpf_subprog_info *subprog = env->subprog_info;
2949 struct bpf_insn *insn = env->prog->insnsi;
2950 int ret_insn[MAX_CALL_FRAMES];
2951 int ret_prog[MAX_CALL_FRAMES];
2954 /* round up to 32-bytes, since this is granularity
2955 * of interpreter stack size
2957 depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
2958 if (depth > MAX_BPF_STACK) {
2959 verbose(env, "combined stack size of %d calls is %d. Too large\n",
2964 subprog_end = subprog[idx + 1].start;
2965 for (; i < subprog_end; i++) {
2966 if (insn[i].code != (BPF_JMP | BPF_CALL))
2968 if (insn[i].src_reg != BPF_PSEUDO_CALL)
2970 /* remember insn and function to return to */
2971 ret_insn[frame] = i + 1;
2972 ret_prog[frame] = idx;
2974 /* find the callee */
2975 i = i + insn[i].imm + 1;
2976 idx = find_subprog(env, i);
2978 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
2983 if (frame >= MAX_CALL_FRAMES) {
2984 verbose(env, "the call stack of %d frames is too deep !\n",
2990 /* end of for() loop means the last insn of the 'subprog'
2991 * was reached. Doesn't matter whether it was JA or EXIT
2995 depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
2997 i = ret_insn[frame];
2998 idx = ret_prog[frame];
3002 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
3003 static int get_callee_stack_depth(struct bpf_verifier_env *env,
3004 const struct bpf_insn *insn, int idx)
3006 int start = idx + insn->imm + 1, subprog;
3008 subprog = find_subprog(env, start);
3010 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
3014 return env->subprog_info[subprog].stack_depth;
3018 int check_ctx_reg(struct bpf_verifier_env *env,
3019 const struct bpf_reg_state *reg, int regno)
3021 /* Access to ctx or passing it to a helper is only allowed in
3022 * its original, unmodified form.
3026 verbose(env, "dereference of modified ctx ptr R%d off=%d disallowed\n",
3031 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3034 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3035 verbose(env, "variable ctx access var_off=%s disallowed\n", tn_buf);
3042 static int check_tp_buffer_access(struct bpf_verifier_env *env,
3043 const struct bpf_reg_state *reg,
3044 int regno, int off, int size)
3048 "R%d invalid tracepoint buffer access: off=%d, size=%d",
3052 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3055 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3057 "R%d invalid variable buffer offset: off=%d, var_off=%s",
3058 regno, off, tn_buf);
3061 if (off + size > env->prog->aux->max_tp_access)
3062 env->prog->aux->max_tp_access = off + size;
3067 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
3068 static void zext_32_to_64(struct bpf_reg_state *reg)
3070 reg->var_off = tnum_subreg(reg->var_off);
3071 __reg_assign_32_into_64(reg);
3074 /* truncate register to smaller size (in bytes)
3075 * must be called with size < BPF_REG_SIZE
3077 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
3081 /* clear high bits in bit representation */
3082 reg->var_off = tnum_cast(reg->var_off, size);
3084 /* fix arithmetic bounds */
3085 mask = ((u64)1 << (size * 8)) - 1;
3086 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
3087 reg->umin_value &= mask;
3088 reg->umax_value &= mask;
3090 reg->umin_value = 0;
3091 reg->umax_value = mask;
3093 reg->smin_value = reg->umin_value;
3094 reg->smax_value = reg->umax_value;
3096 /* If size is smaller than 32bit register the 32bit register
3097 * values are also truncated so we push 64-bit bounds into
3098 * 32-bit bounds. Above were truncated < 32-bits already.
3102 __reg_combine_64_into_32(reg);
3105 static bool bpf_map_is_rdonly(const struct bpf_map *map)
3107 return (map->map_flags & BPF_F_RDONLY_PROG) && map->frozen;
3110 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val)
3116 err = map->ops->map_direct_value_addr(map, &addr, off);
3119 ptr = (void *)(long)addr + off;
3123 *val = (u64)*(u8 *)ptr;
3126 *val = (u64)*(u16 *)ptr;
3129 *val = (u64)*(u32 *)ptr;
3140 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
3141 struct bpf_reg_state *regs,
3142 int regno, int off, int size,
3143 enum bpf_access_type atype,
3146 struct bpf_reg_state *reg = regs + regno;
3147 const struct btf_type *t = btf_type_by_id(btf_vmlinux, reg->btf_id);
3148 const char *tname = btf_name_by_offset(btf_vmlinux, t->name_off);
3154 "R%d is ptr_%s invalid negative access: off=%d\n",
3158 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3161 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3163 "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
3164 regno, tname, off, tn_buf);
3168 if (env->ops->btf_struct_access) {
3169 ret = env->ops->btf_struct_access(&env->log, t, off, size,
3172 if (atype != BPF_READ) {
3173 verbose(env, "only read is supported\n");
3177 ret = btf_struct_access(&env->log, t, off, size, atype,
3184 if (atype == BPF_READ && value_regno >= 0) {
3185 if (ret == SCALAR_VALUE) {
3186 mark_reg_unknown(env, regs, value_regno);
3189 mark_reg_known_zero(env, regs, value_regno);
3190 regs[value_regno].type = PTR_TO_BTF_ID;
3191 regs[value_regno].btf_id = btf_id;
3197 /* check whether memory at (regno + off) is accessible for t = (read | write)
3198 * if t==write, value_regno is a register which value is stored into memory
3199 * if t==read, value_regno is a register which will receive the value from memory
3200 * if t==write && value_regno==-1, some unknown value is stored into memory
3201 * if t==read && value_regno==-1, don't care what we read from memory
3203 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
3204 int off, int bpf_size, enum bpf_access_type t,
3205 int value_regno, bool strict_alignment_once)
3207 struct bpf_reg_state *regs = cur_regs(env);
3208 struct bpf_reg_state *reg = regs + regno;
3209 struct bpf_func_state *state;
3212 size = bpf_size_to_bytes(bpf_size);
3216 /* alignment checks will add in reg->off themselves */
3217 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
3221 /* for access checks, reg->off is just part of off */
3224 if (reg->type == PTR_TO_MAP_VALUE) {
3225 if (t == BPF_WRITE && value_regno >= 0 &&
3226 is_pointer_value(env, value_regno)) {
3227 verbose(env, "R%d leaks addr into map\n", value_regno);
3230 err = check_map_access_type(env, regno, off, size, t);
3233 err = check_map_access(env, regno, off, size, false);
3234 if (!err && t == BPF_READ && value_regno >= 0) {
3235 struct bpf_map *map = reg->map_ptr;
3237 /* if map is read-only, track its contents as scalars */
3238 if (tnum_is_const(reg->var_off) &&
3239 bpf_map_is_rdonly(map) &&
3240 map->ops->map_direct_value_addr) {
3241 int map_off = off + reg->var_off.value;
3244 err = bpf_map_direct_read(map, map_off, size,
3249 regs[value_regno].type = SCALAR_VALUE;
3250 __mark_reg_known(®s[value_regno], val);
3252 mark_reg_unknown(env, regs, value_regno);
3255 } else if (reg->type == PTR_TO_MEM) {
3256 if (t == BPF_WRITE && value_regno >= 0 &&
3257 is_pointer_value(env, value_regno)) {
3258 verbose(env, "R%d leaks addr into mem\n", value_regno);
3261 err = check_mem_region_access(env, regno, off, size,
3262 reg->mem_size, false);
3263 if (!err && t == BPF_READ && value_regno >= 0)
3264 mark_reg_unknown(env, regs, value_regno);
3265 } else if (reg->type == PTR_TO_CTX) {
3266 enum bpf_reg_type reg_type = SCALAR_VALUE;
3269 if (t == BPF_WRITE && value_regno >= 0 &&
3270 is_pointer_value(env, value_regno)) {
3271 verbose(env, "R%d leaks addr into ctx\n", value_regno);
3275 err = check_ctx_reg(env, reg, regno);
3279 err = check_ctx_access(env, insn_idx, off, size, t, ®_type, &btf_id);
3281 verbose_linfo(env, insn_idx, "; ");
3282 if (!err && t == BPF_READ && value_regno >= 0) {
3283 /* ctx access returns either a scalar, or a
3284 * PTR_TO_PACKET[_META,_END]. In the latter
3285 * case, we know the offset is zero.
3287 if (reg_type == SCALAR_VALUE) {
3288 mark_reg_unknown(env, regs, value_regno);
3290 mark_reg_known_zero(env, regs,
3292 if (reg_type_may_be_null(reg_type))
3293 regs[value_regno].id = ++env->id_gen;
3294 /* A load of ctx field could have different
3295 * actual load size with the one encoded in the
3296 * insn. When the dst is PTR, it is for sure not
3299 regs[value_regno].subreg_def = DEF_NOT_SUBREG;
3300 if (reg_type == PTR_TO_BTF_ID ||
3301 reg_type == PTR_TO_BTF_ID_OR_NULL)
3302 regs[value_regno].btf_id = btf_id;
3304 regs[value_regno].type = reg_type;
3307 } else if (reg->type == PTR_TO_STACK) {
3308 off += reg->var_off.value;
3309 err = check_stack_access(env, reg, off, size);
3313 state = func(env, reg);
3314 err = update_stack_depth(env, state, off);
3319 err = check_stack_write(env, state, off, size,
3320 value_regno, insn_idx);
3322 err = check_stack_read(env, state, off, size,
3324 } else if (reg_is_pkt_pointer(reg)) {
3325 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
3326 verbose(env, "cannot write into packet\n");
3329 if (t == BPF_WRITE && value_regno >= 0 &&
3330 is_pointer_value(env, value_regno)) {
3331 verbose(env, "R%d leaks addr into packet\n",
3335 err = check_packet_access(env, regno, off, size, false);
3336 if (!err && t == BPF_READ && value_regno >= 0)
3337 mark_reg_unknown(env, regs, value_regno);
3338 } else if (reg->type == PTR_TO_FLOW_KEYS) {
3339 if (t == BPF_WRITE && value_regno >= 0 &&
3340 is_pointer_value(env, value_regno)) {
3341 verbose(env, "R%d leaks addr into flow keys\n",
3346 err = check_flow_keys_access(env, off, size);
3347 if (!err && t == BPF_READ && value_regno >= 0)
3348 mark_reg_unknown(env, regs, value_regno);
3349 } else if (type_is_sk_pointer(reg->type)) {
3350 if (t == BPF_WRITE) {
3351 verbose(env, "R%d cannot write into %s\n",
3352 regno, reg_type_str[reg->type]);
3355 err = check_sock_access(env, insn_idx, regno, off, size, t);
3356 if (!err && value_regno >= 0)
3357 mark_reg_unknown(env, regs, value_regno);
3358 } else if (reg->type == PTR_TO_TP_BUFFER) {
3359 err = check_tp_buffer_access(env, reg, regno, off, size);
3360 if (!err && t == BPF_READ && value_regno >= 0)
3361 mark_reg_unknown(env, regs, value_regno);
3362 } else if (reg->type == PTR_TO_BTF_ID) {
3363 err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
3366 verbose(env, "R%d invalid mem access '%s'\n", regno,
3367 reg_type_str[reg->type]);
3371 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
3372 regs[value_regno].type == SCALAR_VALUE) {
3373 /* b/h/w load zero-extends, mark upper bits as known 0 */
3374 coerce_reg_to_size(®s[value_regno], size);
3379 static int check_xadd(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
3383 if ((BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) ||
3385 verbose(env, "BPF_XADD uses reserved fields\n");
3389 /* check src1 operand */
3390 err = check_reg_arg(env, insn->src_reg, SRC_OP);
3394 /* check src2 operand */
3395 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
3399 if (is_pointer_value(env, insn->src_reg)) {
3400 verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
3404 if (is_ctx_reg(env, insn->dst_reg) ||
3405 is_pkt_reg(env, insn->dst_reg) ||
3406 is_flow_key_reg(env, insn->dst_reg) ||
3407 is_sk_reg(env, insn->dst_reg)) {
3408 verbose(env, "BPF_XADD stores into R%d %s is not allowed\n",
3410 reg_type_str[reg_state(env, insn->dst_reg)->type]);
3414 /* check whether atomic_add can read the memory */
3415 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
3416 BPF_SIZE(insn->code), BPF_READ, -1, true);
3420 /* check whether atomic_add can write into the same memory */
3421 return check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
3422 BPF_SIZE(insn->code), BPF_WRITE, -1, true);
3425 static int __check_stack_boundary(struct bpf_verifier_env *env, u32 regno,
3426 int off, int access_size,
3427 bool zero_size_allowed)
3429 struct bpf_reg_state *reg = reg_state(env, regno);
3431 if (off >= 0 || off < -MAX_BPF_STACK || off + access_size > 0 ||
3432 access_size < 0 || (access_size == 0 && !zero_size_allowed)) {
3433 if (tnum_is_const(reg->var_off)) {
3434 verbose(env, "invalid stack type R%d off=%d access_size=%d\n",
3435 regno, off, access_size);
3439 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3440 verbose(env, "invalid stack type R%d var_off=%s access_size=%d\n",
3441 regno, tn_buf, access_size);
3448 /* when register 'regno' is passed into function that will read 'access_size'
3449 * bytes from that pointer, make sure that it's within stack boundary
3450 * and all elements of stack are initialized.
3451 * Unlike most pointer bounds-checking functions, this one doesn't take an
3452 * 'off' argument, so it has to add in reg->off itself.
3454 static int check_stack_boundary(struct bpf_verifier_env *env, int regno,
3455 int access_size, bool zero_size_allowed,
3456 struct bpf_call_arg_meta *meta)
3458 struct bpf_reg_state *reg = reg_state(env, regno);
3459 struct bpf_func_state *state = func(env, reg);
3460 int err, min_off, max_off, i, j, slot, spi;
3462 if (reg->type != PTR_TO_STACK) {
3463 /* Allow zero-byte read from NULL, regardless of pointer type */
3464 if (zero_size_allowed && access_size == 0 &&
3465 register_is_null(reg))
3468 verbose(env, "R%d type=%s expected=%s\n", regno,
3469 reg_type_str[reg->type],
3470 reg_type_str[PTR_TO_STACK]);
3474 if (tnum_is_const(reg->var_off)) {
3475 min_off = max_off = reg->var_off.value + reg->off;
3476 err = __check_stack_boundary(env, regno, min_off, access_size,
3481 /* Variable offset is prohibited for unprivileged mode for
3482 * simplicity since it requires corresponding support in
3483 * Spectre masking for stack ALU.
3484 * See also retrieve_ptr_limit().
3486 if (!env->bypass_spec_v1) {
3489 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3490 verbose(env, "R%d indirect variable offset stack access prohibited for !root, var_off=%s\n",
3494 /* Only initialized buffer on stack is allowed to be accessed
3495 * with variable offset. With uninitialized buffer it's hard to
3496 * guarantee that whole memory is marked as initialized on
3497 * helper return since specific bounds are unknown what may
3498 * cause uninitialized stack leaking.
3500 if (meta && meta->raw_mode)
3503 if (reg->smax_value >= BPF_MAX_VAR_OFF ||
3504 reg->smax_value <= -BPF_MAX_VAR_OFF) {
3505 verbose(env, "R%d unbounded indirect variable offset stack access\n",
3509 min_off = reg->smin_value + reg->off;
3510 max_off = reg->smax_value + reg->off;
3511 err = __check_stack_boundary(env, regno, min_off, access_size,
3514 verbose(env, "R%d min value is outside of stack bound\n",
3518 err = __check_stack_boundary(env, regno, max_off, access_size,
3521 verbose(env, "R%d max value is outside of stack bound\n",
3527 if (meta && meta->raw_mode) {
3528 meta->access_size = access_size;
3529 meta->regno = regno;
3533 for (i = min_off; i < max_off + access_size; i++) {
3537 spi = slot / BPF_REG_SIZE;
3538 if (state->allocated_stack <= slot)
3540 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
3541 if (*stype == STACK_MISC)
3543 if (*stype == STACK_ZERO) {
3544 /* helper can write anything into the stack */
3545 *stype = STACK_MISC;
3549 if (state->stack[spi].slot_type[0] == STACK_SPILL &&
3550 state->stack[spi].spilled_ptr.type == PTR_TO_BTF_ID)
3553 if (state->stack[spi].slot_type[0] == STACK_SPILL &&
3554 state->stack[spi].spilled_ptr.type == SCALAR_VALUE) {
3555 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
3556 for (j = 0; j < BPF_REG_SIZE; j++)
3557 state->stack[spi].slot_type[j] = STACK_MISC;
3562 if (tnum_is_const(reg->var_off)) {
3563 verbose(env, "invalid indirect read from stack off %d+%d size %d\n",
3564 min_off, i - min_off, access_size);
3568 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3569 verbose(env, "invalid indirect read from stack var_off %s+%d size %d\n",
3570 tn_buf, i - min_off, access_size);
3574 /* reading any byte out of 8-byte 'spill_slot' will cause
3575 * the whole slot to be marked as 'read'
3577 mark_reg_read(env, &state->stack[spi].spilled_ptr,
3578 state->stack[spi].spilled_ptr.parent,
3581 return update_stack_depth(env, state, min_off);
3584 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
3585 int access_size, bool zero_size_allowed,
3586 struct bpf_call_arg_meta *meta)
3588 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
3590 switch (reg->type) {
3592 case PTR_TO_PACKET_META:
3593 return check_packet_access(env, regno, reg->off, access_size,
3595 case PTR_TO_MAP_VALUE:
3596 if (check_map_access_type(env, regno, reg->off, access_size,
3597 meta && meta->raw_mode ? BPF_WRITE :
3600 return check_map_access(env, regno, reg->off, access_size,
3603 return check_mem_region_access(env, regno, reg->off,
3604 access_size, reg->mem_size,
3606 default: /* scalar_value|ptr_to_stack or invalid ptr */
3607 return check_stack_boundary(env, regno, access_size,
3608 zero_size_allowed, meta);
3612 /* Implementation details:
3613 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL
3614 * Two bpf_map_lookups (even with the same key) will have different reg->id.
3615 * For traditional PTR_TO_MAP_VALUE the verifier clears reg->id after
3616 * value_or_null->value transition, since the verifier only cares about
3617 * the range of access to valid map value pointer and doesn't care about actual
3618 * address of the map element.
3619 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
3620 * reg->id > 0 after value_or_null->value transition. By doing so
3621 * two bpf_map_lookups will be considered two different pointers that
3622 * point to different bpf_spin_locks.
3623 * The verifier allows taking only one bpf_spin_lock at a time to avoid
3625 * Since only one bpf_spin_lock is allowed the checks are simpler than
3626 * reg_is_refcounted() logic. The verifier needs to remember only
3627 * one spin_lock instead of array of acquired_refs.
3628 * cur_state->active_spin_lock remembers which map value element got locked
3629 * and clears it after bpf_spin_unlock.
3631 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
3634 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
3635 struct bpf_verifier_state *cur = env->cur_state;
3636 bool is_const = tnum_is_const(reg->var_off);
3637 struct bpf_map *map = reg->map_ptr;
3638 u64 val = reg->var_off.value;
3640 if (reg->type != PTR_TO_MAP_VALUE) {
3641 verbose(env, "R%d is not a pointer to map_value\n", regno);
3646 "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
3652 "map '%s' has to have BTF in order to use bpf_spin_lock\n",
3656 if (!map_value_has_spin_lock(map)) {
3657 if (map->spin_lock_off == -E2BIG)
3659 "map '%s' has more than one 'struct bpf_spin_lock'\n",
3661 else if (map->spin_lock_off == -ENOENT)
3663 "map '%s' doesn't have 'struct bpf_spin_lock'\n",
3667 "map '%s' is not a struct type or bpf_spin_lock is mangled\n",
3671 if (map->spin_lock_off != val + reg->off) {
3672 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock'\n",
3677 if (cur->active_spin_lock) {
3679 "Locking two bpf_spin_locks are not allowed\n");
3682 cur->active_spin_lock = reg->id;
3684 if (!cur->active_spin_lock) {
3685 verbose(env, "bpf_spin_unlock without taking a lock\n");
3688 if (cur->active_spin_lock != reg->id) {
3689 verbose(env, "bpf_spin_unlock of different lock\n");
3692 cur->active_spin_lock = 0;
3697 static bool arg_type_is_mem_ptr(enum bpf_arg_type type)
3699 return type == ARG_PTR_TO_MEM ||
3700 type == ARG_PTR_TO_MEM_OR_NULL ||
3701 type == ARG_PTR_TO_UNINIT_MEM;
3704 static bool arg_type_is_mem_size(enum bpf_arg_type type)
3706 return type == ARG_CONST_SIZE ||
3707 type == ARG_CONST_SIZE_OR_ZERO;
3710 static bool arg_type_is_alloc_mem_ptr(enum bpf_arg_type type)
3712 return type == ARG_PTR_TO_ALLOC_MEM ||
3713 type == ARG_PTR_TO_ALLOC_MEM_OR_NULL;
3716 static bool arg_type_is_alloc_size(enum bpf_arg_type type)
3718 return type == ARG_CONST_ALLOC_SIZE_OR_ZERO;
3721 static bool arg_type_is_int_ptr(enum bpf_arg_type type)
3723 return type == ARG_PTR_TO_INT ||
3724 type == ARG_PTR_TO_LONG;
3727 static int int_ptr_type_to_size(enum bpf_arg_type type)
3729 if (type == ARG_PTR_TO_INT)
3731 else if (type == ARG_PTR_TO_LONG)
3737 static int check_func_arg(struct bpf_verifier_env *env, u32 regno,
3738 enum bpf_arg_type arg_type,
3739 struct bpf_call_arg_meta *meta)
3741 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
3742 enum bpf_reg_type expected_type, type = reg->type;
3745 if (arg_type == ARG_DONTCARE)
3748 err = check_reg_arg(env, regno, SRC_OP);
3752 if (arg_type == ARG_ANYTHING) {
3753 if (is_pointer_value(env, regno)) {
3754 verbose(env, "R%d leaks addr into helper function\n",
3761 if (type_is_pkt_pointer(type) &&
3762 !may_access_direct_pkt_data(env, meta, BPF_READ)) {
3763 verbose(env, "helper access to the packet is not allowed\n");
3767 if (arg_type == ARG_PTR_TO_MAP_KEY ||
3768 arg_type == ARG_PTR_TO_MAP_VALUE ||
3769 arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE ||
3770 arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL) {
3771 expected_type = PTR_TO_STACK;
3772 if (register_is_null(reg) &&
3773 arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL)
3774 /* final test in check_stack_boundary() */;
3775 else if (!type_is_pkt_pointer(type) &&
3776 type != PTR_TO_MAP_VALUE &&
3777 type != expected_type)
3779 } else if (arg_type == ARG_CONST_SIZE ||
3780 arg_type == ARG_CONST_SIZE_OR_ZERO ||
3781 arg_type == ARG_CONST_ALLOC_SIZE_OR_ZERO) {
3782 expected_type = SCALAR_VALUE;
3783 if (type != expected_type)
3785 } else if (arg_type == ARG_CONST_MAP_PTR) {
3786 expected_type = CONST_PTR_TO_MAP;
3787 if (type != expected_type)
3789 } else if (arg_type == ARG_PTR_TO_CTX ||
3790 arg_type == ARG_PTR_TO_CTX_OR_NULL) {
3791 expected_type = PTR_TO_CTX;
3792 if (!(register_is_null(reg) &&
3793 arg_type == ARG_PTR_TO_CTX_OR_NULL)) {
3794 if (type != expected_type)
3796 err = check_ctx_reg(env, reg, regno);
3800 } else if (arg_type == ARG_PTR_TO_SOCK_COMMON) {
3801 expected_type = PTR_TO_SOCK_COMMON;
3802 /* Any sk pointer can be ARG_PTR_TO_SOCK_COMMON */
3803 if (!type_is_sk_pointer(type))
3805 if (reg->ref_obj_id) {
3806 if (meta->ref_obj_id) {
3807 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
3808 regno, reg->ref_obj_id,
3812 meta->ref_obj_id = reg->ref_obj_id;
3814 } else if (arg_type == ARG_PTR_TO_SOCKET) {
3815 expected_type = PTR_TO_SOCKET;
3816 if (type != expected_type)
3818 } else if (arg_type == ARG_PTR_TO_BTF_ID) {
3819 expected_type = PTR_TO_BTF_ID;
3820 if (type != expected_type)
3822 if (reg->btf_id != meta->btf_id) {
3823 verbose(env, "Helper has type %s got %s in R%d\n",
3824 kernel_type_name(meta->btf_id),
3825 kernel_type_name(reg->btf_id), regno);
3829 if (!tnum_is_const(reg->var_off) || reg->var_off.value || reg->off) {
3830 verbose(env, "R%d is a pointer to in-kernel struct with non-zero offset\n",
3834 } else if (arg_type == ARG_PTR_TO_SPIN_LOCK) {
3835 if (meta->func_id == BPF_FUNC_spin_lock) {
3836 if (process_spin_lock(env, regno, true))
3838 } else if (meta->func_id == BPF_FUNC_spin_unlock) {
3839 if (process_spin_lock(env, regno, false))
3842 verbose(env, "verifier internal error\n");
3845 } else if (arg_type_is_mem_ptr(arg_type)) {
3846 expected_type = PTR_TO_STACK;
3847 /* One exception here. In case function allows for NULL to be
3848 * passed in as argument, it's a SCALAR_VALUE type. Final test
3849 * happens during stack boundary checking.
3851 if (register_is_null(reg) &&
3852 (arg_type == ARG_PTR_TO_MEM_OR_NULL ||
3853 arg_type == ARG_PTR_TO_ALLOC_MEM_OR_NULL))
3854 /* final test in check_stack_boundary() */;
3855 else if (!type_is_pkt_pointer(type) &&
3856 type != PTR_TO_MAP_VALUE &&
3857 type != PTR_TO_MEM &&
3858 type != expected_type)
3860 meta->raw_mode = arg_type == ARG_PTR_TO_UNINIT_MEM;
3861 } else if (arg_type_is_alloc_mem_ptr(arg_type)) {
3862 expected_type = PTR_TO_MEM;
3863 if (register_is_null(reg) &&
3864 arg_type == ARG_PTR_TO_ALLOC_MEM_OR_NULL)
3865 /* final test in check_stack_boundary() */;
3866 else if (type != expected_type)
3868 if (meta->ref_obj_id) {
3869 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
3870 regno, reg->ref_obj_id,
3874 meta->ref_obj_id = reg->ref_obj_id;
3875 } else if (arg_type_is_int_ptr(arg_type)) {
3876 expected_type = PTR_TO_STACK;
3877 if (!type_is_pkt_pointer(type) &&
3878 type != PTR_TO_MAP_VALUE &&
3879 type != expected_type)
3882 verbose(env, "unsupported arg_type %d\n", arg_type);
3886 if (arg_type == ARG_CONST_MAP_PTR) {
3887 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
3888 meta->map_ptr = reg->map_ptr;
3889 } else if (arg_type == ARG_PTR_TO_MAP_KEY) {
3890 /* bpf_map_xxx(..., map_ptr, ..., key) call:
3891 * check that [key, key + map->key_size) are within
3892 * stack limits and initialized
3894 if (!meta->map_ptr) {
3895 /* in function declaration map_ptr must come before
3896 * map_key, so that it's verified and known before
3897 * we have to check map_key here. Otherwise it means
3898 * that kernel subsystem misconfigured verifier
3900 verbose(env, "invalid map_ptr to access map->key\n");
3903 err = check_helper_mem_access(env, regno,
3904 meta->map_ptr->key_size, false,
3906 } else if (arg_type == ARG_PTR_TO_MAP_VALUE ||
3907 (arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL &&
3908 !register_is_null(reg)) ||
3909 arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE) {
3910 /* bpf_map_xxx(..., map_ptr, ..., value) call:
3911 * check [value, value + map->value_size) validity
3913 if (!meta->map_ptr) {
3914 /* kernel subsystem misconfigured verifier */
3915 verbose(env, "invalid map_ptr to access map->value\n");
3918 meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE);
3919 err = check_helper_mem_access(env, regno,
3920 meta->map_ptr->value_size, false,
3922 } else if (arg_type_is_mem_size(arg_type)) {
3923 bool zero_size_allowed = (arg_type == ARG_CONST_SIZE_OR_ZERO);
3925 /* This is used to refine r0 return value bounds for helpers
3926 * that enforce this value as an upper bound on return values.
3927 * See do_refine_retval_range() for helpers that can refine
3928 * the return value. C type of helper is u32 so we pull register
3929 * bound from umax_value however, if negative verifier errors
3930 * out. Only upper bounds can be learned because retval is an
3931 * int type and negative retvals are allowed.
3933 meta->msize_max_value = reg->umax_value;
3935 /* The register is SCALAR_VALUE; the access check
3936 * happens using its boundaries.
3938 if (!tnum_is_const(reg->var_off))
3939 /* For unprivileged variable accesses, disable raw
3940 * mode so that the program is required to
3941 * initialize all the memory that the helper could
3942 * just partially fill up.
3946 if (reg->smin_value < 0) {
3947 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
3952 if (reg->umin_value == 0) {
3953 err = check_helper_mem_access(env, regno - 1, 0,
3960 if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
3961 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
3965 err = check_helper_mem_access(env, regno - 1,
3967 zero_size_allowed, meta);
3969 err = mark_chain_precision(env, regno);
3970 } else if (arg_type_is_alloc_size(arg_type)) {
3971 if (!tnum_is_const(reg->var_off)) {
3972 verbose(env, "R%d unbounded size, use 'var &= const' or 'if (var < const)'\n",
3976 meta->mem_size = reg->var_off.value;
3977 } else if (arg_type_is_int_ptr(arg_type)) {
3978 int size = int_ptr_type_to_size(arg_type);
3980 err = check_helper_mem_access(env, regno, size, false, meta);
3983 err = check_ptr_alignment(env, reg, 0, size, true);
3988 verbose(env, "R%d type=%s expected=%s\n", regno,
3989 reg_type_str[type], reg_type_str[expected_type]);
3993 static int check_map_func_compatibility(struct bpf_verifier_env *env,
3994 struct bpf_map *map, int func_id)
3999 /* We need a two way check, first is from map perspective ... */
4000 switch (map->map_type) {
4001 case BPF_MAP_TYPE_PROG_ARRAY:
4002 if (func_id != BPF_FUNC_tail_call)
4005 case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
4006 if (func_id != BPF_FUNC_perf_event_read &&
4007 func_id != BPF_FUNC_perf_event_output &&
4008 func_id != BPF_FUNC_skb_output &&
4009 func_id != BPF_FUNC_perf_event_read_value &&
4010 func_id != BPF_FUNC_xdp_output)
4013 case BPF_MAP_TYPE_RINGBUF:
4014 if (func_id != BPF_FUNC_ringbuf_output &&
4015 func_id != BPF_FUNC_ringbuf_reserve &&
4016 func_id != BPF_FUNC_ringbuf_submit &&
4017 func_id != BPF_FUNC_ringbuf_discard &&
4018 func_id != BPF_FUNC_ringbuf_query)
4021 case BPF_MAP_TYPE_STACK_TRACE:
4022 if (func_id != BPF_FUNC_get_stackid)
4025 case BPF_MAP_TYPE_CGROUP_ARRAY:
4026 if (func_id != BPF_FUNC_skb_under_cgroup &&
4027 func_id != BPF_FUNC_current_task_under_cgroup)
4030 case BPF_MAP_TYPE_CGROUP_STORAGE:
4031 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
4032 if (func_id != BPF_FUNC_get_local_storage)
4035 case BPF_MAP_TYPE_DEVMAP:
4036 case BPF_MAP_TYPE_DEVMAP_HASH:
4037 if (func_id != BPF_FUNC_redirect_map &&
4038 func_id != BPF_FUNC_map_lookup_elem)
4041 /* Restrict bpf side of cpumap and xskmap, open when use-cases
4044 case BPF_MAP_TYPE_CPUMAP:
4045 if (func_id != BPF_FUNC_redirect_map)
4048 case BPF_MAP_TYPE_XSKMAP:
4049 if (func_id != BPF_FUNC_redirect_map &&
4050 func_id != BPF_FUNC_map_lookup_elem)
4053 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
4054 case BPF_MAP_TYPE_HASH_OF_MAPS:
4055 if (func_id != BPF_FUNC_map_lookup_elem)
4058 case BPF_MAP_TYPE_SOCKMAP:
4059 if (func_id != BPF_FUNC_sk_redirect_map &&
4060 func_id != BPF_FUNC_sock_map_update &&
4061 func_id != BPF_FUNC_map_delete_elem &&
4062 func_id != BPF_FUNC_msg_redirect_map &&
4063 func_id != BPF_FUNC_sk_select_reuseport &&
4064 func_id != BPF_FUNC_map_lookup_elem)
4067 case BPF_MAP_TYPE_SOCKHASH:
4068 if (func_id != BPF_FUNC_sk_redirect_hash &&
4069 func_id != BPF_FUNC_sock_hash_update &&
4070 func_id != BPF_FUNC_map_delete_elem &&
4071 func_id != BPF_FUNC_msg_redirect_hash &&
4072 func_id != BPF_FUNC_sk_select_reuseport &&
4073 func_id != BPF_FUNC_map_lookup_elem)
4076 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
4077 if (func_id != BPF_FUNC_sk_select_reuseport)
4080 case BPF_MAP_TYPE_QUEUE:
4081 case BPF_MAP_TYPE_STACK:
4082 if (func_id != BPF_FUNC_map_peek_elem &&
4083 func_id != BPF_FUNC_map_pop_elem &&
4084 func_id != BPF_FUNC_map_push_elem)
4087 case BPF_MAP_TYPE_SK_STORAGE:
4088 if (func_id != BPF_FUNC_sk_storage_get &&
4089 func_id != BPF_FUNC_sk_storage_delete)
4096 /* ... and second from the function itself. */
4098 case BPF_FUNC_tail_call:
4099 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
4101 if (env->subprog_cnt > 1) {
4102 verbose(env, "tail_calls are not allowed in programs with bpf-to-bpf calls\n");
4106 case BPF_FUNC_perf_event_read:
4107 case BPF_FUNC_perf_event_output:
4108 case BPF_FUNC_perf_event_read_value:
4109 case BPF_FUNC_skb_output:
4110 case BPF_FUNC_xdp_output:
4111 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
4114 case BPF_FUNC_get_stackid:
4115 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
4118 case BPF_FUNC_current_task_under_cgroup:
4119 case BPF_FUNC_skb_under_cgroup:
4120 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
4123 case BPF_FUNC_redirect_map:
4124 if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
4125 map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
4126 map->map_type != BPF_MAP_TYPE_CPUMAP &&
4127 map->map_type != BPF_MAP_TYPE_XSKMAP)
4130 case BPF_FUNC_sk_redirect_map:
4131 case BPF_FUNC_msg_redirect_map:
4132 case BPF_FUNC_sock_map_update:
4133 if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
4136 case BPF_FUNC_sk_redirect_hash:
4137 case BPF_FUNC_msg_redirect_hash:
4138 case BPF_FUNC_sock_hash_update:
4139 if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
4142 case BPF_FUNC_get_local_storage:
4143 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
4144 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
4147 case BPF_FUNC_sk_select_reuseport:
4148 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
4149 map->map_type != BPF_MAP_TYPE_SOCKMAP &&
4150 map->map_type != BPF_MAP_TYPE_SOCKHASH)
4153 case BPF_FUNC_map_peek_elem:
4154 case BPF_FUNC_map_pop_elem:
4155 case BPF_FUNC_map_push_elem:
4156 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
4157 map->map_type != BPF_MAP_TYPE_STACK)
4160 case BPF_FUNC_sk_storage_get:
4161 case BPF_FUNC_sk_storage_delete:
4162 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
4171 verbose(env, "cannot pass map_type %d into func %s#%d\n",
4172 map->map_type, func_id_name(func_id), func_id);
4176 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
4180 if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
4182 if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
4184 if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
4186 if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
4188 if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
4191 /* We only support one arg being in raw mode at the moment,
4192 * which is sufficient for the helper functions we have
4198 static bool check_args_pair_invalid(enum bpf_arg_type arg_curr,
4199 enum bpf_arg_type arg_next)
4201 return (arg_type_is_mem_ptr(arg_curr) &&
4202 !arg_type_is_mem_size(arg_next)) ||
4203 (!arg_type_is_mem_ptr(arg_curr) &&
4204 arg_type_is_mem_size(arg_next));
4207 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
4209 /* bpf_xxx(..., buf, len) call will access 'len'
4210 * bytes from memory 'buf'. Both arg types need
4211 * to be paired, so make sure there's no buggy
4212 * helper function specification.
4214 if (arg_type_is_mem_size(fn->arg1_type) ||
4215 arg_type_is_mem_ptr(fn->arg5_type) ||
4216 check_args_pair_invalid(fn->arg1_type, fn->arg2_type) ||
4217 check_args_pair_invalid(fn->arg2_type, fn->arg3_type) ||
4218 check_args_pair_invalid(fn->arg3_type, fn->arg4_type) ||
4219 check_args_pair_invalid(fn->arg4_type, fn->arg5_type))
4225 static bool check_refcount_ok(const struct bpf_func_proto *fn, int func_id)
4229 if (arg_type_may_be_refcounted(fn->arg1_type))
4231 if (arg_type_may_be_refcounted(fn->arg2_type))
4233 if (arg_type_may_be_refcounted(fn->arg3_type))
4235 if (arg_type_may_be_refcounted(fn->arg4_type))
4237 if (arg_type_may_be_refcounted(fn->arg5_type))
4240 /* A reference acquiring function cannot acquire
4241 * another refcounted ptr.
4243 if (may_be_acquire_function(func_id) && count)
4246 /* We only support one arg being unreferenced at the moment,
4247 * which is sufficient for the helper functions we have right now.
4252 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
4254 return check_raw_mode_ok(fn) &&
4255 check_arg_pair_ok(fn) &&
4256 check_refcount_ok(fn, func_id) ? 0 : -EINVAL;
4259 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
4260 * are now invalid, so turn them into unknown SCALAR_VALUE.
4262 static void __clear_all_pkt_pointers(struct bpf_verifier_env *env,
4263 struct bpf_func_state *state)
4265 struct bpf_reg_state *regs = state->regs, *reg;
4268 for (i = 0; i < MAX_BPF_REG; i++)
4269 if (reg_is_pkt_pointer_any(®s[i]))
4270 mark_reg_unknown(env, regs, i);
4272 bpf_for_each_spilled_reg(i, state, reg) {
4275 if (reg_is_pkt_pointer_any(reg))
4276 __mark_reg_unknown(env, reg);
4280 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
4282 struct bpf_verifier_state *vstate = env->cur_state;
4285 for (i = 0; i <= vstate->curframe; i++)
4286 __clear_all_pkt_pointers(env, vstate->frame[i]);
4289 static void release_reg_references(struct bpf_verifier_env *env,
4290 struct bpf_func_state *state,
4293 struct bpf_reg_state *regs = state->regs, *reg;
4296 for (i = 0; i < MAX_BPF_REG; i++)
4297 if (regs[i].ref_obj_id == ref_obj_id)
4298 mark_reg_unknown(env, regs, i);
4300 bpf_for_each_spilled_reg(i, state, reg) {
4303 if (reg->ref_obj_id == ref_obj_id)
4304 __mark_reg_unknown(env, reg);
4308 /* The pointer with the specified id has released its reference to kernel
4309 * resources. Identify all copies of the same pointer and clear the reference.
4311 static int release_reference(struct bpf_verifier_env *env,
4314 struct bpf_verifier_state *vstate = env->cur_state;
4318 err = release_reference_state(cur_func(env), ref_obj_id);
4322 for (i = 0; i <= vstate->curframe; i++)
4323 release_reg_references(env, vstate->frame[i], ref_obj_id);
4328 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
4329 struct bpf_reg_state *regs)
4333 /* after the call registers r0 - r5 were scratched */
4334 for (i = 0; i < CALLER_SAVED_REGS; i++) {
4335 mark_reg_not_init(env, regs, caller_saved[i]);
4336 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
4340 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
4343 struct bpf_verifier_state *state = env->cur_state;
4344 struct bpf_func_info_aux *func_info_aux;
4345 struct bpf_func_state *caller, *callee;
4346 int i, err, subprog, target_insn;
4347 bool is_global = false;
4349 if (state->curframe + 1 >= MAX_CALL_FRAMES) {
4350 verbose(env, "the call stack of %d frames is too deep\n",
4351 state->curframe + 2);
4355 target_insn = *insn_idx + insn->imm;
4356 subprog = find_subprog(env, target_insn + 1);
4358 verbose(env, "verifier bug. No program starts at insn %d\n",
4363 caller = state->frame[state->curframe];
4364 if (state->frame[state->curframe + 1]) {
4365 verbose(env, "verifier bug. Frame %d already allocated\n",
4366 state->curframe + 1);
4370 func_info_aux = env->prog->aux->func_info_aux;
4372 is_global = func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
4373 err = btf_check_func_arg_match(env, subprog, caller->regs);
4378 verbose(env, "Caller passes invalid args into func#%d\n",
4382 if (env->log.level & BPF_LOG_LEVEL)
4384 "Func#%d is global and valid. Skipping.\n",
4386 clear_caller_saved_regs(env, caller->regs);
4388 /* All global functions return SCALAR_VALUE */
4389 mark_reg_unknown(env, caller->regs, BPF_REG_0);
4391 /* continue with next insn after call */
4396 callee = kzalloc(sizeof(*callee), GFP_KERNEL);
4399 state->frame[state->curframe + 1] = callee;
4401 /* callee cannot access r0, r6 - r9 for reading and has to write
4402 * into its own stack before reading from it.
4403 * callee can read/write into caller's stack
4405 init_func_state(env, callee,
4406 /* remember the callsite, it will be used by bpf_exit */
4407 *insn_idx /* callsite */,
4408 state->curframe + 1 /* frameno within this callchain */,
4409 subprog /* subprog number within this prog */);
4411 /* Transfer references to the callee */
4412 err = transfer_reference_state(callee, caller);
4416 /* copy r1 - r5 args that callee can access. The copy includes parent
4417 * pointers, which connects us up to the liveness chain
4419 for (i = BPF_REG_1; i <= BPF_REG_5; i++)
4420 callee->regs[i] = caller->regs[i];
4422 clear_caller_saved_regs(env, caller->regs);
4424 /* only increment it after check_reg_arg() finished */
4427 /* and go analyze first insn of the callee */
4428 *insn_idx = target_insn;
4430 if (env->log.level & BPF_LOG_LEVEL) {
4431 verbose(env, "caller:\n");
4432 print_verifier_state(env, caller);
4433 verbose(env, "callee:\n");
4434 print_verifier_state(env, callee);
4439 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
4441 struct bpf_verifier_state *state = env->cur_state;
4442 struct bpf_func_state *caller, *callee;
4443 struct bpf_reg_state *r0;
4446 callee = state->frame[state->curframe];
4447 r0 = &callee->regs[BPF_REG_0];
4448 if (r0->type == PTR_TO_STACK) {
4449 /* technically it's ok to return caller's stack pointer
4450 * (or caller's caller's pointer) back to the caller,
4451 * since these pointers are valid. Only current stack
4452 * pointer will be invalid as soon as function exits,
4453 * but let's be conservative
4455 verbose(env, "cannot return stack pointer to the caller\n");
4460 caller = state->frame[state->curframe];
4461 /* return to the caller whatever r0 had in the callee */
4462 caller->regs[BPF_REG_0] = *r0;
4464 /* Transfer references to the caller */
4465 err = transfer_reference_state(caller, callee);
4469 *insn_idx = callee->callsite + 1;
4470 if (env->log.level & BPF_LOG_LEVEL) {
4471 verbose(env, "returning from callee:\n");
4472 print_verifier_state(env, callee);
4473 verbose(env, "to caller at %d:\n", *insn_idx);
4474 print_verifier_state(env, caller);
4476 /* clear everything in the callee */
4477 free_func_state(callee);
4478 state->frame[state->curframe + 1] = NULL;
4482 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
4484 struct bpf_call_arg_meta *meta)
4486 struct bpf_reg_state *ret_reg = ®s[BPF_REG_0];
4488 if (ret_type != RET_INTEGER ||
4489 (func_id != BPF_FUNC_get_stack &&
4490 func_id != BPF_FUNC_probe_read_str &&
4491 func_id != BPF_FUNC_probe_read_kernel_str &&
4492 func_id != BPF_FUNC_probe_read_user_str))
4495 ret_reg->smax_value = meta->msize_max_value;
4496 ret_reg->s32_max_value = meta->msize_max_value;
4497 __reg_deduce_bounds(ret_reg);
4498 __reg_bound_offset(ret_reg);
4499 __update_reg_bounds(ret_reg);
4503 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
4504 int func_id, int insn_idx)
4506 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
4507 struct bpf_map *map = meta->map_ptr;
4509 if (func_id != BPF_FUNC_tail_call &&
4510 func_id != BPF_FUNC_map_lookup_elem &&
4511 func_id != BPF_FUNC_map_update_elem &&
4512 func_id != BPF_FUNC_map_delete_elem &&
4513 func_id != BPF_FUNC_map_push_elem &&
4514 func_id != BPF_FUNC_map_pop_elem &&
4515 func_id != BPF_FUNC_map_peek_elem)
4519 verbose(env, "kernel subsystem misconfigured verifier\n");
4523 /* In case of read-only, some additional restrictions
4524 * need to be applied in order to prevent altering the
4525 * state of the map from program side.
4527 if ((map->map_flags & BPF_F_RDONLY_PROG) &&
4528 (func_id == BPF_FUNC_map_delete_elem ||
4529 func_id == BPF_FUNC_map_update_elem ||
4530 func_id == BPF_FUNC_map_push_elem ||
4531 func_id == BPF_FUNC_map_pop_elem)) {
4532 verbose(env, "write into map forbidden\n");
4536 if (!BPF_MAP_PTR(aux->map_ptr_state))
4537 bpf_map_ptr_store(aux, meta->map_ptr,
4538 !meta->map_ptr->bypass_spec_v1);
4539 else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
4540 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
4541 !meta->map_ptr->bypass_spec_v1);
4546 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
4547 int func_id, int insn_idx)
4549 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
4550 struct bpf_reg_state *regs = cur_regs(env), *reg;
4551 struct bpf_map *map = meta->map_ptr;
4556 if (func_id != BPF_FUNC_tail_call)
4558 if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
4559 verbose(env, "kernel subsystem misconfigured verifier\n");
4563 range = tnum_range(0, map->max_entries - 1);
4564 reg = ®s[BPF_REG_3];
4566 if (!register_is_const(reg) || !tnum_in(range, reg->var_off)) {
4567 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
4571 err = mark_chain_precision(env, BPF_REG_3);
4575 val = reg->var_off.value;
4576 if (bpf_map_key_unseen(aux))
4577 bpf_map_key_store(aux, val);
4578 else if (!bpf_map_key_poisoned(aux) &&
4579 bpf_map_key_immediate(aux) != val)
4580 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
4584 static int check_reference_leak(struct bpf_verifier_env *env)
4586 struct bpf_func_state *state = cur_func(env);
4589 for (i = 0; i < state->acquired_refs; i++) {
4590 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
4591 state->refs[i].id, state->refs[i].insn_idx);
4593 return state->acquired_refs ? -EINVAL : 0;
4596 static int check_helper_call(struct bpf_verifier_env *env, int func_id, int insn_idx)
4598 const struct bpf_func_proto *fn = NULL;
4599 struct bpf_reg_state *regs;
4600 struct bpf_call_arg_meta meta;
4604 /* find function prototype */
4605 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
4606 verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
4611 if (env->ops->get_func_proto)
4612 fn = env->ops->get_func_proto(func_id, env->prog);
4614 verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
4619 /* eBPF programs must be GPL compatible to use GPL-ed functions */
4620 if (!env->prog->gpl_compatible && fn->gpl_only) {
4621 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
4625 /* With LD_ABS/IND some JITs save/restore skb from r1. */
4626 changes_data = bpf_helper_changes_pkt_data(fn->func);
4627 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
4628 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
4629 func_id_name(func_id), func_id);
4633 memset(&meta, 0, sizeof(meta));
4634 meta.pkt_access = fn->pkt_access;
4636 err = check_func_proto(fn, func_id);
4638 verbose(env, "kernel subsystem misconfigured func %s#%d\n",
4639 func_id_name(func_id), func_id);
4643 meta.func_id = func_id;
4645 for (i = 0; i < 5; i++) {
4646 err = btf_resolve_helper_id(&env->log, fn, i);
4649 err = check_func_arg(env, BPF_REG_1 + i, fn->arg_type[i], &meta);
4654 err = record_func_map(env, &meta, func_id, insn_idx);
4658 err = record_func_key(env, &meta, func_id, insn_idx);
4662 /* Mark slots with STACK_MISC in case of raw mode, stack offset
4663 * is inferred from register state.
4665 for (i = 0; i < meta.access_size; i++) {
4666 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
4667 BPF_WRITE, -1, false);
4672 if (func_id == BPF_FUNC_tail_call) {
4673 err = check_reference_leak(env);
4675 verbose(env, "tail_call would lead to reference leak\n");
4678 } else if (is_release_function(func_id)) {
4679 err = release_reference(env, meta.ref_obj_id);
4681 verbose(env, "func %s#%d reference has not been acquired before\n",
4682 func_id_name(func_id), func_id);
4687 regs = cur_regs(env);
4689 /* check that flags argument in get_local_storage(map, flags) is 0,
4690 * this is required because get_local_storage() can't return an error.
4692 if (func_id == BPF_FUNC_get_local_storage &&
4693 !register_is_null(®s[BPF_REG_2])) {
4694 verbose(env, "get_local_storage() doesn't support non-zero flags\n");
4698 /* reset caller saved regs */
4699 for (i = 0; i < CALLER_SAVED_REGS; i++) {
4700 mark_reg_not_init(env, regs, caller_saved[i]);
4701 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
4704 /* helper call returns 64-bit value. */
4705 regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
4707 /* update return register (already marked as written above) */
4708 if (fn->ret_type == RET_INTEGER) {
4709 /* sets type to SCALAR_VALUE */
4710 mark_reg_unknown(env, regs, BPF_REG_0);
4711 } else if (fn->ret_type == RET_VOID) {
4712 regs[BPF_REG_0].type = NOT_INIT;
4713 } else if (fn->ret_type == RET_PTR_TO_MAP_VALUE_OR_NULL ||
4714 fn->ret_type == RET_PTR_TO_MAP_VALUE) {
4715 /* There is no offset yet applied, variable or fixed */
4716 mark_reg_known_zero(env, regs, BPF_REG_0);
4717 /* remember map_ptr, so that check_map_access()
4718 * can check 'value_size' boundary of memory access
4719 * to map element returned from bpf_map_lookup_elem()
4721 if (meta.map_ptr == NULL) {
4723 "kernel subsystem misconfigured verifier\n");
4726 regs[BPF_REG_0].map_ptr = meta.map_ptr;
4727 if (fn->ret_type == RET_PTR_TO_MAP_VALUE) {
4728 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE;
4729 if (map_value_has_spin_lock(meta.map_ptr))
4730 regs[BPF_REG_0].id = ++env->id_gen;
4732 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE_OR_NULL;
4733 regs[BPF_REG_0].id = ++env->id_gen;
4735 } else if (fn->ret_type == RET_PTR_TO_SOCKET_OR_NULL) {
4736 mark_reg_known_zero(env, regs, BPF_REG_0);
4737 regs[BPF_REG_0].type = PTR_TO_SOCKET_OR_NULL;
4738 regs[BPF_REG_0].id = ++env->id_gen;
4739 } else if (fn->ret_type == RET_PTR_TO_SOCK_COMMON_OR_NULL) {
4740 mark_reg_known_zero(env, regs, BPF_REG_0);
4741 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON_OR_NULL;
4742 regs[BPF_REG_0].id = ++env->id_gen;
4743 } else if (fn->ret_type == RET_PTR_TO_TCP_SOCK_OR_NULL) {
4744 mark_reg_known_zero(env, regs, BPF_REG_0);
4745 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK_OR_NULL;
4746 regs[BPF_REG_0].id = ++env->id_gen;
4747 } else if (fn->ret_type == RET_PTR_TO_ALLOC_MEM_OR_NULL) {
4748 mark_reg_known_zero(env, regs, BPF_REG_0);
4749 regs[BPF_REG_0].type = PTR_TO_MEM_OR_NULL;
4750 regs[BPF_REG_0].id = ++env->id_gen;
4751 regs[BPF_REG_0].mem_size = meta.mem_size;
4753 verbose(env, "unknown return type %d of func %s#%d\n",
4754 fn->ret_type, func_id_name(func_id), func_id);
4758 if (is_ptr_cast_function(func_id)) {
4759 /* For release_reference() */
4760 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
4761 } else if (is_acquire_function(func_id, meta.map_ptr)) {
4762 int id = acquire_reference_state(env, insn_idx);
4766 /* For mark_ptr_or_null_reg() */
4767 regs[BPF_REG_0].id = id;
4768 /* For release_reference() */
4769 regs[BPF_REG_0].ref_obj_id = id;
4772 do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
4774 err = check_map_func_compatibility(env, meta.map_ptr, func_id);
4778 if (func_id == BPF_FUNC_get_stack && !env->prog->has_callchain_buf) {
4779 const char *err_str;
4781 #ifdef CONFIG_PERF_EVENTS
4782 err = get_callchain_buffers(sysctl_perf_event_max_stack);
4783 err_str = "cannot get callchain buffer for func %s#%d\n";
4786 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
4789 verbose(env, err_str, func_id_name(func_id), func_id);
4793 env->prog->has_callchain_buf = true;
4797 clear_all_pkt_pointers(env);
4801 static bool signed_add_overflows(s64 a, s64 b)
4803 /* Do the add in u64, where overflow is well-defined */
4804 s64 res = (s64)((u64)a + (u64)b);
4811 static bool signed_add32_overflows(s64 a, s64 b)
4813 /* Do the add in u32, where overflow is well-defined */
4814 s32 res = (s32)((u32)a + (u32)b);
4821 static bool signed_sub_overflows(s32 a, s32 b)
4823 /* Do the sub in u64, where overflow is well-defined */
4824 s64 res = (s64)((u64)a - (u64)b);
4831 static bool signed_sub32_overflows(s32 a, s32 b)
4833 /* Do the sub in u64, where overflow is well-defined */
4834 s32 res = (s32)((u32)a - (u32)b);
4841 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
4842 const struct bpf_reg_state *reg,
4843 enum bpf_reg_type type)
4845 bool known = tnum_is_const(reg->var_off);
4846 s64 val = reg->var_off.value;
4847 s64 smin = reg->smin_value;
4849 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
4850 verbose(env, "math between %s pointer and %lld is not allowed\n",
4851 reg_type_str[type], val);
4855 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
4856 verbose(env, "%s pointer offset %d is not allowed\n",
4857 reg_type_str[type], reg->off);
4861 if (smin == S64_MIN) {
4862 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
4863 reg_type_str[type]);
4867 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
4868 verbose(env, "value %lld makes %s pointer be out of bounds\n",
4869 smin, reg_type_str[type]);
4876 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
4878 return &env->insn_aux_data[env->insn_idx];
4881 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
4882 u32 *ptr_limit, u8 opcode, bool off_is_neg)
4884 bool mask_to_left = (opcode == BPF_ADD && off_is_neg) ||
4885 (opcode == BPF_SUB && !off_is_neg);
4888 switch (ptr_reg->type) {
4890 /* Indirect variable offset stack access is prohibited in
4891 * unprivileged mode so it's not handled here.
4893 off = ptr_reg->off + ptr_reg->var_off.value;
4895 *ptr_limit = MAX_BPF_STACK + off;
4899 case PTR_TO_MAP_VALUE:
4901 *ptr_limit = ptr_reg->umax_value + ptr_reg->off;
4903 off = ptr_reg->smin_value + ptr_reg->off;
4904 *ptr_limit = ptr_reg->map_ptr->value_size - off;
4912 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
4913 const struct bpf_insn *insn)
4915 return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
4918 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
4919 u32 alu_state, u32 alu_limit)
4921 /* If we arrived here from different branches with different
4922 * state or limits to sanitize, then this won't work.
4924 if (aux->alu_state &&
4925 (aux->alu_state != alu_state ||
4926 aux->alu_limit != alu_limit))
4929 /* Corresponding fixup done in fixup_bpf_calls(). */
4930 aux->alu_state = alu_state;
4931 aux->alu_limit = alu_limit;
4935 static int sanitize_val_alu(struct bpf_verifier_env *env,
4936 struct bpf_insn *insn)
4938 struct bpf_insn_aux_data *aux = cur_aux(env);
4940 if (can_skip_alu_sanitation(env, insn))
4943 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
4946 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
4947 struct bpf_insn *insn,
4948 const struct bpf_reg_state *ptr_reg,
4949 struct bpf_reg_state *dst_reg,
4952 struct bpf_verifier_state *vstate = env->cur_state;
4953 struct bpf_insn_aux_data *aux = cur_aux(env);
4954 bool ptr_is_dst_reg = ptr_reg == dst_reg;
4955 u8 opcode = BPF_OP(insn->code);
4956 u32 alu_state, alu_limit;
4957 struct bpf_reg_state tmp;
4960 if (can_skip_alu_sanitation(env, insn))
4963 /* We already marked aux for masking from non-speculative
4964 * paths, thus we got here in the first place. We only care
4965 * to explore bad access from here.
4967 if (vstate->speculative)
4970 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
4971 alu_state |= ptr_is_dst_reg ?
4972 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
4974 if (retrieve_ptr_limit(ptr_reg, &alu_limit, opcode, off_is_neg))
4976 if (update_alu_sanitation_state(aux, alu_state, alu_limit))
4979 /* Simulate and find potential out-of-bounds access under
4980 * speculative execution from truncation as a result of
4981 * masking when off was not within expected range. If off
4982 * sits in dst, then we temporarily need to move ptr there
4983 * to simulate dst (== 0) +/-= ptr. Needed, for example,
4984 * for cases where we use K-based arithmetic in one direction
4985 * and truncated reg-based in the other in order to explore
4988 if (!ptr_is_dst_reg) {
4990 *dst_reg = *ptr_reg;
4992 ret = push_stack(env, env->insn_idx + 1, env->insn_idx, true);
4993 if (!ptr_is_dst_reg && ret)
4995 return !ret ? -EFAULT : 0;
4998 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
4999 * Caller should also handle BPF_MOV case separately.
5000 * If we return -EACCES, caller may want to try again treating pointer as a
5001 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks.
5003 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
5004 struct bpf_insn *insn,
5005 const struct bpf_reg_state *ptr_reg,
5006 const struct bpf_reg_state *off_reg)
5008 struct bpf_verifier_state *vstate = env->cur_state;
5009 struct bpf_func_state *state = vstate->frame[vstate->curframe];
5010 struct bpf_reg_state *regs = state->regs, *dst_reg;
5011 bool known = tnum_is_const(off_reg->var_off);
5012 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
5013 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
5014 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
5015 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
5016 u32 dst = insn->dst_reg, src = insn->src_reg;
5017 u8 opcode = BPF_OP(insn->code);
5020 dst_reg = ®s[dst];
5022 if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
5023 smin_val > smax_val || umin_val > umax_val) {
5024 /* Taint dst register if offset had invalid bounds derived from
5025 * e.g. dead branches.
5027 __mark_reg_unknown(env, dst_reg);
5031 if (BPF_CLASS(insn->code) != BPF_ALU64) {
5032 /* 32-bit ALU ops on pointers produce (meaningless) scalars */
5034 "R%d 32-bit pointer arithmetic prohibited\n",
5039 switch (ptr_reg->type) {
5040 case PTR_TO_MAP_VALUE_OR_NULL:
5041 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
5042 dst, reg_type_str[ptr_reg->type]);
5044 case CONST_PTR_TO_MAP:
5045 case PTR_TO_PACKET_END:
5047 case PTR_TO_SOCKET_OR_NULL:
5048 case PTR_TO_SOCK_COMMON:
5049 case PTR_TO_SOCK_COMMON_OR_NULL:
5050 case PTR_TO_TCP_SOCK:
5051 case PTR_TO_TCP_SOCK_OR_NULL:
5052 case PTR_TO_XDP_SOCK:
5053 verbose(env, "R%d pointer arithmetic on %s prohibited\n",
5054 dst, reg_type_str[ptr_reg->type]);
5056 case PTR_TO_MAP_VALUE:
5057 if (!env->allow_ptr_leaks && !known && (smin_val < 0) != (smax_val < 0)) {
5058 verbose(env, "R%d has unknown scalar with mixed signed bounds, pointer arithmetic with it prohibited for !root\n",
5059 off_reg == dst_reg ? dst : src);
5067 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
5068 * The id may be overwritten later if we create a new variable offset.
5070 dst_reg->type = ptr_reg->type;
5071 dst_reg->id = ptr_reg->id;
5073 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
5074 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
5077 /* pointer types do not carry 32-bit bounds at the moment. */
5078 __mark_reg32_unbounded(dst_reg);
5082 ret = sanitize_ptr_alu(env, insn, ptr_reg, dst_reg, smin_val < 0);
5084 verbose(env, "R%d tried to add from different maps or paths\n", dst);
5087 /* We can take a fixed offset as long as it doesn't overflow
5088 * the s32 'off' field
5090 if (known && (ptr_reg->off + smin_val ==
5091 (s64)(s32)(ptr_reg->off + smin_val))) {
5092 /* pointer += K. Accumulate it into fixed offset */
5093 dst_reg->smin_value = smin_ptr;
5094 dst_reg->smax_value = smax_ptr;
5095 dst_reg->umin_value = umin_ptr;
5096 dst_reg->umax_value = umax_ptr;
5097 dst_reg->var_off = ptr_reg->var_off;
5098 dst_reg->off = ptr_reg->off + smin_val;
5099 dst_reg->raw = ptr_reg->raw;
5102 /* A new variable offset is created. Note that off_reg->off
5103 * == 0, since it's a scalar.
5104 * dst_reg gets the pointer type and since some positive
5105 * integer value was added to the pointer, give it a new 'id'
5106 * if it's a PTR_TO_PACKET.
5107 * this creates a new 'base' pointer, off_reg (variable) gets
5108 * added into the variable offset, and we copy the fixed offset
5111 if (signed_add_overflows(smin_ptr, smin_val) ||
5112 signed_add_overflows(smax_ptr, smax_val)) {
5113 dst_reg->smin_value = S64_MIN;
5114 dst_reg->smax_value = S64_MAX;
5116 dst_reg->smin_value = smin_ptr + smin_val;
5117 dst_reg->smax_value = smax_ptr + smax_val;
5119 if (umin_ptr + umin_val < umin_ptr ||
5120 umax_ptr + umax_val < umax_ptr) {
5121 dst_reg->umin_value = 0;
5122 dst_reg->umax_value = U64_MAX;
5124 dst_reg->umin_value = umin_ptr + umin_val;
5125 dst_reg->umax_value = umax_ptr + umax_val;
5127 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
5128 dst_reg->off = ptr_reg->off;
5129 dst_reg->raw = ptr_reg->raw;
5130 if (reg_is_pkt_pointer(ptr_reg)) {
5131 dst_reg->id = ++env->id_gen;
5132 /* something was added to pkt_ptr, set range to zero */
5137 ret = sanitize_ptr_alu(env, insn, ptr_reg, dst_reg, smin_val < 0);
5139 verbose(env, "R%d tried to sub from different maps or paths\n", dst);
5142 if (dst_reg == off_reg) {
5143 /* scalar -= pointer. Creates an unknown scalar */
5144 verbose(env, "R%d tried to subtract pointer from scalar\n",
5148 /* We don't allow subtraction from FP, because (according to
5149 * test_verifier.c test "invalid fp arithmetic", JITs might not
5150 * be able to deal with it.
5152 if (ptr_reg->type == PTR_TO_STACK) {
5153 verbose(env, "R%d subtraction from stack pointer prohibited\n",
5157 if (known && (ptr_reg->off - smin_val ==
5158 (s64)(s32)(ptr_reg->off - smin_val))) {
5159 /* pointer -= K. Subtract it from fixed offset */
5160 dst_reg->smin_value = smin_ptr;
5161 dst_reg->smax_value = smax_ptr;
5162 dst_reg->umin_value = umin_ptr;
5163 dst_reg->umax_value = umax_ptr;
5164 dst_reg->var_off = ptr_reg->var_off;
5165 dst_reg->id = ptr_reg->id;
5166 dst_reg->off = ptr_reg->off - smin_val;
5167 dst_reg->raw = ptr_reg->raw;
5170 /* A new variable offset is created. If the subtrahend is known
5171 * nonnegative, then any reg->range we had before is still good.
5173 if (signed_sub_overflows(smin_ptr, smax_val) ||
5174 signed_sub_overflows(smax_ptr, smin_val)) {
5175 /* Overflow possible, we know nothing */
5176 dst_reg->smin_value = S64_MIN;
5177 dst_reg->smax_value = S64_MAX;
5179 dst_reg->smin_value = smin_ptr - smax_val;
5180 dst_reg->smax_value = smax_ptr - smin_val;
5182 if (umin_ptr < umax_val) {
5183 /* Overflow possible, we know nothing */
5184 dst_reg->umin_value = 0;
5185 dst_reg->umax_value = U64_MAX;
5187 /* Cannot overflow (as long as bounds are consistent) */
5188 dst_reg->umin_value = umin_ptr - umax_val;
5189 dst_reg->umax_value = umax_ptr - umin_val;
5191 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
5192 dst_reg->off = ptr_reg->off;
5193 dst_reg->raw = ptr_reg->raw;
5194 if (reg_is_pkt_pointer(ptr_reg)) {
5195 dst_reg->id = ++env->id_gen;
5196 /* something was added to pkt_ptr, set range to zero */
5204 /* bitwise ops on pointers are troublesome, prohibit. */
5205 verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
5206 dst, bpf_alu_string[opcode >> 4]);
5209 /* other operators (e.g. MUL,LSH) produce non-pointer results */
5210 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
5211 dst, bpf_alu_string[opcode >> 4]);
5215 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
5218 __update_reg_bounds(dst_reg);
5219 __reg_deduce_bounds(dst_reg);
5220 __reg_bound_offset(dst_reg);
5222 /* For unprivileged we require that resulting offset must be in bounds
5223 * in order to be able to sanitize access later on.
5225 if (!env->bypass_spec_v1) {
5226 if (dst_reg->type == PTR_TO_MAP_VALUE &&
5227 check_map_access(env, dst, dst_reg->off, 1, false)) {
5228 verbose(env, "R%d pointer arithmetic of map value goes out of range, "
5229 "prohibited for !root\n", dst);
5231 } else if (dst_reg->type == PTR_TO_STACK &&
5232 check_stack_access(env, dst_reg, dst_reg->off +
5233 dst_reg->var_off.value, 1)) {
5234 verbose(env, "R%d stack pointer arithmetic goes out of range, "
5235 "prohibited for !root\n", dst);
5243 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
5244 struct bpf_reg_state *src_reg)
5246 s32 smin_val = src_reg->s32_min_value;
5247 s32 smax_val = src_reg->s32_max_value;
5248 u32 umin_val = src_reg->u32_min_value;
5249 u32 umax_val = src_reg->u32_max_value;
5251 if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
5252 signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
5253 dst_reg->s32_min_value = S32_MIN;
5254 dst_reg->s32_max_value = S32_MAX;
5256 dst_reg->s32_min_value += smin_val;
5257 dst_reg->s32_max_value += smax_val;
5259 if (dst_reg->u32_min_value + umin_val < umin_val ||
5260 dst_reg->u32_max_value + umax_val < umax_val) {
5261 dst_reg->u32_min_value = 0;
5262 dst_reg->u32_max_value = U32_MAX;
5264 dst_reg->u32_min_value += umin_val;
5265 dst_reg->u32_max_value += umax_val;
5269 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
5270 struct bpf_reg_state *src_reg)
5272 s64 smin_val = src_reg->smin_value;
5273 s64 smax_val = src_reg->smax_value;
5274 u64 umin_val = src_reg->umin_value;
5275 u64 umax_val = src_reg->umax_value;
5277 if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
5278 signed_add_overflows(dst_reg->smax_value, smax_val)) {
5279 dst_reg->smin_value = S64_MIN;
5280 dst_reg->smax_value = S64_MAX;
5282 dst_reg->smin_value += smin_val;
5283 dst_reg->smax_value += smax_val;
5285 if (dst_reg->umin_value + umin_val < umin_val ||
5286 dst_reg->umax_value + umax_val < umax_val) {
5287 dst_reg->umin_value = 0;
5288 dst_reg->umax_value = U64_MAX;
5290 dst_reg->umin_value += umin_val;
5291 dst_reg->umax_value += umax_val;
5295 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
5296 struct bpf_reg_state *src_reg)
5298 s32 smin_val = src_reg->s32_min_value;
5299 s32 smax_val = src_reg->s32_max_value;
5300 u32 umin_val = src_reg->u32_min_value;
5301 u32 umax_val = src_reg->u32_max_value;
5303 if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
5304 signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
5305 /* Overflow possible, we know nothing */
5306 dst_reg->s32_min_value = S32_MIN;
5307 dst_reg->s32_max_value = S32_MAX;
5309 dst_reg->s32_min_value -= smax_val;
5310 dst_reg->s32_max_value -= smin_val;
5312 if (dst_reg->u32_min_value < umax_val) {
5313 /* Overflow possible, we know nothing */
5314 dst_reg->u32_min_value = 0;
5315 dst_reg->u32_max_value = U32_MAX;
5317 /* Cannot overflow (as long as bounds are consistent) */
5318 dst_reg->u32_min_value -= umax_val;
5319 dst_reg->u32_max_value -= umin_val;
5323 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
5324 struct bpf_reg_state *src_reg)
5326 s64 smin_val = src_reg->smin_value;
5327 s64 smax_val = src_reg->smax_value;
5328 u64 umin_val = src_reg->umin_value;
5329 u64 umax_val = src_reg->umax_value;
5331 if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
5332 signed_sub_overflows(dst_reg->smax_value, smin_val)) {
5333 /* Overflow possible, we know nothing */
5334 dst_reg->smin_value = S64_MIN;
5335 dst_reg->smax_value = S64_MAX;
5337 dst_reg->smin_value -= smax_val;
5338 dst_reg->smax_value -= smin_val;
5340 if (dst_reg->umin_value < umax_val) {
5341 /* Overflow possible, we know nothing */
5342 dst_reg->umin_value = 0;
5343 dst_reg->umax_value = U64_MAX;
5345 /* Cannot overflow (as long as bounds are consistent) */
5346 dst_reg->umin_value -= umax_val;
5347 dst_reg->umax_value -= umin_val;
5351 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
5352 struct bpf_reg_state *src_reg)
5354 s32 smin_val = src_reg->s32_min_value;
5355 u32 umin_val = src_reg->u32_min_value;
5356 u32 umax_val = src_reg->u32_max_value;
5358 if (smin_val < 0 || dst_reg->s32_min_value < 0) {
5359 /* Ain't nobody got time to multiply that sign */
5360 __mark_reg32_unbounded(dst_reg);
5363 /* Both values are positive, so we can work with unsigned and
5364 * copy the result to signed (unless it exceeds S32_MAX).
5366 if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
5367 /* Potential overflow, we know nothing */
5368 __mark_reg32_unbounded(dst_reg);
5371 dst_reg->u32_min_value *= umin_val;
5372 dst_reg->u32_max_value *= umax_val;
5373 if (dst_reg->u32_max_value > S32_MAX) {
5374 /* Overflow possible, we know nothing */
5375 dst_reg->s32_min_value = S32_MIN;
5376 dst_reg->s32_max_value = S32_MAX;
5378 dst_reg->s32_min_value = dst_reg->u32_min_value;
5379 dst_reg->s32_max_value = dst_reg->u32_max_value;
5383 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
5384 struct bpf_reg_state *src_reg)
5386 s64 smin_val = src_reg->smin_value;
5387 u64 umin_val = src_reg->umin_value;
5388 u64 umax_val = src_reg->umax_value;
5390 if (smin_val < 0 || dst_reg->smin_value < 0) {
5391 /* Ain't nobody got time to multiply that sign */
5392 __mark_reg64_unbounded(dst_reg);
5395 /* Both values are positive, so we can work with unsigned and
5396 * copy the result to signed (unless it exceeds S64_MAX).
5398 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
5399 /* Potential overflow, we know nothing */
5400 __mark_reg64_unbounded(dst_reg);
5403 dst_reg->umin_value *= umin_val;
5404 dst_reg->umax_value *= umax_val;
5405 if (dst_reg->umax_value > S64_MAX) {
5406 /* Overflow possible, we know nothing */
5407 dst_reg->smin_value = S64_MIN;
5408 dst_reg->smax_value = S64_MAX;
5410 dst_reg->smin_value = dst_reg->umin_value;
5411 dst_reg->smax_value = dst_reg->umax_value;
5415 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
5416 struct bpf_reg_state *src_reg)
5418 bool src_known = tnum_subreg_is_const(src_reg->var_off);
5419 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
5420 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
5421 s32 smin_val = src_reg->s32_min_value;
5422 u32 umax_val = src_reg->u32_max_value;
5424 /* Assuming scalar64_min_max_and will be called so its safe
5425 * to skip updating register for known 32-bit case.
5427 if (src_known && dst_known)
5430 /* We get our minimum from the var_off, since that's inherently
5431 * bitwise. Our maximum is the minimum of the operands' maxima.
5433 dst_reg->u32_min_value = var32_off.value;
5434 dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
5435 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
5436 /* Lose signed bounds when ANDing negative numbers,
5437 * ain't nobody got time for that.
5439 dst_reg->s32_min_value = S32_MIN;
5440 dst_reg->s32_max_value = S32_MAX;
5442 /* ANDing two positives gives a positive, so safe to
5443 * cast result into s64.
5445 dst_reg->s32_min_value = dst_reg->u32_min_value;
5446 dst_reg->s32_max_value = dst_reg->u32_max_value;
5451 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
5452 struct bpf_reg_state *src_reg)
5454 bool src_known = tnum_is_const(src_reg->var_off);
5455 bool dst_known = tnum_is_const(dst_reg->var_off);
5456 s64 smin_val = src_reg->smin_value;
5457 u64 umax_val = src_reg->umax_value;
5459 if (src_known && dst_known) {
5460 __mark_reg_known(dst_reg, dst_reg->var_off.value &
5461 src_reg->var_off.value);
5465 /* We get our minimum from the var_off, since that's inherently
5466 * bitwise. Our maximum is the minimum of the operands' maxima.
5468 dst_reg->umin_value = dst_reg->var_off.value;
5469 dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
5470 if (dst_reg->smin_value < 0 || smin_val < 0) {
5471 /* Lose signed bounds when ANDing negative numbers,
5472 * ain't nobody got time for that.
5474 dst_reg->smin_value = S64_MIN;
5475 dst_reg->smax_value = S64_MAX;
5477 /* ANDing two positives gives a positive, so safe to
5478 * cast result into s64.
5480 dst_reg->smin_value = dst_reg->umin_value;
5481 dst_reg->smax_value = dst_reg->umax_value;
5483 /* We may learn something more from the var_off */
5484 __update_reg_bounds(dst_reg);
5487 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
5488 struct bpf_reg_state *src_reg)
5490 bool src_known = tnum_subreg_is_const(src_reg->var_off);
5491 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
5492 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
5493 s32 smin_val = src_reg->smin_value;
5494 u32 umin_val = src_reg->umin_value;
5496 /* Assuming scalar64_min_max_or will be called so it is safe
5497 * to skip updating register for known case.
5499 if (src_known && dst_known)
5502 /* We get our maximum from the var_off, and our minimum is the
5503 * maximum of the operands' minima
5505 dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
5506 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
5507 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
5508 /* Lose signed bounds when ORing negative numbers,
5509 * ain't nobody got time for that.
5511 dst_reg->s32_min_value = S32_MIN;
5512 dst_reg->s32_max_value = S32_MAX;
5514 /* ORing two positives gives a positive, so safe to
5515 * cast result into s64.
5517 dst_reg->s32_min_value = dst_reg->umin_value;
5518 dst_reg->s32_max_value = dst_reg->umax_value;
5522 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
5523 struct bpf_reg_state *src_reg)
5525 bool src_known = tnum_is_const(src_reg->var_off);
5526 bool dst_known = tnum_is_const(dst_reg->var_off);
5527 s64 smin_val = src_reg->smin_value;
5528 u64 umin_val = src_reg->umin_value;
5530 if (src_known && dst_known) {
5531 __mark_reg_known(dst_reg, dst_reg->var_off.value |
5532 src_reg->var_off.value);
5536 /* We get our maximum from the var_off, and our minimum is the
5537 * maximum of the operands' minima
5539 dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
5540 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
5541 if (dst_reg->smin_value < 0 || smin_val < 0) {
5542 /* Lose signed bounds when ORing negative numbers,
5543 * ain't nobody got time for that.
5545 dst_reg->smin_value = S64_MIN;
5546 dst_reg->smax_value = S64_MAX;
5548 /* ORing two positives gives a positive, so safe to
5549 * cast result into s64.
5551 dst_reg->smin_value = dst_reg->umin_value;
5552 dst_reg->smax_value = dst_reg->umax_value;
5554 /* We may learn something more from the var_off */
5555 __update_reg_bounds(dst_reg);
5558 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
5559 u64 umin_val, u64 umax_val)
5561 /* We lose all sign bit information (except what we can pick
5564 dst_reg->s32_min_value = S32_MIN;
5565 dst_reg->s32_max_value = S32_MAX;
5566 /* If we might shift our top bit out, then we know nothing */
5567 if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
5568 dst_reg->u32_min_value = 0;
5569 dst_reg->u32_max_value = U32_MAX;
5571 dst_reg->u32_min_value <<= umin_val;
5572 dst_reg->u32_max_value <<= umax_val;
5576 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
5577 struct bpf_reg_state *src_reg)
5579 u32 umax_val = src_reg->u32_max_value;
5580 u32 umin_val = src_reg->u32_min_value;
5581 /* u32 alu operation will zext upper bits */
5582 struct tnum subreg = tnum_subreg(dst_reg->var_off);
5584 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
5585 dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
5586 /* Not required but being careful mark reg64 bounds as unknown so
5587 * that we are forced to pick them up from tnum and zext later and
5588 * if some path skips this step we are still safe.
5590 __mark_reg64_unbounded(dst_reg);
5591 __update_reg32_bounds(dst_reg);
5594 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
5595 u64 umin_val, u64 umax_val)
5597 /* Special case <<32 because it is a common compiler pattern to sign
5598 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
5599 * positive we know this shift will also be positive so we can track
5600 * bounds correctly. Otherwise we lose all sign bit information except
5601 * what we can pick up from var_off. Perhaps we can generalize this
5602 * later to shifts of any length.
5604 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
5605 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
5607 dst_reg->smax_value = S64_MAX;
5609 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
5610 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
5612 dst_reg->smin_value = S64_MIN;
5614 /* If we might shift our top bit out, then we know nothing */
5615 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
5616 dst_reg->umin_value = 0;
5617 dst_reg->umax_value = U64_MAX;
5619 dst_reg->umin_value <<= umin_val;
5620 dst_reg->umax_value <<= umax_val;
5624 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
5625 struct bpf_reg_state *src_reg)
5627 u64 umax_val = src_reg->umax_value;
5628 u64 umin_val = src_reg->umin_value;
5630 /* scalar64 calc uses 32bit unshifted bounds so must be called first */
5631 __scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
5632 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
5634 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
5635 /* We may learn something more from the var_off */
5636 __update_reg_bounds(dst_reg);
5639 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
5640 struct bpf_reg_state *src_reg)
5642 struct tnum subreg = tnum_subreg(dst_reg->var_off);
5643 u32 umax_val = src_reg->u32_max_value;
5644 u32 umin_val = src_reg->u32_min_value;
5646 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
5647 * be negative, then either:
5648 * 1) src_reg might be zero, so the sign bit of the result is
5649 * unknown, so we lose our signed bounds
5650 * 2) it's known negative, thus the unsigned bounds capture the
5652 * 3) the signed bounds cross zero, so they tell us nothing
5654 * If the value in dst_reg is known nonnegative, then again the
5655 * unsigned bounts capture the signed bounds.
5656 * Thus, in all cases it suffices to blow away our signed bounds
5657 * and rely on inferring new ones from the unsigned bounds and
5658 * var_off of the result.
5660 dst_reg->s32_min_value = S32_MIN;
5661 dst_reg->s32_max_value = S32_MAX;
5663 dst_reg->var_off = tnum_rshift(subreg, umin_val);
5664 dst_reg->u32_min_value >>= umax_val;
5665 dst_reg->u32_max_value >>= umin_val;
5667 __mark_reg64_unbounded(dst_reg);
5668 __update_reg32_bounds(dst_reg);
5671 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
5672 struct bpf_reg_state *src_reg)
5674 u64 umax_val = src_reg->umax_value;
5675 u64 umin_val = src_reg->umin_value;
5677 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
5678 * be negative, then either:
5679 * 1) src_reg might be zero, so the sign bit of the result is
5680 * unknown, so we lose our signed bounds
5681 * 2) it's known negative, thus the unsigned bounds capture the
5683 * 3) the signed bounds cross zero, so they tell us nothing
5685 * If the value in dst_reg is known nonnegative, then again the
5686 * unsigned bounts capture the signed bounds.
5687 * Thus, in all cases it suffices to blow away our signed bounds
5688 * and rely on inferring new ones from the unsigned bounds and
5689 * var_off of the result.
5691 dst_reg->smin_value = S64_MIN;
5692 dst_reg->smax_value = S64_MAX;
5693 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
5694 dst_reg->umin_value >>= umax_val;
5695 dst_reg->umax_value >>= umin_val;
5697 /* Its not easy to operate on alu32 bounds here because it depends
5698 * on bits being shifted in. Take easy way out and mark unbounded
5699 * so we can recalculate later from tnum.
5701 __mark_reg32_unbounded(dst_reg);
5702 __update_reg_bounds(dst_reg);
5705 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
5706 struct bpf_reg_state *src_reg)
5708 u64 umin_val = src_reg->u32_min_value;
5710 /* Upon reaching here, src_known is true and
5711 * umax_val is equal to umin_val.
5713 dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
5714 dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
5716 dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
5718 /* blow away the dst_reg umin_value/umax_value and rely on
5719 * dst_reg var_off to refine the result.
5721 dst_reg->u32_min_value = 0;
5722 dst_reg->u32_max_value = U32_MAX;
5724 __mark_reg64_unbounded(dst_reg);
5725 __update_reg32_bounds(dst_reg);
5728 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
5729 struct bpf_reg_state *src_reg)
5731 u64 umin_val = src_reg->umin_value;
5733 /* Upon reaching here, src_known is true and umax_val is equal
5736 dst_reg->smin_value >>= umin_val;
5737 dst_reg->smax_value >>= umin_val;
5739 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
5741 /* blow away the dst_reg umin_value/umax_value and rely on
5742 * dst_reg var_off to refine the result.
5744 dst_reg->umin_value = 0;
5745 dst_reg->umax_value = U64_MAX;
5747 /* Its not easy to operate on alu32 bounds here because it depends
5748 * on bits being shifted in from upper 32-bits. Take easy way out
5749 * and mark unbounded so we can recalculate later from tnum.
5751 __mark_reg32_unbounded(dst_reg);
5752 __update_reg_bounds(dst_reg);
5755 /* WARNING: This function does calculations on 64-bit values, but the actual
5756 * execution may occur on 32-bit values. Therefore, things like bitshifts
5757 * need extra checks in the 32-bit case.
5759 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
5760 struct bpf_insn *insn,
5761 struct bpf_reg_state *dst_reg,
5762 struct bpf_reg_state src_reg)
5764 struct bpf_reg_state *regs = cur_regs(env);
5765 u8 opcode = BPF_OP(insn->code);
5767 s64 smin_val, smax_val;
5768 u64 umin_val, umax_val;
5769 s32 s32_min_val, s32_max_val;
5770 u32 u32_min_val, u32_max_val;
5771 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
5772 u32 dst = insn->dst_reg;
5774 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
5776 smin_val = src_reg.smin_value;
5777 smax_val = src_reg.smax_value;
5778 umin_val = src_reg.umin_value;
5779 umax_val = src_reg.umax_value;
5781 s32_min_val = src_reg.s32_min_value;
5782 s32_max_val = src_reg.s32_max_value;
5783 u32_min_val = src_reg.u32_min_value;
5784 u32_max_val = src_reg.u32_max_value;
5787 src_known = tnum_subreg_is_const(src_reg.var_off);
5789 (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
5790 s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
5791 /* Taint dst register if offset had invalid bounds
5792 * derived from e.g. dead branches.
5794 __mark_reg_unknown(env, dst_reg);
5798 src_known = tnum_is_const(src_reg.var_off);
5800 (smin_val != smax_val || umin_val != umax_val)) ||
5801 smin_val > smax_val || umin_val > umax_val) {
5802 /* Taint dst register if offset had invalid bounds
5803 * derived from e.g. dead branches.
5805 __mark_reg_unknown(env, dst_reg);
5811 opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
5812 __mark_reg_unknown(env, dst_reg);
5816 /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
5817 * There are two classes of instructions: The first class we track both
5818 * alu32 and alu64 sign/unsigned bounds independently this provides the
5819 * greatest amount of precision when alu operations are mixed with jmp32
5820 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
5821 * and BPF_OR. This is possible because these ops have fairly easy to
5822 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
5823 * See alu32 verifier tests for examples. The second class of
5824 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
5825 * with regards to tracking sign/unsigned bounds because the bits may
5826 * cross subreg boundaries in the alu64 case. When this happens we mark
5827 * the reg unbounded in the subreg bound space and use the resulting
5828 * tnum to calculate an approximation of the sign/unsigned bounds.
5832 ret = sanitize_val_alu(env, insn);
5834 verbose(env, "R%d tried to add from different pointers or scalars\n", dst);
5837 scalar32_min_max_add(dst_reg, &src_reg);
5838 scalar_min_max_add(dst_reg, &src_reg);
5839 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
5842 ret = sanitize_val_alu(env, insn);
5844 verbose(env, "R%d tried to sub from different pointers or scalars\n", dst);
5847 scalar32_min_max_sub(dst_reg, &src_reg);
5848 scalar_min_max_sub(dst_reg, &src_reg);
5849 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
5852 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
5853 scalar32_min_max_mul(dst_reg, &src_reg);
5854 scalar_min_max_mul(dst_reg, &src_reg);
5857 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
5858 scalar32_min_max_and(dst_reg, &src_reg);
5859 scalar_min_max_and(dst_reg, &src_reg);
5862 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
5863 scalar32_min_max_or(dst_reg, &src_reg);
5864 scalar_min_max_or(dst_reg, &src_reg);
5867 if (umax_val >= insn_bitness) {
5868 /* Shifts greater than 31 or 63 are undefined.
5869 * This includes shifts by a negative number.
5871 mark_reg_unknown(env, regs, insn->dst_reg);
5875 scalar32_min_max_lsh(dst_reg, &src_reg);
5877 scalar_min_max_lsh(dst_reg, &src_reg);
5880 if (umax_val >= insn_bitness) {
5881 /* Shifts greater than 31 or 63 are undefined.
5882 * This includes shifts by a negative number.
5884 mark_reg_unknown(env, regs, insn->dst_reg);
5888 scalar32_min_max_rsh(dst_reg, &src_reg);
5890 scalar_min_max_rsh(dst_reg, &src_reg);
5893 if (umax_val >= insn_bitness) {
5894 /* Shifts greater than 31 or 63 are undefined.
5895 * This includes shifts by a negative number.
5897 mark_reg_unknown(env, regs, insn->dst_reg);
5901 scalar32_min_max_arsh(dst_reg, &src_reg);
5903 scalar_min_max_arsh(dst_reg, &src_reg);
5906 mark_reg_unknown(env, regs, insn->dst_reg);
5910 /* ALU32 ops are zero extended into 64bit register */
5912 zext_32_to_64(dst_reg);
5914 __update_reg_bounds(dst_reg);
5915 __reg_deduce_bounds(dst_reg);
5916 __reg_bound_offset(dst_reg);
5920 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
5923 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
5924 struct bpf_insn *insn)
5926 struct bpf_verifier_state *vstate = env->cur_state;
5927 struct bpf_func_state *state = vstate->frame[vstate->curframe];
5928 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
5929 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
5930 u8 opcode = BPF_OP(insn->code);
5933 dst_reg = ®s[insn->dst_reg];
5935 if (dst_reg->type != SCALAR_VALUE)
5937 if (BPF_SRC(insn->code) == BPF_X) {
5938 src_reg = ®s[insn->src_reg];
5939 if (src_reg->type != SCALAR_VALUE) {
5940 if (dst_reg->type != SCALAR_VALUE) {
5941 /* Combining two pointers by any ALU op yields
5942 * an arbitrary scalar. Disallow all math except
5943 * pointer subtraction
5945 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
5946 mark_reg_unknown(env, regs, insn->dst_reg);
5949 verbose(env, "R%d pointer %s pointer prohibited\n",
5951 bpf_alu_string[opcode >> 4]);
5954 /* scalar += pointer
5955 * This is legal, but we have to reverse our
5956 * src/dest handling in computing the range
5958 err = mark_chain_precision(env, insn->dst_reg);
5961 return adjust_ptr_min_max_vals(env, insn,
5964 } else if (ptr_reg) {
5965 /* pointer += scalar */
5966 err = mark_chain_precision(env, insn->src_reg);
5969 return adjust_ptr_min_max_vals(env, insn,
5973 /* Pretend the src is a reg with a known value, since we only
5974 * need to be able to read from this state.
5976 off_reg.type = SCALAR_VALUE;
5977 __mark_reg_known(&off_reg, insn->imm);
5979 if (ptr_reg) /* pointer += K */
5980 return adjust_ptr_min_max_vals(env, insn,
5984 /* Got here implies adding two SCALAR_VALUEs */
5985 if (WARN_ON_ONCE(ptr_reg)) {
5986 print_verifier_state(env, state);
5987 verbose(env, "verifier internal error: unexpected ptr_reg\n");
5990 if (WARN_ON(!src_reg)) {
5991 print_verifier_state(env, state);
5992 verbose(env, "verifier internal error: no src_reg\n");
5995 return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
5998 /* check validity of 32-bit and 64-bit arithmetic operations */
5999 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
6001 struct bpf_reg_state *regs = cur_regs(env);
6002 u8 opcode = BPF_OP(insn->code);
6005 if (opcode == BPF_END || opcode == BPF_NEG) {
6006 if (opcode == BPF_NEG) {
6007 if (BPF_SRC(insn->code) != 0 ||
6008 insn->src_reg != BPF_REG_0 ||
6009 insn->off != 0 || insn->imm != 0) {
6010 verbose(env, "BPF_NEG uses reserved fields\n");
6014 if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
6015 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
6016 BPF_CLASS(insn->code) == BPF_ALU64) {
6017 verbose(env, "BPF_END uses reserved fields\n");
6022 /* check src operand */
6023 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
6027 if (is_pointer_value(env, insn->dst_reg)) {
6028 verbose(env, "R%d pointer arithmetic prohibited\n",
6033 /* check dest operand */
6034 err = check_reg_arg(env, insn->dst_reg, DST_OP);
6038 } else if (opcode == BPF_MOV) {
6040 if (BPF_SRC(insn->code) == BPF_X) {
6041 if (insn->imm != 0 || insn->off != 0) {
6042 verbose(env, "BPF_MOV uses reserved fields\n");
6046 /* check src operand */
6047 err = check_reg_arg(env, insn->src_reg, SRC_OP);
6051 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
6052 verbose(env, "BPF_MOV uses reserved fields\n");
6057 /* check dest operand, mark as required later */
6058 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
6062 if (BPF_SRC(insn->code) == BPF_X) {
6063 struct bpf_reg_state *src_reg = regs + insn->src_reg;
6064 struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
6066 if (BPF_CLASS(insn->code) == BPF_ALU64) {
6068 * copy register state to dest reg
6070 *dst_reg = *src_reg;
6071 dst_reg->live |= REG_LIVE_WRITTEN;
6072 dst_reg->subreg_def = DEF_NOT_SUBREG;
6075 if (is_pointer_value(env, insn->src_reg)) {
6077 "R%d partial copy of pointer\n",
6080 } else if (src_reg->type == SCALAR_VALUE) {
6081 *dst_reg = *src_reg;
6082 dst_reg->live |= REG_LIVE_WRITTEN;
6083 dst_reg->subreg_def = env->insn_idx + 1;
6085 mark_reg_unknown(env, regs,
6088 zext_32_to_64(dst_reg);
6092 * remember the value we stored into this reg
6094 /* clear any state __mark_reg_known doesn't set */
6095 mark_reg_unknown(env, regs, insn->dst_reg);
6096 regs[insn->dst_reg].type = SCALAR_VALUE;
6097 if (BPF_CLASS(insn->code) == BPF_ALU64) {
6098 __mark_reg_known(regs + insn->dst_reg,
6101 __mark_reg_known(regs + insn->dst_reg,
6106 } else if (opcode > BPF_END) {
6107 verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
6110 } else { /* all other ALU ops: and, sub, xor, add, ... */
6112 if (BPF_SRC(insn->code) == BPF_X) {
6113 if (insn->imm != 0 || insn->off != 0) {
6114 verbose(env, "BPF_ALU uses reserved fields\n");
6117 /* check src1 operand */
6118 err = check_reg_arg(env, insn->src_reg, SRC_OP);
6122 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
6123 verbose(env, "BPF_ALU uses reserved fields\n");
6128 /* check src2 operand */
6129 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
6133 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
6134 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
6135 verbose(env, "div by zero\n");
6139 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
6140 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
6141 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
6143 if (insn->imm < 0 || insn->imm >= size) {
6144 verbose(env, "invalid shift %d\n", insn->imm);
6149 /* check dest operand */
6150 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
6154 return adjust_reg_min_max_vals(env, insn);
6160 static void __find_good_pkt_pointers(struct bpf_func_state *state,
6161 struct bpf_reg_state *dst_reg,
6162 enum bpf_reg_type type, u16 new_range)
6164 struct bpf_reg_state *reg;
6167 for (i = 0; i < MAX_BPF_REG; i++) {
6168 reg = &state->regs[i];
6169 if (reg->type == type && reg->id == dst_reg->id)
6170 /* keep the maximum range already checked */
6171 reg->range = max(reg->range, new_range);
6174 bpf_for_each_spilled_reg(i, state, reg) {
6177 if (reg->type == type && reg->id == dst_reg->id)
6178 reg->range = max(reg->range, new_range);
6182 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
6183 struct bpf_reg_state *dst_reg,
6184 enum bpf_reg_type type,
6185 bool range_right_open)
6190 if (dst_reg->off < 0 ||
6191 (dst_reg->off == 0 && range_right_open))
6192 /* This doesn't give us any range */
6195 if (dst_reg->umax_value > MAX_PACKET_OFF ||
6196 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
6197 /* Risk of overflow. For instance, ptr + (1<<63) may be less
6198 * than pkt_end, but that's because it's also less than pkt.
6202 new_range = dst_reg->off;
6203 if (range_right_open)
6206 /* Examples for register markings:
6208 * pkt_data in dst register:
6212 * if (r2 > pkt_end) goto <handle exception>
6217 * if (r2 < pkt_end) goto <access okay>
6218 * <handle exception>
6221 * r2 == dst_reg, pkt_end == src_reg
6222 * r2=pkt(id=n,off=8,r=0)
6223 * r3=pkt(id=n,off=0,r=0)
6225 * pkt_data in src register:
6229 * if (pkt_end >= r2) goto <access okay>
6230 * <handle exception>
6234 * if (pkt_end <= r2) goto <handle exception>
6238 * pkt_end == dst_reg, r2 == src_reg
6239 * r2=pkt(id=n,off=8,r=0)
6240 * r3=pkt(id=n,off=0,r=0)
6242 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
6243 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
6244 * and [r3, r3 + 8-1) respectively is safe to access depending on
6248 /* If our ids match, then we must have the same max_value. And we
6249 * don't care about the other reg's fixed offset, since if it's too big
6250 * the range won't allow anything.
6251 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
6253 for (i = 0; i <= vstate->curframe; i++)
6254 __find_good_pkt_pointers(vstate->frame[i], dst_reg, type,
6258 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
6260 struct tnum subreg = tnum_subreg(reg->var_off);
6261 s32 sval = (s32)val;
6265 if (tnum_is_const(subreg))
6266 return !!tnum_equals_const(subreg, val);
6269 if (tnum_is_const(subreg))
6270 return !tnum_equals_const(subreg, val);
6273 if ((~subreg.mask & subreg.value) & val)
6275 if (!((subreg.mask | subreg.value) & val))
6279 if (reg->u32_min_value > val)
6281 else if (reg->u32_max_value <= val)
6285 if (reg->s32_min_value > sval)
6287 else if (reg->s32_max_value < sval)
6291 if (reg->u32_max_value < val)
6293 else if (reg->u32_min_value >= val)
6297 if (reg->s32_max_value < sval)
6299 else if (reg->s32_min_value >= sval)
6303 if (reg->u32_min_value >= val)
6305 else if (reg->u32_max_value < val)
6309 if (reg->s32_min_value >= sval)
6311 else if (reg->s32_max_value < sval)
6315 if (reg->u32_max_value <= val)
6317 else if (reg->u32_min_value > val)
6321 if (reg->s32_max_value <= sval)
6323 else if (reg->s32_min_value > sval)
6332 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
6334 s64 sval = (s64)val;
6338 if (tnum_is_const(reg->var_off))
6339 return !!tnum_equals_const(reg->var_off, val);
6342 if (tnum_is_const(reg->var_off))
6343 return !tnum_equals_const(reg->var_off, val);
6346 if ((~reg->var_off.mask & reg->var_off.value) & val)
6348 if (!((reg->var_off.mask | reg->var_off.value) & val))
6352 if (reg->umin_value > val)
6354 else if (reg->umax_value <= val)
6358 if (reg->smin_value > sval)
6360 else if (reg->smax_value < sval)
6364 if (reg->umax_value < val)
6366 else if (reg->umin_value >= val)
6370 if (reg->smax_value < sval)
6372 else if (reg->smin_value >= sval)
6376 if (reg->umin_value >= val)
6378 else if (reg->umax_value < val)
6382 if (reg->smin_value >= sval)
6384 else if (reg->smax_value < sval)
6388 if (reg->umax_value <= val)
6390 else if (reg->umin_value > val)
6394 if (reg->smax_value <= sval)
6396 else if (reg->smin_value > sval)
6404 /* compute branch direction of the expression "if (reg opcode val) goto target;"
6406 * 1 - branch will be taken and "goto target" will be executed
6407 * 0 - branch will not be taken and fall-through to next insn
6408 * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
6411 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
6414 if (__is_pointer_value(false, reg)) {
6415 if (!reg_type_not_null(reg->type))
6418 /* If pointer is valid tests against zero will fail so we can
6419 * use this to direct branch taken.
6435 return is_branch32_taken(reg, val, opcode);
6436 return is_branch64_taken(reg, val, opcode);
6439 /* Adjusts the register min/max values in the case that the dst_reg is the
6440 * variable register that we are working on, and src_reg is a constant or we're
6441 * simply doing a BPF_K check.
6442 * In JEQ/JNE cases we also adjust the var_off values.
6444 static void reg_set_min_max(struct bpf_reg_state *true_reg,
6445 struct bpf_reg_state *false_reg,
6447 u8 opcode, bool is_jmp32)
6449 struct tnum false_32off = tnum_subreg(false_reg->var_off);
6450 struct tnum false_64off = false_reg->var_off;
6451 struct tnum true_32off = tnum_subreg(true_reg->var_off);
6452 struct tnum true_64off = true_reg->var_off;
6453 s64 sval = (s64)val;
6454 s32 sval32 = (s32)val32;
6456 /* If the dst_reg is a pointer, we can't learn anything about its
6457 * variable offset from the compare (unless src_reg were a pointer into
6458 * the same object, but we don't bother with that.
6459 * Since false_reg and true_reg have the same type by construction, we
6460 * only need to check one of them for pointerness.
6462 if (__is_pointer_value(false, false_reg))
6469 struct bpf_reg_state *reg =
6470 opcode == BPF_JEQ ? true_reg : false_reg;
6472 /* For BPF_JEQ, if this is false we know nothing Jon Snow, but
6473 * if it is true we know the value for sure. Likewise for
6477 __mark_reg32_known(reg, val32);
6479 __mark_reg_known(reg, val);
6484 false_32off = tnum_and(false_32off, tnum_const(~val32));
6485 if (is_power_of_2(val32))
6486 true_32off = tnum_or(true_32off,
6489 false_64off = tnum_and(false_64off, tnum_const(~val));
6490 if (is_power_of_2(val))
6491 true_64off = tnum_or(true_64off,
6499 u32 false_umax = opcode == BPF_JGT ? val32 : val32 - 1;
6500 u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
6502 false_reg->u32_max_value = min(false_reg->u32_max_value,
6504 true_reg->u32_min_value = max(true_reg->u32_min_value,
6507 u64 false_umax = opcode == BPF_JGT ? val : val - 1;
6508 u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
6510 false_reg->umax_value = min(false_reg->umax_value, false_umax);
6511 true_reg->umin_value = max(true_reg->umin_value, true_umin);
6519 s32 false_smax = opcode == BPF_JSGT ? sval32 : sval32 - 1;
6520 s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
6522 false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
6523 true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
6525 s64 false_smax = opcode == BPF_JSGT ? sval : sval - 1;
6526 s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
6528 false_reg->smax_value = min(false_reg->smax_value, false_smax);
6529 true_reg->smin_value = max(true_reg->smin_value, true_smin);
6537 u32 false_umin = opcode == BPF_JLT ? val32 : val32 + 1;
6538 u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
6540 false_reg->u32_min_value = max(false_reg->u32_min_value,
6542 true_reg->u32_max_value = min(true_reg->u32_max_value,
6545 u64 false_umin = opcode == BPF_JLT ? val : val + 1;
6546 u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
6548 false_reg->umin_value = max(false_reg->umin_value, false_umin);
6549 true_reg->umax_value = min(true_reg->umax_value, true_umax);
6557 s32 false_smin = opcode == BPF_JSLT ? sval32 : sval32 + 1;
6558 s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
6560 false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
6561 true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
6563 s64 false_smin = opcode == BPF_JSLT ? sval : sval + 1;
6564 s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
6566 false_reg->smin_value = max(false_reg->smin_value, false_smin);
6567 true_reg->smax_value = min(true_reg->smax_value, true_smax);
6576 false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
6577 tnum_subreg(false_32off));
6578 true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
6579 tnum_subreg(true_32off));
6580 __reg_combine_32_into_64(false_reg);
6581 __reg_combine_32_into_64(true_reg);
6583 false_reg->var_off = false_64off;
6584 true_reg->var_off = true_64off;
6585 __reg_combine_64_into_32(false_reg);
6586 __reg_combine_64_into_32(true_reg);
6590 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
6593 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
6594 struct bpf_reg_state *false_reg,
6596 u8 opcode, bool is_jmp32)
6598 /* How can we transform "a <op> b" into "b <op> a"? */
6599 static const u8 opcode_flip[16] = {
6600 /* these stay the same */
6601 [BPF_JEQ >> 4] = BPF_JEQ,
6602 [BPF_JNE >> 4] = BPF_JNE,
6603 [BPF_JSET >> 4] = BPF_JSET,
6604 /* these swap "lesser" and "greater" (L and G in the opcodes) */
6605 [BPF_JGE >> 4] = BPF_JLE,
6606 [BPF_JGT >> 4] = BPF_JLT,
6607 [BPF_JLE >> 4] = BPF_JGE,
6608 [BPF_JLT >> 4] = BPF_JGT,
6609 [BPF_JSGE >> 4] = BPF_JSLE,
6610 [BPF_JSGT >> 4] = BPF_JSLT,
6611 [BPF_JSLE >> 4] = BPF_JSGE,
6612 [BPF_JSLT >> 4] = BPF_JSGT
6614 opcode = opcode_flip[opcode >> 4];
6615 /* This uses zero as "not present in table"; luckily the zero opcode,
6616 * BPF_JA, can't get here.
6619 reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
6622 /* Regs are known to be equal, so intersect their min/max/var_off */
6623 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
6624 struct bpf_reg_state *dst_reg)
6626 src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
6627 dst_reg->umin_value);
6628 src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
6629 dst_reg->umax_value);
6630 src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
6631 dst_reg->smin_value);
6632 src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
6633 dst_reg->smax_value);
6634 src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
6636 /* We might have learned new bounds from the var_off. */
6637 __update_reg_bounds(src_reg);
6638 __update_reg_bounds(dst_reg);
6639 /* We might have learned something about the sign bit. */
6640 __reg_deduce_bounds(src_reg);
6641 __reg_deduce_bounds(dst_reg);
6642 /* We might have learned some bits from the bounds. */
6643 __reg_bound_offset(src_reg);
6644 __reg_bound_offset(dst_reg);
6645 /* Intersecting with the old var_off might have improved our bounds
6646 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
6647 * then new var_off is (0; 0x7f...fc) which improves our umax.
6649 __update_reg_bounds(src_reg);
6650 __update_reg_bounds(dst_reg);
6653 static void reg_combine_min_max(struct bpf_reg_state *true_src,
6654 struct bpf_reg_state *true_dst,
6655 struct bpf_reg_state *false_src,
6656 struct bpf_reg_state *false_dst,
6661 __reg_combine_min_max(true_src, true_dst);
6664 __reg_combine_min_max(false_src, false_dst);
6669 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
6670 struct bpf_reg_state *reg, u32 id,
6673 if (reg_type_may_be_null(reg->type) && reg->id == id) {
6674 /* Old offset (both fixed and variable parts) should
6675 * have been known-zero, because we don't allow pointer
6676 * arithmetic on pointers that might be NULL.
6678 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value ||
6679 !tnum_equals_const(reg->var_off, 0) ||
6681 __mark_reg_known_zero(reg);
6685 reg->type = SCALAR_VALUE;
6686 } else if (reg->type == PTR_TO_MAP_VALUE_OR_NULL) {
6687 const struct bpf_map *map = reg->map_ptr;
6689 if (map->inner_map_meta) {
6690 reg->type = CONST_PTR_TO_MAP;
6691 reg->map_ptr = map->inner_map_meta;
6692 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
6693 reg->type = PTR_TO_XDP_SOCK;
6694 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
6695 map->map_type == BPF_MAP_TYPE_SOCKHASH) {
6696 reg->type = PTR_TO_SOCKET;
6698 reg->type = PTR_TO_MAP_VALUE;
6700 } else if (reg->type == PTR_TO_SOCKET_OR_NULL) {
6701 reg->type = PTR_TO_SOCKET;
6702 } else if (reg->type == PTR_TO_SOCK_COMMON_OR_NULL) {
6703 reg->type = PTR_TO_SOCK_COMMON;
6704 } else if (reg->type == PTR_TO_TCP_SOCK_OR_NULL) {
6705 reg->type = PTR_TO_TCP_SOCK;
6706 } else if (reg->type == PTR_TO_BTF_ID_OR_NULL) {
6707 reg->type = PTR_TO_BTF_ID;
6708 } else if (reg->type == PTR_TO_MEM_OR_NULL) {
6709 reg->type = PTR_TO_MEM;
6712 /* We don't need id and ref_obj_id from this point
6713 * onwards anymore, thus we should better reset it,
6714 * so that state pruning has chances to take effect.
6717 reg->ref_obj_id = 0;
6718 } else if (!reg_may_point_to_spin_lock(reg)) {
6719 /* For not-NULL ptr, reg->ref_obj_id will be reset
6720 * in release_reg_references().
6722 * reg->id is still used by spin_lock ptr. Other
6723 * than spin_lock ptr type, reg->id can be reset.
6730 static void __mark_ptr_or_null_regs(struct bpf_func_state *state, u32 id,
6733 struct bpf_reg_state *reg;
6736 for (i = 0; i < MAX_BPF_REG; i++)
6737 mark_ptr_or_null_reg(state, &state->regs[i], id, is_null);
6739 bpf_for_each_spilled_reg(i, state, reg) {
6742 mark_ptr_or_null_reg(state, reg, id, is_null);
6746 /* The logic is similar to find_good_pkt_pointers(), both could eventually
6747 * be folded together at some point.
6749 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
6752 struct bpf_func_state *state = vstate->frame[vstate->curframe];
6753 struct bpf_reg_state *regs = state->regs;
6754 u32 ref_obj_id = regs[regno].ref_obj_id;
6755 u32 id = regs[regno].id;
6758 if (ref_obj_id && ref_obj_id == id && is_null)
6759 /* regs[regno] is in the " == NULL" branch.
6760 * No one could have freed the reference state before
6761 * doing the NULL check.
6763 WARN_ON_ONCE(release_reference_state(state, id));
6765 for (i = 0; i <= vstate->curframe; i++)
6766 __mark_ptr_or_null_regs(vstate->frame[i], id, is_null);
6769 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
6770 struct bpf_reg_state *dst_reg,
6771 struct bpf_reg_state *src_reg,
6772 struct bpf_verifier_state *this_branch,
6773 struct bpf_verifier_state *other_branch)
6775 if (BPF_SRC(insn->code) != BPF_X)
6778 /* Pointers are always 64-bit. */
6779 if (BPF_CLASS(insn->code) == BPF_JMP32)
6782 switch (BPF_OP(insn->code)) {
6784 if ((dst_reg->type == PTR_TO_PACKET &&
6785 src_reg->type == PTR_TO_PACKET_END) ||
6786 (dst_reg->type == PTR_TO_PACKET_META &&
6787 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
6788 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
6789 find_good_pkt_pointers(this_branch, dst_reg,
6790 dst_reg->type, false);
6791 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
6792 src_reg->type == PTR_TO_PACKET) ||
6793 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
6794 src_reg->type == PTR_TO_PACKET_META)) {
6795 /* pkt_end > pkt_data', pkt_data > pkt_meta' */
6796 find_good_pkt_pointers(other_branch, src_reg,
6797 src_reg->type, true);
6803 if ((dst_reg->type == PTR_TO_PACKET &&
6804 src_reg->type == PTR_TO_PACKET_END) ||
6805 (dst_reg->type == PTR_TO_PACKET_META &&
6806 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
6807 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
6808 find_good_pkt_pointers(other_branch, dst_reg,
6809 dst_reg->type, true);
6810 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
6811 src_reg->type == PTR_TO_PACKET) ||
6812 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
6813 src_reg->type == PTR_TO_PACKET_META)) {
6814 /* pkt_end < pkt_data', pkt_data > pkt_meta' */
6815 find_good_pkt_pointers(this_branch, src_reg,
6816 src_reg->type, false);
6822 if ((dst_reg->type == PTR_TO_PACKET &&
6823 src_reg->type == PTR_TO_PACKET_END) ||
6824 (dst_reg->type == PTR_TO_PACKET_META &&
6825 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
6826 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
6827 find_good_pkt_pointers(this_branch, dst_reg,
6828 dst_reg->type, true);
6829 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
6830 src_reg->type == PTR_TO_PACKET) ||
6831 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
6832 src_reg->type == PTR_TO_PACKET_META)) {
6833 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
6834 find_good_pkt_pointers(other_branch, src_reg,
6835 src_reg->type, false);
6841 if ((dst_reg->type == PTR_TO_PACKET &&
6842 src_reg->type == PTR_TO_PACKET_END) ||
6843 (dst_reg->type == PTR_TO_PACKET_META &&
6844 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
6845 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
6846 find_good_pkt_pointers(other_branch, dst_reg,
6847 dst_reg->type, false);
6848 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
6849 src_reg->type == PTR_TO_PACKET) ||
6850 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
6851 src_reg->type == PTR_TO_PACKET_META)) {
6852 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
6853 find_good_pkt_pointers(this_branch, src_reg,
6854 src_reg->type, true);
6866 static int check_cond_jmp_op(struct bpf_verifier_env *env,
6867 struct bpf_insn *insn, int *insn_idx)
6869 struct bpf_verifier_state *this_branch = env->cur_state;
6870 struct bpf_verifier_state *other_branch;
6871 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
6872 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
6873 u8 opcode = BPF_OP(insn->code);
6878 /* Only conditional jumps are expected to reach here. */
6879 if (opcode == BPF_JA || opcode > BPF_JSLE) {
6880 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
6884 if (BPF_SRC(insn->code) == BPF_X) {
6885 if (insn->imm != 0) {
6886 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
6890 /* check src1 operand */
6891 err = check_reg_arg(env, insn->src_reg, SRC_OP);
6895 if (is_pointer_value(env, insn->src_reg)) {
6896 verbose(env, "R%d pointer comparison prohibited\n",
6900 src_reg = ®s[insn->src_reg];
6902 if (insn->src_reg != BPF_REG_0) {
6903 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
6908 /* check src2 operand */
6909 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
6913 dst_reg = ®s[insn->dst_reg];
6914 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
6916 if (BPF_SRC(insn->code) == BPF_K) {
6917 pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
6918 } else if (src_reg->type == SCALAR_VALUE &&
6919 is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
6920 pred = is_branch_taken(dst_reg,
6921 tnum_subreg(src_reg->var_off).value,
6924 } else if (src_reg->type == SCALAR_VALUE &&
6925 !is_jmp32 && tnum_is_const(src_reg->var_off)) {
6926 pred = is_branch_taken(dst_reg,
6927 src_reg->var_off.value,
6933 /* If we get here with a dst_reg pointer type it is because
6934 * above is_branch_taken() special cased the 0 comparison.
6936 if (!__is_pointer_value(false, dst_reg))
6937 err = mark_chain_precision(env, insn->dst_reg);
6938 if (BPF_SRC(insn->code) == BPF_X && !err)
6939 err = mark_chain_precision(env, insn->src_reg);
6944 /* only follow the goto, ignore fall-through */
6945 *insn_idx += insn->off;
6947 } else if (pred == 0) {
6948 /* only follow fall-through branch, since
6949 * that's where the program will go
6954 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
6958 other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
6960 /* detect if we are comparing against a constant value so we can adjust
6961 * our min/max values for our dst register.
6962 * this is only legit if both are scalars (or pointers to the same
6963 * object, I suppose, but we don't support that right now), because
6964 * otherwise the different base pointers mean the offsets aren't
6967 if (BPF_SRC(insn->code) == BPF_X) {
6968 struct bpf_reg_state *src_reg = ®s[insn->src_reg];
6970 if (dst_reg->type == SCALAR_VALUE &&
6971 src_reg->type == SCALAR_VALUE) {
6972 if (tnum_is_const(src_reg->var_off) ||
6974 tnum_is_const(tnum_subreg(src_reg->var_off))))
6975 reg_set_min_max(&other_branch_regs[insn->dst_reg],
6977 src_reg->var_off.value,
6978 tnum_subreg(src_reg->var_off).value,
6980 else if (tnum_is_const(dst_reg->var_off) ||
6982 tnum_is_const(tnum_subreg(dst_reg->var_off))))
6983 reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
6985 dst_reg->var_off.value,
6986 tnum_subreg(dst_reg->var_off).value,
6988 else if (!is_jmp32 &&
6989 (opcode == BPF_JEQ || opcode == BPF_JNE))
6990 /* Comparing for equality, we can combine knowledge */
6991 reg_combine_min_max(&other_branch_regs[insn->src_reg],
6992 &other_branch_regs[insn->dst_reg],
6993 src_reg, dst_reg, opcode);
6995 } else if (dst_reg->type == SCALAR_VALUE) {
6996 reg_set_min_max(&other_branch_regs[insn->dst_reg],
6997 dst_reg, insn->imm, (u32)insn->imm,
7001 /* detect if R == 0 where R is returned from bpf_map_lookup_elem().
7002 * NOTE: these optimizations below are related with pointer comparison
7003 * which will never be JMP32.
7005 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
7006 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
7007 reg_type_may_be_null(dst_reg->type)) {
7008 /* Mark all identical registers in each branch as either
7009 * safe or unknown depending R == 0 or R != 0 conditional.
7011 mark_ptr_or_null_regs(this_branch, insn->dst_reg,
7013 mark_ptr_or_null_regs(other_branch, insn->dst_reg,
7015 } else if (!try_match_pkt_pointers(insn, dst_reg, ®s[insn->src_reg],
7016 this_branch, other_branch) &&
7017 is_pointer_value(env, insn->dst_reg)) {
7018 verbose(env, "R%d pointer comparison prohibited\n",
7022 if (env->log.level & BPF_LOG_LEVEL)
7023 print_verifier_state(env, this_branch->frame[this_branch->curframe]);
7027 /* verify BPF_LD_IMM64 instruction */
7028 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
7030 struct bpf_insn_aux_data *aux = cur_aux(env);
7031 struct bpf_reg_state *regs = cur_regs(env);
7032 struct bpf_map *map;
7035 if (BPF_SIZE(insn->code) != BPF_DW) {
7036 verbose(env, "invalid BPF_LD_IMM insn\n");
7039 if (insn->off != 0) {
7040 verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
7044 err = check_reg_arg(env, insn->dst_reg, DST_OP);
7048 if (insn->src_reg == 0) {
7049 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
7051 regs[insn->dst_reg].type = SCALAR_VALUE;
7052 __mark_reg_known(®s[insn->dst_reg], imm);
7056 map = env->used_maps[aux->map_index];
7057 mark_reg_known_zero(env, regs, insn->dst_reg);
7058 regs[insn->dst_reg].map_ptr = map;
7060 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE) {
7061 regs[insn->dst_reg].type = PTR_TO_MAP_VALUE;
7062 regs[insn->dst_reg].off = aux->map_off;
7063 if (map_value_has_spin_lock(map))
7064 regs[insn->dst_reg].id = ++env->id_gen;
7065 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD) {
7066 regs[insn->dst_reg].type = CONST_PTR_TO_MAP;
7068 verbose(env, "bpf verifier is misconfigured\n");
7075 static bool may_access_skb(enum bpf_prog_type type)
7078 case BPF_PROG_TYPE_SOCKET_FILTER:
7079 case BPF_PROG_TYPE_SCHED_CLS:
7080 case BPF_PROG_TYPE_SCHED_ACT:
7087 /* verify safety of LD_ABS|LD_IND instructions:
7088 * - they can only appear in the programs where ctx == skb
7089 * - since they are wrappers of function calls, they scratch R1-R5 registers,
7090 * preserve R6-R9, and store return value into R0
7093 * ctx == skb == R6 == CTX
7096 * SRC == any register
7097 * IMM == 32-bit immediate
7100 * R0 - 8/16/32-bit skb data converted to cpu endianness
7102 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
7104 struct bpf_reg_state *regs = cur_regs(env);
7105 static const int ctx_reg = BPF_REG_6;
7106 u8 mode = BPF_MODE(insn->code);
7109 if (!may_access_skb(env->prog->type)) {
7110 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
7114 if (!env->ops->gen_ld_abs) {
7115 verbose(env, "bpf verifier is misconfigured\n");
7119 if (env->subprog_cnt > 1) {
7120 /* when program has LD_ABS insn JITs and interpreter assume
7121 * that r1 == ctx == skb which is not the case for callees
7122 * that can have arbitrary arguments. It's problematic
7123 * for main prog as well since JITs would need to analyze
7124 * all functions in order to make proper register save/restore
7125 * decisions in the main prog. Hence disallow LD_ABS with calls
7127 verbose(env, "BPF_LD_[ABS|IND] instructions cannot be mixed with bpf-to-bpf calls\n");
7131 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
7132 BPF_SIZE(insn->code) == BPF_DW ||
7133 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
7134 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
7138 /* check whether implicit source operand (register R6) is readable */
7139 err = check_reg_arg(env, ctx_reg, SRC_OP);
7143 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
7144 * gen_ld_abs() may terminate the program at runtime, leading to
7147 err = check_reference_leak(env);
7149 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
7153 if (env->cur_state->active_spin_lock) {
7154 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
7158 if (regs[ctx_reg].type != PTR_TO_CTX) {
7160 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
7164 if (mode == BPF_IND) {
7165 /* check explicit source operand */
7166 err = check_reg_arg(env, insn->src_reg, SRC_OP);
7171 err = check_ctx_reg(env, ®s[ctx_reg], ctx_reg);
7175 /* reset caller saved regs to unreadable */
7176 for (i = 0; i < CALLER_SAVED_REGS; i++) {
7177 mark_reg_not_init(env, regs, caller_saved[i]);
7178 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
7181 /* mark destination R0 register as readable, since it contains
7182 * the value fetched from the packet.
7183 * Already marked as written above.
7185 mark_reg_unknown(env, regs, BPF_REG_0);
7186 /* ld_abs load up to 32-bit skb data. */
7187 regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
7191 static int check_return_code(struct bpf_verifier_env *env)
7193 struct tnum enforce_attach_type_range = tnum_unknown;
7194 const struct bpf_prog *prog = env->prog;
7195 struct bpf_reg_state *reg;
7196 struct tnum range = tnum_range(0, 1);
7199 /* LSM and struct_ops func-ptr's return type could be "void" */
7200 if ((env->prog->type == BPF_PROG_TYPE_STRUCT_OPS ||
7201 env->prog->type == BPF_PROG_TYPE_LSM) &&
7202 !prog->aux->attach_func_proto->type)
7205 /* eBPF calling convetion is such that R0 is used
7206 * to return the value from eBPF program.
7207 * Make sure that it's readable at this time
7208 * of bpf_exit, which means that program wrote
7209 * something into it earlier
7211 err = check_reg_arg(env, BPF_REG_0, SRC_OP);
7215 if (is_pointer_value(env, BPF_REG_0)) {
7216 verbose(env, "R0 leaks addr as return value\n");
7220 switch (env->prog->type) {
7221 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
7222 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
7223 env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
7224 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
7225 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
7226 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
7227 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
7228 range = tnum_range(1, 1);
7230 case BPF_PROG_TYPE_CGROUP_SKB:
7231 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
7232 range = tnum_range(0, 3);
7233 enforce_attach_type_range = tnum_range(2, 3);
7236 case BPF_PROG_TYPE_CGROUP_SOCK:
7237 case BPF_PROG_TYPE_SOCK_OPS:
7238 case BPF_PROG_TYPE_CGROUP_DEVICE:
7239 case BPF_PROG_TYPE_CGROUP_SYSCTL:
7240 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
7242 case BPF_PROG_TYPE_RAW_TRACEPOINT:
7243 if (!env->prog->aux->attach_btf_id)
7245 range = tnum_const(0);
7247 case BPF_PROG_TYPE_TRACING:
7248 switch (env->prog->expected_attach_type) {
7249 case BPF_TRACE_FENTRY:
7250 case BPF_TRACE_FEXIT:
7251 range = tnum_const(0);
7253 case BPF_TRACE_RAW_TP:
7254 case BPF_MODIFY_RETURN:
7256 case BPF_TRACE_ITER:
7262 case BPF_PROG_TYPE_EXT:
7263 /* freplace program can return anything as its return value
7264 * depends on the to-be-replaced kernel func or bpf program.
7270 reg = cur_regs(env) + BPF_REG_0;
7271 if (reg->type != SCALAR_VALUE) {
7272 verbose(env, "At program exit the register R0 is not a known value (%s)\n",
7273 reg_type_str[reg->type]);
7277 if (!tnum_in(range, reg->var_off)) {
7280 verbose(env, "At program exit the register R0 ");
7281 if (!tnum_is_unknown(reg->var_off)) {
7282 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7283 verbose(env, "has value %s", tn_buf);
7285 verbose(env, "has unknown scalar value");
7287 tnum_strn(tn_buf, sizeof(tn_buf), range);
7288 verbose(env, " should have been in %s\n", tn_buf);
7292 if (!tnum_is_unknown(enforce_attach_type_range) &&
7293 tnum_in(enforce_attach_type_range, reg->var_off))
7294 env->prog->enforce_expected_attach_type = 1;
7298 /* non-recursive DFS pseudo code
7299 * 1 procedure DFS-iterative(G,v):
7300 * 2 label v as discovered
7301 * 3 let S be a stack
7303 * 5 while S is not empty
7305 * 7 if t is what we're looking for:
7307 * 9 for all edges e in G.adjacentEdges(t) do
7308 * 10 if edge e is already labelled
7309 * 11 continue with the next edge
7310 * 12 w <- G.adjacentVertex(t,e)
7311 * 13 if vertex w is not discovered and not explored
7312 * 14 label e as tree-edge
7313 * 15 label w as discovered
7316 * 18 else if vertex w is discovered
7317 * 19 label e as back-edge
7319 * 21 // vertex w is explored
7320 * 22 label e as forward- or cross-edge
7321 * 23 label t as explored
7326 * 0x11 - discovered and fall-through edge labelled
7327 * 0x12 - discovered and fall-through and branch edges labelled
7338 static u32 state_htab_size(struct bpf_verifier_env *env)
7340 return env->prog->len;
7343 static struct bpf_verifier_state_list **explored_state(
7344 struct bpf_verifier_env *env,
7347 struct bpf_verifier_state *cur = env->cur_state;
7348 struct bpf_func_state *state = cur->frame[cur->curframe];
7350 return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
7353 static void init_explored_state(struct bpf_verifier_env *env, int idx)
7355 env->insn_aux_data[idx].prune_point = true;
7358 /* t, w, e - match pseudo-code above:
7359 * t - index of current instruction
7360 * w - next instruction
7363 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
7366 int *insn_stack = env->cfg.insn_stack;
7367 int *insn_state = env->cfg.insn_state;
7369 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
7372 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
7375 if (w < 0 || w >= env->prog->len) {
7376 verbose_linfo(env, t, "%d: ", t);
7377 verbose(env, "jump out of range from insn %d to %d\n", t, w);
7382 /* mark branch target for state pruning */
7383 init_explored_state(env, w);
7385 if (insn_state[w] == 0) {
7387 insn_state[t] = DISCOVERED | e;
7388 insn_state[w] = DISCOVERED;
7389 if (env->cfg.cur_stack >= env->prog->len)
7391 insn_stack[env->cfg.cur_stack++] = w;
7393 } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
7394 if (loop_ok && env->bpf_capable)
7396 verbose_linfo(env, t, "%d: ", t);
7397 verbose_linfo(env, w, "%d: ", w);
7398 verbose(env, "back-edge from insn %d to %d\n", t, w);
7400 } else if (insn_state[w] == EXPLORED) {
7401 /* forward- or cross-edge */
7402 insn_state[t] = DISCOVERED | e;
7404 verbose(env, "insn state internal bug\n");
7410 /* non-recursive depth-first-search to detect loops in BPF program
7411 * loop == back-edge in directed graph
7413 static int check_cfg(struct bpf_verifier_env *env)
7415 struct bpf_insn *insns = env->prog->insnsi;
7416 int insn_cnt = env->prog->len;
7417 int *insn_stack, *insn_state;
7421 insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
7425 insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
7431 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
7432 insn_stack[0] = 0; /* 0 is the first instruction */
7433 env->cfg.cur_stack = 1;
7436 if (env->cfg.cur_stack == 0)
7438 t = insn_stack[env->cfg.cur_stack - 1];
7440 if (BPF_CLASS(insns[t].code) == BPF_JMP ||
7441 BPF_CLASS(insns[t].code) == BPF_JMP32) {
7442 u8 opcode = BPF_OP(insns[t].code);
7444 if (opcode == BPF_EXIT) {
7446 } else if (opcode == BPF_CALL) {
7447 ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
7452 if (t + 1 < insn_cnt)
7453 init_explored_state(env, t + 1);
7454 if (insns[t].src_reg == BPF_PSEUDO_CALL) {
7455 init_explored_state(env, t);
7456 ret = push_insn(t, t + insns[t].imm + 1, BRANCH,
7463 } else if (opcode == BPF_JA) {
7464 if (BPF_SRC(insns[t].code) != BPF_K) {
7468 /* unconditional jump with single edge */
7469 ret = push_insn(t, t + insns[t].off + 1,
7470 FALLTHROUGH, env, true);
7475 /* unconditional jmp is not a good pruning point,
7476 * but it's marked, since backtracking needs
7477 * to record jmp history in is_state_visited().
7479 init_explored_state(env, t + insns[t].off + 1);
7480 /* tell verifier to check for equivalent states
7481 * after every call and jump
7483 if (t + 1 < insn_cnt)
7484 init_explored_state(env, t + 1);
7486 /* conditional jump with two edges */
7487 init_explored_state(env, t);
7488 ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
7494 ret = push_insn(t, t + insns[t].off + 1, BRANCH, env, true);
7501 /* all other non-branch instructions with single
7504 ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
7512 insn_state[t] = EXPLORED;
7513 if (env->cfg.cur_stack-- <= 0) {
7514 verbose(env, "pop stack internal bug\n");
7521 for (i = 0; i < insn_cnt; i++) {
7522 if (insn_state[i] != EXPLORED) {
7523 verbose(env, "unreachable insn %d\n", i);
7528 ret = 0; /* cfg looks good */
7533 env->cfg.insn_state = env->cfg.insn_stack = NULL;
7537 /* The minimum supported BTF func info size */
7538 #define MIN_BPF_FUNCINFO_SIZE 8
7539 #define MAX_FUNCINFO_REC_SIZE 252
7541 static int check_btf_func(struct bpf_verifier_env *env,
7542 const union bpf_attr *attr,
7543 union bpf_attr __user *uattr)
7545 u32 i, nfuncs, urec_size, min_size;
7546 u32 krec_size = sizeof(struct bpf_func_info);
7547 struct bpf_func_info *krecord;
7548 struct bpf_func_info_aux *info_aux = NULL;
7549 const struct btf_type *type;
7550 struct bpf_prog *prog;
7551 const struct btf *btf;
7552 void __user *urecord;
7553 u32 prev_offset = 0;
7556 nfuncs = attr->func_info_cnt;
7560 if (nfuncs != env->subprog_cnt) {
7561 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
7565 urec_size = attr->func_info_rec_size;
7566 if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
7567 urec_size > MAX_FUNCINFO_REC_SIZE ||
7568 urec_size % sizeof(u32)) {
7569 verbose(env, "invalid func info rec size %u\n", urec_size);
7574 btf = prog->aux->btf;
7576 urecord = u64_to_user_ptr(attr->func_info);
7577 min_size = min_t(u32, krec_size, urec_size);
7579 krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
7582 info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
7586 for (i = 0; i < nfuncs; i++) {
7587 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
7589 if (ret == -E2BIG) {
7590 verbose(env, "nonzero tailing record in func info");
7591 /* set the size kernel expects so loader can zero
7592 * out the rest of the record.
7594 if (put_user(min_size, &uattr->func_info_rec_size))
7600 if (copy_from_user(&krecord[i], urecord, min_size)) {
7605 /* check insn_off */
7607 if (krecord[i].insn_off) {
7609 "nonzero insn_off %u for the first func info record",
7610 krecord[i].insn_off);
7614 } else if (krecord[i].insn_off <= prev_offset) {
7616 "same or smaller insn offset (%u) than previous func info record (%u)",
7617 krecord[i].insn_off, prev_offset);
7622 if (env->subprog_info[i].start != krecord[i].insn_off) {
7623 verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
7629 type = btf_type_by_id(btf, krecord[i].type_id);
7630 if (!type || !btf_type_is_func(type)) {
7631 verbose(env, "invalid type id %d in func info",
7632 krecord[i].type_id);
7636 info_aux[i].linkage = BTF_INFO_VLEN(type->info);
7637 prev_offset = krecord[i].insn_off;
7638 urecord += urec_size;
7641 prog->aux->func_info = krecord;
7642 prog->aux->func_info_cnt = nfuncs;
7643 prog->aux->func_info_aux = info_aux;
7652 static void adjust_btf_func(struct bpf_verifier_env *env)
7654 struct bpf_prog_aux *aux = env->prog->aux;
7657 if (!aux->func_info)
7660 for (i = 0; i < env->subprog_cnt; i++)
7661 aux->func_info[i].insn_off = env->subprog_info[i].start;
7664 #define MIN_BPF_LINEINFO_SIZE (offsetof(struct bpf_line_info, line_col) + \
7665 sizeof(((struct bpf_line_info *)(0))->line_col))
7666 #define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE
7668 static int check_btf_line(struct bpf_verifier_env *env,
7669 const union bpf_attr *attr,
7670 union bpf_attr __user *uattr)
7672 u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
7673 struct bpf_subprog_info *sub;
7674 struct bpf_line_info *linfo;
7675 struct bpf_prog *prog;
7676 const struct btf *btf;
7677 void __user *ulinfo;
7680 nr_linfo = attr->line_info_cnt;
7684 rec_size = attr->line_info_rec_size;
7685 if (rec_size < MIN_BPF_LINEINFO_SIZE ||
7686 rec_size > MAX_LINEINFO_REC_SIZE ||
7687 rec_size & (sizeof(u32) - 1))
7690 /* Need to zero it in case the userspace may
7691 * pass in a smaller bpf_line_info object.
7693 linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
7694 GFP_KERNEL | __GFP_NOWARN);
7699 btf = prog->aux->btf;
7702 sub = env->subprog_info;
7703 ulinfo = u64_to_user_ptr(attr->line_info);
7704 expected_size = sizeof(struct bpf_line_info);
7705 ncopy = min_t(u32, expected_size, rec_size);
7706 for (i = 0; i < nr_linfo; i++) {
7707 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
7709 if (err == -E2BIG) {
7710 verbose(env, "nonzero tailing record in line_info");
7711 if (put_user(expected_size,
7712 &uattr->line_info_rec_size))
7718 if (copy_from_user(&linfo[i], ulinfo, ncopy)) {
7724 * Check insn_off to ensure
7725 * 1) strictly increasing AND
7726 * 2) bounded by prog->len
7728 * The linfo[0].insn_off == 0 check logically falls into
7729 * the later "missing bpf_line_info for func..." case
7730 * because the first linfo[0].insn_off must be the
7731 * first sub also and the first sub must have
7732 * subprog_info[0].start == 0.
7734 if ((i && linfo[i].insn_off <= prev_offset) ||
7735 linfo[i].insn_off >= prog->len) {
7736 verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
7737 i, linfo[i].insn_off, prev_offset,
7743 if (!prog->insnsi[linfo[i].insn_off].code) {
7745 "Invalid insn code at line_info[%u].insn_off\n",
7751 if (!btf_name_by_offset(btf, linfo[i].line_off) ||
7752 !btf_name_by_offset(btf, linfo[i].file_name_off)) {
7753 verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
7758 if (s != env->subprog_cnt) {
7759 if (linfo[i].insn_off == sub[s].start) {
7760 sub[s].linfo_idx = i;
7762 } else if (sub[s].start < linfo[i].insn_off) {
7763 verbose(env, "missing bpf_line_info for func#%u\n", s);
7769 prev_offset = linfo[i].insn_off;
7773 if (s != env->subprog_cnt) {
7774 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
7775 env->subprog_cnt - s, s);
7780 prog->aux->linfo = linfo;
7781 prog->aux->nr_linfo = nr_linfo;
7790 static int check_btf_info(struct bpf_verifier_env *env,
7791 const union bpf_attr *attr,
7792 union bpf_attr __user *uattr)
7797 if (!attr->func_info_cnt && !attr->line_info_cnt)
7800 btf = btf_get_by_fd(attr->prog_btf_fd);
7802 return PTR_ERR(btf);
7803 env->prog->aux->btf = btf;
7805 err = check_btf_func(env, attr, uattr);
7809 err = check_btf_line(env, attr, uattr);
7816 /* check %cur's range satisfies %old's */
7817 static bool range_within(struct bpf_reg_state *old,
7818 struct bpf_reg_state *cur)
7820 return old->umin_value <= cur->umin_value &&
7821 old->umax_value >= cur->umax_value &&
7822 old->smin_value <= cur->smin_value &&
7823 old->smax_value >= cur->smax_value;
7826 /* Maximum number of register states that can exist at once */
7827 #define ID_MAP_SIZE (MAX_BPF_REG + MAX_BPF_STACK / BPF_REG_SIZE)
7833 /* If in the old state two registers had the same id, then they need to have
7834 * the same id in the new state as well. But that id could be different from
7835 * the old state, so we need to track the mapping from old to new ids.
7836 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
7837 * regs with old id 5 must also have new id 9 for the new state to be safe. But
7838 * regs with a different old id could still have new id 9, we don't care about
7840 * So we look through our idmap to see if this old id has been seen before. If
7841 * so, we require the new id to match; otherwise, we add the id pair to the map.
7843 static bool check_ids(u32 old_id, u32 cur_id, struct idpair *idmap)
7847 for (i = 0; i < ID_MAP_SIZE; i++) {
7848 if (!idmap[i].old) {
7849 /* Reached an empty slot; haven't seen this id before */
7850 idmap[i].old = old_id;
7851 idmap[i].cur = cur_id;
7854 if (idmap[i].old == old_id)
7855 return idmap[i].cur == cur_id;
7857 /* We ran out of idmap slots, which should be impossible */
7862 static void clean_func_state(struct bpf_verifier_env *env,
7863 struct bpf_func_state *st)
7865 enum bpf_reg_liveness live;
7868 for (i = 0; i < BPF_REG_FP; i++) {
7869 live = st->regs[i].live;
7870 /* liveness must not touch this register anymore */
7871 st->regs[i].live |= REG_LIVE_DONE;
7872 if (!(live & REG_LIVE_READ))
7873 /* since the register is unused, clear its state
7874 * to make further comparison simpler
7876 __mark_reg_not_init(env, &st->regs[i]);
7879 for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
7880 live = st->stack[i].spilled_ptr.live;
7881 /* liveness must not touch this stack slot anymore */
7882 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
7883 if (!(live & REG_LIVE_READ)) {
7884 __mark_reg_not_init(env, &st->stack[i].spilled_ptr);
7885 for (j = 0; j < BPF_REG_SIZE; j++)
7886 st->stack[i].slot_type[j] = STACK_INVALID;
7891 static void clean_verifier_state(struct bpf_verifier_env *env,
7892 struct bpf_verifier_state *st)
7896 if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
7897 /* all regs in this state in all frames were already marked */
7900 for (i = 0; i <= st->curframe; i++)
7901 clean_func_state(env, st->frame[i]);
7904 /* the parentage chains form a tree.
7905 * the verifier states are added to state lists at given insn and
7906 * pushed into state stack for future exploration.
7907 * when the verifier reaches bpf_exit insn some of the verifer states
7908 * stored in the state lists have their final liveness state already,
7909 * but a lot of states will get revised from liveness point of view when
7910 * the verifier explores other branches.
7913 * 2: if r1 == 100 goto pc+1
7916 * when the verifier reaches exit insn the register r0 in the state list of
7917 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
7918 * of insn 2 and goes exploring further. At the insn 4 it will walk the
7919 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
7921 * Since the verifier pushes the branch states as it sees them while exploring
7922 * the program the condition of walking the branch instruction for the second
7923 * time means that all states below this branch were already explored and
7924 * their final liveness markes are already propagated.
7925 * Hence when the verifier completes the search of state list in is_state_visited()
7926 * we can call this clean_live_states() function to mark all liveness states
7927 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
7929 * This function also clears the registers and stack for states that !READ
7930 * to simplify state merging.
7932 * Important note here that walking the same branch instruction in the callee
7933 * doesn't meant that the states are DONE. The verifier has to compare
7936 static void clean_live_states(struct bpf_verifier_env *env, int insn,
7937 struct bpf_verifier_state *cur)
7939 struct bpf_verifier_state_list *sl;
7942 sl = *explored_state(env, insn);
7944 if (sl->state.branches)
7946 if (sl->state.insn_idx != insn ||
7947 sl->state.curframe != cur->curframe)
7949 for (i = 0; i <= cur->curframe; i++)
7950 if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
7952 clean_verifier_state(env, &sl->state);
7958 /* Returns true if (rold safe implies rcur safe) */
7959 static bool regsafe(struct bpf_reg_state *rold, struct bpf_reg_state *rcur,
7960 struct idpair *idmap)
7964 if (!(rold->live & REG_LIVE_READ))
7965 /* explored state didn't use this */
7968 equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, parent)) == 0;
7970 if (rold->type == PTR_TO_STACK)
7971 /* two stack pointers are equal only if they're pointing to
7972 * the same stack frame, since fp-8 in foo != fp-8 in bar
7974 return equal && rold->frameno == rcur->frameno;
7979 if (rold->type == NOT_INIT)
7980 /* explored state can't have used this */
7982 if (rcur->type == NOT_INIT)
7984 switch (rold->type) {
7986 if (rcur->type == SCALAR_VALUE) {
7987 if (!rold->precise && !rcur->precise)
7989 /* new val must satisfy old val knowledge */
7990 return range_within(rold, rcur) &&
7991 tnum_in(rold->var_off, rcur->var_off);
7993 /* We're trying to use a pointer in place of a scalar.
7994 * Even if the scalar was unbounded, this could lead to
7995 * pointer leaks because scalars are allowed to leak
7996 * while pointers are not. We could make this safe in
7997 * special cases if root is calling us, but it's
7998 * probably not worth the hassle.
8002 case PTR_TO_MAP_VALUE:
8003 /* If the new min/max/var_off satisfy the old ones and
8004 * everything else matches, we are OK.
8005 * 'id' is not compared, since it's only used for maps with
8006 * bpf_spin_lock inside map element and in such cases if
8007 * the rest of the prog is valid for one map element then
8008 * it's valid for all map elements regardless of the key
8009 * used in bpf_map_lookup()
8011 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
8012 range_within(rold, rcur) &&
8013 tnum_in(rold->var_off, rcur->var_off);
8014 case PTR_TO_MAP_VALUE_OR_NULL:
8015 /* a PTR_TO_MAP_VALUE could be safe to use as a
8016 * PTR_TO_MAP_VALUE_OR_NULL into the same map.
8017 * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
8018 * checked, doing so could have affected others with the same
8019 * id, and we can't check for that because we lost the id when
8020 * we converted to a PTR_TO_MAP_VALUE.
8022 if (rcur->type != PTR_TO_MAP_VALUE_OR_NULL)
8024 if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
8026 /* Check our ids match any regs they're supposed to */
8027 return check_ids(rold->id, rcur->id, idmap);
8028 case PTR_TO_PACKET_META:
8030 if (rcur->type != rold->type)
8032 /* We must have at least as much range as the old ptr
8033 * did, so that any accesses which were safe before are
8034 * still safe. This is true even if old range < old off,
8035 * since someone could have accessed through (ptr - k), or
8036 * even done ptr -= k in a register, to get a safe access.
8038 if (rold->range > rcur->range)
8040 /* If the offsets don't match, we can't trust our alignment;
8041 * nor can we be sure that we won't fall out of range.
8043 if (rold->off != rcur->off)
8045 /* id relations must be preserved */
8046 if (rold->id && !check_ids(rold->id, rcur->id, idmap))
8048 /* new val must satisfy old val knowledge */
8049 return range_within(rold, rcur) &&
8050 tnum_in(rold->var_off, rcur->var_off);
8052 case CONST_PTR_TO_MAP:
8053 case PTR_TO_PACKET_END:
8054 case PTR_TO_FLOW_KEYS:
8056 case PTR_TO_SOCKET_OR_NULL:
8057 case PTR_TO_SOCK_COMMON:
8058 case PTR_TO_SOCK_COMMON_OR_NULL:
8059 case PTR_TO_TCP_SOCK:
8060 case PTR_TO_TCP_SOCK_OR_NULL:
8061 case PTR_TO_XDP_SOCK:
8062 /* Only valid matches are exact, which memcmp() above
8063 * would have accepted
8066 /* Don't know what's going on, just say it's not safe */
8070 /* Shouldn't get here; if we do, say it's not safe */
8075 static bool stacksafe(struct bpf_func_state *old,
8076 struct bpf_func_state *cur,
8077 struct idpair *idmap)
8081 /* walk slots of the explored stack and ignore any additional
8082 * slots in the current stack, since explored(safe) state
8085 for (i = 0; i < old->allocated_stack; i++) {
8086 spi = i / BPF_REG_SIZE;
8088 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
8089 i += BPF_REG_SIZE - 1;
8090 /* explored state didn't use this */
8094 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
8097 /* explored stack has more populated slots than current stack
8098 * and these slots were used
8100 if (i >= cur->allocated_stack)
8103 /* if old state was safe with misc data in the stack
8104 * it will be safe with zero-initialized stack.
8105 * The opposite is not true
8107 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
8108 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
8110 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
8111 cur->stack[spi].slot_type[i % BPF_REG_SIZE])
8112 /* Ex: old explored (safe) state has STACK_SPILL in
8113 * this stack slot, but current has has STACK_MISC ->
8114 * this verifier states are not equivalent,
8115 * return false to continue verification of this path
8118 if (i % BPF_REG_SIZE)
8120 if (old->stack[spi].slot_type[0] != STACK_SPILL)
8122 if (!regsafe(&old->stack[spi].spilled_ptr,
8123 &cur->stack[spi].spilled_ptr,
8125 /* when explored and current stack slot are both storing
8126 * spilled registers, check that stored pointers types
8127 * are the same as well.
8128 * Ex: explored safe path could have stored
8129 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
8130 * but current path has stored:
8131 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
8132 * such verifier states are not equivalent.
8133 * return false to continue verification of this path
8140 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur)
8142 if (old->acquired_refs != cur->acquired_refs)
8144 return !memcmp(old->refs, cur->refs,
8145 sizeof(*old->refs) * old->acquired_refs);
8148 /* compare two verifier states
8150 * all states stored in state_list are known to be valid, since
8151 * verifier reached 'bpf_exit' instruction through them
8153 * this function is called when verifier exploring different branches of
8154 * execution popped from the state stack. If it sees an old state that has
8155 * more strict register state and more strict stack state then this execution
8156 * branch doesn't need to be explored further, since verifier already
8157 * concluded that more strict state leads to valid finish.
8159 * Therefore two states are equivalent if register state is more conservative
8160 * and explored stack state is more conservative than the current one.
8163 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
8164 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
8166 * In other words if current stack state (one being explored) has more
8167 * valid slots than old one that already passed validation, it means
8168 * the verifier can stop exploring and conclude that current state is valid too
8170 * Similarly with registers. If explored state has register type as invalid
8171 * whereas register type in current state is meaningful, it means that
8172 * the current state will reach 'bpf_exit' instruction safely
8174 static bool func_states_equal(struct bpf_func_state *old,
8175 struct bpf_func_state *cur)
8177 struct idpair *idmap;
8181 idmap = kcalloc(ID_MAP_SIZE, sizeof(struct idpair), GFP_KERNEL);
8182 /* If we failed to allocate the idmap, just say it's not safe */
8186 for (i = 0; i < MAX_BPF_REG; i++) {
8187 if (!regsafe(&old->regs[i], &cur->regs[i], idmap))
8191 if (!stacksafe(old, cur, idmap))
8194 if (!refsafe(old, cur))
8202 static bool states_equal(struct bpf_verifier_env *env,
8203 struct bpf_verifier_state *old,
8204 struct bpf_verifier_state *cur)
8208 if (old->curframe != cur->curframe)
8211 /* Verification state from speculative execution simulation
8212 * must never prune a non-speculative execution one.
8214 if (old->speculative && !cur->speculative)
8217 if (old->active_spin_lock != cur->active_spin_lock)
8220 /* for states to be equal callsites have to be the same
8221 * and all frame states need to be equivalent
8223 for (i = 0; i <= old->curframe; i++) {
8224 if (old->frame[i]->callsite != cur->frame[i]->callsite)
8226 if (!func_states_equal(old->frame[i], cur->frame[i]))
8232 /* Return 0 if no propagation happened. Return negative error code if error
8233 * happened. Otherwise, return the propagated bit.
8235 static int propagate_liveness_reg(struct bpf_verifier_env *env,
8236 struct bpf_reg_state *reg,
8237 struct bpf_reg_state *parent_reg)
8239 u8 parent_flag = parent_reg->live & REG_LIVE_READ;
8240 u8 flag = reg->live & REG_LIVE_READ;
8243 /* When comes here, read flags of PARENT_REG or REG could be any of
8244 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
8245 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
8247 if (parent_flag == REG_LIVE_READ64 ||
8248 /* Or if there is no read flag from REG. */
8250 /* Or if the read flag from REG is the same as PARENT_REG. */
8251 parent_flag == flag)
8254 err = mark_reg_read(env, reg, parent_reg, flag);
8261 /* A write screens off any subsequent reads; but write marks come from the
8262 * straight-line code between a state and its parent. When we arrive at an
8263 * equivalent state (jump target or such) we didn't arrive by the straight-line
8264 * code, so read marks in the state must propagate to the parent regardless
8265 * of the state's write marks. That's what 'parent == state->parent' comparison
8266 * in mark_reg_read() is for.
8268 static int propagate_liveness(struct bpf_verifier_env *env,
8269 const struct bpf_verifier_state *vstate,
8270 struct bpf_verifier_state *vparent)
8272 struct bpf_reg_state *state_reg, *parent_reg;
8273 struct bpf_func_state *state, *parent;
8274 int i, frame, err = 0;
8276 if (vparent->curframe != vstate->curframe) {
8277 WARN(1, "propagate_live: parent frame %d current frame %d\n",
8278 vparent->curframe, vstate->curframe);
8281 /* Propagate read liveness of registers... */
8282 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
8283 for (frame = 0; frame <= vstate->curframe; frame++) {
8284 parent = vparent->frame[frame];
8285 state = vstate->frame[frame];
8286 parent_reg = parent->regs;
8287 state_reg = state->regs;
8288 /* We don't need to worry about FP liveness, it's read-only */
8289 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
8290 err = propagate_liveness_reg(env, &state_reg[i],
8294 if (err == REG_LIVE_READ64)
8295 mark_insn_zext(env, &parent_reg[i]);
8298 /* Propagate stack slots. */
8299 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
8300 i < parent->allocated_stack / BPF_REG_SIZE; i++) {
8301 parent_reg = &parent->stack[i].spilled_ptr;
8302 state_reg = &state->stack[i].spilled_ptr;
8303 err = propagate_liveness_reg(env, state_reg,
8312 /* find precise scalars in the previous equivalent state and
8313 * propagate them into the current state
8315 static int propagate_precision(struct bpf_verifier_env *env,
8316 const struct bpf_verifier_state *old)
8318 struct bpf_reg_state *state_reg;
8319 struct bpf_func_state *state;
8322 state = old->frame[old->curframe];
8323 state_reg = state->regs;
8324 for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
8325 if (state_reg->type != SCALAR_VALUE ||
8326 !state_reg->precise)
8328 if (env->log.level & BPF_LOG_LEVEL2)
8329 verbose(env, "propagating r%d\n", i);
8330 err = mark_chain_precision(env, i);
8335 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
8336 if (state->stack[i].slot_type[0] != STACK_SPILL)
8338 state_reg = &state->stack[i].spilled_ptr;
8339 if (state_reg->type != SCALAR_VALUE ||
8340 !state_reg->precise)
8342 if (env->log.level & BPF_LOG_LEVEL2)
8343 verbose(env, "propagating fp%d\n",
8344 (-i - 1) * BPF_REG_SIZE);
8345 err = mark_chain_precision_stack(env, i);
8352 static bool states_maybe_looping(struct bpf_verifier_state *old,
8353 struct bpf_verifier_state *cur)
8355 struct bpf_func_state *fold, *fcur;
8356 int i, fr = cur->curframe;
8358 if (old->curframe != fr)
8361 fold = old->frame[fr];
8362 fcur = cur->frame[fr];
8363 for (i = 0; i < MAX_BPF_REG; i++)
8364 if (memcmp(&fold->regs[i], &fcur->regs[i],
8365 offsetof(struct bpf_reg_state, parent)))
8371 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
8373 struct bpf_verifier_state_list *new_sl;
8374 struct bpf_verifier_state_list *sl, **pprev;
8375 struct bpf_verifier_state *cur = env->cur_state, *new;
8376 int i, j, err, states_cnt = 0;
8377 bool add_new_state = env->test_state_freq ? true : false;
8379 cur->last_insn_idx = env->prev_insn_idx;
8380 if (!env->insn_aux_data[insn_idx].prune_point)
8381 /* this 'insn_idx' instruction wasn't marked, so we will not
8382 * be doing state search here
8386 /* bpf progs typically have pruning point every 4 instructions
8387 * http://vger.kernel.org/bpfconf2019.html#session-1
8388 * Do not add new state for future pruning if the verifier hasn't seen
8389 * at least 2 jumps and at least 8 instructions.
8390 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
8391 * In tests that amounts to up to 50% reduction into total verifier
8392 * memory consumption and 20% verifier time speedup.
8394 if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
8395 env->insn_processed - env->prev_insn_processed >= 8)
8396 add_new_state = true;
8398 pprev = explored_state(env, insn_idx);
8401 clean_live_states(env, insn_idx, cur);
8405 if (sl->state.insn_idx != insn_idx)
8407 if (sl->state.branches) {
8408 if (states_maybe_looping(&sl->state, cur) &&
8409 states_equal(env, &sl->state, cur)) {
8410 verbose_linfo(env, insn_idx, "; ");
8411 verbose(env, "infinite loop detected at insn %d\n", insn_idx);
8414 /* if the verifier is processing a loop, avoid adding new state
8415 * too often, since different loop iterations have distinct
8416 * states and may not help future pruning.
8417 * This threshold shouldn't be too low to make sure that
8418 * a loop with large bound will be rejected quickly.
8419 * The most abusive loop will be:
8421 * if r1 < 1000000 goto pc-2
8422 * 1M insn_procssed limit / 100 == 10k peak states.
8423 * This threshold shouldn't be too high either, since states
8424 * at the end of the loop are likely to be useful in pruning.
8426 if (env->jmps_processed - env->prev_jmps_processed < 20 &&
8427 env->insn_processed - env->prev_insn_processed < 100)
8428 add_new_state = false;
8431 if (states_equal(env, &sl->state, cur)) {
8433 /* reached equivalent register/stack state,
8435 * Registers read by the continuation are read by us.
8436 * If we have any write marks in env->cur_state, they
8437 * will prevent corresponding reads in the continuation
8438 * from reaching our parent (an explored_state). Our
8439 * own state will get the read marks recorded, but
8440 * they'll be immediately forgotten as we're pruning
8441 * this state and will pop a new one.
8443 err = propagate_liveness(env, &sl->state, cur);
8445 /* if previous state reached the exit with precision and
8446 * current state is equivalent to it (except precsion marks)
8447 * the precision needs to be propagated back in
8448 * the current state.
8450 err = err ? : push_jmp_history(env, cur);
8451 err = err ? : propagate_precision(env, &sl->state);
8457 /* when new state is not going to be added do not increase miss count.
8458 * Otherwise several loop iterations will remove the state
8459 * recorded earlier. The goal of these heuristics is to have
8460 * states from some iterations of the loop (some in the beginning
8461 * and some at the end) to help pruning.
8465 /* heuristic to determine whether this state is beneficial
8466 * to keep checking from state equivalence point of view.
8467 * Higher numbers increase max_states_per_insn and verification time,
8468 * but do not meaningfully decrease insn_processed.
8470 if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
8471 /* the state is unlikely to be useful. Remove it to
8472 * speed up verification
8475 if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
8476 u32 br = sl->state.branches;
8479 "BUG live_done but branches_to_explore %d\n",
8481 free_verifier_state(&sl->state, false);
8485 /* cannot free this state, since parentage chain may
8486 * walk it later. Add it for free_list instead to
8487 * be freed at the end of verification
8489 sl->next = env->free_list;
8490 env->free_list = sl;
8500 if (env->max_states_per_insn < states_cnt)
8501 env->max_states_per_insn = states_cnt;
8503 if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
8504 return push_jmp_history(env, cur);
8507 return push_jmp_history(env, cur);
8509 /* There were no equivalent states, remember the current one.
8510 * Technically the current state is not proven to be safe yet,
8511 * but it will either reach outer most bpf_exit (which means it's safe)
8512 * or it will be rejected. When there are no loops the verifier won't be
8513 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
8514 * again on the way to bpf_exit.
8515 * When looping the sl->state.branches will be > 0 and this state
8516 * will not be considered for equivalence until branches == 0.
8518 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
8521 env->total_states++;
8523 env->prev_jmps_processed = env->jmps_processed;
8524 env->prev_insn_processed = env->insn_processed;
8526 /* add new state to the head of linked list */
8527 new = &new_sl->state;
8528 err = copy_verifier_state(new, cur);
8530 free_verifier_state(new, false);
8534 new->insn_idx = insn_idx;
8535 WARN_ONCE(new->branches != 1,
8536 "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
8539 cur->first_insn_idx = insn_idx;
8540 clear_jmp_history(cur);
8541 new_sl->next = *explored_state(env, insn_idx);
8542 *explored_state(env, insn_idx) = new_sl;
8543 /* connect new state to parentage chain. Current frame needs all
8544 * registers connected. Only r6 - r9 of the callers are alive (pushed
8545 * to the stack implicitly by JITs) so in callers' frames connect just
8546 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
8547 * the state of the call instruction (with WRITTEN set), and r0 comes
8548 * from callee with its full parentage chain, anyway.
8550 /* clear write marks in current state: the writes we did are not writes
8551 * our child did, so they don't screen off its reads from us.
8552 * (There are no read marks in current state, because reads always mark
8553 * their parent and current state never has children yet. Only
8554 * explored_states can get read marks.)
8556 for (j = 0; j <= cur->curframe; j++) {
8557 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
8558 cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
8559 for (i = 0; i < BPF_REG_FP; i++)
8560 cur->frame[j]->regs[i].live = REG_LIVE_NONE;
8563 /* all stack frames are accessible from callee, clear them all */
8564 for (j = 0; j <= cur->curframe; j++) {
8565 struct bpf_func_state *frame = cur->frame[j];
8566 struct bpf_func_state *newframe = new->frame[j];
8568 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
8569 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
8570 frame->stack[i].spilled_ptr.parent =
8571 &newframe->stack[i].spilled_ptr;
8577 /* Return true if it's OK to have the same insn return a different type. */
8578 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
8583 case PTR_TO_SOCKET_OR_NULL:
8584 case PTR_TO_SOCK_COMMON:
8585 case PTR_TO_SOCK_COMMON_OR_NULL:
8586 case PTR_TO_TCP_SOCK:
8587 case PTR_TO_TCP_SOCK_OR_NULL:
8588 case PTR_TO_XDP_SOCK:
8590 case PTR_TO_BTF_ID_OR_NULL:
8597 /* If an instruction was previously used with particular pointer types, then we
8598 * need to be careful to avoid cases such as the below, where it may be ok
8599 * for one branch accessing the pointer, but not ok for the other branch:
8604 * R1 = some_other_valid_ptr;
8607 * R2 = *(u32 *)(R1 + 0);
8609 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
8611 return src != prev && (!reg_type_mismatch_ok(src) ||
8612 !reg_type_mismatch_ok(prev));
8615 static int do_check(struct bpf_verifier_env *env)
8617 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
8618 struct bpf_verifier_state *state = env->cur_state;
8619 struct bpf_insn *insns = env->prog->insnsi;
8620 struct bpf_reg_state *regs;
8621 int insn_cnt = env->prog->len;
8622 bool do_print_state = false;
8623 int prev_insn_idx = -1;
8626 struct bpf_insn *insn;
8630 env->prev_insn_idx = prev_insn_idx;
8631 if (env->insn_idx >= insn_cnt) {
8632 verbose(env, "invalid insn idx %d insn_cnt %d\n",
8633 env->insn_idx, insn_cnt);
8637 insn = &insns[env->insn_idx];
8638 class = BPF_CLASS(insn->code);
8640 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
8642 "BPF program is too large. Processed %d insn\n",
8643 env->insn_processed);
8647 err = is_state_visited(env, env->insn_idx);
8651 /* found equivalent state, can prune the search */
8652 if (env->log.level & BPF_LOG_LEVEL) {
8654 verbose(env, "\nfrom %d to %d%s: safe\n",
8655 env->prev_insn_idx, env->insn_idx,
8656 env->cur_state->speculative ?
8657 " (speculative execution)" : "");
8659 verbose(env, "%d: safe\n", env->insn_idx);
8661 goto process_bpf_exit;
8664 if (signal_pending(current))
8670 if (env->log.level & BPF_LOG_LEVEL2 ||
8671 (env->log.level & BPF_LOG_LEVEL && do_print_state)) {
8672 if (env->log.level & BPF_LOG_LEVEL2)
8673 verbose(env, "%d:", env->insn_idx);
8675 verbose(env, "\nfrom %d to %d%s:",
8676 env->prev_insn_idx, env->insn_idx,
8677 env->cur_state->speculative ?
8678 " (speculative execution)" : "");
8679 print_verifier_state(env, state->frame[state->curframe]);
8680 do_print_state = false;
8683 if (env->log.level & BPF_LOG_LEVEL) {
8684 const struct bpf_insn_cbs cbs = {
8685 .cb_print = verbose,
8686 .private_data = env,
8689 verbose_linfo(env, env->insn_idx, "; ");
8690 verbose(env, "%d: ", env->insn_idx);
8691 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
8694 if (bpf_prog_is_dev_bound(env->prog->aux)) {
8695 err = bpf_prog_offload_verify_insn(env, env->insn_idx,
8696 env->prev_insn_idx);
8701 regs = cur_regs(env);
8702 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
8703 prev_insn_idx = env->insn_idx;
8705 if (class == BPF_ALU || class == BPF_ALU64) {
8706 err = check_alu_op(env, insn);
8710 } else if (class == BPF_LDX) {
8711 enum bpf_reg_type *prev_src_type, src_reg_type;
8713 /* check for reserved fields is already done */
8715 /* check src operand */
8716 err = check_reg_arg(env, insn->src_reg, SRC_OP);
8720 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
8724 src_reg_type = regs[insn->src_reg].type;
8726 /* check that memory (src_reg + off) is readable,
8727 * the state of dst_reg will be updated by this func
8729 err = check_mem_access(env, env->insn_idx, insn->src_reg,
8730 insn->off, BPF_SIZE(insn->code),
8731 BPF_READ, insn->dst_reg, false);
8735 prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type;
8737 if (*prev_src_type == NOT_INIT) {
8739 * dst_reg = *(u32 *)(src_reg + off)
8740 * save type to validate intersecting paths
8742 *prev_src_type = src_reg_type;
8744 } else if (reg_type_mismatch(src_reg_type, *prev_src_type)) {
8745 /* ABuser program is trying to use the same insn
8746 * dst_reg = *(u32*) (src_reg + off)
8747 * with different pointer types:
8748 * src_reg == ctx in one branch and
8749 * src_reg == stack|map in some other branch.
8752 verbose(env, "same insn cannot be used with different pointers\n");
8756 } else if (class == BPF_STX) {
8757 enum bpf_reg_type *prev_dst_type, dst_reg_type;
8759 if (BPF_MODE(insn->code) == BPF_XADD) {
8760 err = check_xadd(env, env->insn_idx, insn);
8767 /* check src1 operand */
8768 err = check_reg_arg(env, insn->src_reg, SRC_OP);
8771 /* check src2 operand */
8772 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
8776 dst_reg_type = regs[insn->dst_reg].type;
8778 /* check that memory (dst_reg + off) is writeable */
8779 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
8780 insn->off, BPF_SIZE(insn->code),
8781 BPF_WRITE, insn->src_reg, false);
8785 prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type;
8787 if (*prev_dst_type == NOT_INIT) {
8788 *prev_dst_type = dst_reg_type;
8789 } else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) {
8790 verbose(env, "same insn cannot be used with different pointers\n");
8794 } else if (class == BPF_ST) {
8795 if (BPF_MODE(insn->code) != BPF_MEM ||
8796 insn->src_reg != BPF_REG_0) {
8797 verbose(env, "BPF_ST uses reserved fields\n");
8800 /* check src operand */
8801 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
8805 if (is_ctx_reg(env, insn->dst_reg)) {
8806 verbose(env, "BPF_ST stores into R%d %s is not allowed\n",
8808 reg_type_str[reg_state(env, insn->dst_reg)->type]);
8812 /* check that memory (dst_reg + off) is writeable */
8813 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
8814 insn->off, BPF_SIZE(insn->code),
8815 BPF_WRITE, -1, false);
8819 } else if (class == BPF_JMP || class == BPF_JMP32) {
8820 u8 opcode = BPF_OP(insn->code);
8822 env->jmps_processed++;
8823 if (opcode == BPF_CALL) {
8824 if (BPF_SRC(insn->code) != BPF_K ||
8826 (insn->src_reg != BPF_REG_0 &&
8827 insn->src_reg != BPF_PSEUDO_CALL) ||
8828 insn->dst_reg != BPF_REG_0 ||
8829 class == BPF_JMP32) {
8830 verbose(env, "BPF_CALL uses reserved fields\n");
8834 if (env->cur_state->active_spin_lock &&
8835 (insn->src_reg == BPF_PSEUDO_CALL ||
8836 insn->imm != BPF_FUNC_spin_unlock)) {
8837 verbose(env, "function calls are not allowed while holding a lock\n");
8840 if (insn->src_reg == BPF_PSEUDO_CALL)
8841 err = check_func_call(env, insn, &env->insn_idx);
8843 err = check_helper_call(env, insn->imm, env->insn_idx);
8847 } else if (opcode == BPF_JA) {
8848 if (BPF_SRC(insn->code) != BPF_K ||
8850 insn->src_reg != BPF_REG_0 ||
8851 insn->dst_reg != BPF_REG_0 ||
8852 class == BPF_JMP32) {
8853 verbose(env, "BPF_JA uses reserved fields\n");
8857 env->insn_idx += insn->off + 1;
8860 } else if (opcode == BPF_EXIT) {
8861 if (BPF_SRC(insn->code) != BPF_K ||
8863 insn->src_reg != BPF_REG_0 ||
8864 insn->dst_reg != BPF_REG_0 ||
8865 class == BPF_JMP32) {
8866 verbose(env, "BPF_EXIT uses reserved fields\n");
8870 if (env->cur_state->active_spin_lock) {
8871 verbose(env, "bpf_spin_unlock is missing\n");
8875 if (state->curframe) {
8876 /* exit from nested function */
8877 err = prepare_func_exit(env, &env->insn_idx);
8880 do_print_state = true;
8884 err = check_reference_leak(env);
8888 err = check_return_code(env);
8892 update_branch_counts(env, env->cur_state);
8893 err = pop_stack(env, &prev_insn_idx,
8894 &env->insn_idx, pop_log);
8900 do_print_state = true;
8904 err = check_cond_jmp_op(env, insn, &env->insn_idx);
8908 } else if (class == BPF_LD) {
8909 u8 mode = BPF_MODE(insn->code);
8911 if (mode == BPF_ABS || mode == BPF_IND) {
8912 err = check_ld_abs(env, insn);
8916 } else if (mode == BPF_IMM) {
8917 err = check_ld_imm(env, insn);
8922 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
8924 verbose(env, "invalid BPF_LD mode\n");
8928 verbose(env, "unknown insn class %d\n", class);
8938 static int check_map_prealloc(struct bpf_map *map)
8940 return (map->map_type != BPF_MAP_TYPE_HASH &&
8941 map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
8942 map->map_type != BPF_MAP_TYPE_HASH_OF_MAPS) ||
8943 !(map->map_flags & BPF_F_NO_PREALLOC);
8946 static bool is_tracing_prog_type(enum bpf_prog_type type)
8949 case BPF_PROG_TYPE_KPROBE:
8950 case BPF_PROG_TYPE_TRACEPOINT:
8951 case BPF_PROG_TYPE_PERF_EVENT:
8952 case BPF_PROG_TYPE_RAW_TRACEPOINT:
8959 static bool is_preallocated_map(struct bpf_map *map)
8961 if (!check_map_prealloc(map))
8963 if (map->inner_map_meta && !check_map_prealloc(map->inner_map_meta))
8968 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
8969 struct bpf_map *map,
8970 struct bpf_prog *prog)
8974 * Validate that trace type programs use preallocated hash maps.
8976 * For programs attached to PERF events this is mandatory as the
8977 * perf NMI can hit any arbitrary code sequence.
8979 * All other trace types using preallocated hash maps are unsafe as
8980 * well because tracepoint or kprobes can be inside locked regions
8981 * of the memory allocator or at a place where a recursion into the
8982 * memory allocator would see inconsistent state.
8984 * On RT enabled kernels run-time allocation of all trace type
8985 * programs is strictly prohibited due to lock type constraints. On
8986 * !RT kernels it is allowed for backwards compatibility reasons for
8987 * now, but warnings are emitted so developers are made aware of
8988 * the unsafety and can fix their programs before this is enforced.
8990 if (is_tracing_prog_type(prog->type) && !is_preallocated_map(map)) {
8991 if (prog->type == BPF_PROG_TYPE_PERF_EVENT) {
8992 verbose(env, "perf_event programs can only use preallocated hash map\n");
8995 if (IS_ENABLED(CONFIG_PREEMPT_RT)) {
8996 verbose(env, "trace type programs can only use preallocated hash map\n");
8999 WARN_ONCE(1, "trace type BPF program uses run-time allocation\n");
9000 verbose(env, "trace type programs with run-time allocated hash maps are unsafe. Switch to preallocated hash maps.\n");
9003 if ((is_tracing_prog_type(prog->type) ||
9004 prog->type == BPF_PROG_TYPE_SOCKET_FILTER) &&
9005 map_value_has_spin_lock(map)) {
9006 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
9010 if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) &&
9011 !bpf_offload_prog_map_match(prog, map)) {
9012 verbose(env, "offload device mismatch between prog and map\n");
9016 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
9017 verbose(env, "bpf_struct_ops map cannot be used in prog\n");
9024 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
9026 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
9027 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
9030 /* look for pseudo eBPF instructions that access map FDs and
9031 * replace them with actual map pointers
9033 static int replace_map_fd_with_map_ptr(struct bpf_verifier_env *env)
9035 struct bpf_insn *insn = env->prog->insnsi;
9036 int insn_cnt = env->prog->len;
9039 err = bpf_prog_calc_tag(env->prog);
9043 for (i = 0; i < insn_cnt; i++, insn++) {
9044 if (BPF_CLASS(insn->code) == BPF_LDX &&
9045 (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
9046 verbose(env, "BPF_LDX uses reserved fields\n");
9050 if (BPF_CLASS(insn->code) == BPF_STX &&
9051 ((BPF_MODE(insn->code) != BPF_MEM &&
9052 BPF_MODE(insn->code) != BPF_XADD) || insn->imm != 0)) {
9053 verbose(env, "BPF_STX uses reserved fields\n");
9057 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
9058 struct bpf_insn_aux_data *aux;
9059 struct bpf_map *map;
9063 if (i == insn_cnt - 1 || insn[1].code != 0 ||
9064 insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
9066 verbose(env, "invalid bpf_ld_imm64 insn\n");
9070 if (insn[0].src_reg == 0)
9071 /* valid generic load 64-bit imm */
9074 /* In final convert_pseudo_ld_imm64() step, this is
9075 * converted into regular 64-bit imm load insn.
9077 if ((insn[0].src_reg != BPF_PSEUDO_MAP_FD &&
9078 insn[0].src_reg != BPF_PSEUDO_MAP_VALUE) ||
9079 (insn[0].src_reg == BPF_PSEUDO_MAP_FD &&
9080 insn[1].imm != 0)) {
9082 "unrecognized bpf_ld_imm64 insn\n");
9086 f = fdget(insn[0].imm);
9087 map = __bpf_map_get(f);
9089 verbose(env, "fd %d is not pointing to valid bpf_map\n",
9091 return PTR_ERR(map);
9094 err = check_map_prog_compatibility(env, map, env->prog);
9100 aux = &env->insn_aux_data[i];
9101 if (insn->src_reg == BPF_PSEUDO_MAP_FD) {
9102 addr = (unsigned long)map;
9104 u32 off = insn[1].imm;
9106 if (off >= BPF_MAX_VAR_OFF) {
9107 verbose(env, "direct value offset of %u is not allowed\n", off);
9112 if (!map->ops->map_direct_value_addr) {
9113 verbose(env, "no direct value access support for this map type\n");
9118 err = map->ops->map_direct_value_addr(map, &addr, off);
9120 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
9121 map->value_size, off);
9130 insn[0].imm = (u32)addr;
9131 insn[1].imm = addr >> 32;
9133 /* check whether we recorded this map already */
9134 for (j = 0; j < env->used_map_cnt; j++) {
9135 if (env->used_maps[j] == map) {
9142 if (env->used_map_cnt >= MAX_USED_MAPS) {
9147 /* hold the map. If the program is rejected by verifier,
9148 * the map will be released by release_maps() or it
9149 * will be used by the valid program until it's unloaded
9150 * and all maps are released in free_used_maps()
9154 aux->map_index = env->used_map_cnt;
9155 env->used_maps[env->used_map_cnt++] = map;
9157 if (bpf_map_is_cgroup_storage(map) &&
9158 bpf_cgroup_storage_assign(env->prog->aux, map)) {
9159 verbose(env, "only one cgroup storage of each type is allowed\n");
9171 /* Basic sanity check before we invest more work here. */
9172 if (!bpf_opcode_in_insntable(insn->code)) {
9173 verbose(env, "unknown opcode %02x\n", insn->code);
9178 /* now all pseudo BPF_LD_IMM64 instructions load valid
9179 * 'struct bpf_map *' into a register instead of user map_fd.
9180 * These pointers will be used later by verifier to validate map access.
9185 /* drop refcnt of maps used by the rejected program */
9186 static void release_maps(struct bpf_verifier_env *env)
9188 __bpf_free_used_maps(env->prog->aux, env->used_maps,
9192 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
9193 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
9195 struct bpf_insn *insn = env->prog->insnsi;
9196 int insn_cnt = env->prog->len;
9199 for (i = 0; i < insn_cnt; i++, insn++)
9200 if (insn->code == (BPF_LD | BPF_IMM | BPF_DW))
9204 /* single env->prog->insni[off] instruction was replaced with the range
9205 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying
9206 * [0, off) and [off, end) to new locations, so the patched range stays zero
9208 static int adjust_insn_aux_data(struct bpf_verifier_env *env,
9209 struct bpf_prog *new_prog, u32 off, u32 cnt)
9211 struct bpf_insn_aux_data *new_data, *old_data = env->insn_aux_data;
9212 struct bpf_insn *insn = new_prog->insnsi;
9216 /* aux info at OFF always needs adjustment, no matter fast path
9217 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
9218 * original insn at old prog.
9220 old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
9224 prog_len = new_prog->len;
9225 new_data = vzalloc(array_size(prog_len,
9226 sizeof(struct bpf_insn_aux_data)));
9229 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
9230 memcpy(new_data + off + cnt - 1, old_data + off,
9231 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
9232 for (i = off; i < off + cnt - 1; i++) {
9233 new_data[i].seen = env->pass_cnt;
9234 new_data[i].zext_dst = insn_has_def32(env, insn + i);
9236 env->insn_aux_data = new_data;
9241 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
9247 /* NOTE: fake 'exit' subprog should be updated as well. */
9248 for (i = 0; i <= env->subprog_cnt; i++) {
9249 if (env->subprog_info[i].start <= off)
9251 env->subprog_info[i].start += len - 1;
9255 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
9256 const struct bpf_insn *patch, u32 len)
9258 struct bpf_prog *new_prog;
9260 new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
9261 if (IS_ERR(new_prog)) {
9262 if (PTR_ERR(new_prog) == -ERANGE)
9264 "insn %d cannot be patched due to 16-bit range\n",
9265 env->insn_aux_data[off].orig_idx);
9268 if (adjust_insn_aux_data(env, new_prog, off, len))
9270 adjust_subprog_starts(env, off, len);
9274 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
9279 /* find first prog starting at or after off (first to remove) */
9280 for (i = 0; i < env->subprog_cnt; i++)
9281 if (env->subprog_info[i].start >= off)
9283 /* find first prog starting at or after off + cnt (first to stay) */
9284 for (j = i; j < env->subprog_cnt; j++)
9285 if (env->subprog_info[j].start >= off + cnt)
9287 /* if j doesn't start exactly at off + cnt, we are just removing
9288 * the front of previous prog
9290 if (env->subprog_info[j].start != off + cnt)
9294 struct bpf_prog_aux *aux = env->prog->aux;
9297 /* move fake 'exit' subprog as well */
9298 move = env->subprog_cnt + 1 - j;
9300 memmove(env->subprog_info + i,
9301 env->subprog_info + j,
9302 sizeof(*env->subprog_info) * move);
9303 env->subprog_cnt -= j - i;
9305 /* remove func_info */
9306 if (aux->func_info) {
9307 move = aux->func_info_cnt - j;
9309 memmove(aux->func_info + i,
9311 sizeof(*aux->func_info) * move);
9312 aux->func_info_cnt -= j - i;
9313 /* func_info->insn_off is set after all code rewrites,
9314 * in adjust_btf_func() - no need to adjust
9318 /* convert i from "first prog to remove" to "first to adjust" */
9319 if (env->subprog_info[i].start == off)
9323 /* update fake 'exit' subprog as well */
9324 for (; i <= env->subprog_cnt; i++)
9325 env->subprog_info[i].start -= cnt;
9330 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
9333 struct bpf_prog *prog = env->prog;
9334 u32 i, l_off, l_cnt, nr_linfo;
9335 struct bpf_line_info *linfo;
9337 nr_linfo = prog->aux->nr_linfo;
9341 linfo = prog->aux->linfo;
9343 /* find first line info to remove, count lines to be removed */
9344 for (i = 0; i < nr_linfo; i++)
9345 if (linfo[i].insn_off >= off)
9350 for (; i < nr_linfo; i++)
9351 if (linfo[i].insn_off < off + cnt)
9356 /* First live insn doesn't match first live linfo, it needs to "inherit"
9357 * last removed linfo. prog is already modified, so prog->len == off
9358 * means no live instructions after (tail of the program was removed).
9360 if (prog->len != off && l_cnt &&
9361 (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
9363 linfo[--i].insn_off = off + cnt;
9366 /* remove the line info which refer to the removed instructions */
9368 memmove(linfo + l_off, linfo + i,
9369 sizeof(*linfo) * (nr_linfo - i));
9371 prog->aux->nr_linfo -= l_cnt;
9372 nr_linfo = prog->aux->nr_linfo;
9375 /* pull all linfo[i].insn_off >= off + cnt in by cnt */
9376 for (i = l_off; i < nr_linfo; i++)
9377 linfo[i].insn_off -= cnt;
9379 /* fix up all subprogs (incl. 'exit') which start >= off */
9380 for (i = 0; i <= env->subprog_cnt; i++)
9381 if (env->subprog_info[i].linfo_idx > l_off) {
9382 /* program may have started in the removed region but
9383 * may not be fully removed
9385 if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
9386 env->subprog_info[i].linfo_idx -= l_cnt;
9388 env->subprog_info[i].linfo_idx = l_off;
9394 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
9396 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
9397 unsigned int orig_prog_len = env->prog->len;
9400 if (bpf_prog_is_dev_bound(env->prog->aux))
9401 bpf_prog_offload_remove_insns(env, off, cnt);
9403 err = bpf_remove_insns(env->prog, off, cnt);
9407 err = adjust_subprog_starts_after_remove(env, off, cnt);
9411 err = bpf_adj_linfo_after_remove(env, off, cnt);
9415 memmove(aux_data + off, aux_data + off + cnt,
9416 sizeof(*aux_data) * (orig_prog_len - off - cnt));
9421 /* The verifier does more data flow analysis than llvm and will not
9422 * explore branches that are dead at run time. Malicious programs can
9423 * have dead code too. Therefore replace all dead at-run-time code
9426 * Just nops are not optimal, e.g. if they would sit at the end of the
9427 * program and through another bug we would manage to jump there, then
9428 * we'd execute beyond program memory otherwise. Returning exception
9429 * code also wouldn't work since we can have subprogs where the dead
9430 * code could be located.
9432 static void sanitize_dead_code(struct bpf_verifier_env *env)
9434 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
9435 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
9436 struct bpf_insn *insn = env->prog->insnsi;
9437 const int insn_cnt = env->prog->len;
9440 for (i = 0; i < insn_cnt; i++) {
9441 if (aux_data[i].seen)
9443 memcpy(insn + i, &trap, sizeof(trap));
9447 static bool insn_is_cond_jump(u8 code)
9451 if (BPF_CLASS(code) == BPF_JMP32)
9454 if (BPF_CLASS(code) != BPF_JMP)
9458 return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
9461 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
9463 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
9464 struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
9465 struct bpf_insn *insn = env->prog->insnsi;
9466 const int insn_cnt = env->prog->len;
9469 for (i = 0; i < insn_cnt; i++, insn++) {
9470 if (!insn_is_cond_jump(insn->code))
9473 if (!aux_data[i + 1].seen)
9475 else if (!aux_data[i + 1 + insn->off].seen)
9480 if (bpf_prog_is_dev_bound(env->prog->aux))
9481 bpf_prog_offload_replace_insn(env, i, &ja);
9483 memcpy(insn, &ja, sizeof(ja));
9487 static int opt_remove_dead_code(struct bpf_verifier_env *env)
9489 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
9490 int insn_cnt = env->prog->len;
9493 for (i = 0; i < insn_cnt; i++) {
9497 while (i + j < insn_cnt && !aux_data[i + j].seen)
9502 err = verifier_remove_insns(env, i, j);
9505 insn_cnt = env->prog->len;
9511 static int opt_remove_nops(struct bpf_verifier_env *env)
9513 const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
9514 struct bpf_insn *insn = env->prog->insnsi;
9515 int insn_cnt = env->prog->len;
9518 for (i = 0; i < insn_cnt; i++) {
9519 if (memcmp(&insn[i], &ja, sizeof(ja)))
9522 err = verifier_remove_insns(env, i, 1);
9532 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
9533 const union bpf_attr *attr)
9535 struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
9536 struct bpf_insn_aux_data *aux = env->insn_aux_data;
9537 int i, patch_len, delta = 0, len = env->prog->len;
9538 struct bpf_insn *insns = env->prog->insnsi;
9539 struct bpf_prog *new_prog;
9542 rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
9543 zext_patch[1] = BPF_ZEXT_REG(0);
9544 rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
9545 rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
9546 rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
9547 for (i = 0; i < len; i++) {
9548 int adj_idx = i + delta;
9549 struct bpf_insn insn;
9551 insn = insns[adj_idx];
9552 if (!aux[adj_idx].zext_dst) {
9560 class = BPF_CLASS(code);
9561 if (insn_no_def(&insn))
9564 /* NOTE: arg "reg" (the fourth one) is only used for
9565 * BPF_STX which has been ruled out in above
9566 * check, it is safe to pass NULL here.
9568 if (is_reg64(env, &insn, insn.dst_reg, NULL, DST_OP)) {
9569 if (class == BPF_LD &&
9570 BPF_MODE(code) == BPF_IMM)
9575 /* ctx load could be transformed into wider load. */
9576 if (class == BPF_LDX &&
9577 aux[adj_idx].ptr_type == PTR_TO_CTX)
9580 imm_rnd = get_random_int();
9581 rnd_hi32_patch[0] = insn;
9582 rnd_hi32_patch[1].imm = imm_rnd;
9583 rnd_hi32_patch[3].dst_reg = insn.dst_reg;
9584 patch = rnd_hi32_patch;
9586 goto apply_patch_buffer;
9589 if (!bpf_jit_needs_zext())
9592 zext_patch[0] = insn;
9593 zext_patch[1].dst_reg = insn.dst_reg;
9594 zext_patch[1].src_reg = insn.dst_reg;
9598 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
9601 env->prog = new_prog;
9602 insns = new_prog->insnsi;
9603 aux = env->insn_aux_data;
9604 delta += patch_len - 1;
9610 /* convert load instructions that access fields of a context type into a
9611 * sequence of instructions that access fields of the underlying structure:
9612 * struct __sk_buff -> struct sk_buff
9613 * struct bpf_sock_ops -> struct sock
9615 static int convert_ctx_accesses(struct bpf_verifier_env *env)
9617 const struct bpf_verifier_ops *ops = env->ops;
9618 int i, cnt, size, ctx_field_size, delta = 0;
9619 const int insn_cnt = env->prog->len;
9620 struct bpf_insn insn_buf[16], *insn;
9621 u32 target_size, size_default, off;
9622 struct bpf_prog *new_prog;
9623 enum bpf_access_type type;
9624 bool is_narrower_load;
9626 if (ops->gen_prologue || env->seen_direct_write) {
9627 if (!ops->gen_prologue) {
9628 verbose(env, "bpf verifier is misconfigured\n");
9631 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
9633 if (cnt >= ARRAY_SIZE(insn_buf)) {
9634 verbose(env, "bpf verifier is misconfigured\n");
9637 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
9641 env->prog = new_prog;
9646 if (bpf_prog_is_dev_bound(env->prog->aux))
9649 insn = env->prog->insnsi + delta;
9651 for (i = 0; i < insn_cnt; i++, insn++) {
9652 bpf_convert_ctx_access_t convert_ctx_access;
9654 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
9655 insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
9656 insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
9657 insn->code == (BPF_LDX | BPF_MEM | BPF_DW))
9659 else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
9660 insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
9661 insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
9662 insn->code == (BPF_STX | BPF_MEM | BPF_DW))
9667 if (type == BPF_WRITE &&
9668 env->insn_aux_data[i + delta].sanitize_stack_off) {
9669 struct bpf_insn patch[] = {
9670 /* Sanitize suspicious stack slot with zero.
9671 * There are no memory dependencies for this store,
9672 * since it's only using frame pointer and immediate
9675 BPF_ST_MEM(BPF_DW, BPF_REG_FP,
9676 env->insn_aux_data[i + delta].sanitize_stack_off,
9678 /* the original STX instruction will immediately
9679 * overwrite the same stack slot with appropriate value
9684 cnt = ARRAY_SIZE(patch);
9685 new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
9690 env->prog = new_prog;
9691 insn = new_prog->insnsi + i + delta;
9695 switch (env->insn_aux_data[i + delta].ptr_type) {
9697 if (!ops->convert_ctx_access)
9699 convert_ctx_access = ops->convert_ctx_access;
9702 case PTR_TO_SOCK_COMMON:
9703 convert_ctx_access = bpf_sock_convert_ctx_access;
9705 case PTR_TO_TCP_SOCK:
9706 convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
9708 case PTR_TO_XDP_SOCK:
9709 convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
9712 if (type == BPF_READ) {
9713 insn->code = BPF_LDX | BPF_PROBE_MEM |
9714 BPF_SIZE((insn)->code);
9715 env->prog->aux->num_exentries++;
9716 } else if (env->prog->type != BPF_PROG_TYPE_STRUCT_OPS) {
9717 verbose(env, "Writes through BTF pointers are not allowed\n");
9725 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
9726 size = BPF_LDST_BYTES(insn);
9728 /* If the read access is a narrower load of the field,
9729 * convert to a 4/8-byte load, to minimum program type specific
9730 * convert_ctx_access changes. If conversion is successful,
9731 * we will apply proper mask to the result.
9733 is_narrower_load = size < ctx_field_size;
9734 size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
9736 if (is_narrower_load) {
9739 if (type == BPF_WRITE) {
9740 verbose(env, "bpf verifier narrow ctx access misconfigured\n");
9745 if (ctx_field_size == 4)
9747 else if (ctx_field_size == 8)
9750 insn->off = off & ~(size_default - 1);
9751 insn->code = BPF_LDX | BPF_MEM | size_code;
9755 cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
9757 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
9758 (ctx_field_size && !target_size)) {
9759 verbose(env, "bpf verifier is misconfigured\n");
9763 if (is_narrower_load && size < target_size) {
9764 u8 shift = bpf_ctx_narrow_access_offset(
9765 off, size, size_default) * 8;
9766 if (ctx_field_size <= 4) {
9768 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
9771 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
9772 (1 << size * 8) - 1);
9775 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
9778 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
9779 (1ULL << size * 8) - 1);
9783 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
9789 /* keep walking new program and skip insns we just inserted */
9790 env->prog = new_prog;
9791 insn = new_prog->insnsi + i + delta;
9797 static int jit_subprogs(struct bpf_verifier_env *env)
9799 struct bpf_prog *prog = env->prog, **func, *tmp;
9800 int i, j, subprog_start, subprog_end = 0, len, subprog;
9801 struct bpf_insn *insn;
9803 int err, num_exentries;
9805 if (env->subprog_cnt <= 1)
9808 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
9809 if (insn->code != (BPF_JMP | BPF_CALL) ||
9810 insn->src_reg != BPF_PSEUDO_CALL)
9812 /* Upon error here we cannot fall back to interpreter but
9813 * need a hard reject of the program. Thus -EFAULT is
9814 * propagated in any case.
9816 subprog = find_subprog(env, i + insn->imm + 1);
9818 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
9822 /* temporarily remember subprog id inside insn instead of
9823 * aux_data, since next loop will split up all insns into funcs
9825 insn->off = subprog;
9826 /* remember original imm in case JIT fails and fallback
9827 * to interpreter will be needed
9829 env->insn_aux_data[i].call_imm = insn->imm;
9830 /* point imm to __bpf_call_base+1 from JITs point of view */
9834 err = bpf_prog_alloc_jited_linfo(prog);
9839 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
9843 for (i = 0; i < env->subprog_cnt; i++) {
9844 subprog_start = subprog_end;
9845 subprog_end = env->subprog_info[i + 1].start;
9847 len = subprog_end - subprog_start;
9848 /* BPF_PROG_RUN doesn't call subprogs directly,
9849 * hence main prog stats include the runtime of subprogs.
9850 * subprogs don't have IDs and not reachable via prog_get_next_id
9851 * func[i]->aux->stats will never be accessed and stays NULL
9853 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
9856 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
9857 len * sizeof(struct bpf_insn));
9858 func[i]->type = prog->type;
9860 if (bpf_prog_calc_tag(func[i]))
9862 func[i]->is_func = 1;
9863 func[i]->aux->func_idx = i;
9864 /* the btf and func_info will be freed only at prog->aux */
9865 func[i]->aux->btf = prog->aux->btf;
9866 func[i]->aux->func_info = prog->aux->func_info;
9868 /* Use bpf_prog_F_tag to indicate functions in stack traces.
9869 * Long term would need debug info to populate names
9871 func[i]->aux->name[0] = 'F';
9872 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
9873 func[i]->jit_requested = 1;
9874 func[i]->aux->linfo = prog->aux->linfo;
9875 func[i]->aux->nr_linfo = prog->aux->nr_linfo;
9876 func[i]->aux->jited_linfo = prog->aux->jited_linfo;
9877 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
9879 insn = func[i]->insnsi;
9880 for (j = 0; j < func[i]->len; j++, insn++) {
9881 if (BPF_CLASS(insn->code) == BPF_LDX &&
9882 BPF_MODE(insn->code) == BPF_PROBE_MEM)
9885 func[i]->aux->num_exentries = num_exentries;
9886 func[i] = bpf_int_jit_compile(func[i]);
9887 if (!func[i]->jited) {
9893 /* at this point all bpf functions were successfully JITed
9894 * now populate all bpf_calls with correct addresses and
9895 * run last pass of JIT
9897 for (i = 0; i < env->subprog_cnt; i++) {
9898 insn = func[i]->insnsi;
9899 for (j = 0; j < func[i]->len; j++, insn++) {
9900 if (insn->code != (BPF_JMP | BPF_CALL) ||
9901 insn->src_reg != BPF_PSEUDO_CALL)
9903 subprog = insn->off;
9904 insn->imm = BPF_CAST_CALL(func[subprog]->bpf_func) -
9908 /* we use the aux data to keep a list of the start addresses
9909 * of the JITed images for each function in the program
9911 * for some architectures, such as powerpc64, the imm field
9912 * might not be large enough to hold the offset of the start
9913 * address of the callee's JITed image from __bpf_call_base
9915 * in such cases, we can lookup the start address of a callee
9916 * by using its subprog id, available from the off field of
9917 * the call instruction, as an index for this list
9919 func[i]->aux->func = func;
9920 func[i]->aux->func_cnt = env->subprog_cnt;
9922 for (i = 0; i < env->subprog_cnt; i++) {
9923 old_bpf_func = func[i]->bpf_func;
9924 tmp = bpf_int_jit_compile(func[i]);
9925 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
9926 verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
9933 /* finally lock prog and jit images for all functions and
9936 for (i = 0; i < env->subprog_cnt; i++) {
9937 bpf_prog_lock_ro(func[i]);
9938 bpf_prog_kallsyms_add(func[i]);
9941 /* Last step: make now unused interpreter insns from main
9942 * prog consistent for later dump requests, so they can
9943 * later look the same as if they were interpreted only.
9945 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
9946 if (insn->code != (BPF_JMP | BPF_CALL) ||
9947 insn->src_reg != BPF_PSEUDO_CALL)
9949 insn->off = env->insn_aux_data[i].call_imm;
9950 subprog = find_subprog(env, i + insn->off + 1);
9951 insn->imm = subprog;
9955 prog->bpf_func = func[0]->bpf_func;
9956 prog->aux->func = func;
9957 prog->aux->func_cnt = env->subprog_cnt;
9958 bpf_prog_free_unused_jited_linfo(prog);
9961 for (i = 0; i < env->subprog_cnt; i++)
9963 bpf_jit_free(func[i]);
9966 /* cleanup main prog to be interpreted */
9967 prog->jit_requested = 0;
9968 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
9969 if (insn->code != (BPF_JMP | BPF_CALL) ||
9970 insn->src_reg != BPF_PSEUDO_CALL)
9973 insn->imm = env->insn_aux_data[i].call_imm;
9975 bpf_prog_free_jited_linfo(prog);
9979 static int fixup_call_args(struct bpf_verifier_env *env)
9981 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
9982 struct bpf_prog *prog = env->prog;
9983 struct bpf_insn *insn = prog->insnsi;
9988 if (env->prog->jit_requested &&
9989 !bpf_prog_is_dev_bound(env->prog->aux)) {
9990 err = jit_subprogs(env);
9996 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
9997 for (i = 0; i < prog->len; i++, insn++) {
9998 if (insn->code != (BPF_JMP | BPF_CALL) ||
9999 insn->src_reg != BPF_PSEUDO_CALL)
10001 depth = get_callee_stack_depth(env, insn, i);
10004 bpf_patch_call_args(insn, depth);
10011 /* fixup insn->imm field of bpf_call instructions
10012 * and inline eligible helpers as explicit sequence of BPF instructions
10014 * this function is called after eBPF program passed verification
10016 static int fixup_bpf_calls(struct bpf_verifier_env *env)
10018 struct bpf_prog *prog = env->prog;
10019 bool expect_blinding = bpf_jit_blinding_enabled(prog);
10020 struct bpf_insn *insn = prog->insnsi;
10021 const struct bpf_func_proto *fn;
10022 const int insn_cnt = prog->len;
10023 const struct bpf_map_ops *ops;
10024 struct bpf_insn_aux_data *aux;
10025 struct bpf_insn insn_buf[16];
10026 struct bpf_prog *new_prog;
10027 struct bpf_map *map_ptr;
10028 int i, ret, cnt, delta = 0;
10030 for (i = 0; i < insn_cnt; i++, insn++) {
10031 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
10032 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
10033 insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
10034 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
10035 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
10036 struct bpf_insn mask_and_div[] = {
10037 BPF_MOV32_REG(insn->src_reg, insn->src_reg),
10038 /* Rx div 0 -> 0 */
10039 BPF_JMP_IMM(BPF_JNE, insn->src_reg, 0, 2),
10040 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
10041 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
10044 struct bpf_insn mask_and_mod[] = {
10045 BPF_MOV32_REG(insn->src_reg, insn->src_reg),
10046 /* Rx mod 0 -> Rx */
10047 BPF_JMP_IMM(BPF_JEQ, insn->src_reg, 0, 1),
10050 struct bpf_insn *patchlet;
10052 if (insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
10053 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
10054 patchlet = mask_and_div + (is64 ? 1 : 0);
10055 cnt = ARRAY_SIZE(mask_and_div) - (is64 ? 1 : 0);
10057 patchlet = mask_and_mod + (is64 ? 1 : 0);
10058 cnt = ARRAY_SIZE(mask_and_mod) - (is64 ? 1 : 0);
10061 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
10066 env->prog = prog = new_prog;
10067 insn = new_prog->insnsi + i + delta;
10071 if (BPF_CLASS(insn->code) == BPF_LD &&
10072 (BPF_MODE(insn->code) == BPF_ABS ||
10073 BPF_MODE(insn->code) == BPF_IND)) {
10074 cnt = env->ops->gen_ld_abs(insn, insn_buf);
10075 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
10076 verbose(env, "bpf verifier is misconfigured\n");
10080 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
10085 env->prog = prog = new_prog;
10086 insn = new_prog->insnsi + i + delta;
10090 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
10091 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
10092 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
10093 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
10094 struct bpf_insn insn_buf[16];
10095 struct bpf_insn *patch = &insn_buf[0];
10099 aux = &env->insn_aux_data[i + delta];
10100 if (!aux->alu_state ||
10101 aux->alu_state == BPF_ALU_NON_POINTER)
10104 isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
10105 issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
10106 BPF_ALU_SANITIZE_SRC;
10108 off_reg = issrc ? insn->src_reg : insn->dst_reg;
10110 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
10111 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit - 1);
10112 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
10113 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
10114 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
10115 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
10117 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX,
10119 insn->src_reg = BPF_REG_AX;
10121 *patch++ = BPF_ALU64_REG(BPF_AND, off_reg,
10125 insn->code = insn->code == code_add ?
10126 code_sub : code_add;
10128 if (issrc && isneg)
10129 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
10130 cnt = patch - insn_buf;
10132 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
10137 env->prog = prog = new_prog;
10138 insn = new_prog->insnsi + i + delta;
10142 if (insn->code != (BPF_JMP | BPF_CALL))
10144 if (insn->src_reg == BPF_PSEUDO_CALL)
10147 if (insn->imm == BPF_FUNC_get_route_realm)
10148 prog->dst_needed = 1;
10149 if (insn->imm == BPF_FUNC_get_prandom_u32)
10150 bpf_user_rnd_init_once();
10151 if (insn->imm == BPF_FUNC_override_return)
10152 prog->kprobe_override = 1;
10153 if (insn->imm == BPF_FUNC_tail_call) {
10154 /* If we tail call into other programs, we
10155 * cannot make any assumptions since they can
10156 * be replaced dynamically during runtime in
10157 * the program array.
10159 prog->cb_access = 1;
10160 env->prog->aux->stack_depth = MAX_BPF_STACK;
10161 env->prog->aux->max_pkt_offset = MAX_PACKET_OFF;
10163 /* mark bpf_tail_call as different opcode to avoid
10164 * conditional branch in the interpeter for every normal
10165 * call and to prevent accidental JITing by JIT compiler
10166 * that doesn't support bpf_tail_call yet
10169 insn->code = BPF_JMP | BPF_TAIL_CALL;
10171 aux = &env->insn_aux_data[i + delta];
10172 if (env->bpf_capable && !expect_blinding &&
10173 prog->jit_requested &&
10174 !bpf_map_key_poisoned(aux) &&
10175 !bpf_map_ptr_poisoned(aux) &&
10176 !bpf_map_ptr_unpriv(aux)) {
10177 struct bpf_jit_poke_descriptor desc = {
10178 .reason = BPF_POKE_REASON_TAIL_CALL,
10179 .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
10180 .tail_call.key = bpf_map_key_immediate(aux),
10183 ret = bpf_jit_add_poke_descriptor(prog, &desc);
10185 verbose(env, "adding tail call poke descriptor failed\n");
10189 insn->imm = ret + 1;
10193 if (!bpf_map_ptr_unpriv(aux))
10196 /* instead of changing every JIT dealing with tail_call
10197 * emit two extra insns:
10198 * if (index >= max_entries) goto out;
10199 * index &= array->index_mask;
10200 * to avoid out-of-bounds cpu speculation
10202 if (bpf_map_ptr_poisoned(aux)) {
10203 verbose(env, "tail_call abusing map_ptr\n");
10207 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
10208 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
10209 map_ptr->max_entries, 2);
10210 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
10211 container_of(map_ptr,
10214 insn_buf[2] = *insn;
10216 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
10221 env->prog = prog = new_prog;
10222 insn = new_prog->insnsi + i + delta;
10226 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
10227 * and other inlining handlers are currently limited to 64 bit
10230 if (prog->jit_requested && BITS_PER_LONG == 64 &&
10231 (insn->imm == BPF_FUNC_map_lookup_elem ||
10232 insn->imm == BPF_FUNC_map_update_elem ||
10233 insn->imm == BPF_FUNC_map_delete_elem ||
10234 insn->imm == BPF_FUNC_map_push_elem ||
10235 insn->imm == BPF_FUNC_map_pop_elem ||
10236 insn->imm == BPF_FUNC_map_peek_elem)) {
10237 aux = &env->insn_aux_data[i + delta];
10238 if (bpf_map_ptr_poisoned(aux))
10239 goto patch_call_imm;
10241 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
10242 ops = map_ptr->ops;
10243 if (insn->imm == BPF_FUNC_map_lookup_elem &&
10244 ops->map_gen_lookup) {
10245 cnt = ops->map_gen_lookup(map_ptr, insn_buf);
10246 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
10247 verbose(env, "bpf verifier is misconfigured\n");
10251 new_prog = bpf_patch_insn_data(env, i + delta,
10257 env->prog = prog = new_prog;
10258 insn = new_prog->insnsi + i + delta;
10262 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
10263 (void *(*)(struct bpf_map *map, void *key))NULL));
10264 BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
10265 (int (*)(struct bpf_map *map, void *key))NULL));
10266 BUILD_BUG_ON(!__same_type(ops->map_update_elem,
10267 (int (*)(struct bpf_map *map, void *key, void *value,
10269 BUILD_BUG_ON(!__same_type(ops->map_push_elem,
10270 (int (*)(struct bpf_map *map, void *value,
10272 BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
10273 (int (*)(struct bpf_map *map, void *value))NULL));
10274 BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
10275 (int (*)(struct bpf_map *map, void *value))NULL));
10277 switch (insn->imm) {
10278 case BPF_FUNC_map_lookup_elem:
10279 insn->imm = BPF_CAST_CALL(ops->map_lookup_elem) -
10282 case BPF_FUNC_map_update_elem:
10283 insn->imm = BPF_CAST_CALL(ops->map_update_elem) -
10286 case BPF_FUNC_map_delete_elem:
10287 insn->imm = BPF_CAST_CALL(ops->map_delete_elem) -
10290 case BPF_FUNC_map_push_elem:
10291 insn->imm = BPF_CAST_CALL(ops->map_push_elem) -
10294 case BPF_FUNC_map_pop_elem:
10295 insn->imm = BPF_CAST_CALL(ops->map_pop_elem) -
10298 case BPF_FUNC_map_peek_elem:
10299 insn->imm = BPF_CAST_CALL(ops->map_peek_elem) -
10304 goto patch_call_imm;
10307 if (prog->jit_requested && BITS_PER_LONG == 64 &&
10308 insn->imm == BPF_FUNC_jiffies64) {
10309 struct bpf_insn ld_jiffies_addr[2] = {
10310 BPF_LD_IMM64(BPF_REG_0,
10311 (unsigned long)&jiffies),
10314 insn_buf[0] = ld_jiffies_addr[0];
10315 insn_buf[1] = ld_jiffies_addr[1];
10316 insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
10320 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
10326 env->prog = prog = new_prog;
10327 insn = new_prog->insnsi + i + delta;
10332 fn = env->ops->get_func_proto(insn->imm, env->prog);
10333 /* all functions that have prototype and verifier allowed
10334 * programs to call them, must be real in-kernel functions
10338 "kernel subsystem misconfigured func %s#%d\n",
10339 func_id_name(insn->imm), insn->imm);
10342 insn->imm = fn->func - __bpf_call_base;
10345 /* Since poke tab is now finalized, publish aux to tracker. */
10346 for (i = 0; i < prog->aux->size_poke_tab; i++) {
10347 map_ptr = prog->aux->poke_tab[i].tail_call.map;
10348 if (!map_ptr->ops->map_poke_track ||
10349 !map_ptr->ops->map_poke_untrack ||
10350 !map_ptr->ops->map_poke_run) {
10351 verbose(env, "bpf verifier is misconfigured\n");
10355 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
10357 verbose(env, "tracking tail call prog failed\n");
10365 static void free_states(struct bpf_verifier_env *env)
10367 struct bpf_verifier_state_list *sl, *sln;
10370 sl = env->free_list;
10373 free_verifier_state(&sl->state, false);
10377 env->free_list = NULL;
10379 if (!env->explored_states)
10382 for (i = 0; i < state_htab_size(env); i++) {
10383 sl = env->explored_states[i];
10387 free_verifier_state(&sl->state, false);
10391 env->explored_states[i] = NULL;
10395 /* The verifier is using insn_aux_data[] to store temporary data during
10396 * verification and to store information for passes that run after the
10397 * verification like dead code sanitization. do_check_common() for subprogram N
10398 * may analyze many other subprograms. sanitize_insn_aux_data() clears all
10399 * temporary data after do_check_common() finds that subprogram N cannot be
10400 * verified independently. pass_cnt counts the number of times
10401 * do_check_common() was run and insn->aux->seen tells the pass number
10402 * insn_aux_data was touched. These variables are compared to clear temporary
10403 * data from failed pass. For testing and experiments do_check_common() can be
10404 * run multiple times even when prior attempt to verify is unsuccessful.
10406 static void sanitize_insn_aux_data(struct bpf_verifier_env *env)
10408 struct bpf_insn *insn = env->prog->insnsi;
10409 struct bpf_insn_aux_data *aux;
10412 for (i = 0; i < env->prog->len; i++) {
10413 class = BPF_CLASS(insn[i].code);
10414 if (class != BPF_LDX && class != BPF_STX)
10416 aux = &env->insn_aux_data[i];
10417 if (aux->seen != env->pass_cnt)
10419 memset(aux, 0, offsetof(typeof(*aux), orig_idx));
10423 static int do_check_common(struct bpf_verifier_env *env, int subprog)
10425 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
10426 struct bpf_verifier_state *state;
10427 struct bpf_reg_state *regs;
10430 env->prev_linfo = NULL;
10433 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
10436 state->curframe = 0;
10437 state->speculative = false;
10438 state->branches = 1;
10439 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
10440 if (!state->frame[0]) {
10444 env->cur_state = state;
10445 init_func_state(env, state->frame[0],
10446 BPF_MAIN_FUNC /* callsite */,
10450 regs = state->frame[state->curframe]->regs;
10451 if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
10452 ret = btf_prepare_func_args(env, subprog, regs);
10455 for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
10456 if (regs[i].type == PTR_TO_CTX)
10457 mark_reg_known_zero(env, regs, i);
10458 else if (regs[i].type == SCALAR_VALUE)
10459 mark_reg_unknown(env, regs, i);
10462 /* 1st arg to a function */
10463 regs[BPF_REG_1].type = PTR_TO_CTX;
10464 mark_reg_known_zero(env, regs, BPF_REG_1);
10465 ret = btf_check_func_arg_match(env, subprog, regs);
10466 if (ret == -EFAULT)
10467 /* unlikely verifier bug. abort.
10468 * ret == 0 and ret < 0 are sadly acceptable for
10469 * main() function due to backward compatibility.
10470 * Like socket filter program may be written as:
10471 * int bpf_prog(struct pt_regs *ctx)
10472 * and never dereference that ctx in the program.
10473 * 'struct pt_regs' is a type mismatch for socket
10474 * filter that should be using 'struct __sk_buff'.
10479 ret = do_check(env);
10481 /* check for NULL is necessary, since cur_state can be freed inside
10482 * do_check() under memory pressure.
10484 if (env->cur_state) {
10485 free_verifier_state(env->cur_state, true);
10486 env->cur_state = NULL;
10488 while (!pop_stack(env, NULL, NULL, false));
10489 if (!ret && pop_log)
10490 bpf_vlog_reset(&env->log, 0);
10493 /* clean aux data in case subprog was rejected */
10494 sanitize_insn_aux_data(env);
10498 /* Verify all global functions in a BPF program one by one based on their BTF.
10499 * All global functions must pass verification. Otherwise the whole program is rejected.
10510 * foo() will be verified first for R1=any_scalar_value. During verification it
10511 * will be assumed that bar() already verified successfully and call to bar()
10512 * from foo() will be checked for type match only. Later bar() will be verified
10513 * independently to check that it's safe for R1=any_scalar_value.
10515 static int do_check_subprogs(struct bpf_verifier_env *env)
10517 struct bpf_prog_aux *aux = env->prog->aux;
10520 if (!aux->func_info)
10523 for (i = 1; i < env->subprog_cnt; i++) {
10524 if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
10526 env->insn_idx = env->subprog_info[i].start;
10527 WARN_ON_ONCE(env->insn_idx == 0);
10528 ret = do_check_common(env, i);
10531 } else if (env->log.level & BPF_LOG_LEVEL) {
10533 "Func#%d is safe for any args that match its prototype\n",
10540 static int do_check_main(struct bpf_verifier_env *env)
10545 ret = do_check_common(env, 0);
10547 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
10552 static void print_verification_stats(struct bpf_verifier_env *env)
10556 if (env->log.level & BPF_LOG_STATS) {
10557 verbose(env, "verification time %lld usec\n",
10558 div_u64(env->verification_time, 1000));
10559 verbose(env, "stack depth ");
10560 for (i = 0; i < env->subprog_cnt; i++) {
10561 u32 depth = env->subprog_info[i].stack_depth;
10563 verbose(env, "%d", depth);
10564 if (i + 1 < env->subprog_cnt)
10567 verbose(env, "\n");
10569 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
10570 "total_states %d peak_states %d mark_read %d\n",
10571 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
10572 env->max_states_per_insn, env->total_states,
10573 env->peak_states, env->longest_mark_read_walk);
10576 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
10578 const struct btf_type *t, *func_proto;
10579 const struct bpf_struct_ops *st_ops;
10580 const struct btf_member *member;
10581 struct bpf_prog *prog = env->prog;
10582 u32 btf_id, member_idx;
10585 btf_id = prog->aux->attach_btf_id;
10586 st_ops = bpf_struct_ops_find(btf_id);
10588 verbose(env, "attach_btf_id %u is not a supported struct\n",
10594 member_idx = prog->expected_attach_type;
10595 if (member_idx >= btf_type_vlen(t)) {
10596 verbose(env, "attach to invalid member idx %u of struct %s\n",
10597 member_idx, st_ops->name);
10601 member = &btf_type_member(t)[member_idx];
10602 mname = btf_name_by_offset(btf_vmlinux, member->name_off);
10603 func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
10606 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
10607 mname, member_idx, st_ops->name);
10611 if (st_ops->check_member) {
10612 int err = st_ops->check_member(t, member);
10615 verbose(env, "attach to unsupported member %s of struct %s\n",
10616 mname, st_ops->name);
10621 prog->aux->attach_func_proto = func_proto;
10622 prog->aux->attach_func_name = mname;
10623 env->ops = st_ops->verifier_ops;
10627 #define SECURITY_PREFIX "security_"
10629 static int check_attach_modify_return(struct bpf_prog *prog, unsigned long addr)
10631 if (within_error_injection_list(addr) ||
10632 !strncmp(SECURITY_PREFIX, prog->aux->attach_func_name,
10633 sizeof(SECURITY_PREFIX) - 1))
10639 static int check_attach_btf_id(struct bpf_verifier_env *env)
10641 struct bpf_prog *prog = env->prog;
10642 bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
10643 struct bpf_prog *tgt_prog = prog->aux->linked_prog;
10644 u32 btf_id = prog->aux->attach_btf_id;
10645 const char prefix[] = "btf_trace_";
10646 struct btf_func_model fmodel;
10647 int ret = 0, subprog = -1, i;
10648 struct bpf_trampoline *tr;
10649 const struct btf_type *t;
10650 bool conservative = true;
10656 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
10657 return check_struct_ops_btf_id(env);
10659 if (prog->type != BPF_PROG_TYPE_TRACING &&
10660 prog->type != BPF_PROG_TYPE_LSM &&
10665 verbose(env, "Tracing programs must provide btf_id\n");
10668 btf = bpf_prog_get_target_btf(prog);
10671 "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
10674 t = btf_type_by_id(btf, btf_id);
10676 verbose(env, "attach_btf_id %u is invalid\n", btf_id);
10679 tname = btf_name_by_offset(btf, t->name_off);
10681 verbose(env, "attach_btf_id %u doesn't have a name\n", btf_id);
10685 struct bpf_prog_aux *aux = tgt_prog->aux;
10687 for (i = 0; i < aux->func_info_cnt; i++)
10688 if (aux->func_info[i].type_id == btf_id) {
10692 if (subprog == -1) {
10693 verbose(env, "Subprog %s doesn't exist\n", tname);
10696 conservative = aux->func_info_aux[subprog].unreliable;
10697 if (prog_extension) {
10698 if (conservative) {
10700 "Cannot replace static functions\n");
10703 if (!prog->jit_requested) {
10705 "Extension programs should be JITed\n");
10708 env->ops = bpf_verifier_ops[tgt_prog->type];
10709 prog->expected_attach_type = tgt_prog->expected_attach_type;
10711 if (!tgt_prog->jited) {
10712 verbose(env, "Can attach to only JITed progs\n");
10715 if (tgt_prog->type == prog->type) {
10716 /* Cannot fentry/fexit another fentry/fexit program.
10717 * Cannot attach program extension to another extension.
10718 * It's ok to attach fentry/fexit to extension program.
10720 verbose(env, "Cannot recursively attach\n");
10723 if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
10725 (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
10726 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
10727 /* Program extensions can extend all program types
10728 * except fentry/fexit. The reason is the following.
10729 * The fentry/fexit programs are used for performance
10730 * analysis, stats and can be attached to any program
10731 * type except themselves. When extension program is
10732 * replacing XDP function it is necessary to allow
10733 * performance analysis of all functions. Both original
10734 * XDP program and its program extension. Hence
10735 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
10736 * allowed. If extending of fentry/fexit was allowed it
10737 * would be possible to create long call chain
10738 * fentry->extension->fentry->extension beyond
10739 * reasonable stack size. Hence extending fentry is not
10742 verbose(env, "Cannot extend fentry/fexit\n");
10745 key = ((u64)aux->id) << 32 | btf_id;
10747 if (prog_extension) {
10748 verbose(env, "Cannot replace kernel functions\n");
10754 switch (prog->expected_attach_type) {
10755 case BPF_TRACE_RAW_TP:
10758 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
10761 if (!btf_type_is_typedef(t)) {
10762 verbose(env, "attach_btf_id %u is not a typedef\n",
10766 if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
10767 verbose(env, "attach_btf_id %u points to wrong type name %s\n",
10771 tname += sizeof(prefix) - 1;
10772 t = btf_type_by_id(btf, t->type);
10773 if (!btf_type_is_ptr(t))
10774 /* should never happen in valid vmlinux build */
10776 t = btf_type_by_id(btf, t->type);
10777 if (!btf_type_is_func_proto(t))
10778 /* should never happen in valid vmlinux build */
10781 /* remember two read only pointers that are valid for
10782 * the life time of the kernel
10784 prog->aux->attach_func_name = tname;
10785 prog->aux->attach_func_proto = t;
10786 prog->aux->attach_btf_trace = true;
10788 case BPF_TRACE_ITER:
10789 if (!btf_type_is_func(t)) {
10790 verbose(env, "attach_btf_id %u is not a function\n",
10794 t = btf_type_by_id(btf, t->type);
10795 if (!btf_type_is_func_proto(t))
10797 prog->aux->attach_func_name = tname;
10798 prog->aux->attach_func_proto = t;
10799 if (!bpf_iter_prog_supported(prog))
10801 ret = btf_distill_func_proto(&env->log, btf, t,
10805 if (!prog_extension)
10808 case BPF_MODIFY_RETURN:
10810 case BPF_TRACE_FENTRY:
10811 case BPF_TRACE_FEXIT:
10812 prog->aux->attach_func_name = tname;
10813 if (prog->type == BPF_PROG_TYPE_LSM) {
10814 ret = bpf_lsm_verify_prog(&env->log, prog);
10819 if (!btf_type_is_func(t)) {
10820 verbose(env, "attach_btf_id %u is not a function\n",
10824 if (prog_extension &&
10825 btf_check_type_match(env, prog, btf, t))
10827 t = btf_type_by_id(btf, t->type);
10828 if (!btf_type_is_func_proto(t))
10830 tr = bpf_trampoline_lookup(key);
10833 /* t is either vmlinux type or another program's type */
10834 prog->aux->attach_func_proto = t;
10835 mutex_lock(&tr->mutex);
10836 if (tr->func.addr) {
10837 prog->aux->trampoline = tr;
10840 if (tgt_prog && conservative) {
10841 prog->aux->attach_func_proto = NULL;
10844 ret = btf_distill_func_proto(&env->log, btf, t,
10845 tname, &tr->func.model);
10850 addr = (long) tgt_prog->bpf_func;
10852 addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
10854 addr = kallsyms_lookup_name(tname);
10857 "The address of function %s cannot be found\n",
10864 if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
10865 ret = check_attach_modify_return(prog, addr);
10867 verbose(env, "%s() is not modifiable\n",
10868 prog->aux->attach_func_name);
10873 tr->func.addr = (void *)addr;
10874 prog->aux->trampoline = tr;
10876 mutex_unlock(&tr->mutex);
10878 bpf_trampoline_put(tr);
10883 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr,
10884 union bpf_attr __user *uattr)
10886 u64 start_time = ktime_get_ns();
10887 struct bpf_verifier_env *env;
10888 struct bpf_verifier_log *log;
10889 int i, len, ret = -EINVAL;
10892 /* no program is valid */
10893 if (ARRAY_SIZE(bpf_verifier_ops) == 0)
10896 /* 'struct bpf_verifier_env' can be global, but since it's not small,
10897 * allocate/free it every time bpf_check() is called
10899 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
10904 len = (*prog)->len;
10905 env->insn_aux_data =
10906 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
10908 if (!env->insn_aux_data)
10910 for (i = 0; i < len; i++)
10911 env->insn_aux_data[i].orig_idx = i;
10913 env->ops = bpf_verifier_ops[env->prog->type];
10914 is_priv = bpf_capable();
10916 if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
10917 mutex_lock(&bpf_verifier_lock);
10919 btf_vmlinux = btf_parse_vmlinux();
10920 mutex_unlock(&bpf_verifier_lock);
10923 /* grab the mutex to protect few globals used by verifier */
10925 mutex_lock(&bpf_verifier_lock);
10927 if (attr->log_level || attr->log_buf || attr->log_size) {
10928 /* user requested verbose verifier output
10929 * and supplied buffer to store the verification trace
10931 log->level = attr->log_level;
10932 log->ubuf = (char __user *) (unsigned long) attr->log_buf;
10933 log->len_total = attr->log_size;
10936 /* log attributes have to be sane */
10937 if (log->len_total < 128 || log->len_total > UINT_MAX >> 2 ||
10938 !log->level || !log->ubuf || log->level & ~BPF_LOG_MASK)
10942 if (IS_ERR(btf_vmlinux)) {
10943 /* Either gcc or pahole or kernel are broken. */
10944 verbose(env, "in-kernel BTF is malformed\n");
10945 ret = PTR_ERR(btf_vmlinux);
10946 goto skip_full_check;
10949 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
10950 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
10951 env->strict_alignment = true;
10952 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
10953 env->strict_alignment = false;
10955 env->allow_ptr_leaks = bpf_allow_ptr_leaks();
10956 env->bypass_spec_v1 = bpf_bypass_spec_v1();
10957 env->bypass_spec_v4 = bpf_bypass_spec_v4();
10958 env->bpf_capable = bpf_capable();
10961 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
10963 ret = replace_map_fd_with_map_ptr(env);
10965 goto skip_full_check;
10967 if (bpf_prog_is_dev_bound(env->prog->aux)) {
10968 ret = bpf_prog_offload_verifier_prep(env->prog);
10970 goto skip_full_check;
10973 env->explored_states = kvcalloc(state_htab_size(env),
10974 sizeof(struct bpf_verifier_state_list *),
10977 if (!env->explored_states)
10978 goto skip_full_check;
10980 ret = check_subprogs(env);
10982 goto skip_full_check;
10984 ret = check_btf_info(env, attr, uattr);
10986 goto skip_full_check;
10988 ret = check_attach_btf_id(env);
10990 goto skip_full_check;
10992 ret = check_cfg(env);
10994 goto skip_full_check;
10996 ret = do_check_subprogs(env);
10997 ret = ret ?: do_check_main(env);
10999 if (ret == 0 && bpf_prog_is_dev_bound(env->prog->aux))
11000 ret = bpf_prog_offload_finalize(env);
11003 kvfree(env->explored_states);
11006 ret = check_max_stack_depth(env);
11008 /* instruction rewrites happen after this point */
11011 opt_hard_wire_dead_code_branches(env);
11013 ret = opt_remove_dead_code(env);
11015 ret = opt_remove_nops(env);
11018 sanitize_dead_code(env);
11022 /* program is valid, convert *(u32*)(ctx + off) accesses */
11023 ret = convert_ctx_accesses(env);
11026 ret = fixup_bpf_calls(env);
11028 /* do 32-bit optimization after insn patching has done so those patched
11029 * insns could be handled correctly.
11031 if (ret == 0 && !bpf_prog_is_dev_bound(env->prog->aux)) {
11032 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
11033 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
11038 ret = fixup_call_args(env);
11040 env->verification_time = ktime_get_ns() - start_time;
11041 print_verification_stats(env);
11043 if (log->level && bpf_verifier_log_full(log))
11045 if (log->level && !log->ubuf) {
11047 goto err_release_maps;
11050 if (ret == 0 && env->used_map_cnt) {
11051 /* if program passed verifier, update used_maps in bpf_prog_info */
11052 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
11053 sizeof(env->used_maps[0]),
11056 if (!env->prog->aux->used_maps) {
11058 goto err_release_maps;
11061 memcpy(env->prog->aux->used_maps, env->used_maps,
11062 sizeof(env->used_maps[0]) * env->used_map_cnt);
11063 env->prog->aux->used_map_cnt = env->used_map_cnt;
11065 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
11066 * bpf_ld_imm64 instructions
11068 convert_pseudo_ld_imm64(env);
11072 adjust_btf_func(env);
11075 if (!env->prog->aux->used_maps)
11076 /* if we didn't copy map pointers into bpf_prog_info, release
11077 * them now. Otherwise free_used_maps() will release them.
11081 /* extension progs temporarily inherit the attach_type of their targets
11082 for verification purposes, so set it back to zero before returning
11084 if (env->prog->type == BPF_PROG_TYPE_EXT)
11085 env->prog->expected_attach_type = 0;
11090 mutex_unlock(&bpf_verifier_lock);
11091 vfree(env->insn_aux_data);