1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com
3 * Copyright (c) 2016 Facebook
4 * Copyright (c) 2018 Covalent IO, Inc. http://covalent.io
6 #include <uapi/linux/btf.h>
7 #include <linux/kernel.h>
8 #include <linux/types.h>
9 #include <linux/slab.h>
10 #include <linux/bpf.h>
11 #include <linux/btf.h>
12 #include <linux/bpf_verifier.h>
13 #include <linux/filter.h>
14 #include <net/netlink.h>
15 #include <linux/file.h>
16 #include <linux/vmalloc.h>
17 #include <linux/stringify.h>
18 #include <linux/bsearch.h>
19 #include <linux/sort.h>
20 #include <linux/perf_event.h>
21 #include <linux/ctype.h>
22 #include <linux/error-injection.h>
23 #include <linux/bpf_lsm.h>
24 #include <linux/btf_ids.h>
28 static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
29 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
30 [_id] = & _name ## _verifier_ops,
31 #define BPF_MAP_TYPE(_id, _ops)
32 #define BPF_LINK_TYPE(_id, _name)
33 #include <linux/bpf_types.h>
39 /* bpf_check() is a static code analyzer that walks eBPF program
40 * instruction by instruction and updates register/stack state.
41 * All paths of conditional branches are analyzed until 'bpf_exit' insn.
43 * The first pass is depth-first-search to check that the program is a DAG.
44 * It rejects the following programs:
45 * - larger than BPF_MAXINSNS insns
46 * - if loop is present (detected via back-edge)
47 * - unreachable insns exist (shouldn't be a forest. program = one function)
48 * - out of bounds or malformed jumps
49 * The second pass is all possible path descent from the 1st insn.
50 * Since it's analyzing all pathes through the program, the length of the
51 * analysis is limited to 64k insn, which may be hit even if total number of
52 * insn is less then 4K, but there are too many branches that change stack/regs.
53 * Number of 'branches to be analyzed' is limited to 1k
55 * On entry to each instruction, each register has a type, and the instruction
56 * changes the types of the registers depending on instruction semantics.
57 * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
60 * All registers are 64-bit.
61 * R0 - return register
62 * R1-R5 argument passing registers
63 * R6-R9 callee saved registers
64 * R10 - frame pointer read-only
66 * At the start of BPF program the register R1 contains a pointer to bpf_context
67 * and has type PTR_TO_CTX.
69 * Verifier tracks arithmetic operations on pointers in case:
70 * BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
71 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
72 * 1st insn copies R10 (which has FRAME_PTR) type into R1
73 * and 2nd arithmetic instruction is pattern matched to recognize
74 * that it wants to construct a pointer to some element within stack.
75 * So after 2nd insn, the register R1 has type PTR_TO_STACK
76 * (and -20 constant is saved for further stack bounds checking).
77 * Meaning that this reg is a pointer to stack plus known immediate constant.
79 * Most of the time the registers have SCALAR_VALUE type, which
80 * means the register has some value, but it's not a valid pointer.
81 * (like pointer plus pointer becomes SCALAR_VALUE type)
83 * When verifier sees load or store instructions the type of base register
84 * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are
85 * four pointer types recognized by check_mem_access() function.
87 * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
88 * and the range of [ptr, ptr + map's value_size) is accessible.
90 * registers used to pass values to function calls are checked against
91 * function argument constraints.
93 * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
94 * It means that the register type passed to this function must be
95 * PTR_TO_STACK and it will be used inside the function as
96 * 'pointer to map element key'
98 * For example the argument constraints for bpf_map_lookup_elem():
99 * .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
100 * .arg1_type = ARG_CONST_MAP_PTR,
101 * .arg2_type = ARG_PTR_TO_MAP_KEY,
103 * ret_type says that this function returns 'pointer to map elem value or null'
104 * function expects 1st argument to be a const pointer to 'struct bpf_map' and
105 * 2nd argument should be a pointer to stack, which will be used inside
106 * the helper function as a pointer to map element key.
108 * On the kernel side the helper function looks like:
109 * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
111 * struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
112 * void *key = (void *) (unsigned long) r2;
115 * here kernel can access 'key' and 'map' pointers safely, knowing that
116 * [key, key + map->key_size) bytes are valid and were initialized on
117 * the stack of eBPF program.
120 * Corresponding eBPF program may look like:
121 * BPF_MOV64_REG(BPF_REG_2, BPF_REG_10), // after this insn R2 type is FRAME_PTR
122 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
123 * BPF_LD_MAP_FD(BPF_REG_1, map_fd), // after this insn R1 type is CONST_PTR_TO_MAP
124 * BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
125 * here verifier looks at prototype of map_lookup_elem() and sees:
126 * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
127 * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
129 * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
130 * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
131 * and were initialized prior to this call.
132 * If it's ok, then verifier allows this BPF_CALL insn and looks at
133 * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
134 * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
135 * returns ether pointer to map value or NULL.
137 * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
138 * insn, the register holding that pointer in the true branch changes state to
139 * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
140 * branch. See check_cond_jmp_op().
142 * After the call R0 is set to return type of the function and registers R1-R5
143 * are set to NOT_INIT to indicate that they are no longer readable.
145 * The following reference types represent a potential reference to a kernel
146 * resource which, after first being allocated, must be checked and freed by
148 * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET
150 * When the verifier sees a helper call return a reference type, it allocates a
151 * pointer id for the reference and stores it in the current function state.
152 * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into
153 * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type
154 * passes through a NULL-check conditional. For the branch wherein the state is
155 * changed to CONST_IMM, the verifier releases the reference.
157 * For each helper function that allocates a reference, such as
158 * bpf_sk_lookup_tcp(), there is a corresponding release function, such as
159 * bpf_sk_release(). When a reference type passes into the release function,
160 * the verifier also releases the reference. If any unchecked or unreleased
161 * reference remains at the end of the program, the verifier rejects it.
164 /* verifier_state + insn_idx are pushed to stack when branch is encountered */
165 struct bpf_verifier_stack_elem {
166 /* verifer state is 'st'
167 * before processing instruction 'insn_idx'
168 * and after processing instruction 'prev_insn_idx'
170 struct bpf_verifier_state st;
173 struct bpf_verifier_stack_elem *next;
174 /* length of verifier log at the time this state was pushed on stack */
178 #define BPF_COMPLEXITY_LIMIT_JMP_SEQ 8192
179 #define BPF_COMPLEXITY_LIMIT_STATES 64
181 #define BPF_MAP_KEY_POISON (1ULL << 63)
182 #define BPF_MAP_KEY_SEEN (1ULL << 62)
184 #define BPF_MAP_PTR_UNPRIV 1UL
185 #define BPF_MAP_PTR_POISON ((void *)((0xeB9FUL << 1) + \
186 POISON_POINTER_DELTA))
187 #define BPF_MAP_PTR(X) ((struct bpf_map *)((X) & ~BPF_MAP_PTR_UNPRIV))
189 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux)
191 return BPF_MAP_PTR(aux->map_ptr_state) == BPF_MAP_PTR_POISON;
194 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux)
196 return aux->map_ptr_state & BPF_MAP_PTR_UNPRIV;
199 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
200 const struct bpf_map *map, bool unpriv)
202 BUILD_BUG_ON((unsigned long)BPF_MAP_PTR_POISON & BPF_MAP_PTR_UNPRIV);
203 unpriv |= bpf_map_ptr_unpriv(aux);
204 aux->map_ptr_state = (unsigned long)map |
205 (unpriv ? BPF_MAP_PTR_UNPRIV : 0UL);
208 static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux)
210 return aux->map_key_state & BPF_MAP_KEY_POISON;
213 static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux)
215 return !(aux->map_key_state & BPF_MAP_KEY_SEEN);
218 static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux)
220 return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON);
223 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state)
225 bool poisoned = bpf_map_key_poisoned(aux);
227 aux->map_key_state = state | BPF_MAP_KEY_SEEN |
228 (poisoned ? BPF_MAP_KEY_POISON : 0ULL);
231 static bool bpf_pseudo_call(const struct bpf_insn *insn)
233 return insn->code == (BPF_JMP | BPF_CALL) &&
234 insn->src_reg == BPF_PSEUDO_CALL;
237 struct bpf_call_arg_meta {
238 struct bpf_map *map_ptr;
253 struct btf *btf_vmlinux;
255 static DEFINE_MUTEX(bpf_verifier_lock);
257 static const struct bpf_line_info *
258 find_linfo(const struct bpf_verifier_env *env, u32 insn_off)
260 const struct bpf_line_info *linfo;
261 const struct bpf_prog *prog;
265 nr_linfo = prog->aux->nr_linfo;
267 if (!nr_linfo || insn_off >= prog->len)
270 linfo = prog->aux->linfo;
271 for (i = 1; i < nr_linfo; i++)
272 if (insn_off < linfo[i].insn_off)
275 return &linfo[i - 1];
278 void bpf_verifier_vlog(struct bpf_verifier_log *log, const char *fmt,
283 n = vscnprintf(log->kbuf, BPF_VERIFIER_TMP_LOG_SIZE, fmt, args);
285 WARN_ONCE(n >= BPF_VERIFIER_TMP_LOG_SIZE - 1,
286 "verifier log line truncated - local buffer too short\n");
288 n = min(log->len_total - log->len_used - 1, n);
291 if (log->level == BPF_LOG_KERNEL) {
292 pr_err("BPF:%s\n", log->kbuf);
295 if (!copy_to_user(log->ubuf + log->len_used, log->kbuf, n + 1))
301 static void bpf_vlog_reset(struct bpf_verifier_log *log, u32 new_pos)
305 if (!bpf_verifier_log_needed(log))
308 log->len_used = new_pos;
309 if (put_user(zero, log->ubuf + new_pos))
313 /* log_level controls verbosity level of eBPF verifier.
314 * bpf_verifier_log_write() is used to dump the verification trace to the log,
315 * so the user can figure out what's wrong with the program
317 __printf(2, 3) void bpf_verifier_log_write(struct bpf_verifier_env *env,
318 const char *fmt, ...)
322 if (!bpf_verifier_log_needed(&env->log))
326 bpf_verifier_vlog(&env->log, fmt, args);
329 EXPORT_SYMBOL_GPL(bpf_verifier_log_write);
331 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
333 struct bpf_verifier_env *env = private_data;
336 if (!bpf_verifier_log_needed(&env->log))
340 bpf_verifier_vlog(&env->log, fmt, args);
344 __printf(2, 3) void bpf_log(struct bpf_verifier_log *log,
345 const char *fmt, ...)
349 if (!bpf_verifier_log_needed(log))
353 bpf_verifier_vlog(log, fmt, args);
357 static const char *ltrim(const char *s)
365 __printf(3, 4) static void verbose_linfo(struct bpf_verifier_env *env,
367 const char *prefix_fmt, ...)
369 const struct bpf_line_info *linfo;
371 if (!bpf_verifier_log_needed(&env->log))
374 linfo = find_linfo(env, insn_off);
375 if (!linfo || linfo == env->prev_linfo)
381 va_start(args, prefix_fmt);
382 bpf_verifier_vlog(&env->log, prefix_fmt, args);
387 ltrim(btf_name_by_offset(env->prog->aux->btf,
390 env->prev_linfo = linfo;
393 static bool type_is_pkt_pointer(enum bpf_reg_type type)
395 return type == PTR_TO_PACKET ||
396 type == PTR_TO_PACKET_META;
399 static bool type_is_sk_pointer(enum bpf_reg_type type)
401 return type == PTR_TO_SOCKET ||
402 type == PTR_TO_SOCK_COMMON ||
403 type == PTR_TO_TCP_SOCK ||
404 type == PTR_TO_XDP_SOCK;
407 static bool reg_type_not_null(enum bpf_reg_type type)
409 return type == PTR_TO_SOCKET ||
410 type == PTR_TO_TCP_SOCK ||
411 type == PTR_TO_MAP_VALUE ||
412 type == PTR_TO_SOCK_COMMON;
415 static bool reg_type_may_be_null(enum bpf_reg_type type)
417 return type == PTR_TO_MAP_VALUE_OR_NULL ||
418 type == PTR_TO_SOCKET_OR_NULL ||
419 type == PTR_TO_SOCK_COMMON_OR_NULL ||
420 type == PTR_TO_TCP_SOCK_OR_NULL ||
421 type == PTR_TO_BTF_ID_OR_NULL ||
422 type == PTR_TO_MEM_OR_NULL ||
423 type == PTR_TO_RDONLY_BUF_OR_NULL ||
424 type == PTR_TO_RDWR_BUF_OR_NULL;
427 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
429 return reg->type == PTR_TO_MAP_VALUE &&
430 map_value_has_spin_lock(reg->map_ptr);
433 static bool reg_type_may_be_refcounted_or_null(enum bpf_reg_type type)
435 return type == PTR_TO_SOCKET ||
436 type == PTR_TO_SOCKET_OR_NULL ||
437 type == PTR_TO_TCP_SOCK ||
438 type == PTR_TO_TCP_SOCK_OR_NULL ||
439 type == PTR_TO_MEM ||
440 type == PTR_TO_MEM_OR_NULL;
443 static bool arg_type_may_be_refcounted(enum bpf_arg_type type)
445 return type == ARG_PTR_TO_SOCK_COMMON;
448 static bool arg_type_may_be_null(enum bpf_arg_type type)
450 return type == ARG_PTR_TO_MAP_VALUE_OR_NULL ||
451 type == ARG_PTR_TO_MEM_OR_NULL ||
452 type == ARG_PTR_TO_CTX_OR_NULL ||
453 type == ARG_PTR_TO_SOCKET_OR_NULL ||
454 type == ARG_PTR_TO_ALLOC_MEM_OR_NULL;
457 /* Determine whether the function releases some resources allocated by another
458 * function call. The first reference type argument will be assumed to be
459 * released by release_reference().
461 static bool is_release_function(enum bpf_func_id func_id)
463 return func_id == BPF_FUNC_sk_release ||
464 func_id == BPF_FUNC_ringbuf_submit ||
465 func_id == BPF_FUNC_ringbuf_discard;
468 static bool may_be_acquire_function(enum bpf_func_id func_id)
470 return func_id == BPF_FUNC_sk_lookup_tcp ||
471 func_id == BPF_FUNC_sk_lookup_udp ||
472 func_id == BPF_FUNC_skc_lookup_tcp ||
473 func_id == BPF_FUNC_map_lookup_elem ||
474 func_id == BPF_FUNC_ringbuf_reserve;
477 static bool is_acquire_function(enum bpf_func_id func_id,
478 const struct bpf_map *map)
480 enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
482 if (func_id == BPF_FUNC_sk_lookup_tcp ||
483 func_id == BPF_FUNC_sk_lookup_udp ||
484 func_id == BPF_FUNC_skc_lookup_tcp ||
485 func_id == BPF_FUNC_ringbuf_reserve)
488 if (func_id == BPF_FUNC_map_lookup_elem &&
489 (map_type == BPF_MAP_TYPE_SOCKMAP ||
490 map_type == BPF_MAP_TYPE_SOCKHASH))
496 static bool is_ptr_cast_function(enum bpf_func_id func_id)
498 return func_id == BPF_FUNC_tcp_sock ||
499 func_id == BPF_FUNC_sk_fullsock ||
500 func_id == BPF_FUNC_skc_to_tcp_sock ||
501 func_id == BPF_FUNC_skc_to_tcp6_sock ||
502 func_id == BPF_FUNC_skc_to_udp6_sock ||
503 func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
504 func_id == BPF_FUNC_skc_to_tcp_request_sock;
507 /* string representation of 'enum bpf_reg_type' */
508 static const char * const reg_type_str[] = {
510 [SCALAR_VALUE] = "inv",
511 [PTR_TO_CTX] = "ctx",
512 [CONST_PTR_TO_MAP] = "map_ptr",
513 [PTR_TO_MAP_VALUE] = "map_value",
514 [PTR_TO_MAP_VALUE_OR_NULL] = "map_value_or_null",
515 [PTR_TO_STACK] = "fp",
516 [PTR_TO_PACKET] = "pkt",
517 [PTR_TO_PACKET_META] = "pkt_meta",
518 [PTR_TO_PACKET_END] = "pkt_end",
519 [PTR_TO_FLOW_KEYS] = "flow_keys",
520 [PTR_TO_SOCKET] = "sock",
521 [PTR_TO_SOCKET_OR_NULL] = "sock_or_null",
522 [PTR_TO_SOCK_COMMON] = "sock_common",
523 [PTR_TO_SOCK_COMMON_OR_NULL] = "sock_common_or_null",
524 [PTR_TO_TCP_SOCK] = "tcp_sock",
525 [PTR_TO_TCP_SOCK_OR_NULL] = "tcp_sock_or_null",
526 [PTR_TO_TP_BUFFER] = "tp_buffer",
527 [PTR_TO_XDP_SOCK] = "xdp_sock",
528 [PTR_TO_BTF_ID] = "ptr_",
529 [PTR_TO_BTF_ID_OR_NULL] = "ptr_or_null_",
530 [PTR_TO_PERCPU_BTF_ID] = "percpu_ptr_",
531 [PTR_TO_MEM] = "mem",
532 [PTR_TO_MEM_OR_NULL] = "mem_or_null",
533 [PTR_TO_RDONLY_BUF] = "rdonly_buf",
534 [PTR_TO_RDONLY_BUF_OR_NULL] = "rdonly_buf_or_null",
535 [PTR_TO_RDWR_BUF] = "rdwr_buf",
536 [PTR_TO_RDWR_BUF_OR_NULL] = "rdwr_buf_or_null",
539 static char slot_type_char[] = {
540 [STACK_INVALID] = '?',
546 static void print_liveness(struct bpf_verifier_env *env,
547 enum bpf_reg_liveness live)
549 if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE))
551 if (live & REG_LIVE_READ)
553 if (live & REG_LIVE_WRITTEN)
555 if (live & REG_LIVE_DONE)
559 static struct bpf_func_state *func(struct bpf_verifier_env *env,
560 const struct bpf_reg_state *reg)
562 struct bpf_verifier_state *cur = env->cur_state;
564 return cur->frame[reg->frameno];
567 static const char *kernel_type_name(const struct btf* btf, u32 id)
569 return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off);
572 static void print_verifier_state(struct bpf_verifier_env *env,
573 const struct bpf_func_state *state)
575 const struct bpf_reg_state *reg;
580 verbose(env, " frame%d:", state->frameno);
581 for (i = 0; i < MAX_BPF_REG; i++) {
582 reg = &state->regs[i];
586 verbose(env, " R%d", i);
587 print_liveness(env, reg->live);
588 verbose(env, "=%s", reg_type_str[t]);
589 if (t == SCALAR_VALUE && reg->precise)
591 if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
592 tnum_is_const(reg->var_off)) {
593 /* reg->off should be 0 for SCALAR_VALUE */
594 verbose(env, "%lld", reg->var_off.value + reg->off);
596 if (t == PTR_TO_BTF_ID ||
597 t == PTR_TO_BTF_ID_OR_NULL ||
598 t == PTR_TO_PERCPU_BTF_ID)
599 verbose(env, "%s", kernel_type_name(reg->btf, reg->btf_id));
600 verbose(env, "(id=%d", reg->id);
601 if (reg_type_may_be_refcounted_or_null(t))
602 verbose(env, ",ref_obj_id=%d", reg->ref_obj_id);
603 if (t != SCALAR_VALUE)
604 verbose(env, ",off=%d", reg->off);
605 if (type_is_pkt_pointer(t))
606 verbose(env, ",r=%d", reg->range);
607 else if (t == CONST_PTR_TO_MAP ||
608 t == PTR_TO_MAP_VALUE ||
609 t == PTR_TO_MAP_VALUE_OR_NULL)
610 verbose(env, ",ks=%d,vs=%d",
611 reg->map_ptr->key_size,
612 reg->map_ptr->value_size);
613 if (tnum_is_const(reg->var_off)) {
614 /* Typically an immediate SCALAR_VALUE, but
615 * could be a pointer whose offset is too big
618 verbose(env, ",imm=%llx", reg->var_off.value);
620 if (reg->smin_value != reg->umin_value &&
621 reg->smin_value != S64_MIN)
622 verbose(env, ",smin_value=%lld",
623 (long long)reg->smin_value);
624 if (reg->smax_value != reg->umax_value &&
625 reg->smax_value != S64_MAX)
626 verbose(env, ",smax_value=%lld",
627 (long long)reg->smax_value);
628 if (reg->umin_value != 0)
629 verbose(env, ",umin_value=%llu",
630 (unsigned long long)reg->umin_value);
631 if (reg->umax_value != U64_MAX)
632 verbose(env, ",umax_value=%llu",
633 (unsigned long long)reg->umax_value);
634 if (!tnum_is_unknown(reg->var_off)) {
637 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
638 verbose(env, ",var_off=%s", tn_buf);
640 if (reg->s32_min_value != reg->smin_value &&
641 reg->s32_min_value != S32_MIN)
642 verbose(env, ",s32_min_value=%d",
643 (int)(reg->s32_min_value));
644 if (reg->s32_max_value != reg->smax_value &&
645 reg->s32_max_value != S32_MAX)
646 verbose(env, ",s32_max_value=%d",
647 (int)(reg->s32_max_value));
648 if (reg->u32_min_value != reg->umin_value &&
649 reg->u32_min_value != U32_MIN)
650 verbose(env, ",u32_min_value=%d",
651 (int)(reg->u32_min_value));
652 if (reg->u32_max_value != reg->umax_value &&
653 reg->u32_max_value != U32_MAX)
654 verbose(env, ",u32_max_value=%d",
655 (int)(reg->u32_max_value));
660 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
661 char types_buf[BPF_REG_SIZE + 1];
665 for (j = 0; j < BPF_REG_SIZE; j++) {
666 if (state->stack[i].slot_type[j] != STACK_INVALID)
668 types_buf[j] = slot_type_char[
669 state->stack[i].slot_type[j]];
671 types_buf[BPF_REG_SIZE] = 0;
674 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
675 print_liveness(env, state->stack[i].spilled_ptr.live);
676 if (state->stack[i].slot_type[0] == STACK_SPILL) {
677 reg = &state->stack[i].spilled_ptr;
679 verbose(env, "=%s", reg_type_str[t]);
680 if (t == SCALAR_VALUE && reg->precise)
682 if (t == SCALAR_VALUE && tnum_is_const(reg->var_off))
683 verbose(env, "%lld", reg->var_off.value + reg->off);
685 verbose(env, "=%s", types_buf);
688 if (state->acquired_refs && state->refs[0].id) {
689 verbose(env, " refs=%d", state->refs[0].id);
690 for (i = 1; i < state->acquired_refs; i++)
691 if (state->refs[i].id)
692 verbose(env, ",%d", state->refs[i].id);
697 #define COPY_STATE_FN(NAME, COUNT, FIELD, SIZE) \
698 static int copy_##NAME##_state(struct bpf_func_state *dst, \
699 const struct bpf_func_state *src) \
703 if (WARN_ON_ONCE(dst->COUNT < src->COUNT)) { \
704 /* internal bug, make state invalid to reject the program */ \
705 memset(dst, 0, sizeof(*dst)); \
708 memcpy(dst->FIELD, src->FIELD, \
709 sizeof(*src->FIELD) * (src->COUNT / SIZE)); \
712 /* copy_reference_state() */
713 COPY_STATE_FN(reference, acquired_refs, refs, 1)
714 /* copy_stack_state() */
715 COPY_STATE_FN(stack, allocated_stack, stack, BPF_REG_SIZE)
718 #define REALLOC_STATE_FN(NAME, COUNT, FIELD, SIZE) \
719 static int realloc_##NAME##_state(struct bpf_func_state *state, int size, \
722 u32 old_size = state->COUNT; \
723 struct bpf_##NAME##_state *new_##FIELD; \
724 int slot = size / SIZE; \
726 if (size <= old_size || !size) { \
729 state->COUNT = slot * SIZE; \
730 if (!size && old_size) { \
731 kfree(state->FIELD); \
732 state->FIELD = NULL; \
736 new_##FIELD = kmalloc_array(slot, sizeof(struct bpf_##NAME##_state), \
742 memcpy(new_##FIELD, state->FIELD, \
743 sizeof(*new_##FIELD) * (old_size / SIZE)); \
744 memset(new_##FIELD + old_size / SIZE, 0, \
745 sizeof(*new_##FIELD) * (size - old_size) / SIZE); \
747 state->COUNT = slot * SIZE; \
748 kfree(state->FIELD); \
749 state->FIELD = new_##FIELD; \
752 /* realloc_reference_state() */
753 REALLOC_STATE_FN(reference, acquired_refs, refs, 1)
754 /* realloc_stack_state() */
755 REALLOC_STATE_FN(stack, allocated_stack, stack, BPF_REG_SIZE)
756 #undef REALLOC_STATE_FN
758 /* do_check() starts with zero-sized stack in struct bpf_verifier_state to
759 * make it consume minimal amount of memory. check_stack_write() access from
760 * the program calls into realloc_func_state() to grow the stack size.
761 * Note there is a non-zero 'parent' pointer inside bpf_verifier_state
762 * which realloc_stack_state() copies over. It points to previous
763 * bpf_verifier_state which is never reallocated.
765 static int realloc_func_state(struct bpf_func_state *state, int stack_size,
766 int refs_size, bool copy_old)
768 int err = realloc_reference_state(state, refs_size, copy_old);
771 return realloc_stack_state(state, stack_size, copy_old);
774 /* Acquire a pointer id from the env and update the state->refs to include
775 * this new pointer reference.
776 * On success, returns a valid pointer id to associate with the register
777 * On failure, returns a negative errno.
779 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
781 struct bpf_func_state *state = cur_func(env);
782 int new_ofs = state->acquired_refs;
785 err = realloc_reference_state(state, state->acquired_refs + 1, true);
789 state->refs[new_ofs].id = id;
790 state->refs[new_ofs].insn_idx = insn_idx;
795 /* release function corresponding to acquire_reference_state(). Idempotent. */
796 static int release_reference_state(struct bpf_func_state *state, int ptr_id)
800 last_idx = state->acquired_refs - 1;
801 for (i = 0; i < state->acquired_refs; i++) {
802 if (state->refs[i].id == ptr_id) {
803 if (last_idx && i != last_idx)
804 memcpy(&state->refs[i], &state->refs[last_idx],
805 sizeof(*state->refs));
806 memset(&state->refs[last_idx], 0, sizeof(*state->refs));
807 state->acquired_refs--;
814 static int transfer_reference_state(struct bpf_func_state *dst,
815 struct bpf_func_state *src)
817 int err = realloc_reference_state(dst, src->acquired_refs, false);
820 err = copy_reference_state(dst, src);
826 static void free_func_state(struct bpf_func_state *state)
835 static void clear_jmp_history(struct bpf_verifier_state *state)
837 kfree(state->jmp_history);
838 state->jmp_history = NULL;
839 state->jmp_history_cnt = 0;
842 static void free_verifier_state(struct bpf_verifier_state *state,
847 for (i = 0; i <= state->curframe; i++) {
848 free_func_state(state->frame[i]);
849 state->frame[i] = NULL;
851 clear_jmp_history(state);
856 /* copy verifier state from src to dst growing dst stack space
857 * when necessary to accommodate larger src stack
859 static int copy_func_state(struct bpf_func_state *dst,
860 const struct bpf_func_state *src)
864 err = realloc_func_state(dst, src->allocated_stack, src->acquired_refs,
868 memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
869 err = copy_reference_state(dst, src);
872 return copy_stack_state(dst, src);
875 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
876 const struct bpf_verifier_state *src)
878 struct bpf_func_state *dst;
879 u32 jmp_sz = sizeof(struct bpf_idx_pair) * src->jmp_history_cnt;
882 if (dst_state->jmp_history_cnt < src->jmp_history_cnt) {
883 kfree(dst_state->jmp_history);
884 dst_state->jmp_history = kmalloc(jmp_sz, GFP_USER);
885 if (!dst_state->jmp_history)
888 memcpy(dst_state->jmp_history, src->jmp_history, jmp_sz);
889 dst_state->jmp_history_cnt = src->jmp_history_cnt;
891 /* if dst has more stack frames then src frame, free them */
892 for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
893 free_func_state(dst_state->frame[i]);
894 dst_state->frame[i] = NULL;
896 dst_state->speculative = src->speculative;
897 dst_state->curframe = src->curframe;
898 dst_state->active_spin_lock = src->active_spin_lock;
899 dst_state->branches = src->branches;
900 dst_state->parent = src->parent;
901 dst_state->first_insn_idx = src->first_insn_idx;
902 dst_state->last_insn_idx = src->last_insn_idx;
903 for (i = 0; i <= src->curframe; i++) {
904 dst = dst_state->frame[i];
906 dst = kzalloc(sizeof(*dst), GFP_KERNEL);
909 dst_state->frame[i] = dst;
911 err = copy_func_state(dst, src->frame[i]);
918 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
921 u32 br = --st->branches;
923 /* WARN_ON(br > 1) technically makes sense here,
924 * but see comment in push_stack(), hence:
926 WARN_ONCE((int)br < 0,
927 "BUG update_branch_counts:branches_to_explore=%d\n",
935 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
936 int *insn_idx, bool pop_log)
938 struct bpf_verifier_state *cur = env->cur_state;
939 struct bpf_verifier_stack_elem *elem, *head = env->head;
942 if (env->head == NULL)
946 err = copy_verifier_state(cur, &head->st);
951 bpf_vlog_reset(&env->log, head->log_pos);
953 *insn_idx = head->insn_idx;
955 *prev_insn_idx = head->prev_insn_idx;
957 free_verifier_state(&head->st, false);
964 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
965 int insn_idx, int prev_insn_idx,
968 struct bpf_verifier_state *cur = env->cur_state;
969 struct bpf_verifier_stack_elem *elem;
972 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
976 elem->insn_idx = insn_idx;
977 elem->prev_insn_idx = prev_insn_idx;
978 elem->next = env->head;
979 elem->log_pos = env->log.len_used;
982 err = copy_verifier_state(&elem->st, cur);
985 elem->st.speculative |= speculative;
986 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
987 verbose(env, "The sequence of %d jumps is too complex.\n",
991 if (elem->st.parent) {
992 ++elem->st.parent->branches;
993 /* WARN_ON(branches > 2) technically makes sense here,
995 * 1. speculative states will bump 'branches' for non-branch
997 * 2. is_state_visited() heuristics may decide not to create
998 * a new state for a sequence of branches and all such current
999 * and cloned states will be pointing to a single parent state
1000 * which might have large 'branches' count.
1005 free_verifier_state(env->cur_state, true);
1006 env->cur_state = NULL;
1007 /* pop all elements and return */
1008 while (!pop_stack(env, NULL, NULL, false));
1012 #define CALLER_SAVED_REGS 6
1013 static const int caller_saved[CALLER_SAVED_REGS] = {
1014 BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
1017 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1018 struct bpf_reg_state *reg);
1020 /* This helper doesn't clear reg->id */
1021 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1023 reg->var_off = tnum_const(imm);
1024 reg->smin_value = (s64)imm;
1025 reg->smax_value = (s64)imm;
1026 reg->umin_value = imm;
1027 reg->umax_value = imm;
1029 reg->s32_min_value = (s32)imm;
1030 reg->s32_max_value = (s32)imm;
1031 reg->u32_min_value = (u32)imm;
1032 reg->u32_max_value = (u32)imm;
1035 /* Mark the unknown part of a register (variable offset or scalar value) as
1036 * known to have the value @imm.
1038 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1040 /* Clear id, off, and union(map_ptr, range) */
1041 memset(((u8 *)reg) + sizeof(reg->type), 0,
1042 offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
1043 ___mark_reg_known(reg, imm);
1046 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1048 reg->var_off = tnum_const_subreg(reg->var_off, imm);
1049 reg->s32_min_value = (s32)imm;
1050 reg->s32_max_value = (s32)imm;
1051 reg->u32_min_value = (u32)imm;
1052 reg->u32_max_value = (u32)imm;
1055 /* Mark the 'variable offset' part of a register as zero. This should be
1056 * used only on registers holding a pointer type.
1058 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
1060 __mark_reg_known(reg, 0);
1063 static void __mark_reg_const_zero(struct bpf_reg_state *reg)
1065 __mark_reg_known(reg, 0);
1066 reg->type = SCALAR_VALUE;
1069 static void mark_reg_known_zero(struct bpf_verifier_env *env,
1070 struct bpf_reg_state *regs, u32 regno)
1072 if (WARN_ON(regno >= MAX_BPF_REG)) {
1073 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
1074 /* Something bad happened, let's kill all regs */
1075 for (regno = 0; regno < MAX_BPF_REG; regno++)
1076 __mark_reg_not_init(env, regs + regno);
1079 __mark_reg_known_zero(regs + regno);
1082 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
1084 switch (reg->type) {
1085 case PTR_TO_MAP_VALUE_OR_NULL: {
1086 const struct bpf_map *map = reg->map_ptr;
1088 if (map->inner_map_meta) {
1089 reg->type = CONST_PTR_TO_MAP;
1090 reg->map_ptr = map->inner_map_meta;
1091 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
1092 reg->type = PTR_TO_XDP_SOCK;
1093 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
1094 map->map_type == BPF_MAP_TYPE_SOCKHASH) {
1095 reg->type = PTR_TO_SOCKET;
1097 reg->type = PTR_TO_MAP_VALUE;
1101 case PTR_TO_SOCKET_OR_NULL:
1102 reg->type = PTR_TO_SOCKET;
1104 case PTR_TO_SOCK_COMMON_OR_NULL:
1105 reg->type = PTR_TO_SOCK_COMMON;
1107 case PTR_TO_TCP_SOCK_OR_NULL:
1108 reg->type = PTR_TO_TCP_SOCK;
1110 case PTR_TO_BTF_ID_OR_NULL:
1111 reg->type = PTR_TO_BTF_ID;
1113 case PTR_TO_MEM_OR_NULL:
1114 reg->type = PTR_TO_MEM;
1116 case PTR_TO_RDONLY_BUF_OR_NULL:
1117 reg->type = PTR_TO_RDONLY_BUF;
1119 case PTR_TO_RDWR_BUF_OR_NULL:
1120 reg->type = PTR_TO_RDWR_BUF;
1123 WARN_ON("unknown nullable register type");
1127 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1129 return type_is_pkt_pointer(reg->type);
1132 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
1134 return reg_is_pkt_pointer(reg) ||
1135 reg->type == PTR_TO_PACKET_END;
1138 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
1139 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
1140 enum bpf_reg_type which)
1142 /* The register can already have a range from prior markings.
1143 * This is fine as long as it hasn't been advanced from its
1146 return reg->type == which &&
1149 tnum_equals_const(reg->var_off, 0);
1152 /* Reset the min/max bounds of a register */
1153 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
1155 reg->smin_value = S64_MIN;
1156 reg->smax_value = S64_MAX;
1157 reg->umin_value = 0;
1158 reg->umax_value = U64_MAX;
1160 reg->s32_min_value = S32_MIN;
1161 reg->s32_max_value = S32_MAX;
1162 reg->u32_min_value = 0;
1163 reg->u32_max_value = U32_MAX;
1166 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
1168 reg->smin_value = S64_MIN;
1169 reg->smax_value = S64_MAX;
1170 reg->umin_value = 0;
1171 reg->umax_value = U64_MAX;
1174 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
1176 reg->s32_min_value = S32_MIN;
1177 reg->s32_max_value = S32_MAX;
1178 reg->u32_min_value = 0;
1179 reg->u32_max_value = U32_MAX;
1182 static void __update_reg32_bounds(struct bpf_reg_state *reg)
1184 struct tnum var32_off = tnum_subreg(reg->var_off);
1186 /* min signed is max(sign bit) | min(other bits) */
1187 reg->s32_min_value = max_t(s32, reg->s32_min_value,
1188 var32_off.value | (var32_off.mask & S32_MIN));
1189 /* max signed is min(sign bit) | max(other bits) */
1190 reg->s32_max_value = min_t(s32, reg->s32_max_value,
1191 var32_off.value | (var32_off.mask & S32_MAX));
1192 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
1193 reg->u32_max_value = min(reg->u32_max_value,
1194 (u32)(var32_off.value | var32_off.mask));
1197 static void __update_reg64_bounds(struct bpf_reg_state *reg)
1199 /* min signed is max(sign bit) | min(other bits) */
1200 reg->smin_value = max_t(s64, reg->smin_value,
1201 reg->var_off.value | (reg->var_off.mask & S64_MIN));
1202 /* max signed is min(sign bit) | max(other bits) */
1203 reg->smax_value = min_t(s64, reg->smax_value,
1204 reg->var_off.value | (reg->var_off.mask & S64_MAX));
1205 reg->umin_value = max(reg->umin_value, reg->var_off.value);
1206 reg->umax_value = min(reg->umax_value,
1207 reg->var_off.value | reg->var_off.mask);
1210 static void __update_reg_bounds(struct bpf_reg_state *reg)
1212 __update_reg32_bounds(reg);
1213 __update_reg64_bounds(reg);
1216 /* Uses signed min/max values to inform unsigned, and vice-versa */
1217 static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
1219 /* Learn sign from signed bounds.
1220 * If we cannot cross the sign boundary, then signed and unsigned bounds
1221 * are the same, so combine. This works even in the negative case, e.g.
1222 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1224 if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) {
1225 reg->s32_min_value = reg->u32_min_value =
1226 max_t(u32, reg->s32_min_value, reg->u32_min_value);
1227 reg->s32_max_value = reg->u32_max_value =
1228 min_t(u32, reg->s32_max_value, reg->u32_max_value);
1231 /* Learn sign from unsigned bounds. Signed bounds cross the sign
1232 * boundary, so we must be careful.
1234 if ((s32)reg->u32_max_value >= 0) {
1235 /* Positive. We can't learn anything from the smin, but smax
1236 * is positive, hence safe.
1238 reg->s32_min_value = reg->u32_min_value;
1239 reg->s32_max_value = reg->u32_max_value =
1240 min_t(u32, reg->s32_max_value, reg->u32_max_value);
1241 } else if ((s32)reg->u32_min_value < 0) {
1242 /* Negative. We can't learn anything from the smax, but smin
1243 * is negative, hence safe.
1245 reg->s32_min_value = reg->u32_min_value =
1246 max_t(u32, reg->s32_min_value, reg->u32_min_value);
1247 reg->s32_max_value = reg->u32_max_value;
1251 static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
1253 /* Learn sign from signed bounds.
1254 * If we cannot cross the sign boundary, then signed and unsigned bounds
1255 * are the same, so combine. This works even in the negative case, e.g.
1256 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1258 if (reg->smin_value >= 0 || reg->smax_value < 0) {
1259 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1261 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1265 /* Learn sign from unsigned bounds. Signed bounds cross the sign
1266 * boundary, so we must be careful.
1268 if ((s64)reg->umax_value >= 0) {
1269 /* Positive. We can't learn anything from the smin, but smax
1270 * is positive, hence safe.
1272 reg->smin_value = reg->umin_value;
1273 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1275 } else if ((s64)reg->umin_value < 0) {
1276 /* Negative. We can't learn anything from the smax, but smin
1277 * is negative, hence safe.
1279 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1281 reg->smax_value = reg->umax_value;
1285 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
1287 __reg32_deduce_bounds(reg);
1288 __reg64_deduce_bounds(reg);
1291 /* Attempts to improve var_off based on unsigned min/max information */
1292 static void __reg_bound_offset(struct bpf_reg_state *reg)
1294 struct tnum var64_off = tnum_intersect(reg->var_off,
1295 tnum_range(reg->umin_value,
1297 struct tnum var32_off = tnum_intersect(tnum_subreg(reg->var_off),
1298 tnum_range(reg->u32_min_value,
1299 reg->u32_max_value));
1301 reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
1304 static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
1306 reg->umin_value = reg->u32_min_value;
1307 reg->umax_value = reg->u32_max_value;
1308 /* Attempt to pull 32-bit signed bounds into 64-bit bounds
1309 * but must be positive otherwise set to worse case bounds
1310 * and refine later from tnum.
1312 if (reg->s32_min_value >= 0 && reg->s32_max_value >= 0)
1313 reg->smax_value = reg->s32_max_value;
1315 reg->smax_value = U32_MAX;
1316 if (reg->s32_min_value >= 0)
1317 reg->smin_value = reg->s32_min_value;
1319 reg->smin_value = 0;
1322 static void __reg_combine_32_into_64(struct bpf_reg_state *reg)
1324 /* special case when 64-bit register has upper 32-bit register
1325 * zeroed. Typically happens after zext or <<32, >>32 sequence
1326 * allowing us to use 32-bit bounds directly,
1328 if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) {
1329 __reg_assign_32_into_64(reg);
1331 /* Otherwise the best we can do is push lower 32bit known and
1332 * unknown bits into register (var_off set from jmp logic)
1333 * then learn as much as possible from the 64-bit tnum
1334 * known and unknown bits. The previous smin/smax bounds are
1335 * invalid here because of jmp32 compare so mark them unknown
1336 * so they do not impact tnum bounds calculation.
1338 __mark_reg64_unbounded(reg);
1339 __update_reg_bounds(reg);
1342 /* Intersecting with the old var_off might have improved our bounds
1343 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1344 * then new var_off is (0; 0x7f...fc) which improves our umax.
1346 __reg_deduce_bounds(reg);
1347 __reg_bound_offset(reg);
1348 __update_reg_bounds(reg);
1351 static bool __reg64_bound_s32(s64 a)
1353 return a > S32_MIN && a < S32_MAX;
1356 static bool __reg64_bound_u32(u64 a)
1358 if (a > U32_MIN && a < U32_MAX)
1363 static void __reg_combine_64_into_32(struct bpf_reg_state *reg)
1365 __mark_reg32_unbounded(reg);
1367 if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) {
1368 reg->s32_min_value = (s32)reg->smin_value;
1369 reg->s32_max_value = (s32)reg->smax_value;
1371 if (__reg64_bound_u32(reg->umin_value))
1372 reg->u32_min_value = (u32)reg->umin_value;
1373 if (__reg64_bound_u32(reg->umax_value))
1374 reg->u32_max_value = (u32)reg->umax_value;
1376 /* Intersecting with the old var_off might have improved our bounds
1377 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1378 * then new var_off is (0; 0x7f...fc) which improves our umax.
1380 __reg_deduce_bounds(reg);
1381 __reg_bound_offset(reg);
1382 __update_reg_bounds(reg);
1385 /* Mark a register as having a completely unknown (scalar) value. */
1386 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
1387 struct bpf_reg_state *reg)
1390 * Clear type, id, off, and union(map_ptr, range) and
1391 * padding between 'type' and union
1393 memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
1394 reg->type = SCALAR_VALUE;
1395 reg->var_off = tnum_unknown;
1397 reg->precise = env->subprog_cnt > 1 || !env->bpf_capable;
1398 __mark_reg_unbounded(reg);
1401 static void mark_reg_unknown(struct bpf_verifier_env *env,
1402 struct bpf_reg_state *regs, u32 regno)
1404 if (WARN_ON(regno >= MAX_BPF_REG)) {
1405 verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
1406 /* Something bad happened, let's kill all regs except FP */
1407 for (regno = 0; regno < BPF_REG_FP; regno++)
1408 __mark_reg_not_init(env, regs + regno);
1411 __mark_reg_unknown(env, regs + regno);
1414 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1415 struct bpf_reg_state *reg)
1417 __mark_reg_unknown(env, reg);
1418 reg->type = NOT_INIT;
1421 static void mark_reg_not_init(struct bpf_verifier_env *env,
1422 struct bpf_reg_state *regs, u32 regno)
1424 if (WARN_ON(regno >= MAX_BPF_REG)) {
1425 verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
1426 /* Something bad happened, let's kill all regs except FP */
1427 for (regno = 0; regno < BPF_REG_FP; regno++)
1428 __mark_reg_not_init(env, regs + regno);
1431 __mark_reg_not_init(env, regs + regno);
1434 static void mark_btf_ld_reg(struct bpf_verifier_env *env,
1435 struct bpf_reg_state *regs, u32 regno,
1436 enum bpf_reg_type reg_type,
1437 struct btf *btf, u32 btf_id)
1439 if (reg_type == SCALAR_VALUE) {
1440 mark_reg_unknown(env, regs, regno);
1443 mark_reg_known_zero(env, regs, regno);
1444 regs[regno].type = PTR_TO_BTF_ID;
1445 regs[regno].btf = btf;
1446 regs[regno].btf_id = btf_id;
1449 #define DEF_NOT_SUBREG (0)
1450 static void init_reg_state(struct bpf_verifier_env *env,
1451 struct bpf_func_state *state)
1453 struct bpf_reg_state *regs = state->regs;
1456 for (i = 0; i < MAX_BPF_REG; i++) {
1457 mark_reg_not_init(env, regs, i);
1458 regs[i].live = REG_LIVE_NONE;
1459 regs[i].parent = NULL;
1460 regs[i].subreg_def = DEF_NOT_SUBREG;
1464 regs[BPF_REG_FP].type = PTR_TO_STACK;
1465 mark_reg_known_zero(env, regs, BPF_REG_FP);
1466 regs[BPF_REG_FP].frameno = state->frameno;
1469 #define BPF_MAIN_FUNC (-1)
1470 static void init_func_state(struct bpf_verifier_env *env,
1471 struct bpf_func_state *state,
1472 int callsite, int frameno, int subprogno)
1474 state->callsite = callsite;
1475 state->frameno = frameno;
1476 state->subprogno = subprogno;
1477 init_reg_state(env, state);
1481 SRC_OP, /* register is used as source operand */
1482 DST_OP, /* register is used as destination operand */
1483 DST_OP_NO_MARK /* same as above, check only, don't mark */
1486 static int cmp_subprogs(const void *a, const void *b)
1488 return ((struct bpf_subprog_info *)a)->start -
1489 ((struct bpf_subprog_info *)b)->start;
1492 static int find_subprog(struct bpf_verifier_env *env, int off)
1494 struct bpf_subprog_info *p;
1496 p = bsearch(&off, env->subprog_info, env->subprog_cnt,
1497 sizeof(env->subprog_info[0]), cmp_subprogs);
1500 return p - env->subprog_info;
1504 static int add_subprog(struct bpf_verifier_env *env, int off)
1506 int insn_cnt = env->prog->len;
1509 if (off >= insn_cnt || off < 0) {
1510 verbose(env, "call to invalid destination\n");
1513 ret = find_subprog(env, off);
1516 if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
1517 verbose(env, "too many subprograms\n");
1520 env->subprog_info[env->subprog_cnt++].start = off;
1521 sort(env->subprog_info, env->subprog_cnt,
1522 sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
1526 static int check_subprogs(struct bpf_verifier_env *env)
1528 int i, ret, subprog_start, subprog_end, off, cur_subprog = 0;
1529 struct bpf_subprog_info *subprog = env->subprog_info;
1530 struct bpf_insn *insn = env->prog->insnsi;
1531 int insn_cnt = env->prog->len;
1533 /* Add entry function. */
1534 ret = add_subprog(env, 0);
1538 /* determine subprog starts. The end is one before the next starts */
1539 for (i = 0; i < insn_cnt; i++) {
1540 if (!bpf_pseudo_call(insn + i))
1542 if (!env->bpf_capable) {
1544 "function calls to other bpf functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
1547 ret = add_subprog(env, i + insn[i].imm + 1);
1552 /* Add a fake 'exit' subprog which could simplify subprog iteration
1553 * logic. 'subprog_cnt' should not be increased.
1555 subprog[env->subprog_cnt].start = insn_cnt;
1557 if (env->log.level & BPF_LOG_LEVEL2)
1558 for (i = 0; i < env->subprog_cnt; i++)
1559 verbose(env, "func#%d @%d\n", i, subprog[i].start);
1561 /* now check that all jumps are within the same subprog */
1562 subprog_start = subprog[cur_subprog].start;
1563 subprog_end = subprog[cur_subprog + 1].start;
1564 for (i = 0; i < insn_cnt; i++) {
1565 u8 code = insn[i].code;
1567 if (code == (BPF_JMP | BPF_CALL) &&
1568 insn[i].imm == BPF_FUNC_tail_call &&
1569 insn[i].src_reg != BPF_PSEUDO_CALL)
1570 subprog[cur_subprog].has_tail_call = true;
1571 if (BPF_CLASS(code) == BPF_LD &&
1572 (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
1573 subprog[cur_subprog].has_ld_abs = true;
1574 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
1576 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
1578 off = i + insn[i].off + 1;
1579 if (off < subprog_start || off >= subprog_end) {
1580 verbose(env, "jump out of range from insn %d to %d\n", i, off);
1584 if (i == subprog_end - 1) {
1585 /* to avoid fall-through from one subprog into another
1586 * the last insn of the subprog should be either exit
1587 * or unconditional jump back
1589 if (code != (BPF_JMP | BPF_EXIT) &&
1590 code != (BPF_JMP | BPF_JA)) {
1591 verbose(env, "last insn is not an exit or jmp\n");
1594 subprog_start = subprog_end;
1596 if (cur_subprog < env->subprog_cnt)
1597 subprog_end = subprog[cur_subprog + 1].start;
1603 /* Parentage chain of this register (or stack slot) should take care of all
1604 * issues like callee-saved registers, stack slot allocation time, etc.
1606 static int mark_reg_read(struct bpf_verifier_env *env,
1607 const struct bpf_reg_state *state,
1608 struct bpf_reg_state *parent, u8 flag)
1610 bool writes = parent == state->parent; /* Observe write marks */
1614 /* if read wasn't screened by an earlier write ... */
1615 if (writes && state->live & REG_LIVE_WRITTEN)
1617 if (parent->live & REG_LIVE_DONE) {
1618 verbose(env, "verifier BUG type %s var_off %lld off %d\n",
1619 reg_type_str[parent->type],
1620 parent->var_off.value, parent->off);
1623 /* The first condition is more likely to be true than the
1624 * second, checked it first.
1626 if ((parent->live & REG_LIVE_READ) == flag ||
1627 parent->live & REG_LIVE_READ64)
1628 /* The parentage chain never changes and
1629 * this parent was already marked as LIVE_READ.
1630 * There is no need to keep walking the chain again and
1631 * keep re-marking all parents as LIVE_READ.
1632 * This case happens when the same register is read
1633 * multiple times without writes into it in-between.
1634 * Also, if parent has the stronger REG_LIVE_READ64 set,
1635 * then no need to set the weak REG_LIVE_READ32.
1638 /* ... then we depend on parent's value */
1639 parent->live |= flag;
1640 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
1641 if (flag == REG_LIVE_READ64)
1642 parent->live &= ~REG_LIVE_READ32;
1644 parent = state->parent;
1649 if (env->longest_mark_read_walk < cnt)
1650 env->longest_mark_read_walk = cnt;
1654 /* This function is supposed to be used by the following 32-bit optimization
1655 * code only. It returns TRUE if the source or destination register operates
1656 * on 64-bit, otherwise return FALSE.
1658 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
1659 u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
1664 class = BPF_CLASS(code);
1666 if (class == BPF_JMP) {
1667 /* BPF_EXIT for "main" will reach here. Return TRUE
1672 if (op == BPF_CALL) {
1673 /* BPF to BPF call will reach here because of marking
1674 * caller saved clobber with DST_OP_NO_MARK for which we
1675 * don't care the register def because they are anyway
1676 * marked as NOT_INIT already.
1678 if (insn->src_reg == BPF_PSEUDO_CALL)
1680 /* Helper call will reach here because of arg type
1681 * check, conservatively return TRUE.
1690 if (class == BPF_ALU64 || class == BPF_JMP ||
1691 /* BPF_END always use BPF_ALU class. */
1692 (class == BPF_ALU && op == BPF_END && insn->imm == 64))
1695 if (class == BPF_ALU || class == BPF_JMP32)
1698 if (class == BPF_LDX) {
1700 return BPF_SIZE(code) == BPF_DW;
1701 /* LDX source must be ptr. */
1705 if (class == BPF_STX) {
1706 if (reg->type != SCALAR_VALUE)
1708 return BPF_SIZE(code) == BPF_DW;
1711 if (class == BPF_LD) {
1712 u8 mode = BPF_MODE(code);
1715 if (mode == BPF_IMM)
1718 /* Both LD_IND and LD_ABS return 32-bit data. */
1722 /* Implicit ctx ptr. */
1723 if (regno == BPF_REG_6)
1726 /* Explicit source could be any width. */
1730 if (class == BPF_ST)
1731 /* The only source register for BPF_ST is a ptr. */
1734 /* Conservatively return true at default. */
1738 /* Return TRUE if INSN doesn't have explicit value define. */
1739 static bool insn_no_def(struct bpf_insn *insn)
1741 u8 class = BPF_CLASS(insn->code);
1743 return (class == BPF_JMP || class == BPF_JMP32 ||
1744 class == BPF_STX || class == BPF_ST);
1747 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
1748 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
1750 if (insn_no_def(insn))
1753 return !is_reg64(env, insn, insn->dst_reg, NULL, DST_OP);
1756 static void mark_insn_zext(struct bpf_verifier_env *env,
1757 struct bpf_reg_state *reg)
1759 s32 def_idx = reg->subreg_def;
1761 if (def_idx == DEF_NOT_SUBREG)
1764 env->insn_aux_data[def_idx - 1].zext_dst = true;
1765 /* The dst will be zero extended, so won't be sub-register anymore. */
1766 reg->subreg_def = DEF_NOT_SUBREG;
1769 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
1770 enum reg_arg_type t)
1772 struct bpf_verifier_state *vstate = env->cur_state;
1773 struct bpf_func_state *state = vstate->frame[vstate->curframe];
1774 struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
1775 struct bpf_reg_state *reg, *regs = state->regs;
1778 if (regno >= MAX_BPF_REG) {
1779 verbose(env, "R%d is invalid\n", regno);
1784 rw64 = is_reg64(env, insn, regno, reg, t);
1786 /* check whether register used as source operand can be read */
1787 if (reg->type == NOT_INIT) {
1788 verbose(env, "R%d !read_ok\n", regno);
1791 /* We don't need to worry about FP liveness because it's read-only */
1792 if (regno == BPF_REG_FP)
1796 mark_insn_zext(env, reg);
1798 return mark_reg_read(env, reg, reg->parent,
1799 rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
1801 /* check whether register used as dest operand can be written to */
1802 if (regno == BPF_REG_FP) {
1803 verbose(env, "frame pointer is read only\n");
1806 reg->live |= REG_LIVE_WRITTEN;
1807 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
1809 mark_reg_unknown(env, regs, regno);
1814 /* for any branch, call, exit record the history of jmps in the given state */
1815 static int push_jmp_history(struct bpf_verifier_env *env,
1816 struct bpf_verifier_state *cur)
1818 u32 cnt = cur->jmp_history_cnt;
1819 struct bpf_idx_pair *p;
1822 p = krealloc(cur->jmp_history, cnt * sizeof(*p), GFP_USER);
1825 p[cnt - 1].idx = env->insn_idx;
1826 p[cnt - 1].prev_idx = env->prev_insn_idx;
1827 cur->jmp_history = p;
1828 cur->jmp_history_cnt = cnt;
1832 /* Backtrack one insn at a time. If idx is not at the top of recorded
1833 * history then previous instruction came from straight line execution.
1835 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
1840 if (cnt && st->jmp_history[cnt - 1].idx == i) {
1841 i = st->jmp_history[cnt - 1].prev_idx;
1849 /* For given verifier state backtrack_insn() is called from the last insn to
1850 * the first insn. Its purpose is to compute a bitmask of registers and
1851 * stack slots that needs precision in the parent verifier state.
1853 static int backtrack_insn(struct bpf_verifier_env *env, int idx,
1854 u32 *reg_mask, u64 *stack_mask)
1856 const struct bpf_insn_cbs cbs = {
1857 .cb_print = verbose,
1858 .private_data = env,
1860 struct bpf_insn *insn = env->prog->insnsi + idx;
1861 u8 class = BPF_CLASS(insn->code);
1862 u8 opcode = BPF_OP(insn->code);
1863 u8 mode = BPF_MODE(insn->code);
1864 u32 dreg = 1u << insn->dst_reg;
1865 u32 sreg = 1u << insn->src_reg;
1868 if (insn->code == 0)
1870 if (env->log.level & BPF_LOG_LEVEL) {
1871 verbose(env, "regs=%x stack=%llx before ", *reg_mask, *stack_mask);
1872 verbose(env, "%d: ", idx);
1873 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
1876 if (class == BPF_ALU || class == BPF_ALU64) {
1877 if (!(*reg_mask & dreg))
1879 if (opcode == BPF_MOV) {
1880 if (BPF_SRC(insn->code) == BPF_X) {
1882 * dreg needs precision after this insn
1883 * sreg needs precision before this insn
1889 * dreg needs precision after this insn.
1890 * Corresponding register is already marked
1891 * as precise=true in this verifier state.
1892 * No further markings in parent are necessary
1897 if (BPF_SRC(insn->code) == BPF_X) {
1899 * both dreg and sreg need precision
1904 * dreg still needs precision before this insn
1907 } else if (class == BPF_LDX) {
1908 if (!(*reg_mask & dreg))
1912 /* scalars can only be spilled into stack w/o losing precision.
1913 * Load from any other memory can be zero extended.
1914 * The desire to keep that precision is already indicated
1915 * by 'precise' mark in corresponding register of this state.
1916 * No further tracking necessary.
1918 if (insn->src_reg != BPF_REG_FP)
1920 if (BPF_SIZE(insn->code) != BPF_DW)
1923 /* dreg = *(u64 *)[fp - off] was a fill from the stack.
1924 * that [fp - off] slot contains scalar that needs to be
1925 * tracked with precision
1927 spi = (-insn->off - 1) / BPF_REG_SIZE;
1929 verbose(env, "BUG spi %d\n", spi);
1930 WARN_ONCE(1, "verifier backtracking bug");
1933 *stack_mask |= 1ull << spi;
1934 } else if (class == BPF_STX || class == BPF_ST) {
1935 if (*reg_mask & dreg)
1936 /* stx & st shouldn't be using _scalar_ dst_reg
1937 * to access memory. It means backtracking
1938 * encountered a case of pointer subtraction.
1941 /* scalars can only be spilled into stack */
1942 if (insn->dst_reg != BPF_REG_FP)
1944 if (BPF_SIZE(insn->code) != BPF_DW)
1946 spi = (-insn->off - 1) / BPF_REG_SIZE;
1948 verbose(env, "BUG spi %d\n", spi);
1949 WARN_ONCE(1, "verifier backtracking bug");
1952 if (!(*stack_mask & (1ull << spi)))
1954 *stack_mask &= ~(1ull << spi);
1955 if (class == BPF_STX)
1957 } else if (class == BPF_JMP || class == BPF_JMP32) {
1958 if (opcode == BPF_CALL) {
1959 if (insn->src_reg == BPF_PSEUDO_CALL)
1961 /* regular helper call sets R0 */
1963 if (*reg_mask & 0x3f) {
1964 /* if backtracing was looking for registers R1-R5
1965 * they should have been found already.
1967 verbose(env, "BUG regs %x\n", *reg_mask);
1968 WARN_ONCE(1, "verifier backtracking bug");
1971 } else if (opcode == BPF_EXIT) {
1974 } else if (class == BPF_LD) {
1975 if (!(*reg_mask & dreg))
1978 /* It's ld_imm64 or ld_abs or ld_ind.
1979 * For ld_imm64 no further tracking of precision
1980 * into parent is necessary
1982 if (mode == BPF_IND || mode == BPF_ABS)
1983 /* to be analyzed */
1989 /* the scalar precision tracking algorithm:
1990 * . at the start all registers have precise=false.
1991 * . scalar ranges are tracked as normal through alu and jmp insns.
1992 * . once precise value of the scalar register is used in:
1993 * . ptr + scalar alu
1994 * . if (scalar cond K|scalar)
1995 * . helper_call(.., scalar, ...) where ARG_CONST is expected
1996 * backtrack through the verifier states and mark all registers and
1997 * stack slots with spilled constants that these scalar regisers
1998 * should be precise.
1999 * . during state pruning two registers (or spilled stack slots)
2000 * are equivalent if both are not precise.
2002 * Note the verifier cannot simply walk register parentage chain,
2003 * since many different registers and stack slots could have been
2004 * used to compute single precise scalar.
2006 * The approach of starting with precise=true for all registers and then
2007 * backtrack to mark a register as not precise when the verifier detects
2008 * that program doesn't care about specific value (e.g., when helper
2009 * takes register as ARG_ANYTHING parameter) is not safe.
2011 * It's ok to walk single parentage chain of the verifier states.
2012 * It's possible that this backtracking will go all the way till 1st insn.
2013 * All other branches will be explored for needing precision later.
2015 * The backtracking needs to deal with cases like:
2016 * 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)
2019 * if r5 > 0x79f goto pc+7
2020 * R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
2023 * call bpf_perf_event_output#25
2024 * where .arg5_type = ARG_CONST_SIZE_OR_ZERO
2028 * call foo // uses callee's r6 inside to compute r0
2032 * to track above reg_mask/stack_mask needs to be independent for each frame.
2034 * Also if parent's curframe > frame where backtracking started,
2035 * the verifier need to mark registers in both frames, otherwise callees
2036 * may incorrectly prune callers. This is similar to
2037 * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
2039 * For now backtracking falls back into conservative marking.
2041 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
2042 struct bpf_verifier_state *st)
2044 struct bpf_func_state *func;
2045 struct bpf_reg_state *reg;
2048 /* big hammer: mark all scalars precise in this path.
2049 * pop_stack may still get !precise scalars.
2051 for (; st; st = st->parent)
2052 for (i = 0; i <= st->curframe; i++) {
2053 func = st->frame[i];
2054 for (j = 0; j < BPF_REG_FP; j++) {
2055 reg = &func->regs[j];
2056 if (reg->type != SCALAR_VALUE)
2058 reg->precise = true;
2060 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
2061 if (func->stack[j].slot_type[0] != STACK_SPILL)
2063 reg = &func->stack[j].spilled_ptr;
2064 if (reg->type != SCALAR_VALUE)
2066 reg->precise = true;
2071 static int __mark_chain_precision(struct bpf_verifier_env *env, int regno,
2074 struct bpf_verifier_state *st = env->cur_state;
2075 int first_idx = st->first_insn_idx;
2076 int last_idx = env->insn_idx;
2077 struct bpf_func_state *func;
2078 struct bpf_reg_state *reg;
2079 u32 reg_mask = regno >= 0 ? 1u << regno : 0;
2080 u64 stack_mask = spi >= 0 ? 1ull << spi : 0;
2081 bool skip_first = true;
2082 bool new_marks = false;
2085 if (!env->bpf_capable)
2088 func = st->frame[st->curframe];
2090 reg = &func->regs[regno];
2091 if (reg->type != SCALAR_VALUE) {
2092 WARN_ONCE(1, "backtracing misuse");
2099 reg->precise = true;
2103 if (func->stack[spi].slot_type[0] != STACK_SPILL) {
2107 reg = &func->stack[spi].spilled_ptr;
2108 if (reg->type != SCALAR_VALUE) {
2116 reg->precise = true;
2122 if (!reg_mask && !stack_mask)
2125 DECLARE_BITMAP(mask, 64);
2126 u32 history = st->jmp_history_cnt;
2128 if (env->log.level & BPF_LOG_LEVEL)
2129 verbose(env, "last_idx %d first_idx %d\n", last_idx, first_idx);
2130 for (i = last_idx;;) {
2135 err = backtrack_insn(env, i, ®_mask, &stack_mask);
2137 if (err == -ENOTSUPP) {
2138 mark_all_scalars_precise(env, st);
2143 if (!reg_mask && !stack_mask)
2144 /* Found assignment(s) into tracked register in this state.
2145 * Since this state is already marked, just return.
2146 * Nothing to be tracked further in the parent state.
2151 i = get_prev_insn_idx(st, i, &history);
2152 if (i >= env->prog->len) {
2153 /* This can happen if backtracking reached insn 0
2154 * and there are still reg_mask or stack_mask
2156 * It means the backtracking missed the spot where
2157 * particular register was initialized with a constant.
2159 verbose(env, "BUG backtracking idx %d\n", i);
2160 WARN_ONCE(1, "verifier backtracking bug");
2169 func = st->frame[st->curframe];
2170 bitmap_from_u64(mask, reg_mask);
2171 for_each_set_bit(i, mask, 32) {
2172 reg = &func->regs[i];
2173 if (reg->type != SCALAR_VALUE) {
2174 reg_mask &= ~(1u << i);
2179 reg->precise = true;
2182 bitmap_from_u64(mask, stack_mask);
2183 for_each_set_bit(i, mask, 64) {
2184 if (i >= func->allocated_stack / BPF_REG_SIZE) {
2185 /* the sequence of instructions:
2187 * 3: (7b) *(u64 *)(r3 -8) = r0
2188 * 4: (79) r4 = *(u64 *)(r10 -8)
2189 * doesn't contain jmps. It's backtracked
2190 * as a single block.
2191 * During backtracking insn 3 is not recognized as
2192 * stack access, so at the end of backtracking
2193 * stack slot fp-8 is still marked in stack_mask.
2194 * However the parent state may not have accessed
2195 * fp-8 and it's "unallocated" stack space.
2196 * In such case fallback to conservative.
2198 mark_all_scalars_precise(env, st);
2202 if (func->stack[i].slot_type[0] != STACK_SPILL) {
2203 stack_mask &= ~(1ull << i);
2206 reg = &func->stack[i].spilled_ptr;
2207 if (reg->type != SCALAR_VALUE) {
2208 stack_mask &= ~(1ull << i);
2213 reg->precise = true;
2215 if (env->log.level & BPF_LOG_LEVEL) {
2216 print_verifier_state(env, func);
2217 verbose(env, "parent %s regs=%x stack=%llx marks\n",
2218 new_marks ? "didn't have" : "already had",
2219 reg_mask, stack_mask);
2222 if (!reg_mask && !stack_mask)
2227 last_idx = st->last_insn_idx;
2228 first_idx = st->first_insn_idx;
2233 static int mark_chain_precision(struct bpf_verifier_env *env, int regno)
2235 return __mark_chain_precision(env, regno, -1);
2238 static int mark_chain_precision_stack(struct bpf_verifier_env *env, int spi)
2240 return __mark_chain_precision(env, -1, spi);
2243 static bool is_spillable_regtype(enum bpf_reg_type type)
2246 case PTR_TO_MAP_VALUE:
2247 case PTR_TO_MAP_VALUE_OR_NULL:
2251 case PTR_TO_PACKET_META:
2252 case PTR_TO_PACKET_END:
2253 case PTR_TO_FLOW_KEYS:
2254 case CONST_PTR_TO_MAP:
2256 case PTR_TO_SOCKET_OR_NULL:
2257 case PTR_TO_SOCK_COMMON:
2258 case PTR_TO_SOCK_COMMON_OR_NULL:
2259 case PTR_TO_TCP_SOCK:
2260 case PTR_TO_TCP_SOCK_OR_NULL:
2261 case PTR_TO_XDP_SOCK:
2263 case PTR_TO_BTF_ID_OR_NULL:
2264 case PTR_TO_RDONLY_BUF:
2265 case PTR_TO_RDONLY_BUF_OR_NULL:
2266 case PTR_TO_RDWR_BUF:
2267 case PTR_TO_RDWR_BUF_OR_NULL:
2268 case PTR_TO_PERCPU_BTF_ID:
2270 case PTR_TO_MEM_OR_NULL:
2277 /* Does this register contain a constant zero? */
2278 static bool register_is_null(struct bpf_reg_state *reg)
2280 return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
2283 static bool register_is_const(struct bpf_reg_state *reg)
2285 return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
2288 static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
2290 return tnum_is_unknown(reg->var_off) &&
2291 reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
2292 reg->umin_value == 0 && reg->umax_value == U64_MAX &&
2293 reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
2294 reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
2297 static bool register_is_bounded(struct bpf_reg_state *reg)
2299 return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
2302 static bool __is_pointer_value(bool allow_ptr_leaks,
2303 const struct bpf_reg_state *reg)
2305 if (allow_ptr_leaks)
2308 return reg->type != SCALAR_VALUE;
2311 static void save_register_state(struct bpf_func_state *state,
2312 int spi, struct bpf_reg_state *reg)
2316 state->stack[spi].spilled_ptr = *reg;
2317 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
2319 for (i = 0; i < BPF_REG_SIZE; i++)
2320 state->stack[spi].slot_type[i] = STACK_SPILL;
2323 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
2324 * stack boundary and alignment are checked in check_mem_access()
2326 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
2327 /* stack frame we're writing to */
2328 struct bpf_func_state *state,
2329 int off, int size, int value_regno,
2332 struct bpf_func_state *cur; /* state of the current function */
2333 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
2334 u32 dst_reg = env->prog->insnsi[insn_idx].dst_reg;
2335 struct bpf_reg_state *reg = NULL;
2337 err = realloc_func_state(state, round_up(slot + 1, BPF_REG_SIZE),
2338 state->acquired_refs, true);
2341 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
2342 * so it's aligned access and [off, off + size) are within stack limits
2344 if (!env->allow_ptr_leaks &&
2345 state->stack[spi].slot_type[0] == STACK_SPILL &&
2346 size != BPF_REG_SIZE) {
2347 verbose(env, "attempt to corrupt spilled pointer on stack\n");
2351 cur = env->cur_state->frame[env->cur_state->curframe];
2352 if (value_regno >= 0)
2353 reg = &cur->regs[value_regno];
2355 if (reg && size == BPF_REG_SIZE && register_is_bounded(reg) &&
2356 !register_is_null(reg) && env->bpf_capable) {
2357 if (dst_reg != BPF_REG_FP) {
2358 /* The backtracking logic can only recognize explicit
2359 * stack slot address like [fp - 8]. Other spill of
2360 * scalar via different register has to be conervative.
2361 * Backtrack from here and mark all registers as precise
2362 * that contributed into 'reg' being a constant.
2364 err = mark_chain_precision(env, value_regno);
2368 save_register_state(state, spi, reg);
2369 } else if (reg && is_spillable_regtype(reg->type)) {
2370 /* register containing pointer is being spilled into stack */
2371 if (size != BPF_REG_SIZE) {
2372 verbose_linfo(env, insn_idx, "; ");
2373 verbose(env, "invalid size of register spill\n");
2377 if (state != cur && reg->type == PTR_TO_STACK) {
2378 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
2382 if (!env->bypass_spec_v4) {
2383 bool sanitize = false;
2385 if (state->stack[spi].slot_type[0] == STACK_SPILL &&
2386 register_is_const(&state->stack[spi].spilled_ptr))
2388 for (i = 0; i < BPF_REG_SIZE; i++)
2389 if (state->stack[spi].slot_type[i] == STACK_MISC) {
2394 int *poff = &env->insn_aux_data[insn_idx].sanitize_stack_off;
2395 int soff = (-spi - 1) * BPF_REG_SIZE;
2397 /* detected reuse of integer stack slot with a pointer
2398 * which means either llvm is reusing stack slot or
2399 * an attacker is trying to exploit CVE-2018-3639
2400 * (speculative store bypass)
2401 * Have to sanitize that slot with preemptive
2404 if (*poff && *poff != soff) {
2405 /* disallow programs where single insn stores
2406 * into two different stack slots, since verifier
2407 * cannot sanitize them
2410 "insn %d cannot access two stack slots fp%d and fp%d",
2411 insn_idx, *poff, soff);
2417 save_register_state(state, spi, reg);
2419 u8 type = STACK_MISC;
2421 /* regular write of data into stack destroys any spilled ptr */
2422 state->stack[spi].spilled_ptr.type = NOT_INIT;
2423 /* Mark slots as STACK_MISC if they belonged to spilled ptr. */
2424 if (state->stack[spi].slot_type[0] == STACK_SPILL)
2425 for (i = 0; i < BPF_REG_SIZE; i++)
2426 state->stack[spi].slot_type[i] = STACK_MISC;
2428 /* only mark the slot as written if all 8 bytes were written
2429 * otherwise read propagation may incorrectly stop too soon
2430 * when stack slots are partially written.
2431 * This heuristic means that read propagation will be
2432 * conservative, since it will add reg_live_read marks
2433 * to stack slots all the way to first state when programs
2434 * writes+reads less than 8 bytes
2436 if (size == BPF_REG_SIZE)
2437 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
2439 /* when we zero initialize stack slots mark them as such */
2440 if (reg && register_is_null(reg)) {
2441 /* backtracking doesn't work for STACK_ZERO yet. */
2442 err = mark_chain_precision(env, value_regno);
2448 /* Mark slots affected by this stack write. */
2449 for (i = 0; i < size; i++)
2450 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
2456 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
2457 * known to contain a variable offset.
2458 * This function checks whether the write is permitted and conservatively
2459 * tracks the effects of the write, considering that each stack slot in the
2460 * dynamic range is potentially written to.
2462 * 'off' includes 'regno->off'.
2463 * 'value_regno' can be -1, meaning that an unknown value is being written to
2466 * Spilled pointers in range are not marked as written because we don't know
2467 * what's going to be actually written. This means that read propagation for
2468 * future reads cannot be terminated by this write.
2470 * For privileged programs, uninitialized stack slots are considered
2471 * initialized by this write (even though we don't know exactly what offsets
2472 * are going to be written to). The idea is that we don't want the verifier to
2473 * reject future reads that access slots written to through variable offsets.
2475 static int check_stack_write_var_off(struct bpf_verifier_env *env,
2476 /* func where register points to */
2477 struct bpf_func_state *state,
2478 int ptr_regno, int off, int size,
2479 int value_regno, int insn_idx)
2481 struct bpf_func_state *cur; /* state of the current function */
2482 int min_off, max_off;
2484 struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
2485 bool writing_zero = false;
2486 /* set if the fact that we're writing a zero is used to let any
2487 * stack slots remain STACK_ZERO
2489 bool zero_used = false;
2491 cur = env->cur_state->frame[env->cur_state->curframe];
2492 ptr_reg = &cur->regs[ptr_regno];
2493 min_off = ptr_reg->smin_value + off;
2494 max_off = ptr_reg->smax_value + off + size;
2495 if (value_regno >= 0)
2496 value_reg = &cur->regs[value_regno];
2497 if (value_reg && register_is_null(value_reg))
2498 writing_zero = true;
2500 err = realloc_func_state(state, round_up(-min_off, BPF_REG_SIZE),
2501 state->acquired_refs, true);
2506 /* Variable offset writes destroy any spilled pointers in range. */
2507 for (i = min_off; i < max_off; i++) {
2508 u8 new_type, *stype;
2512 spi = slot / BPF_REG_SIZE;
2513 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
2515 if (!env->allow_ptr_leaks
2516 && *stype != NOT_INIT
2517 && *stype != SCALAR_VALUE) {
2518 /* Reject the write if there's are spilled pointers in
2519 * range. If we didn't reject here, the ptr status
2520 * would be erased below (even though not all slots are
2521 * actually overwritten), possibly opening the door to
2524 verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
2529 /* Erase all spilled pointers. */
2530 state->stack[spi].spilled_ptr.type = NOT_INIT;
2532 /* Update the slot type. */
2533 new_type = STACK_MISC;
2534 if (writing_zero && *stype == STACK_ZERO) {
2535 new_type = STACK_ZERO;
2538 /* If the slot is STACK_INVALID, we check whether it's OK to
2539 * pretend that it will be initialized by this write. The slot
2540 * might not actually be written to, and so if we mark it as
2541 * initialized future reads might leak uninitialized memory.
2542 * For privileged programs, we will accept such reads to slots
2543 * that may or may not be written because, if we're reject
2544 * them, the error would be too confusing.
2546 if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
2547 verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
2554 /* backtracking doesn't work for STACK_ZERO yet. */
2555 err = mark_chain_precision(env, value_regno);
2562 /* When register 'dst_regno' is assigned some values from stack[min_off,
2563 * max_off), we set the register's type according to the types of the
2564 * respective stack slots. If all the stack values are known to be zeros, then
2565 * so is the destination reg. Otherwise, the register is considered to be
2566 * SCALAR. This function does not deal with register filling; the caller must
2567 * ensure that all spilled registers in the stack range have been marked as
2570 static void mark_reg_stack_read(struct bpf_verifier_env *env,
2571 /* func where src register points to */
2572 struct bpf_func_state *ptr_state,
2573 int min_off, int max_off, int dst_regno)
2575 struct bpf_verifier_state *vstate = env->cur_state;
2576 struct bpf_func_state *state = vstate->frame[vstate->curframe];
2581 for (i = min_off; i < max_off; i++) {
2583 spi = slot / BPF_REG_SIZE;
2584 stype = ptr_state->stack[spi].slot_type;
2585 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
2589 if (zeros == max_off - min_off) {
2590 /* any access_size read into register is zero extended,
2591 * so the whole register == const_zero
2593 __mark_reg_const_zero(&state->regs[dst_regno]);
2594 /* backtracking doesn't support STACK_ZERO yet,
2595 * so mark it precise here, so that later
2596 * backtracking can stop here.
2597 * Backtracking may not need this if this register
2598 * doesn't participate in pointer adjustment.
2599 * Forward propagation of precise flag is not
2600 * necessary either. This mark is only to stop
2601 * backtracking. Any register that contributed
2602 * to const 0 was marked precise before spill.
2604 state->regs[dst_regno].precise = true;
2606 /* have read misc data from the stack */
2607 mark_reg_unknown(env, state->regs, dst_regno);
2609 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
2612 /* Read the stack at 'off' and put the results into the register indicated by
2613 * 'dst_regno'. It handles reg filling if the addressed stack slot is a
2616 * 'dst_regno' can be -1, meaning that the read value is not going to a
2619 * The access is assumed to be within the current stack bounds.
2621 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
2622 /* func where src register points to */
2623 struct bpf_func_state *reg_state,
2624 int off, int size, int dst_regno)
2626 struct bpf_verifier_state *vstate = env->cur_state;
2627 struct bpf_func_state *state = vstate->frame[vstate->curframe];
2628 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
2629 struct bpf_reg_state *reg;
2632 stype = reg_state->stack[spi].slot_type;
2633 reg = ®_state->stack[spi].spilled_ptr;
2635 if (stype[0] == STACK_SPILL) {
2636 if (size != BPF_REG_SIZE) {
2637 if (reg->type != SCALAR_VALUE) {
2638 verbose_linfo(env, env->insn_idx, "; ");
2639 verbose(env, "invalid size of register fill\n");
2642 if (dst_regno >= 0) {
2643 mark_reg_unknown(env, state->regs, dst_regno);
2644 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
2646 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
2649 for (i = 1; i < BPF_REG_SIZE; i++) {
2650 if (stype[(slot - i) % BPF_REG_SIZE] != STACK_SPILL) {
2651 verbose(env, "corrupted spill memory\n");
2656 if (dst_regno >= 0) {
2657 /* restore register state from stack */
2658 state->regs[dst_regno] = *reg;
2659 /* mark reg as written since spilled pointer state likely
2660 * has its liveness marks cleared by is_state_visited()
2661 * which resets stack/reg liveness for state transitions
2663 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
2664 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
2665 /* If dst_regno==-1, the caller is asking us whether
2666 * it is acceptable to use this value as a SCALAR_VALUE
2668 * We must not allow unprivileged callers to do that
2669 * with spilled pointers.
2671 verbose(env, "leaking pointer from stack off %d\n",
2675 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
2679 for (i = 0; i < size; i++) {
2680 type = stype[(slot - i) % BPF_REG_SIZE];
2681 if (type == STACK_MISC)
2683 if (type == STACK_ZERO)
2685 verbose(env, "invalid read from stack off %d+%d size %d\n",
2689 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
2691 mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
2696 enum stack_access_src {
2697 ACCESS_DIRECT = 1, /* the access is performed by an instruction */
2698 ACCESS_HELPER = 2, /* the access is performed by a helper */
2701 static int check_stack_range_initialized(struct bpf_verifier_env *env,
2702 int regno, int off, int access_size,
2703 bool zero_size_allowed,
2704 enum stack_access_src type,
2705 struct bpf_call_arg_meta *meta);
2707 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
2709 return cur_regs(env) + regno;
2712 /* Read the stack at 'ptr_regno + off' and put the result into the register
2714 * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
2715 * but not its variable offset.
2716 * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
2718 * As opposed to check_stack_read_fixed_off, this function doesn't deal with
2719 * filling registers (i.e. reads of spilled register cannot be detected when
2720 * the offset is not fixed). We conservatively mark 'dst_regno' as containing
2721 * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
2722 * offset; for a fixed offset check_stack_read_fixed_off should be used
2725 static int check_stack_read_var_off(struct bpf_verifier_env *env,
2726 int ptr_regno, int off, int size, int dst_regno)
2728 /* The state of the source register. */
2729 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
2730 struct bpf_func_state *ptr_state = func(env, reg);
2732 int min_off, max_off;
2734 /* Note that we pass a NULL meta, so raw access will not be permitted.
2736 err = check_stack_range_initialized(env, ptr_regno, off, size,
2737 false, ACCESS_DIRECT, NULL);
2741 min_off = reg->smin_value + off;
2742 max_off = reg->smax_value + off;
2743 mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
2747 /* check_stack_read dispatches to check_stack_read_fixed_off or
2748 * check_stack_read_var_off.
2750 * The caller must ensure that the offset falls within the allocated stack
2753 * 'dst_regno' is a register which will receive the value from the stack. It
2754 * can be -1, meaning that the read value is not going to a register.
2756 static int check_stack_read(struct bpf_verifier_env *env,
2757 int ptr_regno, int off, int size,
2760 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
2761 struct bpf_func_state *state = func(env, reg);
2763 /* Some accesses are only permitted with a static offset. */
2764 bool var_off = !tnum_is_const(reg->var_off);
2766 /* The offset is required to be static when reads don't go to a
2767 * register, in order to not leak pointers (see
2768 * check_stack_read_fixed_off).
2770 if (dst_regno < 0 && var_off) {
2773 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
2774 verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
2778 /* Variable offset is prohibited for unprivileged mode for simplicity
2779 * since it requires corresponding support in Spectre masking for stack
2780 * ALU. See also retrieve_ptr_limit().
2782 if (!env->bypass_spec_v1 && var_off) {
2785 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
2786 verbose(env, "R%d variable offset stack access prohibited for !root, var_off=%s\n",
2792 off += reg->var_off.value;
2793 err = check_stack_read_fixed_off(env, state, off, size,
2796 /* Variable offset stack reads need more conservative handling
2797 * than fixed offset ones. Note that dst_regno >= 0 on this
2800 err = check_stack_read_var_off(env, ptr_regno, off, size,
2807 /* check_stack_write dispatches to check_stack_write_fixed_off or
2808 * check_stack_write_var_off.
2810 * 'ptr_regno' is the register used as a pointer into the stack.
2811 * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
2812 * 'value_regno' is the register whose value we're writing to the stack. It can
2813 * be -1, meaning that we're not writing from a register.
2815 * The caller must ensure that the offset falls within the maximum stack size.
2817 static int check_stack_write(struct bpf_verifier_env *env,
2818 int ptr_regno, int off, int size,
2819 int value_regno, int insn_idx)
2821 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
2822 struct bpf_func_state *state = func(env, reg);
2825 if (tnum_is_const(reg->var_off)) {
2826 off += reg->var_off.value;
2827 err = check_stack_write_fixed_off(env, state, off, size,
2828 value_regno, insn_idx);
2830 /* Variable offset stack reads need more conservative handling
2831 * than fixed offset ones.
2833 err = check_stack_write_var_off(env, state,
2834 ptr_regno, off, size,
2835 value_regno, insn_idx);
2840 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
2841 int off, int size, enum bpf_access_type type)
2843 struct bpf_reg_state *regs = cur_regs(env);
2844 struct bpf_map *map = regs[regno].map_ptr;
2845 u32 cap = bpf_map_flags_to_cap(map);
2847 if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
2848 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
2849 map->value_size, off, size);
2853 if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
2854 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
2855 map->value_size, off, size);
2862 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
2863 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
2864 int off, int size, u32 mem_size,
2865 bool zero_size_allowed)
2867 bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
2868 struct bpf_reg_state *reg;
2870 if (off >= 0 && size_ok && (u64)off + size <= mem_size)
2873 reg = &cur_regs(env)[regno];
2874 switch (reg->type) {
2875 case PTR_TO_MAP_VALUE:
2876 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
2877 mem_size, off, size);
2880 case PTR_TO_PACKET_META:
2881 case PTR_TO_PACKET_END:
2882 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
2883 off, size, regno, reg->id, off, mem_size);
2887 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
2888 mem_size, off, size);
2894 /* check read/write into a memory region with possible variable offset */
2895 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
2896 int off, int size, u32 mem_size,
2897 bool zero_size_allowed)
2899 struct bpf_verifier_state *vstate = env->cur_state;
2900 struct bpf_func_state *state = vstate->frame[vstate->curframe];
2901 struct bpf_reg_state *reg = &state->regs[regno];
2904 /* We may have adjusted the register pointing to memory region, so we
2905 * need to try adding each of min_value and max_value to off
2906 * to make sure our theoretical access will be safe.
2908 if (env->log.level & BPF_LOG_LEVEL)
2909 print_verifier_state(env, state);
2911 /* The minimum value is only important with signed
2912 * comparisons where we can't assume the floor of a
2913 * value is 0. If we are using signed variables for our
2914 * index'es we need to make sure that whatever we use
2915 * will have a set floor within our range.
2917 if (reg->smin_value < 0 &&
2918 (reg->smin_value == S64_MIN ||
2919 (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
2920 reg->smin_value + off < 0)) {
2921 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
2925 err = __check_mem_access(env, regno, reg->smin_value + off, size,
2926 mem_size, zero_size_allowed);
2928 verbose(env, "R%d min value is outside of the allowed memory range\n",
2933 /* If we haven't set a max value then we need to bail since we can't be
2934 * sure we won't do bad things.
2935 * If reg->umax_value + off could overflow, treat that as unbounded too.
2937 if (reg->umax_value >= BPF_MAX_VAR_OFF) {
2938 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
2942 err = __check_mem_access(env, regno, reg->umax_value + off, size,
2943 mem_size, zero_size_allowed);
2945 verbose(env, "R%d max value is outside of the allowed memory range\n",
2953 /* check read/write into a map element with possible variable offset */
2954 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
2955 int off, int size, bool zero_size_allowed)
2957 struct bpf_verifier_state *vstate = env->cur_state;
2958 struct bpf_func_state *state = vstate->frame[vstate->curframe];
2959 struct bpf_reg_state *reg = &state->regs[regno];
2960 struct bpf_map *map = reg->map_ptr;
2963 err = check_mem_region_access(env, regno, off, size, map->value_size,
2968 if (map_value_has_spin_lock(map)) {
2969 u32 lock = map->spin_lock_off;
2971 /* if any part of struct bpf_spin_lock can be touched by
2972 * load/store reject this program.
2973 * To check that [x1, x2) overlaps with [y1, y2)
2974 * it is sufficient to check x1 < y2 && y1 < x2.
2976 if (reg->smin_value + off < lock + sizeof(struct bpf_spin_lock) &&
2977 lock < reg->umax_value + off + size) {
2978 verbose(env, "bpf_spin_lock cannot be accessed directly by load/store\n");
2985 #define MAX_PACKET_OFF 0xffff
2987 static enum bpf_prog_type resolve_prog_type(struct bpf_prog *prog)
2989 return prog->aux->dst_prog ? prog->aux->dst_prog->type : prog->type;
2992 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
2993 const struct bpf_call_arg_meta *meta,
2994 enum bpf_access_type t)
2996 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
2998 switch (prog_type) {
2999 /* Program types only with direct read access go here! */
3000 case BPF_PROG_TYPE_LWT_IN:
3001 case BPF_PROG_TYPE_LWT_OUT:
3002 case BPF_PROG_TYPE_LWT_SEG6LOCAL:
3003 case BPF_PROG_TYPE_SK_REUSEPORT:
3004 case BPF_PROG_TYPE_FLOW_DISSECTOR:
3005 case BPF_PROG_TYPE_CGROUP_SKB:
3010 /* Program types with direct read + write access go here! */
3011 case BPF_PROG_TYPE_SCHED_CLS:
3012 case BPF_PROG_TYPE_SCHED_ACT:
3013 case BPF_PROG_TYPE_XDP:
3014 case BPF_PROG_TYPE_LWT_XMIT:
3015 case BPF_PROG_TYPE_SK_SKB:
3016 case BPF_PROG_TYPE_SK_MSG:
3018 return meta->pkt_access;
3020 env->seen_direct_write = true;
3023 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
3025 env->seen_direct_write = true;
3034 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
3035 int size, bool zero_size_allowed)
3037 struct bpf_reg_state *regs = cur_regs(env);
3038 struct bpf_reg_state *reg = ®s[regno];
3041 /* We may have added a variable offset to the packet pointer; but any
3042 * reg->range we have comes after that. We are only checking the fixed
3046 /* We don't allow negative numbers, because we aren't tracking enough
3047 * detail to prove they're safe.
3049 if (reg->smin_value < 0) {
3050 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3055 err = reg->range < 0 ? -EINVAL :
3056 __check_mem_access(env, regno, off, size, reg->range,
3059 verbose(env, "R%d offset is outside of the packet\n", regno);
3063 /* __check_mem_access has made sure "off + size - 1" is within u16.
3064 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
3065 * otherwise find_good_pkt_pointers would have refused to set range info
3066 * that __check_mem_access would have rejected this pkt access.
3067 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
3069 env->prog->aux->max_pkt_offset =
3070 max_t(u32, env->prog->aux->max_pkt_offset,
3071 off + reg->umax_value + size - 1);
3076 /* check access to 'struct bpf_context' fields. Supports fixed offsets only */
3077 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
3078 enum bpf_access_type t, enum bpf_reg_type *reg_type,
3079 struct btf **btf, u32 *btf_id)
3081 struct bpf_insn_access_aux info = {
3082 .reg_type = *reg_type,
3086 if (env->ops->is_valid_access &&
3087 env->ops->is_valid_access(off, size, t, env->prog, &info)) {
3088 /* A non zero info.ctx_field_size indicates that this field is a
3089 * candidate for later verifier transformation to load the whole
3090 * field and then apply a mask when accessed with a narrower
3091 * access than actual ctx access size. A zero info.ctx_field_size
3092 * will only allow for whole field access and rejects any other
3093 * type of narrower access.
3095 *reg_type = info.reg_type;
3097 if (*reg_type == PTR_TO_BTF_ID || *reg_type == PTR_TO_BTF_ID_OR_NULL) {
3099 *btf_id = info.btf_id;
3101 env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
3103 /* remember the offset of last byte accessed in ctx */
3104 if (env->prog->aux->max_ctx_offset < off + size)
3105 env->prog->aux->max_ctx_offset = off + size;
3109 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
3113 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
3116 if (size < 0 || off < 0 ||
3117 (u64)off + size > sizeof(struct bpf_flow_keys)) {
3118 verbose(env, "invalid access to flow keys off=%d size=%d\n",
3125 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
3126 u32 regno, int off, int size,
3127 enum bpf_access_type t)
3129 struct bpf_reg_state *regs = cur_regs(env);
3130 struct bpf_reg_state *reg = ®s[regno];
3131 struct bpf_insn_access_aux info = {};
3134 if (reg->smin_value < 0) {
3135 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3140 switch (reg->type) {
3141 case PTR_TO_SOCK_COMMON:
3142 valid = bpf_sock_common_is_valid_access(off, size, t, &info);
3145 valid = bpf_sock_is_valid_access(off, size, t, &info);
3147 case PTR_TO_TCP_SOCK:
3148 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
3150 case PTR_TO_XDP_SOCK:
3151 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
3159 env->insn_aux_data[insn_idx].ctx_field_size =
3160 info.ctx_field_size;
3164 verbose(env, "R%d invalid %s access off=%d size=%d\n",
3165 regno, reg_type_str[reg->type], off, size);
3170 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
3172 return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
3175 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
3177 const struct bpf_reg_state *reg = reg_state(env, regno);
3179 return reg->type == PTR_TO_CTX;
3182 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
3184 const struct bpf_reg_state *reg = reg_state(env, regno);
3186 return type_is_sk_pointer(reg->type);
3189 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
3191 const struct bpf_reg_state *reg = reg_state(env, regno);
3193 return type_is_pkt_pointer(reg->type);
3196 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
3198 const struct bpf_reg_state *reg = reg_state(env, regno);
3200 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
3201 return reg->type == PTR_TO_FLOW_KEYS;
3204 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
3205 const struct bpf_reg_state *reg,
3206 int off, int size, bool strict)
3208 struct tnum reg_off;
3211 /* Byte size accesses are always allowed. */
3212 if (!strict || size == 1)
3215 /* For platforms that do not have a Kconfig enabling
3216 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
3217 * NET_IP_ALIGN is universally set to '2'. And on platforms
3218 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
3219 * to this code only in strict mode where we want to emulate
3220 * the NET_IP_ALIGN==2 checking. Therefore use an
3221 * unconditional IP align value of '2'.
3225 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
3226 if (!tnum_is_aligned(reg_off, size)) {
3229 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3231 "misaligned packet access off %d+%s+%d+%d size %d\n",
3232 ip_align, tn_buf, reg->off, off, size);
3239 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
3240 const struct bpf_reg_state *reg,
3241 const char *pointer_desc,
3242 int off, int size, bool strict)
3244 struct tnum reg_off;
3246 /* Byte size accesses are always allowed. */
3247 if (!strict || size == 1)
3250 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
3251 if (!tnum_is_aligned(reg_off, size)) {
3254 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3255 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
3256 pointer_desc, tn_buf, reg->off, off, size);
3263 static int check_ptr_alignment(struct bpf_verifier_env *env,
3264 const struct bpf_reg_state *reg, int off,
3265 int size, bool strict_alignment_once)
3267 bool strict = env->strict_alignment || strict_alignment_once;
3268 const char *pointer_desc = "";
3270 switch (reg->type) {
3272 case PTR_TO_PACKET_META:
3273 /* Special case, because of NET_IP_ALIGN. Given metadata sits
3274 * right in front, treat it the very same way.
3276 return check_pkt_ptr_alignment(env, reg, off, size, strict);
3277 case PTR_TO_FLOW_KEYS:
3278 pointer_desc = "flow keys ";
3280 case PTR_TO_MAP_VALUE:
3281 pointer_desc = "value ";
3284 pointer_desc = "context ";
3287 pointer_desc = "stack ";
3288 /* The stack spill tracking logic in check_stack_write_fixed_off()
3289 * and check_stack_read_fixed_off() relies on stack accesses being
3295 pointer_desc = "sock ";
3297 case PTR_TO_SOCK_COMMON:
3298 pointer_desc = "sock_common ";
3300 case PTR_TO_TCP_SOCK:
3301 pointer_desc = "tcp_sock ";
3303 case PTR_TO_XDP_SOCK:
3304 pointer_desc = "xdp_sock ";
3309 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
3313 static int update_stack_depth(struct bpf_verifier_env *env,
3314 const struct bpf_func_state *func,
3317 u16 stack = env->subprog_info[func->subprogno].stack_depth;
3322 /* update known max for given subprogram */
3323 env->subprog_info[func->subprogno].stack_depth = -off;
3327 /* starting from main bpf function walk all instructions of the function
3328 * and recursively walk all callees that given function can call.
3329 * Ignore jump and exit insns.
3330 * Since recursion is prevented by check_cfg() this algorithm
3331 * only needs a local stack of MAX_CALL_FRAMES to remember callsites
3333 static int check_max_stack_depth(struct bpf_verifier_env *env)
3335 int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
3336 struct bpf_subprog_info *subprog = env->subprog_info;
3337 struct bpf_insn *insn = env->prog->insnsi;
3338 bool tail_call_reachable = false;
3339 int ret_insn[MAX_CALL_FRAMES];
3340 int ret_prog[MAX_CALL_FRAMES];
3344 /* protect against potential stack overflow that might happen when
3345 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
3346 * depth for such case down to 256 so that the worst case scenario
3347 * would result in 8k stack size (32 which is tailcall limit * 256 =
3350 * To get the idea what might happen, see an example:
3351 * func1 -> sub rsp, 128
3352 * subfunc1 -> sub rsp, 256
3353 * tailcall1 -> add rsp, 256
3354 * func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
3355 * subfunc2 -> sub rsp, 64
3356 * subfunc22 -> sub rsp, 128
3357 * tailcall2 -> add rsp, 128
3358 * func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
3360 * tailcall will unwind the current stack frame but it will not get rid
3361 * of caller's stack as shown on the example above.
3363 if (idx && subprog[idx].has_tail_call && depth >= 256) {
3365 "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
3369 /* round up to 32-bytes, since this is granularity
3370 * of interpreter stack size
3372 depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
3373 if (depth > MAX_BPF_STACK) {
3374 verbose(env, "combined stack size of %d calls is %d. Too large\n",
3379 subprog_end = subprog[idx + 1].start;
3380 for (; i < subprog_end; i++) {
3381 if (!bpf_pseudo_call(insn + i))
3383 /* remember insn and function to return to */
3384 ret_insn[frame] = i + 1;
3385 ret_prog[frame] = idx;
3387 /* find the callee */
3388 i = i + insn[i].imm + 1;
3389 idx = find_subprog(env, i);
3391 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
3396 if (subprog[idx].has_tail_call)
3397 tail_call_reachable = true;
3400 if (frame >= MAX_CALL_FRAMES) {
3401 verbose(env, "the call stack of %d frames is too deep !\n",
3407 /* if tail call got detected across bpf2bpf calls then mark each of the
3408 * currently present subprog frames as tail call reachable subprogs;
3409 * this info will be utilized by JIT so that we will be preserving the
3410 * tail call counter throughout bpf2bpf calls combined with tailcalls
3412 if (tail_call_reachable)
3413 for (j = 0; j < frame; j++)
3414 subprog[ret_prog[j]].tail_call_reachable = true;
3416 /* end of for() loop means the last insn of the 'subprog'
3417 * was reached. Doesn't matter whether it was JA or EXIT
3421 depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
3423 i = ret_insn[frame];
3424 idx = ret_prog[frame];
3428 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
3429 static int get_callee_stack_depth(struct bpf_verifier_env *env,
3430 const struct bpf_insn *insn, int idx)
3432 int start = idx + insn->imm + 1, subprog;
3434 subprog = find_subprog(env, start);
3436 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
3440 return env->subprog_info[subprog].stack_depth;
3444 int check_ctx_reg(struct bpf_verifier_env *env,
3445 const struct bpf_reg_state *reg, int regno)
3447 /* Access to ctx or passing it to a helper is only allowed in
3448 * its original, unmodified form.
3452 verbose(env, "dereference of modified ctx ptr R%d off=%d disallowed\n",
3457 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3460 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3461 verbose(env, "variable ctx access var_off=%s disallowed\n", tn_buf);
3468 static int __check_buffer_access(struct bpf_verifier_env *env,
3469 const char *buf_info,
3470 const struct bpf_reg_state *reg,
3471 int regno, int off, int size)
3475 "R%d invalid %s buffer access: off=%d, size=%d\n",
3476 regno, buf_info, off, size);
3479 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3482 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3484 "R%d invalid variable buffer offset: off=%d, var_off=%s\n",
3485 regno, off, tn_buf);
3492 static int check_tp_buffer_access(struct bpf_verifier_env *env,
3493 const struct bpf_reg_state *reg,
3494 int regno, int off, int size)
3498 err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
3502 if (off + size > env->prog->aux->max_tp_access)
3503 env->prog->aux->max_tp_access = off + size;
3508 static int check_buffer_access(struct bpf_verifier_env *env,
3509 const struct bpf_reg_state *reg,
3510 int regno, int off, int size,
3511 bool zero_size_allowed,
3512 const char *buf_info,
3517 err = __check_buffer_access(env, buf_info, reg, regno, off, size);
3521 if (off + size > *max_access)
3522 *max_access = off + size;
3527 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
3528 static void zext_32_to_64(struct bpf_reg_state *reg)
3530 reg->var_off = tnum_subreg(reg->var_off);
3531 __reg_assign_32_into_64(reg);
3534 /* truncate register to smaller size (in bytes)
3535 * must be called with size < BPF_REG_SIZE
3537 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
3541 /* clear high bits in bit representation */
3542 reg->var_off = tnum_cast(reg->var_off, size);
3544 /* fix arithmetic bounds */
3545 mask = ((u64)1 << (size * 8)) - 1;
3546 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
3547 reg->umin_value &= mask;
3548 reg->umax_value &= mask;
3550 reg->umin_value = 0;
3551 reg->umax_value = mask;
3553 reg->smin_value = reg->umin_value;
3554 reg->smax_value = reg->umax_value;
3556 /* If size is smaller than 32bit register the 32bit register
3557 * values are also truncated so we push 64-bit bounds into
3558 * 32-bit bounds. Above were truncated < 32-bits already.
3562 __reg_combine_64_into_32(reg);
3565 static bool bpf_map_is_rdonly(const struct bpf_map *map)
3567 return (map->map_flags & BPF_F_RDONLY_PROG) && map->frozen;
3570 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val)
3576 err = map->ops->map_direct_value_addr(map, &addr, off);
3579 ptr = (void *)(long)addr + off;
3583 *val = (u64)*(u8 *)ptr;
3586 *val = (u64)*(u16 *)ptr;
3589 *val = (u64)*(u32 *)ptr;
3600 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
3601 struct bpf_reg_state *regs,
3602 int regno, int off, int size,
3603 enum bpf_access_type atype,
3606 struct bpf_reg_state *reg = regs + regno;
3607 const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
3608 const char *tname = btf_name_by_offset(reg->btf, t->name_off);
3614 "R%d is ptr_%s invalid negative access: off=%d\n",
3618 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3621 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3623 "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
3624 regno, tname, off, tn_buf);
3628 if (env->ops->btf_struct_access) {
3629 ret = env->ops->btf_struct_access(&env->log, reg->btf, t,
3630 off, size, atype, &btf_id);
3632 if (atype != BPF_READ) {
3633 verbose(env, "only read is supported\n");
3637 ret = btf_struct_access(&env->log, reg->btf, t, off, size,
3644 if (atype == BPF_READ && value_regno >= 0)
3645 mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id);
3650 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
3651 struct bpf_reg_state *regs,
3652 int regno, int off, int size,
3653 enum bpf_access_type atype,
3656 struct bpf_reg_state *reg = regs + regno;
3657 struct bpf_map *map = reg->map_ptr;
3658 const struct btf_type *t;
3664 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
3668 if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
3669 verbose(env, "map_ptr access not supported for map type %d\n",
3674 t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
3675 tname = btf_name_by_offset(btf_vmlinux, t->name_off);
3677 if (!env->allow_ptr_to_map_access) {
3679 "%s access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
3685 verbose(env, "R%d is %s invalid negative access: off=%d\n",
3690 if (atype != BPF_READ) {
3691 verbose(env, "only read from %s is supported\n", tname);
3695 ret = btf_struct_access(&env->log, btf_vmlinux, t, off, size, atype, &btf_id);
3699 if (value_regno >= 0)
3700 mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id);
3705 /* Check that the stack access at the given offset is within bounds. The
3706 * maximum valid offset is -1.
3708 * The minimum valid offset is -MAX_BPF_STACK for writes, and
3709 * -state->allocated_stack for reads.
3711 static int check_stack_slot_within_bounds(int off,
3712 struct bpf_func_state *state,
3713 enum bpf_access_type t)
3718 min_valid_off = -MAX_BPF_STACK;
3720 min_valid_off = -state->allocated_stack;
3722 if (off < min_valid_off || off > -1)
3727 /* Check that the stack access at 'regno + off' falls within the maximum stack
3730 * 'off' includes `regno->offset`, but not its dynamic part (if any).
3732 static int check_stack_access_within_bounds(
3733 struct bpf_verifier_env *env,
3734 int regno, int off, int access_size,
3735 enum stack_access_src src, enum bpf_access_type type)
3737 struct bpf_reg_state *regs = cur_regs(env);
3738 struct bpf_reg_state *reg = regs + regno;
3739 struct bpf_func_state *state = func(env, reg);
3740 int min_off, max_off;
3744 if (src == ACCESS_HELPER)
3745 /* We don't know if helpers are reading or writing (or both). */
3746 err_extra = " indirect access to";
3747 else if (type == BPF_READ)
3748 err_extra = " read from";
3750 err_extra = " write to";
3752 if (tnum_is_const(reg->var_off)) {
3753 min_off = reg->var_off.value + off;
3754 if (access_size > 0)
3755 max_off = min_off + access_size - 1;
3759 if (reg->smax_value >= BPF_MAX_VAR_OFF ||
3760 reg->smin_value <= -BPF_MAX_VAR_OFF) {
3761 verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
3765 min_off = reg->smin_value + off;
3766 if (access_size > 0)
3767 max_off = reg->smax_value + off + access_size - 1;
3772 err = check_stack_slot_within_bounds(min_off, state, type);
3774 err = check_stack_slot_within_bounds(max_off, state, type);
3777 if (tnum_is_const(reg->var_off)) {
3778 verbose(env, "invalid%s stack R%d off=%d size=%d\n",
3779 err_extra, regno, off, access_size);
3783 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3784 verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
3785 err_extra, regno, tn_buf, access_size);
3791 /* check whether memory at (regno + off) is accessible for t = (read | write)
3792 * if t==write, value_regno is a register which value is stored into memory
3793 * if t==read, value_regno is a register which will receive the value from memory
3794 * if t==write && value_regno==-1, some unknown value is stored into memory
3795 * if t==read && value_regno==-1, don't care what we read from memory
3797 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
3798 int off, int bpf_size, enum bpf_access_type t,
3799 int value_regno, bool strict_alignment_once)
3801 struct bpf_reg_state *regs = cur_regs(env);
3802 struct bpf_reg_state *reg = regs + regno;
3803 struct bpf_func_state *state;
3806 size = bpf_size_to_bytes(bpf_size);
3810 /* alignment checks will add in reg->off themselves */
3811 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
3815 /* for access checks, reg->off is just part of off */
3818 if (reg->type == PTR_TO_MAP_VALUE) {
3819 if (t == BPF_WRITE && value_regno >= 0 &&
3820 is_pointer_value(env, value_regno)) {
3821 verbose(env, "R%d leaks addr into map\n", value_regno);
3824 err = check_map_access_type(env, regno, off, size, t);
3827 err = check_map_access(env, regno, off, size, false);
3828 if (!err && t == BPF_READ && value_regno >= 0) {
3829 struct bpf_map *map = reg->map_ptr;
3831 /* if map is read-only, track its contents as scalars */
3832 if (tnum_is_const(reg->var_off) &&
3833 bpf_map_is_rdonly(map) &&
3834 map->ops->map_direct_value_addr) {
3835 int map_off = off + reg->var_off.value;
3838 err = bpf_map_direct_read(map, map_off, size,
3843 regs[value_regno].type = SCALAR_VALUE;
3844 __mark_reg_known(®s[value_regno], val);
3846 mark_reg_unknown(env, regs, value_regno);
3849 } else if (reg->type == PTR_TO_MEM) {
3850 if (t == BPF_WRITE && value_regno >= 0 &&
3851 is_pointer_value(env, value_regno)) {
3852 verbose(env, "R%d leaks addr into mem\n", value_regno);
3855 err = check_mem_region_access(env, regno, off, size,
3856 reg->mem_size, false);
3857 if (!err && t == BPF_READ && value_regno >= 0)
3858 mark_reg_unknown(env, regs, value_regno);
3859 } else if (reg->type == PTR_TO_CTX) {
3860 enum bpf_reg_type reg_type = SCALAR_VALUE;
3861 struct btf *btf = NULL;
3864 if (t == BPF_WRITE && value_regno >= 0 &&
3865 is_pointer_value(env, value_regno)) {
3866 verbose(env, "R%d leaks addr into ctx\n", value_regno);
3870 err = check_ctx_reg(env, reg, regno);
3874 err = check_ctx_access(env, insn_idx, off, size, t, ®_type, &btf, &btf_id);
3876 verbose_linfo(env, insn_idx, "; ");
3877 if (!err && t == BPF_READ && value_regno >= 0) {
3878 /* ctx access returns either a scalar, or a
3879 * PTR_TO_PACKET[_META,_END]. In the latter
3880 * case, we know the offset is zero.
3882 if (reg_type == SCALAR_VALUE) {
3883 mark_reg_unknown(env, regs, value_regno);
3885 mark_reg_known_zero(env, regs,
3887 if (reg_type_may_be_null(reg_type))
3888 regs[value_regno].id = ++env->id_gen;
3889 /* A load of ctx field could have different
3890 * actual load size with the one encoded in the
3891 * insn. When the dst is PTR, it is for sure not
3894 regs[value_regno].subreg_def = DEF_NOT_SUBREG;
3895 if (reg_type == PTR_TO_BTF_ID ||
3896 reg_type == PTR_TO_BTF_ID_OR_NULL) {
3897 regs[value_regno].btf = btf;
3898 regs[value_regno].btf_id = btf_id;
3901 regs[value_regno].type = reg_type;
3904 } else if (reg->type == PTR_TO_STACK) {
3905 /* Basic bounds checks. */
3906 err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
3910 state = func(env, reg);
3911 err = update_stack_depth(env, state, off);
3916 err = check_stack_read(env, regno, off, size,
3919 err = check_stack_write(env, regno, off, size,
3920 value_regno, insn_idx);
3921 } else if (reg_is_pkt_pointer(reg)) {
3922 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
3923 verbose(env, "cannot write into packet\n");
3926 if (t == BPF_WRITE && value_regno >= 0 &&
3927 is_pointer_value(env, value_regno)) {
3928 verbose(env, "R%d leaks addr into packet\n",
3932 err = check_packet_access(env, regno, off, size, false);
3933 if (!err && t == BPF_READ && value_regno >= 0)
3934 mark_reg_unknown(env, regs, value_regno);
3935 } else if (reg->type == PTR_TO_FLOW_KEYS) {
3936 if (t == BPF_WRITE && value_regno >= 0 &&
3937 is_pointer_value(env, value_regno)) {
3938 verbose(env, "R%d leaks addr into flow keys\n",
3943 err = check_flow_keys_access(env, off, size);
3944 if (!err && t == BPF_READ && value_regno >= 0)
3945 mark_reg_unknown(env, regs, value_regno);
3946 } else if (type_is_sk_pointer(reg->type)) {
3947 if (t == BPF_WRITE) {
3948 verbose(env, "R%d cannot write into %s\n",
3949 regno, reg_type_str[reg->type]);
3952 err = check_sock_access(env, insn_idx, regno, off, size, t);
3953 if (!err && value_regno >= 0)
3954 mark_reg_unknown(env, regs, value_regno);
3955 } else if (reg->type == PTR_TO_TP_BUFFER) {
3956 err = check_tp_buffer_access(env, reg, regno, off, size);
3957 if (!err && t == BPF_READ && value_regno >= 0)
3958 mark_reg_unknown(env, regs, value_regno);
3959 } else if (reg->type == PTR_TO_BTF_ID) {
3960 err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
3962 } else if (reg->type == CONST_PTR_TO_MAP) {
3963 err = check_ptr_to_map_access(env, regs, regno, off, size, t,
3965 } else if (reg->type == PTR_TO_RDONLY_BUF) {
3966 if (t == BPF_WRITE) {
3967 verbose(env, "R%d cannot write into %s\n",
3968 regno, reg_type_str[reg->type]);
3971 err = check_buffer_access(env, reg, regno, off, size, false,
3973 &env->prog->aux->max_rdonly_access);
3974 if (!err && value_regno >= 0)
3975 mark_reg_unknown(env, regs, value_regno);
3976 } else if (reg->type == PTR_TO_RDWR_BUF) {
3977 err = check_buffer_access(env, reg, regno, off, size, false,
3979 &env->prog->aux->max_rdwr_access);
3980 if (!err && t == BPF_READ && value_regno >= 0)
3981 mark_reg_unknown(env, regs, value_regno);
3983 verbose(env, "R%d invalid mem access '%s'\n", regno,
3984 reg_type_str[reg->type]);
3988 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
3989 regs[value_regno].type == SCALAR_VALUE) {
3990 /* b/h/w load zero-extends, mark upper bits as known 0 */
3991 coerce_reg_to_size(®s[value_regno], size);
3996 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
4001 switch (insn->imm) {
4003 case BPF_ADD | BPF_FETCH:
4005 case BPF_AND | BPF_FETCH:
4007 case BPF_OR | BPF_FETCH:
4009 case BPF_XOR | BPF_FETCH:
4014 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
4018 if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
4019 verbose(env, "invalid atomic operand size\n");
4023 /* check src1 operand */
4024 err = check_reg_arg(env, insn->src_reg, SRC_OP);
4028 /* check src2 operand */
4029 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
4033 if (insn->imm == BPF_CMPXCHG) {
4034 /* Check comparison of R0 with memory location */
4035 err = check_reg_arg(env, BPF_REG_0, SRC_OP);
4040 if (is_pointer_value(env, insn->src_reg)) {
4041 verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
4045 if (is_ctx_reg(env, insn->dst_reg) ||
4046 is_pkt_reg(env, insn->dst_reg) ||
4047 is_flow_key_reg(env, insn->dst_reg) ||
4048 is_sk_reg(env, insn->dst_reg)) {
4049 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
4051 reg_type_str[reg_state(env, insn->dst_reg)->type]);
4055 if (insn->imm & BPF_FETCH) {
4056 if (insn->imm == BPF_CMPXCHG)
4057 load_reg = BPF_REG_0;
4059 load_reg = insn->src_reg;
4061 /* check and record load of old value */
4062 err = check_reg_arg(env, load_reg, DST_OP);
4066 /* This instruction accesses a memory location but doesn't
4067 * actually load it into a register.
4072 /* check whether we can read the memory */
4073 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
4074 BPF_SIZE(insn->code), BPF_READ, load_reg, true);
4078 /* check whether we can write into the same memory */
4079 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
4080 BPF_SIZE(insn->code), BPF_WRITE, -1, true);
4087 /* When register 'regno' is used to read the stack (either directly or through
4088 * a helper function) make sure that it's within stack boundary and, depending
4089 * on the access type, that all elements of the stack are initialized.
4091 * 'off' includes 'regno->off', but not its dynamic part (if any).
4093 * All registers that have been spilled on the stack in the slots within the
4094 * read offsets are marked as read.
4096 static int check_stack_range_initialized(
4097 struct bpf_verifier_env *env, int regno, int off,
4098 int access_size, bool zero_size_allowed,
4099 enum stack_access_src type, struct bpf_call_arg_meta *meta)
4101 struct bpf_reg_state *reg = reg_state(env, regno);
4102 struct bpf_func_state *state = func(env, reg);
4103 int err, min_off, max_off, i, j, slot, spi;
4104 char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
4105 enum bpf_access_type bounds_check_type;
4106 /* Some accesses can write anything into the stack, others are
4109 bool clobber = false;
4111 if (access_size == 0 && !zero_size_allowed) {
4112 verbose(env, "invalid zero-sized read\n");
4116 if (type == ACCESS_HELPER) {
4117 /* The bounds checks for writes are more permissive than for
4118 * reads. However, if raw_mode is not set, we'll do extra
4121 bounds_check_type = BPF_WRITE;
4124 bounds_check_type = BPF_READ;
4126 err = check_stack_access_within_bounds(env, regno, off, access_size,
4127 type, bounds_check_type);
4132 if (tnum_is_const(reg->var_off)) {
4133 min_off = max_off = reg->var_off.value + off;
4135 /* Variable offset is prohibited for unprivileged mode for
4136 * simplicity since it requires corresponding support in
4137 * Spectre masking for stack ALU.
4138 * See also retrieve_ptr_limit().
4140 if (!env->bypass_spec_v1) {
4143 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4144 verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
4145 regno, err_extra, tn_buf);
4148 /* Only initialized buffer on stack is allowed to be accessed
4149 * with variable offset. With uninitialized buffer it's hard to
4150 * guarantee that whole memory is marked as initialized on
4151 * helper return since specific bounds are unknown what may
4152 * cause uninitialized stack leaking.
4154 if (meta && meta->raw_mode)
4157 min_off = reg->smin_value + off;
4158 max_off = reg->smax_value + off;
4161 if (meta && meta->raw_mode) {
4162 meta->access_size = access_size;
4163 meta->regno = regno;
4167 for (i = min_off; i < max_off + access_size; i++) {
4171 spi = slot / BPF_REG_SIZE;
4172 if (state->allocated_stack <= slot)
4174 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
4175 if (*stype == STACK_MISC)
4177 if (*stype == STACK_ZERO) {
4179 /* helper can write anything into the stack */
4180 *stype = STACK_MISC;
4185 if (state->stack[spi].slot_type[0] == STACK_SPILL &&
4186 state->stack[spi].spilled_ptr.type == PTR_TO_BTF_ID)
4189 if (state->stack[spi].slot_type[0] == STACK_SPILL &&
4190 (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
4191 env->allow_ptr_leaks)) {
4193 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
4194 for (j = 0; j < BPF_REG_SIZE; j++)
4195 state->stack[spi].slot_type[j] = STACK_MISC;
4201 if (tnum_is_const(reg->var_off)) {
4202 verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
4203 err_extra, regno, min_off, i - min_off, access_size);
4207 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4208 verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
4209 err_extra, regno, tn_buf, i - min_off, access_size);
4213 /* reading any byte out of 8-byte 'spill_slot' will cause
4214 * the whole slot to be marked as 'read'
4216 mark_reg_read(env, &state->stack[spi].spilled_ptr,
4217 state->stack[spi].spilled_ptr.parent,
4220 return update_stack_depth(env, state, min_off);
4223 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
4224 int access_size, bool zero_size_allowed,
4225 struct bpf_call_arg_meta *meta)
4227 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
4229 switch (reg->type) {
4231 case PTR_TO_PACKET_META:
4232 return check_packet_access(env, regno, reg->off, access_size,
4234 case PTR_TO_MAP_VALUE:
4235 if (check_map_access_type(env, regno, reg->off, access_size,
4236 meta && meta->raw_mode ? BPF_WRITE :
4239 return check_map_access(env, regno, reg->off, access_size,
4242 return check_mem_region_access(env, regno, reg->off,
4243 access_size, reg->mem_size,
4245 case PTR_TO_RDONLY_BUF:
4246 if (meta && meta->raw_mode)
4248 return check_buffer_access(env, reg, regno, reg->off,
4249 access_size, zero_size_allowed,
4251 &env->prog->aux->max_rdonly_access);
4252 case PTR_TO_RDWR_BUF:
4253 return check_buffer_access(env, reg, regno, reg->off,
4254 access_size, zero_size_allowed,
4256 &env->prog->aux->max_rdwr_access);
4258 return check_stack_range_initialized(
4260 regno, reg->off, access_size,
4261 zero_size_allowed, ACCESS_HELPER, meta);
4262 default: /* scalar_value or invalid ptr */
4263 /* Allow zero-byte read from NULL, regardless of pointer type */
4264 if (zero_size_allowed && access_size == 0 &&
4265 register_is_null(reg))
4268 verbose(env, "R%d type=%s expected=%s\n", regno,
4269 reg_type_str[reg->type],
4270 reg_type_str[PTR_TO_STACK]);
4275 int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
4276 u32 regno, u32 mem_size)
4278 if (register_is_null(reg))
4281 if (reg_type_may_be_null(reg->type)) {
4282 /* Assuming that the register contains a value check if the memory
4283 * access is safe. Temporarily save and restore the register's state as
4284 * the conversion shouldn't be visible to a caller.
4286 const struct bpf_reg_state saved_reg = *reg;
4289 mark_ptr_not_null_reg(reg);
4290 rv = check_helper_mem_access(env, regno, mem_size, true, NULL);
4295 return check_helper_mem_access(env, regno, mem_size, true, NULL);
4298 /* Implementation details:
4299 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL
4300 * Two bpf_map_lookups (even with the same key) will have different reg->id.
4301 * For traditional PTR_TO_MAP_VALUE the verifier clears reg->id after
4302 * value_or_null->value transition, since the verifier only cares about
4303 * the range of access to valid map value pointer and doesn't care about actual
4304 * address of the map element.
4305 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
4306 * reg->id > 0 after value_or_null->value transition. By doing so
4307 * two bpf_map_lookups will be considered two different pointers that
4308 * point to different bpf_spin_locks.
4309 * The verifier allows taking only one bpf_spin_lock at a time to avoid
4311 * Since only one bpf_spin_lock is allowed the checks are simpler than
4312 * reg_is_refcounted() logic. The verifier needs to remember only
4313 * one spin_lock instead of array of acquired_refs.
4314 * cur_state->active_spin_lock remembers which map value element got locked
4315 * and clears it after bpf_spin_unlock.
4317 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
4320 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
4321 struct bpf_verifier_state *cur = env->cur_state;
4322 bool is_const = tnum_is_const(reg->var_off);
4323 struct bpf_map *map = reg->map_ptr;
4324 u64 val = reg->var_off.value;
4328 "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
4334 "map '%s' has to have BTF in order to use bpf_spin_lock\n",
4338 if (!map_value_has_spin_lock(map)) {
4339 if (map->spin_lock_off == -E2BIG)
4341 "map '%s' has more than one 'struct bpf_spin_lock'\n",
4343 else if (map->spin_lock_off == -ENOENT)
4345 "map '%s' doesn't have 'struct bpf_spin_lock'\n",
4349 "map '%s' is not a struct type or bpf_spin_lock is mangled\n",
4353 if (map->spin_lock_off != val + reg->off) {
4354 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock'\n",
4359 if (cur->active_spin_lock) {
4361 "Locking two bpf_spin_locks are not allowed\n");
4364 cur->active_spin_lock = reg->id;
4366 if (!cur->active_spin_lock) {
4367 verbose(env, "bpf_spin_unlock without taking a lock\n");
4370 if (cur->active_spin_lock != reg->id) {
4371 verbose(env, "bpf_spin_unlock of different lock\n");
4374 cur->active_spin_lock = 0;
4379 static bool arg_type_is_mem_ptr(enum bpf_arg_type type)
4381 return type == ARG_PTR_TO_MEM ||
4382 type == ARG_PTR_TO_MEM_OR_NULL ||
4383 type == ARG_PTR_TO_UNINIT_MEM;
4386 static bool arg_type_is_mem_size(enum bpf_arg_type type)
4388 return type == ARG_CONST_SIZE ||
4389 type == ARG_CONST_SIZE_OR_ZERO;
4392 static bool arg_type_is_alloc_size(enum bpf_arg_type type)
4394 return type == ARG_CONST_ALLOC_SIZE_OR_ZERO;
4397 static bool arg_type_is_int_ptr(enum bpf_arg_type type)
4399 return type == ARG_PTR_TO_INT ||
4400 type == ARG_PTR_TO_LONG;
4403 static int int_ptr_type_to_size(enum bpf_arg_type type)
4405 if (type == ARG_PTR_TO_INT)
4407 else if (type == ARG_PTR_TO_LONG)
4413 static int resolve_map_arg_type(struct bpf_verifier_env *env,
4414 const struct bpf_call_arg_meta *meta,
4415 enum bpf_arg_type *arg_type)
4417 if (!meta->map_ptr) {
4418 /* kernel subsystem misconfigured verifier */
4419 verbose(env, "invalid map_ptr to access map->type\n");
4423 switch (meta->map_ptr->map_type) {
4424 case BPF_MAP_TYPE_SOCKMAP:
4425 case BPF_MAP_TYPE_SOCKHASH:
4426 if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
4427 *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
4429 verbose(env, "invalid arg_type for sockmap/sockhash\n");
4440 struct bpf_reg_types {
4441 const enum bpf_reg_type types[10];
4445 static const struct bpf_reg_types map_key_value_types = {
4454 static const struct bpf_reg_types sock_types = {
4464 static const struct bpf_reg_types btf_id_sock_common_types = {
4472 .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
4476 static const struct bpf_reg_types mem_types = {
4488 static const struct bpf_reg_types int_ptr_types = {
4497 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
4498 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
4499 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
4500 static const struct bpf_reg_types alloc_mem_types = { .types = { PTR_TO_MEM } };
4501 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
4502 static const struct bpf_reg_types btf_ptr_types = { .types = { PTR_TO_BTF_ID } };
4503 static const struct bpf_reg_types spin_lock_types = { .types = { PTR_TO_MAP_VALUE } };
4504 static const struct bpf_reg_types percpu_btf_ptr_types = { .types = { PTR_TO_PERCPU_BTF_ID } };
4506 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
4507 [ARG_PTR_TO_MAP_KEY] = &map_key_value_types,
4508 [ARG_PTR_TO_MAP_VALUE] = &map_key_value_types,
4509 [ARG_PTR_TO_UNINIT_MAP_VALUE] = &map_key_value_types,
4510 [ARG_PTR_TO_MAP_VALUE_OR_NULL] = &map_key_value_types,
4511 [ARG_CONST_SIZE] = &scalar_types,
4512 [ARG_CONST_SIZE_OR_ZERO] = &scalar_types,
4513 [ARG_CONST_ALLOC_SIZE_OR_ZERO] = &scalar_types,
4514 [ARG_CONST_MAP_PTR] = &const_map_ptr_types,
4515 [ARG_PTR_TO_CTX] = &context_types,
4516 [ARG_PTR_TO_CTX_OR_NULL] = &context_types,
4517 [ARG_PTR_TO_SOCK_COMMON] = &sock_types,
4519 [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types,
4521 [ARG_PTR_TO_SOCKET] = &fullsock_types,
4522 [ARG_PTR_TO_SOCKET_OR_NULL] = &fullsock_types,
4523 [ARG_PTR_TO_BTF_ID] = &btf_ptr_types,
4524 [ARG_PTR_TO_SPIN_LOCK] = &spin_lock_types,
4525 [ARG_PTR_TO_MEM] = &mem_types,
4526 [ARG_PTR_TO_MEM_OR_NULL] = &mem_types,
4527 [ARG_PTR_TO_UNINIT_MEM] = &mem_types,
4528 [ARG_PTR_TO_ALLOC_MEM] = &alloc_mem_types,
4529 [ARG_PTR_TO_ALLOC_MEM_OR_NULL] = &alloc_mem_types,
4530 [ARG_PTR_TO_INT] = &int_ptr_types,
4531 [ARG_PTR_TO_LONG] = &int_ptr_types,
4532 [ARG_PTR_TO_PERCPU_BTF_ID] = &percpu_btf_ptr_types,
4535 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
4536 enum bpf_arg_type arg_type,
4537 const u32 *arg_btf_id)
4539 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
4540 enum bpf_reg_type expected, type = reg->type;
4541 const struct bpf_reg_types *compatible;
4544 compatible = compatible_reg_types[arg_type];
4546 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
4550 for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
4551 expected = compatible->types[i];
4552 if (expected == NOT_INIT)
4555 if (type == expected)
4559 verbose(env, "R%d type=%s expected=", regno, reg_type_str[type]);
4560 for (j = 0; j + 1 < i; j++)
4561 verbose(env, "%s, ", reg_type_str[compatible->types[j]]);
4562 verbose(env, "%s\n", reg_type_str[compatible->types[j]]);
4566 if (type == PTR_TO_BTF_ID) {
4568 if (!compatible->btf_id) {
4569 verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
4572 arg_btf_id = compatible->btf_id;
4575 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
4576 btf_vmlinux, *arg_btf_id)) {
4577 verbose(env, "R%d is of type %s but %s is expected\n",
4578 regno, kernel_type_name(reg->btf, reg->btf_id),
4579 kernel_type_name(btf_vmlinux, *arg_btf_id));
4583 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4584 verbose(env, "R%d is a pointer to in-kernel struct with non-zero offset\n",
4593 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
4594 struct bpf_call_arg_meta *meta,
4595 const struct bpf_func_proto *fn)
4597 u32 regno = BPF_REG_1 + arg;
4598 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
4599 enum bpf_arg_type arg_type = fn->arg_type[arg];
4600 enum bpf_reg_type type = reg->type;
4603 if (arg_type == ARG_DONTCARE)
4606 err = check_reg_arg(env, regno, SRC_OP);
4610 if (arg_type == ARG_ANYTHING) {
4611 if (is_pointer_value(env, regno)) {
4612 verbose(env, "R%d leaks addr into helper function\n",
4619 if (type_is_pkt_pointer(type) &&
4620 !may_access_direct_pkt_data(env, meta, BPF_READ)) {
4621 verbose(env, "helper access to the packet is not allowed\n");
4625 if (arg_type == ARG_PTR_TO_MAP_VALUE ||
4626 arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE ||
4627 arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL) {
4628 err = resolve_map_arg_type(env, meta, &arg_type);
4633 if (register_is_null(reg) && arg_type_may_be_null(arg_type))
4634 /* A NULL register has a SCALAR_VALUE type, so skip
4637 goto skip_type_check;
4639 err = check_reg_type(env, regno, arg_type, fn->arg_btf_id[arg]);
4643 if (type == PTR_TO_CTX) {
4644 err = check_ctx_reg(env, reg, regno);
4650 if (reg->ref_obj_id) {
4651 if (meta->ref_obj_id) {
4652 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
4653 regno, reg->ref_obj_id,
4657 meta->ref_obj_id = reg->ref_obj_id;
4660 if (arg_type == ARG_CONST_MAP_PTR) {
4661 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
4662 meta->map_ptr = reg->map_ptr;
4663 } else if (arg_type == ARG_PTR_TO_MAP_KEY) {
4664 /* bpf_map_xxx(..., map_ptr, ..., key) call:
4665 * check that [key, key + map->key_size) are within
4666 * stack limits and initialized
4668 if (!meta->map_ptr) {
4669 /* in function declaration map_ptr must come before
4670 * map_key, so that it's verified and known before
4671 * we have to check map_key here. Otherwise it means
4672 * that kernel subsystem misconfigured verifier
4674 verbose(env, "invalid map_ptr to access map->key\n");
4677 err = check_helper_mem_access(env, regno,
4678 meta->map_ptr->key_size, false,
4680 } else if (arg_type == ARG_PTR_TO_MAP_VALUE ||
4681 (arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL &&
4682 !register_is_null(reg)) ||
4683 arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE) {
4684 /* bpf_map_xxx(..., map_ptr, ..., value) call:
4685 * check [value, value + map->value_size) validity
4687 if (!meta->map_ptr) {
4688 /* kernel subsystem misconfigured verifier */
4689 verbose(env, "invalid map_ptr to access map->value\n");
4692 meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE);
4693 err = check_helper_mem_access(env, regno,
4694 meta->map_ptr->value_size, false,
4696 } else if (arg_type == ARG_PTR_TO_PERCPU_BTF_ID) {
4698 verbose(env, "Helper has invalid btf_id in R%d\n", regno);
4701 meta->ret_btf = reg->btf;
4702 meta->ret_btf_id = reg->btf_id;
4703 } else if (arg_type == ARG_PTR_TO_SPIN_LOCK) {
4704 if (meta->func_id == BPF_FUNC_spin_lock) {
4705 if (process_spin_lock(env, regno, true))
4707 } else if (meta->func_id == BPF_FUNC_spin_unlock) {
4708 if (process_spin_lock(env, regno, false))
4711 verbose(env, "verifier internal error\n");
4714 } else if (arg_type_is_mem_ptr(arg_type)) {
4715 /* The access to this pointer is only checked when we hit the
4716 * next is_mem_size argument below.
4718 meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MEM);
4719 } else if (arg_type_is_mem_size(arg_type)) {
4720 bool zero_size_allowed = (arg_type == ARG_CONST_SIZE_OR_ZERO);
4722 /* This is used to refine r0 return value bounds for helpers
4723 * that enforce this value as an upper bound on return values.
4724 * See do_refine_retval_range() for helpers that can refine
4725 * the return value. C type of helper is u32 so we pull register
4726 * bound from umax_value however, if negative verifier errors
4727 * out. Only upper bounds can be learned because retval is an
4728 * int type and negative retvals are allowed.
4730 meta->msize_max_value = reg->umax_value;
4732 /* The register is SCALAR_VALUE; the access check
4733 * happens using its boundaries.
4735 if (!tnum_is_const(reg->var_off))
4736 /* For unprivileged variable accesses, disable raw
4737 * mode so that the program is required to
4738 * initialize all the memory that the helper could
4739 * just partially fill up.
4743 if (reg->smin_value < 0) {
4744 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
4749 if (reg->umin_value == 0) {
4750 err = check_helper_mem_access(env, regno - 1, 0,
4757 if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
4758 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
4762 err = check_helper_mem_access(env, regno - 1,
4764 zero_size_allowed, meta);
4766 err = mark_chain_precision(env, regno);
4767 } else if (arg_type_is_alloc_size(arg_type)) {
4768 if (!tnum_is_const(reg->var_off)) {
4769 verbose(env, "R%d is not a known constant'\n",
4773 meta->mem_size = reg->var_off.value;
4774 } else if (arg_type_is_int_ptr(arg_type)) {
4775 int size = int_ptr_type_to_size(arg_type);
4777 err = check_helper_mem_access(env, regno, size, false, meta);
4780 err = check_ptr_alignment(env, reg, 0, size, true);
4786 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
4788 enum bpf_attach_type eatype = env->prog->expected_attach_type;
4789 enum bpf_prog_type type = resolve_prog_type(env->prog);
4791 if (func_id != BPF_FUNC_map_update_elem)
4794 /* It's not possible to get access to a locked struct sock in these
4795 * contexts, so updating is safe.
4798 case BPF_PROG_TYPE_TRACING:
4799 if (eatype == BPF_TRACE_ITER)
4802 case BPF_PROG_TYPE_SOCKET_FILTER:
4803 case BPF_PROG_TYPE_SCHED_CLS:
4804 case BPF_PROG_TYPE_SCHED_ACT:
4805 case BPF_PROG_TYPE_XDP:
4806 case BPF_PROG_TYPE_SK_REUSEPORT:
4807 case BPF_PROG_TYPE_FLOW_DISSECTOR:
4808 case BPF_PROG_TYPE_SK_LOOKUP:
4814 verbose(env, "cannot update sockmap in this context\n");
4818 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
4820 return env->prog->jit_requested && IS_ENABLED(CONFIG_X86_64);
4823 static int check_map_func_compatibility(struct bpf_verifier_env *env,
4824 struct bpf_map *map, int func_id)
4829 /* We need a two way check, first is from map perspective ... */
4830 switch (map->map_type) {
4831 case BPF_MAP_TYPE_PROG_ARRAY:
4832 if (func_id != BPF_FUNC_tail_call)
4835 case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
4836 if (func_id != BPF_FUNC_perf_event_read &&
4837 func_id != BPF_FUNC_perf_event_output &&
4838 func_id != BPF_FUNC_skb_output &&
4839 func_id != BPF_FUNC_perf_event_read_value &&
4840 func_id != BPF_FUNC_xdp_output)
4843 case BPF_MAP_TYPE_RINGBUF:
4844 if (func_id != BPF_FUNC_ringbuf_output &&
4845 func_id != BPF_FUNC_ringbuf_reserve &&
4846 func_id != BPF_FUNC_ringbuf_submit &&
4847 func_id != BPF_FUNC_ringbuf_discard &&
4848 func_id != BPF_FUNC_ringbuf_query)
4851 case BPF_MAP_TYPE_STACK_TRACE:
4852 if (func_id != BPF_FUNC_get_stackid)
4855 case BPF_MAP_TYPE_CGROUP_ARRAY:
4856 if (func_id != BPF_FUNC_skb_under_cgroup &&
4857 func_id != BPF_FUNC_current_task_under_cgroup)
4860 case BPF_MAP_TYPE_CGROUP_STORAGE:
4861 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
4862 if (func_id != BPF_FUNC_get_local_storage)
4865 case BPF_MAP_TYPE_DEVMAP:
4866 case BPF_MAP_TYPE_DEVMAP_HASH:
4867 if (func_id != BPF_FUNC_redirect_map &&
4868 func_id != BPF_FUNC_map_lookup_elem)
4871 /* Restrict bpf side of cpumap and xskmap, open when use-cases
4874 case BPF_MAP_TYPE_CPUMAP:
4875 if (func_id != BPF_FUNC_redirect_map)
4878 case BPF_MAP_TYPE_XSKMAP:
4879 if (func_id != BPF_FUNC_redirect_map &&
4880 func_id != BPF_FUNC_map_lookup_elem)
4883 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
4884 case BPF_MAP_TYPE_HASH_OF_MAPS:
4885 if (func_id != BPF_FUNC_map_lookup_elem)
4888 case BPF_MAP_TYPE_SOCKMAP:
4889 if (func_id != BPF_FUNC_sk_redirect_map &&
4890 func_id != BPF_FUNC_sock_map_update &&
4891 func_id != BPF_FUNC_map_delete_elem &&
4892 func_id != BPF_FUNC_msg_redirect_map &&
4893 func_id != BPF_FUNC_sk_select_reuseport &&
4894 func_id != BPF_FUNC_map_lookup_elem &&
4895 !may_update_sockmap(env, func_id))
4898 case BPF_MAP_TYPE_SOCKHASH:
4899 if (func_id != BPF_FUNC_sk_redirect_hash &&
4900 func_id != BPF_FUNC_sock_hash_update &&
4901 func_id != BPF_FUNC_map_delete_elem &&
4902 func_id != BPF_FUNC_msg_redirect_hash &&
4903 func_id != BPF_FUNC_sk_select_reuseport &&
4904 func_id != BPF_FUNC_map_lookup_elem &&
4905 !may_update_sockmap(env, func_id))
4908 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
4909 if (func_id != BPF_FUNC_sk_select_reuseport)
4912 case BPF_MAP_TYPE_QUEUE:
4913 case BPF_MAP_TYPE_STACK:
4914 if (func_id != BPF_FUNC_map_peek_elem &&
4915 func_id != BPF_FUNC_map_pop_elem &&
4916 func_id != BPF_FUNC_map_push_elem)
4919 case BPF_MAP_TYPE_SK_STORAGE:
4920 if (func_id != BPF_FUNC_sk_storage_get &&
4921 func_id != BPF_FUNC_sk_storage_delete)
4924 case BPF_MAP_TYPE_INODE_STORAGE:
4925 if (func_id != BPF_FUNC_inode_storage_get &&
4926 func_id != BPF_FUNC_inode_storage_delete)
4929 case BPF_MAP_TYPE_TASK_STORAGE:
4930 if (func_id != BPF_FUNC_task_storage_get &&
4931 func_id != BPF_FUNC_task_storage_delete)
4938 /* ... and second from the function itself. */
4940 case BPF_FUNC_tail_call:
4941 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
4943 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
4944 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
4948 case BPF_FUNC_perf_event_read:
4949 case BPF_FUNC_perf_event_output:
4950 case BPF_FUNC_perf_event_read_value:
4951 case BPF_FUNC_skb_output:
4952 case BPF_FUNC_xdp_output:
4953 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
4956 case BPF_FUNC_get_stackid:
4957 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
4960 case BPF_FUNC_current_task_under_cgroup:
4961 case BPF_FUNC_skb_under_cgroup:
4962 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
4965 case BPF_FUNC_redirect_map:
4966 if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
4967 map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
4968 map->map_type != BPF_MAP_TYPE_CPUMAP &&
4969 map->map_type != BPF_MAP_TYPE_XSKMAP)
4972 case BPF_FUNC_sk_redirect_map:
4973 case BPF_FUNC_msg_redirect_map:
4974 case BPF_FUNC_sock_map_update:
4975 if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
4978 case BPF_FUNC_sk_redirect_hash:
4979 case BPF_FUNC_msg_redirect_hash:
4980 case BPF_FUNC_sock_hash_update:
4981 if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
4984 case BPF_FUNC_get_local_storage:
4985 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
4986 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
4989 case BPF_FUNC_sk_select_reuseport:
4990 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
4991 map->map_type != BPF_MAP_TYPE_SOCKMAP &&
4992 map->map_type != BPF_MAP_TYPE_SOCKHASH)
4995 case BPF_FUNC_map_peek_elem:
4996 case BPF_FUNC_map_pop_elem:
4997 case BPF_FUNC_map_push_elem:
4998 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
4999 map->map_type != BPF_MAP_TYPE_STACK)
5002 case BPF_FUNC_sk_storage_get:
5003 case BPF_FUNC_sk_storage_delete:
5004 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
5007 case BPF_FUNC_inode_storage_get:
5008 case BPF_FUNC_inode_storage_delete:
5009 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
5012 case BPF_FUNC_task_storage_get:
5013 case BPF_FUNC_task_storage_delete:
5014 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
5023 verbose(env, "cannot pass map_type %d into func %s#%d\n",
5024 map->map_type, func_id_name(func_id), func_id);
5028 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
5032 if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
5034 if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
5036 if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
5038 if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
5040 if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
5043 /* We only support one arg being in raw mode at the moment,
5044 * which is sufficient for the helper functions we have
5050 static bool check_args_pair_invalid(enum bpf_arg_type arg_curr,
5051 enum bpf_arg_type arg_next)
5053 return (arg_type_is_mem_ptr(arg_curr) &&
5054 !arg_type_is_mem_size(arg_next)) ||
5055 (!arg_type_is_mem_ptr(arg_curr) &&
5056 arg_type_is_mem_size(arg_next));
5059 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
5061 /* bpf_xxx(..., buf, len) call will access 'len'
5062 * bytes from memory 'buf'. Both arg types need
5063 * to be paired, so make sure there's no buggy
5064 * helper function specification.
5066 if (arg_type_is_mem_size(fn->arg1_type) ||
5067 arg_type_is_mem_ptr(fn->arg5_type) ||
5068 check_args_pair_invalid(fn->arg1_type, fn->arg2_type) ||
5069 check_args_pair_invalid(fn->arg2_type, fn->arg3_type) ||
5070 check_args_pair_invalid(fn->arg3_type, fn->arg4_type) ||
5071 check_args_pair_invalid(fn->arg4_type, fn->arg5_type))
5077 static bool check_refcount_ok(const struct bpf_func_proto *fn, int func_id)
5081 if (arg_type_may_be_refcounted(fn->arg1_type))
5083 if (arg_type_may_be_refcounted(fn->arg2_type))
5085 if (arg_type_may_be_refcounted(fn->arg3_type))
5087 if (arg_type_may_be_refcounted(fn->arg4_type))
5089 if (arg_type_may_be_refcounted(fn->arg5_type))
5092 /* A reference acquiring function cannot acquire
5093 * another refcounted ptr.
5095 if (may_be_acquire_function(func_id) && count)
5098 /* We only support one arg being unreferenced at the moment,
5099 * which is sufficient for the helper functions we have right now.
5104 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
5108 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
5109 if (fn->arg_type[i] == ARG_PTR_TO_BTF_ID && !fn->arg_btf_id[i])
5112 if (fn->arg_type[i] != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i])
5119 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
5121 return check_raw_mode_ok(fn) &&
5122 check_arg_pair_ok(fn) &&
5123 check_btf_id_ok(fn) &&
5124 check_refcount_ok(fn, func_id) ? 0 : -EINVAL;
5127 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
5128 * are now invalid, so turn them into unknown SCALAR_VALUE.
5130 static void __clear_all_pkt_pointers(struct bpf_verifier_env *env,
5131 struct bpf_func_state *state)
5133 struct bpf_reg_state *regs = state->regs, *reg;
5136 for (i = 0; i < MAX_BPF_REG; i++)
5137 if (reg_is_pkt_pointer_any(®s[i]))
5138 mark_reg_unknown(env, regs, i);
5140 bpf_for_each_spilled_reg(i, state, reg) {
5143 if (reg_is_pkt_pointer_any(reg))
5144 __mark_reg_unknown(env, reg);
5148 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
5150 struct bpf_verifier_state *vstate = env->cur_state;
5153 for (i = 0; i <= vstate->curframe; i++)
5154 __clear_all_pkt_pointers(env, vstate->frame[i]);
5159 BEYOND_PKT_END = -2,
5162 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
5164 struct bpf_func_state *state = vstate->frame[vstate->curframe];
5165 struct bpf_reg_state *reg = &state->regs[regn];
5167 if (reg->type != PTR_TO_PACKET)
5168 /* PTR_TO_PACKET_META is not supported yet */
5171 /* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
5172 * How far beyond pkt_end it goes is unknown.
5173 * if (!range_open) it's the case of pkt >= pkt_end
5174 * if (range_open) it's the case of pkt > pkt_end
5175 * hence this pointer is at least 1 byte bigger than pkt_end
5178 reg->range = BEYOND_PKT_END;
5180 reg->range = AT_PKT_END;
5183 static void release_reg_references(struct bpf_verifier_env *env,
5184 struct bpf_func_state *state,
5187 struct bpf_reg_state *regs = state->regs, *reg;
5190 for (i = 0; i < MAX_BPF_REG; i++)
5191 if (regs[i].ref_obj_id == ref_obj_id)
5192 mark_reg_unknown(env, regs, i);
5194 bpf_for_each_spilled_reg(i, state, reg) {
5197 if (reg->ref_obj_id == ref_obj_id)
5198 __mark_reg_unknown(env, reg);
5202 /* The pointer with the specified id has released its reference to kernel
5203 * resources. Identify all copies of the same pointer and clear the reference.
5205 static int release_reference(struct bpf_verifier_env *env,
5208 struct bpf_verifier_state *vstate = env->cur_state;
5212 err = release_reference_state(cur_func(env), ref_obj_id);
5216 for (i = 0; i <= vstate->curframe; i++)
5217 release_reg_references(env, vstate->frame[i], ref_obj_id);
5222 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
5223 struct bpf_reg_state *regs)
5227 /* after the call registers r0 - r5 were scratched */
5228 for (i = 0; i < CALLER_SAVED_REGS; i++) {
5229 mark_reg_not_init(env, regs, caller_saved[i]);
5230 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
5234 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
5237 struct bpf_verifier_state *state = env->cur_state;
5238 struct bpf_func_info_aux *func_info_aux;
5239 struct bpf_func_state *caller, *callee;
5240 int i, err, subprog, target_insn;
5241 bool is_global = false;
5243 if (state->curframe + 1 >= MAX_CALL_FRAMES) {
5244 verbose(env, "the call stack of %d frames is too deep\n",
5245 state->curframe + 2);
5249 target_insn = *insn_idx + insn->imm;
5250 subprog = find_subprog(env, target_insn + 1);
5252 verbose(env, "verifier bug. No program starts at insn %d\n",
5257 caller = state->frame[state->curframe];
5258 if (state->frame[state->curframe + 1]) {
5259 verbose(env, "verifier bug. Frame %d already allocated\n",
5260 state->curframe + 1);
5264 func_info_aux = env->prog->aux->func_info_aux;
5266 is_global = func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
5267 err = btf_check_func_arg_match(env, subprog, caller->regs);
5272 verbose(env, "Caller passes invalid args into func#%d\n",
5276 if (env->log.level & BPF_LOG_LEVEL)
5278 "Func#%d is global and valid. Skipping.\n",
5280 clear_caller_saved_regs(env, caller->regs);
5282 /* All global functions return a 64-bit SCALAR_VALUE */
5283 mark_reg_unknown(env, caller->regs, BPF_REG_0);
5284 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
5286 /* continue with next insn after call */
5291 callee = kzalloc(sizeof(*callee), GFP_KERNEL);
5294 state->frame[state->curframe + 1] = callee;
5296 /* callee cannot access r0, r6 - r9 for reading and has to write
5297 * into its own stack before reading from it.
5298 * callee can read/write into caller's stack
5300 init_func_state(env, callee,
5301 /* remember the callsite, it will be used by bpf_exit */
5302 *insn_idx /* callsite */,
5303 state->curframe + 1 /* frameno within this callchain */,
5304 subprog /* subprog number within this prog */);
5306 /* Transfer references to the callee */
5307 err = transfer_reference_state(callee, caller);
5311 /* copy r1 - r5 args that callee can access. The copy includes parent
5312 * pointers, which connects us up to the liveness chain
5314 for (i = BPF_REG_1; i <= BPF_REG_5; i++)
5315 callee->regs[i] = caller->regs[i];
5317 clear_caller_saved_regs(env, caller->regs);
5319 /* only increment it after check_reg_arg() finished */
5322 /* and go analyze first insn of the callee */
5323 *insn_idx = target_insn;
5325 if (env->log.level & BPF_LOG_LEVEL) {
5326 verbose(env, "caller:\n");
5327 print_verifier_state(env, caller);
5328 verbose(env, "callee:\n");
5329 print_verifier_state(env, callee);
5334 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
5336 struct bpf_verifier_state *state = env->cur_state;
5337 struct bpf_func_state *caller, *callee;
5338 struct bpf_reg_state *r0;
5341 callee = state->frame[state->curframe];
5342 r0 = &callee->regs[BPF_REG_0];
5343 if (r0->type == PTR_TO_STACK) {
5344 /* technically it's ok to return caller's stack pointer
5345 * (or caller's caller's pointer) back to the caller,
5346 * since these pointers are valid. Only current stack
5347 * pointer will be invalid as soon as function exits,
5348 * but let's be conservative
5350 verbose(env, "cannot return stack pointer to the caller\n");
5355 caller = state->frame[state->curframe];
5356 /* return to the caller whatever r0 had in the callee */
5357 caller->regs[BPF_REG_0] = *r0;
5359 /* Transfer references to the caller */
5360 err = transfer_reference_state(caller, callee);
5364 *insn_idx = callee->callsite + 1;
5365 if (env->log.level & BPF_LOG_LEVEL) {
5366 verbose(env, "returning from callee:\n");
5367 print_verifier_state(env, callee);
5368 verbose(env, "to caller at %d:\n", *insn_idx);
5369 print_verifier_state(env, caller);
5371 /* clear everything in the callee */
5372 free_func_state(callee);
5373 state->frame[state->curframe + 1] = NULL;
5377 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
5379 struct bpf_call_arg_meta *meta)
5381 struct bpf_reg_state *ret_reg = ®s[BPF_REG_0];
5383 if (ret_type != RET_INTEGER ||
5384 (func_id != BPF_FUNC_get_stack &&
5385 func_id != BPF_FUNC_probe_read_str &&
5386 func_id != BPF_FUNC_probe_read_kernel_str &&
5387 func_id != BPF_FUNC_probe_read_user_str))
5390 ret_reg->smax_value = meta->msize_max_value;
5391 ret_reg->s32_max_value = meta->msize_max_value;
5392 ret_reg->smin_value = -MAX_ERRNO;
5393 ret_reg->s32_min_value = -MAX_ERRNO;
5394 __reg_deduce_bounds(ret_reg);
5395 __reg_bound_offset(ret_reg);
5396 __update_reg_bounds(ret_reg);
5400 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
5401 int func_id, int insn_idx)
5403 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
5404 struct bpf_map *map = meta->map_ptr;
5406 if (func_id != BPF_FUNC_tail_call &&
5407 func_id != BPF_FUNC_map_lookup_elem &&
5408 func_id != BPF_FUNC_map_update_elem &&
5409 func_id != BPF_FUNC_map_delete_elem &&
5410 func_id != BPF_FUNC_map_push_elem &&
5411 func_id != BPF_FUNC_map_pop_elem &&
5412 func_id != BPF_FUNC_map_peek_elem)
5416 verbose(env, "kernel subsystem misconfigured verifier\n");
5420 /* In case of read-only, some additional restrictions
5421 * need to be applied in order to prevent altering the
5422 * state of the map from program side.
5424 if ((map->map_flags & BPF_F_RDONLY_PROG) &&
5425 (func_id == BPF_FUNC_map_delete_elem ||
5426 func_id == BPF_FUNC_map_update_elem ||
5427 func_id == BPF_FUNC_map_push_elem ||
5428 func_id == BPF_FUNC_map_pop_elem)) {
5429 verbose(env, "write into map forbidden\n");
5433 if (!BPF_MAP_PTR(aux->map_ptr_state))
5434 bpf_map_ptr_store(aux, meta->map_ptr,
5435 !meta->map_ptr->bypass_spec_v1);
5436 else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
5437 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
5438 !meta->map_ptr->bypass_spec_v1);
5443 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
5444 int func_id, int insn_idx)
5446 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
5447 struct bpf_reg_state *regs = cur_regs(env), *reg;
5448 struct bpf_map *map = meta->map_ptr;
5453 if (func_id != BPF_FUNC_tail_call)
5455 if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
5456 verbose(env, "kernel subsystem misconfigured verifier\n");
5460 range = tnum_range(0, map->max_entries - 1);
5461 reg = ®s[BPF_REG_3];
5463 if (!register_is_const(reg) || !tnum_in(range, reg->var_off)) {
5464 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
5468 err = mark_chain_precision(env, BPF_REG_3);
5472 val = reg->var_off.value;
5473 if (bpf_map_key_unseen(aux))
5474 bpf_map_key_store(aux, val);
5475 else if (!bpf_map_key_poisoned(aux) &&
5476 bpf_map_key_immediate(aux) != val)
5477 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
5481 static int check_reference_leak(struct bpf_verifier_env *env)
5483 struct bpf_func_state *state = cur_func(env);
5486 for (i = 0; i < state->acquired_refs; i++) {
5487 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
5488 state->refs[i].id, state->refs[i].insn_idx);
5490 return state->acquired_refs ? -EINVAL : 0;
5493 static int check_helper_call(struct bpf_verifier_env *env, int func_id, int insn_idx)
5495 const struct bpf_func_proto *fn = NULL;
5496 struct bpf_reg_state *regs;
5497 struct bpf_call_arg_meta meta;
5501 /* find function prototype */
5502 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
5503 verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
5508 if (env->ops->get_func_proto)
5509 fn = env->ops->get_func_proto(func_id, env->prog);
5511 verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
5516 /* eBPF programs must be GPL compatible to use GPL-ed functions */
5517 if (!env->prog->gpl_compatible && fn->gpl_only) {
5518 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
5522 if (fn->allowed && !fn->allowed(env->prog)) {
5523 verbose(env, "helper call is not allowed in probe\n");
5527 /* With LD_ABS/IND some JITs save/restore skb from r1. */
5528 changes_data = bpf_helper_changes_pkt_data(fn->func);
5529 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
5530 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
5531 func_id_name(func_id), func_id);
5535 memset(&meta, 0, sizeof(meta));
5536 meta.pkt_access = fn->pkt_access;
5538 err = check_func_proto(fn, func_id);
5540 verbose(env, "kernel subsystem misconfigured func %s#%d\n",
5541 func_id_name(func_id), func_id);
5545 meta.func_id = func_id;
5547 for (i = 0; i < 5; i++) {
5548 err = check_func_arg(env, i, &meta, fn);
5553 err = record_func_map(env, &meta, func_id, insn_idx);
5557 err = record_func_key(env, &meta, func_id, insn_idx);
5561 /* Mark slots with STACK_MISC in case of raw mode, stack offset
5562 * is inferred from register state.
5564 for (i = 0; i < meta.access_size; i++) {
5565 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
5566 BPF_WRITE, -1, false);
5571 if (func_id == BPF_FUNC_tail_call) {
5572 err = check_reference_leak(env);
5574 verbose(env, "tail_call would lead to reference leak\n");
5577 } else if (is_release_function(func_id)) {
5578 err = release_reference(env, meta.ref_obj_id);
5580 verbose(env, "func %s#%d reference has not been acquired before\n",
5581 func_id_name(func_id), func_id);
5586 regs = cur_regs(env);
5588 /* check that flags argument in get_local_storage(map, flags) is 0,
5589 * this is required because get_local_storage() can't return an error.
5591 if (func_id == BPF_FUNC_get_local_storage &&
5592 !register_is_null(®s[BPF_REG_2])) {
5593 verbose(env, "get_local_storage() doesn't support non-zero flags\n");
5597 /* reset caller saved regs */
5598 for (i = 0; i < CALLER_SAVED_REGS; i++) {
5599 mark_reg_not_init(env, regs, caller_saved[i]);
5600 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
5603 /* helper call returns 64-bit value. */
5604 regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
5606 /* update return register (already marked as written above) */
5607 if (fn->ret_type == RET_INTEGER) {
5608 /* sets type to SCALAR_VALUE */
5609 mark_reg_unknown(env, regs, BPF_REG_0);
5610 } else if (fn->ret_type == RET_VOID) {
5611 regs[BPF_REG_0].type = NOT_INIT;
5612 } else if (fn->ret_type == RET_PTR_TO_MAP_VALUE_OR_NULL ||
5613 fn->ret_type == RET_PTR_TO_MAP_VALUE) {
5614 /* There is no offset yet applied, variable or fixed */
5615 mark_reg_known_zero(env, regs, BPF_REG_0);
5616 /* remember map_ptr, so that check_map_access()
5617 * can check 'value_size' boundary of memory access
5618 * to map element returned from bpf_map_lookup_elem()
5620 if (meta.map_ptr == NULL) {
5622 "kernel subsystem misconfigured verifier\n");
5625 regs[BPF_REG_0].map_ptr = meta.map_ptr;
5626 if (fn->ret_type == RET_PTR_TO_MAP_VALUE) {
5627 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE;
5628 if (map_value_has_spin_lock(meta.map_ptr))
5629 regs[BPF_REG_0].id = ++env->id_gen;
5631 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE_OR_NULL;
5633 } else if (fn->ret_type == RET_PTR_TO_SOCKET_OR_NULL) {
5634 mark_reg_known_zero(env, regs, BPF_REG_0);
5635 regs[BPF_REG_0].type = PTR_TO_SOCKET_OR_NULL;
5636 } else if (fn->ret_type == RET_PTR_TO_SOCK_COMMON_OR_NULL) {
5637 mark_reg_known_zero(env, regs, BPF_REG_0);
5638 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON_OR_NULL;
5639 } else if (fn->ret_type == RET_PTR_TO_TCP_SOCK_OR_NULL) {
5640 mark_reg_known_zero(env, regs, BPF_REG_0);
5641 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK_OR_NULL;
5642 } else if (fn->ret_type == RET_PTR_TO_ALLOC_MEM_OR_NULL) {
5643 mark_reg_known_zero(env, regs, BPF_REG_0);
5644 regs[BPF_REG_0].type = PTR_TO_MEM_OR_NULL;
5645 regs[BPF_REG_0].mem_size = meta.mem_size;
5646 } else if (fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID_OR_NULL ||
5647 fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID) {
5648 const struct btf_type *t;
5650 mark_reg_known_zero(env, regs, BPF_REG_0);
5651 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
5652 if (!btf_type_is_struct(t)) {
5654 const struct btf_type *ret;
5657 /* resolve the type size of ksym. */
5658 ret = btf_resolve_size(meta.ret_btf, t, &tsize);
5660 tname = btf_name_by_offset(meta.ret_btf, t->name_off);
5661 verbose(env, "unable to resolve the size of type '%s': %ld\n",
5662 tname, PTR_ERR(ret));
5665 regs[BPF_REG_0].type =
5666 fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID ?
5667 PTR_TO_MEM : PTR_TO_MEM_OR_NULL;
5668 regs[BPF_REG_0].mem_size = tsize;
5670 regs[BPF_REG_0].type =
5671 fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID ?
5672 PTR_TO_BTF_ID : PTR_TO_BTF_ID_OR_NULL;
5673 regs[BPF_REG_0].btf = meta.ret_btf;
5674 regs[BPF_REG_0].btf_id = meta.ret_btf_id;
5676 } else if (fn->ret_type == RET_PTR_TO_BTF_ID_OR_NULL ||
5677 fn->ret_type == RET_PTR_TO_BTF_ID) {
5680 mark_reg_known_zero(env, regs, BPF_REG_0);
5681 regs[BPF_REG_0].type = fn->ret_type == RET_PTR_TO_BTF_ID ?
5683 PTR_TO_BTF_ID_OR_NULL;
5684 ret_btf_id = *fn->ret_btf_id;
5685 if (ret_btf_id == 0) {
5686 verbose(env, "invalid return type %d of func %s#%d\n",
5687 fn->ret_type, func_id_name(func_id), func_id);
5690 /* current BPF helper definitions are only coming from
5691 * built-in code with type IDs from vmlinux BTF
5693 regs[BPF_REG_0].btf = btf_vmlinux;
5694 regs[BPF_REG_0].btf_id = ret_btf_id;
5696 verbose(env, "unknown return type %d of func %s#%d\n",
5697 fn->ret_type, func_id_name(func_id), func_id);
5701 if (reg_type_may_be_null(regs[BPF_REG_0].type))
5702 regs[BPF_REG_0].id = ++env->id_gen;
5704 if (is_ptr_cast_function(func_id)) {
5705 /* For release_reference() */
5706 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
5707 } else if (is_acquire_function(func_id, meta.map_ptr)) {
5708 int id = acquire_reference_state(env, insn_idx);
5712 /* For mark_ptr_or_null_reg() */
5713 regs[BPF_REG_0].id = id;
5714 /* For release_reference() */
5715 regs[BPF_REG_0].ref_obj_id = id;
5718 do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
5720 err = check_map_func_compatibility(env, meta.map_ptr, func_id);
5724 if ((func_id == BPF_FUNC_get_stack ||
5725 func_id == BPF_FUNC_get_task_stack) &&
5726 !env->prog->has_callchain_buf) {
5727 const char *err_str;
5729 #ifdef CONFIG_PERF_EVENTS
5730 err = get_callchain_buffers(sysctl_perf_event_max_stack);
5731 err_str = "cannot get callchain buffer for func %s#%d\n";
5734 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
5737 verbose(env, err_str, func_id_name(func_id), func_id);
5741 env->prog->has_callchain_buf = true;
5744 if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
5745 env->prog->call_get_stack = true;
5748 clear_all_pkt_pointers(env);
5752 static bool signed_add_overflows(s64 a, s64 b)
5754 /* Do the add in u64, where overflow is well-defined */
5755 s64 res = (s64)((u64)a + (u64)b);
5762 static bool signed_add32_overflows(s32 a, s32 b)
5764 /* Do the add in u32, where overflow is well-defined */
5765 s32 res = (s32)((u32)a + (u32)b);
5772 static bool signed_sub_overflows(s64 a, s64 b)
5774 /* Do the sub in u64, where overflow is well-defined */
5775 s64 res = (s64)((u64)a - (u64)b);
5782 static bool signed_sub32_overflows(s32 a, s32 b)
5784 /* Do the sub in u32, where overflow is well-defined */
5785 s32 res = (s32)((u32)a - (u32)b);
5792 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
5793 const struct bpf_reg_state *reg,
5794 enum bpf_reg_type type)
5796 bool known = tnum_is_const(reg->var_off);
5797 s64 val = reg->var_off.value;
5798 s64 smin = reg->smin_value;
5800 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
5801 verbose(env, "math between %s pointer and %lld is not allowed\n",
5802 reg_type_str[type], val);
5806 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
5807 verbose(env, "%s pointer offset %d is not allowed\n",
5808 reg_type_str[type], reg->off);
5812 if (smin == S64_MIN) {
5813 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
5814 reg_type_str[type]);
5818 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
5819 verbose(env, "value %lld makes %s pointer be out of bounds\n",
5820 smin, reg_type_str[type]);
5827 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
5829 return &env->insn_aux_data[env->insn_idx];
5832 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
5833 u32 *ptr_limit, u8 opcode, bool off_is_neg)
5835 bool mask_to_left = (opcode == BPF_ADD && off_is_neg) ||
5836 (opcode == BPF_SUB && !off_is_neg);
5839 switch (ptr_reg->type) {
5841 /* Indirect variable offset stack access is prohibited in
5842 * unprivileged mode so it's not handled here.
5844 off = ptr_reg->off + ptr_reg->var_off.value;
5846 *ptr_limit = MAX_BPF_STACK + off;
5850 case PTR_TO_MAP_VALUE:
5852 *ptr_limit = ptr_reg->umax_value + ptr_reg->off;
5854 off = ptr_reg->smin_value + ptr_reg->off;
5855 *ptr_limit = ptr_reg->map_ptr->value_size - off;
5863 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
5864 const struct bpf_insn *insn)
5866 return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
5869 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
5870 u32 alu_state, u32 alu_limit)
5872 /* If we arrived here from different branches with different
5873 * state or limits to sanitize, then this won't work.
5875 if (aux->alu_state &&
5876 (aux->alu_state != alu_state ||
5877 aux->alu_limit != alu_limit))
5880 /* Corresponding fixup done in fixup_bpf_calls(). */
5881 aux->alu_state = alu_state;
5882 aux->alu_limit = alu_limit;
5886 static int sanitize_val_alu(struct bpf_verifier_env *env,
5887 struct bpf_insn *insn)
5889 struct bpf_insn_aux_data *aux = cur_aux(env);
5891 if (can_skip_alu_sanitation(env, insn))
5894 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
5897 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
5898 struct bpf_insn *insn,
5899 const struct bpf_reg_state *ptr_reg,
5900 struct bpf_reg_state *dst_reg,
5903 struct bpf_verifier_state *vstate = env->cur_state;
5904 struct bpf_insn_aux_data *aux = cur_aux(env);
5905 bool ptr_is_dst_reg = ptr_reg == dst_reg;
5906 u8 opcode = BPF_OP(insn->code);
5907 u32 alu_state, alu_limit;
5908 struct bpf_reg_state tmp;
5911 if (can_skip_alu_sanitation(env, insn))
5914 /* We already marked aux for masking from non-speculative
5915 * paths, thus we got here in the first place. We only care
5916 * to explore bad access from here.
5918 if (vstate->speculative)
5921 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
5922 alu_state |= ptr_is_dst_reg ?
5923 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
5925 if (retrieve_ptr_limit(ptr_reg, &alu_limit, opcode, off_is_neg))
5927 if (update_alu_sanitation_state(aux, alu_state, alu_limit))
5930 /* Simulate and find potential out-of-bounds access under
5931 * speculative execution from truncation as a result of
5932 * masking when off was not within expected range. If off
5933 * sits in dst, then we temporarily need to move ptr there
5934 * to simulate dst (== 0) +/-= ptr. Needed, for example,
5935 * for cases where we use K-based arithmetic in one direction
5936 * and truncated reg-based in the other in order to explore
5939 if (!ptr_is_dst_reg) {
5941 *dst_reg = *ptr_reg;
5943 ret = push_stack(env, env->insn_idx + 1, env->insn_idx, true);
5944 if (!ptr_is_dst_reg && ret)
5946 return !ret ? -EFAULT : 0;
5949 /* check that stack access falls within stack limits and that 'reg' doesn't
5950 * have a variable offset.
5952 * Variable offset is prohibited for unprivileged mode for simplicity since it
5953 * requires corresponding support in Spectre masking for stack ALU. See also
5954 * retrieve_ptr_limit().
5957 * 'off' includes 'reg->off'.
5959 static int check_stack_access_for_ptr_arithmetic(
5960 struct bpf_verifier_env *env,
5962 const struct bpf_reg_state *reg,
5965 if (!tnum_is_const(reg->var_off)) {
5968 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5969 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
5970 regno, tn_buf, off);
5974 if (off >= 0 || off < -MAX_BPF_STACK) {
5975 verbose(env, "R%d stack pointer arithmetic goes out of range, "
5976 "prohibited for !root; off=%d\n", regno, off);
5984 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
5985 * Caller should also handle BPF_MOV case separately.
5986 * If we return -EACCES, caller may want to try again treating pointer as a
5987 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks.
5989 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
5990 struct bpf_insn *insn,
5991 const struct bpf_reg_state *ptr_reg,
5992 const struct bpf_reg_state *off_reg)
5994 struct bpf_verifier_state *vstate = env->cur_state;
5995 struct bpf_func_state *state = vstate->frame[vstate->curframe];
5996 struct bpf_reg_state *regs = state->regs, *dst_reg;
5997 bool known = tnum_is_const(off_reg->var_off);
5998 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
5999 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
6000 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
6001 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
6002 u32 dst = insn->dst_reg, src = insn->src_reg;
6003 u8 opcode = BPF_OP(insn->code);
6006 dst_reg = ®s[dst];
6008 if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
6009 smin_val > smax_val || umin_val > umax_val) {
6010 /* Taint dst register if offset had invalid bounds derived from
6011 * e.g. dead branches.
6013 __mark_reg_unknown(env, dst_reg);
6017 if (BPF_CLASS(insn->code) != BPF_ALU64) {
6018 /* 32-bit ALU ops on pointers produce (meaningless) scalars */
6019 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
6020 __mark_reg_unknown(env, dst_reg);
6025 "R%d 32-bit pointer arithmetic prohibited\n",
6030 switch (ptr_reg->type) {
6031 case PTR_TO_MAP_VALUE_OR_NULL:
6032 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
6033 dst, reg_type_str[ptr_reg->type]);
6035 case CONST_PTR_TO_MAP:
6036 /* smin_val represents the known value */
6037 if (known && smin_val == 0 && opcode == BPF_ADD)
6040 case PTR_TO_PACKET_END:
6042 case PTR_TO_SOCKET_OR_NULL:
6043 case PTR_TO_SOCK_COMMON:
6044 case PTR_TO_SOCK_COMMON_OR_NULL:
6045 case PTR_TO_TCP_SOCK:
6046 case PTR_TO_TCP_SOCK_OR_NULL:
6047 case PTR_TO_XDP_SOCK:
6048 verbose(env, "R%d pointer arithmetic on %s prohibited\n",
6049 dst, reg_type_str[ptr_reg->type]);
6051 case PTR_TO_MAP_VALUE:
6052 if (!env->allow_ptr_leaks && !known && (smin_val < 0) != (smax_val < 0)) {
6053 verbose(env, "R%d has unknown scalar with mixed signed bounds, pointer arithmetic with it prohibited for !root\n",
6054 off_reg == dst_reg ? dst : src);
6062 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
6063 * The id may be overwritten later if we create a new variable offset.
6065 dst_reg->type = ptr_reg->type;
6066 dst_reg->id = ptr_reg->id;
6068 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
6069 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
6072 /* pointer types do not carry 32-bit bounds at the moment. */
6073 __mark_reg32_unbounded(dst_reg);
6077 ret = sanitize_ptr_alu(env, insn, ptr_reg, dst_reg, smin_val < 0);
6079 verbose(env, "R%d tried to add from different maps or paths\n", dst);
6082 /* We can take a fixed offset as long as it doesn't overflow
6083 * the s32 'off' field
6085 if (known && (ptr_reg->off + smin_val ==
6086 (s64)(s32)(ptr_reg->off + smin_val))) {
6087 /* pointer += K. Accumulate it into fixed offset */
6088 dst_reg->smin_value = smin_ptr;
6089 dst_reg->smax_value = smax_ptr;
6090 dst_reg->umin_value = umin_ptr;
6091 dst_reg->umax_value = umax_ptr;
6092 dst_reg->var_off = ptr_reg->var_off;
6093 dst_reg->off = ptr_reg->off + smin_val;
6094 dst_reg->raw = ptr_reg->raw;
6097 /* A new variable offset is created. Note that off_reg->off
6098 * == 0, since it's a scalar.
6099 * dst_reg gets the pointer type and since some positive
6100 * integer value was added to the pointer, give it a new 'id'
6101 * if it's a PTR_TO_PACKET.
6102 * this creates a new 'base' pointer, off_reg (variable) gets
6103 * added into the variable offset, and we copy the fixed offset
6106 if (signed_add_overflows(smin_ptr, smin_val) ||
6107 signed_add_overflows(smax_ptr, smax_val)) {
6108 dst_reg->smin_value = S64_MIN;
6109 dst_reg->smax_value = S64_MAX;
6111 dst_reg->smin_value = smin_ptr + smin_val;
6112 dst_reg->smax_value = smax_ptr + smax_val;
6114 if (umin_ptr + umin_val < umin_ptr ||
6115 umax_ptr + umax_val < umax_ptr) {
6116 dst_reg->umin_value = 0;
6117 dst_reg->umax_value = U64_MAX;
6119 dst_reg->umin_value = umin_ptr + umin_val;
6120 dst_reg->umax_value = umax_ptr + umax_val;
6122 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
6123 dst_reg->off = ptr_reg->off;
6124 dst_reg->raw = ptr_reg->raw;
6125 if (reg_is_pkt_pointer(ptr_reg)) {
6126 dst_reg->id = ++env->id_gen;
6127 /* something was added to pkt_ptr, set range to zero */
6128 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
6132 ret = sanitize_ptr_alu(env, insn, ptr_reg, dst_reg, smin_val < 0);
6134 verbose(env, "R%d tried to sub from different maps or paths\n", dst);
6137 if (dst_reg == off_reg) {
6138 /* scalar -= pointer. Creates an unknown scalar */
6139 verbose(env, "R%d tried to subtract pointer from scalar\n",
6143 /* We don't allow subtraction from FP, because (according to
6144 * test_verifier.c test "invalid fp arithmetic", JITs might not
6145 * be able to deal with it.
6147 if (ptr_reg->type == PTR_TO_STACK) {
6148 verbose(env, "R%d subtraction from stack pointer prohibited\n",
6152 if (known && (ptr_reg->off - smin_val ==
6153 (s64)(s32)(ptr_reg->off - smin_val))) {
6154 /* pointer -= K. Subtract it from fixed offset */
6155 dst_reg->smin_value = smin_ptr;
6156 dst_reg->smax_value = smax_ptr;
6157 dst_reg->umin_value = umin_ptr;
6158 dst_reg->umax_value = umax_ptr;
6159 dst_reg->var_off = ptr_reg->var_off;
6160 dst_reg->id = ptr_reg->id;
6161 dst_reg->off = ptr_reg->off - smin_val;
6162 dst_reg->raw = ptr_reg->raw;
6165 /* A new variable offset is created. If the subtrahend is known
6166 * nonnegative, then any reg->range we had before is still good.
6168 if (signed_sub_overflows(smin_ptr, smax_val) ||
6169 signed_sub_overflows(smax_ptr, smin_val)) {
6170 /* Overflow possible, we know nothing */
6171 dst_reg->smin_value = S64_MIN;
6172 dst_reg->smax_value = S64_MAX;
6174 dst_reg->smin_value = smin_ptr - smax_val;
6175 dst_reg->smax_value = smax_ptr - smin_val;
6177 if (umin_ptr < umax_val) {
6178 /* Overflow possible, we know nothing */
6179 dst_reg->umin_value = 0;
6180 dst_reg->umax_value = U64_MAX;
6182 /* Cannot overflow (as long as bounds are consistent) */
6183 dst_reg->umin_value = umin_ptr - umax_val;
6184 dst_reg->umax_value = umax_ptr - umin_val;
6186 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
6187 dst_reg->off = ptr_reg->off;
6188 dst_reg->raw = ptr_reg->raw;
6189 if (reg_is_pkt_pointer(ptr_reg)) {
6190 dst_reg->id = ++env->id_gen;
6191 /* something was added to pkt_ptr, set range to zero */
6193 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
6199 /* bitwise ops on pointers are troublesome, prohibit. */
6200 verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
6201 dst, bpf_alu_string[opcode >> 4]);
6204 /* other operators (e.g. MUL,LSH) produce non-pointer results */
6205 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
6206 dst, bpf_alu_string[opcode >> 4]);
6210 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
6213 __update_reg_bounds(dst_reg);
6214 __reg_deduce_bounds(dst_reg);
6215 __reg_bound_offset(dst_reg);
6217 /* For unprivileged we require that resulting offset must be in bounds
6218 * in order to be able to sanitize access later on.
6220 if (!env->bypass_spec_v1) {
6221 if (dst_reg->type == PTR_TO_MAP_VALUE &&
6222 check_map_access(env, dst, dst_reg->off, 1, false)) {
6223 verbose(env, "R%d pointer arithmetic of map value goes out of range, "
6224 "prohibited for !root\n", dst);
6226 } else if (dst_reg->type == PTR_TO_STACK &&
6227 check_stack_access_for_ptr_arithmetic(
6228 env, dst, dst_reg, dst_reg->off +
6229 dst_reg->var_off.value)) {
6237 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
6238 struct bpf_reg_state *src_reg)
6240 s32 smin_val = src_reg->s32_min_value;
6241 s32 smax_val = src_reg->s32_max_value;
6242 u32 umin_val = src_reg->u32_min_value;
6243 u32 umax_val = src_reg->u32_max_value;
6245 if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
6246 signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
6247 dst_reg->s32_min_value = S32_MIN;
6248 dst_reg->s32_max_value = S32_MAX;
6250 dst_reg->s32_min_value += smin_val;
6251 dst_reg->s32_max_value += smax_val;
6253 if (dst_reg->u32_min_value + umin_val < umin_val ||
6254 dst_reg->u32_max_value + umax_val < umax_val) {
6255 dst_reg->u32_min_value = 0;
6256 dst_reg->u32_max_value = U32_MAX;
6258 dst_reg->u32_min_value += umin_val;
6259 dst_reg->u32_max_value += umax_val;
6263 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
6264 struct bpf_reg_state *src_reg)
6266 s64 smin_val = src_reg->smin_value;
6267 s64 smax_val = src_reg->smax_value;
6268 u64 umin_val = src_reg->umin_value;
6269 u64 umax_val = src_reg->umax_value;
6271 if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
6272 signed_add_overflows(dst_reg->smax_value, smax_val)) {
6273 dst_reg->smin_value = S64_MIN;
6274 dst_reg->smax_value = S64_MAX;
6276 dst_reg->smin_value += smin_val;
6277 dst_reg->smax_value += smax_val;
6279 if (dst_reg->umin_value + umin_val < umin_val ||
6280 dst_reg->umax_value + umax_val < umax_val) {
6281 dst_reg->umin_value = 0;
6282 dst_reg->umax_value = U64_MAX;
6284 dst_reg->umin_value += umin_val;
6285 dst_reg->umax_value += umax_val;
6289 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
6290 struct bpf_reg_state *src_reg)
6292 s32 smin_val = src_reg->s32_min_value;
6293 s32 smax_val = src_reg->s32_max_value;
6294 u32 umin_val = src_reg->u32_min_value;
6295 u32 umax_val = src_reg->u32_max_value;
6297 if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
6298 signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
6299 /* Overflow possible, we know nothing */
6300 dst_reg->s32_min_value = S32_MIN;
6301 dst_reg->s32_max_value = S32_MAX;
6303 dst_reg->s32_min_value -= smax_val;
6304 dst_reg->s32_max_value -= smin_val;
6306 if (dst_reg->u32_min_value < umax_val) {
6307 /* Overflow possible, we know nothing */
6308 dst_reg->u32_min_value = 0;
6309 dst_reg->u32_max_value = U32_MAX;
6311 /* Cannot overflow (as long as bounds are consistent) */
6312 dst_reg->u32_min_value -= umax_val;
6313 dst_reg->u32_max_value -= umin_val;
6317 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
6318 struct bpf_reg_state *src_reg)
6320 s64 smin_val = src_reg->smin_value;
6321 s64 smax_val = src_reg->smax_value;
6322 u64 umin_val = src_reg->umin_value;
6323 u64 umax_val = src_reg->umax_value;
6325 if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
6326 signed_sub_overflows(dst_reg->smax_value, smin_val)) {
6327 /* Overflow possible, we know nothing */
6328 dst_reg->smin_value = S64_MIN;
6329 dst_reg->smax_value = S64_MAX;
6331 dst_reg->smin_value -= smax_val;
6332 dst_reg->smax_value -= smin_val;
6334 if (dst_reg->umin_value < umax_val) {
6335 /* Overflow possible, we know nothing */
6336 dst_reg->umin_value = 0;
6337 dst_reg->umax_value = U64_MAX;
6339 /* Cannot overflow (as long as bounds are consistent) */
6340 dst_reg->umin_value -= umax_val;
6341 dst_reg->umax_value -= umin_val;
6345 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
6346 struct bpf_reg_state *src_reg)
6348 s32 smin_val = src_reg->s32_min_value;
6349 u32 umin_val = src_reg->u32_min_value;
6350 u32 umax_val = src_reg->u32_max_value;
6352 if (smin_val < 0 || dst_reg->s32_min_value < 0) {
6353 /* Ain't nobody got time to multiply that sign */
6354 __mark_reg32_unbounded(dst_reg);
6357 /* Both values are positive, so we can work with unsigned and
6358 * copy the result to signed (unless it exceeds S32_MAX).
6360 if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
6361 /* Potential overflow, we know nothing */
6362 __mark_reg32_unbounded(dst_reg);
6365 dst_reg->u32_min_value *= umin_val;
6366 dst_reg->u32_max_value *= umax_val;
6367 if (dst_reg->u32_max_value > S32_MAX) {
6368 /* Overflow possible, we know nothing */
6369 dst_reg->s32_min_value = S32_MIN;
6370 dst_reg->s32_max_value = S32_MAX;
6372 dst_reg->s32_min_value = dst_reg->u32_min_value;
6373 dst_reg->s32_max_value = dst_reg->u32_max_value;
6377 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
6378 struct bpf_reg_state *src_reg)
6380 s64 smin_val = src_reg->smin_value;
6381 u64 umin_val = src_reg->umin_value;
6382 u64 umax_val = src_reg->umax_value;
6384 if (smin_val < 0 || dst_reg->smin_value < 0) {
6385 /* Ain't nobody got time to multiply that sign */
6386 __mark_reg64_unbounded(dst_reg);
6389 /* Both values are positive, so we can work with unsigned and
6390 * copy the result to signed (unless it exceeds S64_MAX).
6392 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
6393 /* Potential overflow, we know nothing */
6394 __mark_reg64_unbounded(dst_reg);
6397 dst_reg->umin_value *= umin_val;
6398 dst_reg->umax_value *= umax_val;
6399 if (dst_reg->umax_value > S64_MAX) {
6400 /* Overflow possible, we know nothing */
6401 dst_reg->smin_value = S64_MIN;
6402 dst_reg->smax_value = S64_MAX;
6404 dst_reg->smin_value = dst_reg->umin_value;
6405 dst_reg->smax_value = dst_reg->umax_value;
6409 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
6410 struct bpf_reg_state *src_reg)
6412 bool src_known = tnum_subreg_is_const(src_reg->var_off);
6413 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
6414 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
6415 s32 smin_val = src_reg->s32_min_value;
6416 u32 umax_val = src_reg->u32_max_value;
6418 /* Assuming scalar64_min_max_and will be called so its safe
6419 * to skip updating register for known 32-bit case.
6421 if (src_known && dst_known)
6424 /* We get our minimum from the var_off, since that's inherently
6425 * bitwise. Our maximum is the minimum of the operands' maxima.
6427 dst_reg->u32_min_value = var32_off.value;
6428 dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
6429 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
6430 /* Lose signed bounds when ANDing negative numbers,
6431 * ain't nobody got time for that.
6433 dst_reg->s32_min_value = S32_MIN;
6434 dst_reg->s32_max_value = S32_MAX;
6436 /* ANDing two positives gives a positive, so safe to
6437 * cast result into s64.
6439 dst_reg->s32_min_value = dst_reg->u32_min_value;
6440 dst_reg->s32_max_value = dst_reg->u32_max_value;
6445 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
6446 struct bpf_reg_state *src_reg)
6448 bool src_known = tnum_is_const(src_reg->var_off);
6449 bool dst_known = tnum_is_const(dst_reg->var_off);
6450 s64 smin_val = src_reg->smin_value;
6451 u64 umax_val = src_reg->umax_value;
6453 if (src_known && dst_known) {
6454 __mark_reg_known(dst_reg, dst_reg->var_off.value);
6458 /* We get our minimum from the var_off, since that's inherently
6459 * bitwise. Our maximum is the minimum of the operands' maxima.
6461 dst_reg->umin_value = dst_reg->var_off.value;
6462 dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
6463 if (dst_reg->smin_value < 0 || smin_val < 0) {
6464 /* Lose signed bounds when ANDing negative numbers,
6465 * ain't nobody got time for that.
6467 dst_reg->smin_value = S64_MIN;
6468 dst_reg->smax_value = S64_MAX;
6470 /* ANDing two positives gives a positive, so safe to
6471 * cast result into s64.
6473 dst_reg->smin_value = dst_reg->umin_value;
6474 dst_reg->smax_value = dst_reg->umax_value;
6476 /* We may learn something more from the var_off */
6477 __update_reg_bounds(dst_reg);
6480 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
6481 struct bpf_reg_state *src_reg)
6483 bool src_known = tnum_subreg_is_const(src_reg->var_off);
6484 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
6485 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
6486 s32 smin_val = src_reg->s32_min_value;
6487 u32 umin_val = src_reg->u32_min_value;
6489 /* Assuming scalar64_min_max_or will be called so it is safe
6490 * to skip updating register for known case.
6492 if (src_known && dst_known)
6495 /* We get our maximum from the var_off, and our minimum is the
6496 * maximum of the operands' minima
6498 dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
6499 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
6500 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
6501 /* Lose signed bounds when ORing negative numbers,
6502 * ain't nobody got time for that.
6504 dst_reg->s32_min_value = S32_MIN;
6505 dst_reg->s32_max_value = S32_MAX;
6507 /* ORing two positives gives a positive, so safe to
6508 * cast result into s64.
6510 dst_reg->s32_min_value = dst_reg->u32_min_value;
6511 dst_reg->s32_max_value = dst_reg->u32_max_value;
6515 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
6516 struct bpf_reg_state *src_reg)
6518 bool src_known = tnum_is_const(src_reg->var_off);
6519 bool dst_known = tnum_is_const(dst_reg->var_off);
6520 s64 smin_val = src_reg->smin_value;
6521 u64 umin_val = src_reg->umin_value;
6523 if (src_known && dst_known) {
6524 __mark_reg_known(dst_reg, dst_reg->var_off.value);
6528 /* We get our maximum from the var_off, and our minimum is the
6529 * maximum of the operands' minima
6531 dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
6532 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
6533 if (dst_reg->smin_value < 0 || smin_val < 0) {
6534 /* Lose signed bounds when ORing negative numbers,
6535 * ain't nobody got time for that.
6537 dst_reg->smin_value = S64_MIN;
6538 dst_reg->smax_value = S64_MAX;
6540 /* ORing two positives gives a positive, so safe to
6541 * cast result into s64.
6543 dst_reg->smin_value = dst_reg->umin_value;
6544 dst_reg->smax_value = dst_reg->umax_value;
6546 /* We may learn something more from the var_off */
6547 __update_reg_bounds(dst_reg);
6550 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
6551 struct bpf_reg_state *src_reg)
6553 bool src_known = tnum_subreg_is_const(src_reg->var_off);
6554 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
6555 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
6556 s32 smin_val = src_reg->s32_min_value;
6558 /* Assuming scalar64_min_max_xor will be called so it is safe
6559 * to skip updating register for known case.
6561 if (src_known && dst_known)
6564 /* We get both minimum and maximum from the var32_off. */
6565 dst_reg->u32_min_value = var32_off.value;
6566 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
6568 if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
6569 /* XORing two positive sign numbers gives a positive,
6570 * so safe to cast u32 result into s32.
6572 dst_reg->s32_min_value = dst_reg->u32_min_value;
6573 dst_reg->s32_max_value = dst_reg->u32_max_value;
6575 dst_reg->s32_min_value = S32_MIN;
6576 dst_reg->s32_max_value = S32_MAX;
6580 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
6581 struct bpf_reg_state *src_reg)
6583 bool src_known = tnum_is_const(src_reg->var_off);
6584 bool dst_known = tnum_is_const(dst_reg->var_off);
6585 s64 smin_val = src_reg->smin_value;
6587 if (src_known && dst_known) {
6588 /* dst_reg->var_off.value has been updated earlier */
6589 __mark_reg_known(dst_reg, dst_reg->var_off.value);
6593 /* We get both minimum and maximum from the var_off. */
6594 dst_reg->umin_value = dst_reg->var_off.value;
6595 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
6597 if (dst_reg->smin_value >= 0 && smin_val >= 0) {
6598 /* XORing two positive sign numbers gives a positive,
6599 * so safe to cast u64 result into s64.
6601 dst_reg->smin_value = dst_reg->umin_value;
6602 dst_reg->smax_value = dst_reg->umax_value;
6604 dst_reg->smin_value = S64_MIN;
6605 dst_reg->smax_value = S64_MAX;
6608 __update_reg_bounds(dst_reg);
6611 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
6612 u64 umin_val, u64 umax_val)
6614 /* We lose all sign bit information (except what we can pick
6617 dst_reg->s32_min_value = S32_MIN;
6618 dst_reg->s32_max_value = S32_MAX;
6619 /* If we might shift our top bit out, then we know nothing */
6620 if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
6621 dst_reg->u32_min_value = 0;
6622 dst_reg->u32_max_value = U32_MAX;
6624 dst_reg->u32_min_value <<= umin_val;
6625 dst_reg->u32_max_value <<= umax_val;
6629 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
6630 struct bpf_reg_state *src_reg)
6632 u32 umax_val = src_reg->u32_max_value;
6633 u32 umin_val = src_reg->u32_min_value;
6634 /* u32 alu operation will zext upper bits */
6635 struct tnum subreg = tnum_subreg(dst_reg->var_off);
6637 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
6638 dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
6639 /* Not required but being careful mark reg64 bounds as unknown so
6640 * that we are forced to pick them up from tnum and zext later and
6641 * if some path skips this step we are still safe.
6643 __mark_reg64_unbounded(dst_reg);
6644 __update_reg32_bounds(dst_reg);
6647 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
6648 u64 umin_val, u64 umax_val)
6650 /* Special case <<32 because it is a common compiler pattern to sign
6651 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
6652 * positive we know this shift will also be positive so we can track
6653 * bounds correctly. Otherwise we lose all sign bit information except
6654 * what we can pick up from var_off. Perhaps we can generalize this
6655 * later to shifts of any length.
6657 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
6658 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
6660 dst_reg->smax_value = S64_MAX;
6662 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
6663 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
6665 dst_reg->smin_value = S64_MIN;
6667 /* If we might shift our top bit out, then we know nothing */
6668 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
6669 dst_reg->umin_value = 0;
6670 dst_reg->umax_value = U64_MAX;
6672 dst_reg->umin_value <<= umin_val;
6673 dst_reg->umax_value <<= umax_val;
6677 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
6678 struct bpf_reg_state *src_reg)
6680 u64 umax_val = src_reg->umax_value;
6681 u64 umin_val = src_reg->umin_value;
6683 /* scalar64 calc uses 32bit unshifted bounds so must be called first */
6684 __scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
6685 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
6687 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
6688 /* We may learn something more from the var_off */
6689 __update_reg_bounds(dst_reg);
6692 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
6693 struct bpf_reg_state *src_reg)
6695 struct tnum subreg = tnum_subreg(dst_reg->var_off);
6696 u32 umax_val = src_reg->u32_max_value;
6697 u32 umin_val = src_reg->u32_min_value;
6699 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
6700 * be negative, then either:
6701 * 1) src_reg might be zero, so the sign bit of the result is
6702 * unknown, so we lose our signed bounds
6703 * 2) it's known negative, thus the unsigned bounds capture the
6705 * 3) the signed bounds cross zero, so they tell us nothing
6707 * If the value in dst_reg is known nonnegative, then again the
6708 * unsigned bounds capture the signed bounds.
6709 * Thus, in all cases it suffices to blow away our signed bounds
6710 * and rely on inferring new ones from the unsigned bounds and
6711 * var_off of the result.
6713 dst_reg->s32_min_value = S32_MIN;
6714 dst_reg->s32_max_value = S32_MAX;
6716 dst_reg->var_off = tnum_rshift(subreg, umin_val);
6717 dst_reg->u32_min_value >>= umax_val;
6718 dst_reg->u32_max_value >>= umin_val;
6720 __mark_reg64_unbounded(dst_reg);
6721 __update_reg32_bounds(dst_reg);
6724 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
6725 struct bpf_reg_state *src_reg)
6727 u64 umax_val = src_reg->umax_value;
6728 u64 umin_val = src_reg->umin_value;
6730 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
6731 * be negative, then either:
6732 * 1) src_reg might be zero, so the sign bit of the result is
6733 * unknown, so we lose our signed bounds
6734 * 2) it's known negative, thus the unsigned bounds capture the
6736 * 3) the signed bounds cross zero, so they tell us nothing
6738 * If the value in dst_reg is known nonnegative, then again the
6739 * unsigned bounds capture the signed bounds.
6740 * Thus, in all cases it suffices to blow away our signed bounds
6741 * and rely on inferring new ones from the unsigned bounds and
6742 * var_off of the result.
6744 dst_reg->smin_value = S64_MIN;
6745 dst_reg->smax_value = S64_MAX;
6746 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
6747 dst_reg->umin_value >>= umax_val;
6748 dst_reg->umax_value >>= umin_val;
6750 /* Its not easy to operate on alu32 bounds here because it depends
6751 * on bits being shifted in. Take easy way out and mark unbounded
6752 * so we can recalculate later from tnum.
6754 __mark_reg32_unbounded(dst_reg);
6755 __update_reg_bounds(dst_reg);
6758 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
6759 struct bpf_reg_state *src_reg)
6761 u64 umin_val = src_reg->u32_min_value;
6763 /* Upon reaching here, src_known is true and
6764 * umax_val is equal to umin_val.
6766 dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
6767 dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
6769 dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
6771 /* blow away the dst_reg umin_value/umax_value and rely on
6772 * dst_reg var_off to refine the result.
6774 dst_reg->u32_min_value = 0;
6775 dst_reg->u32_max_value = U32_MAX;
6777 __mark_reg64_unbounded(dst_reg);
6778 __update_reg32_bounds(dst_reg);
6781 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
6782 struct bpf_reg_state *src_reg)
6784 u64 umin_val = src_reg->umin_value;
6786 /* Upon reaching here, src_known is true and umax_val is equal
6789 dst_reg->smin_value >>= umin_val;
6790 dst_reg->smax_value >>= umin_val;
6792 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
6794 /* blow away the dst_reg umin_value/umax_value and rely on
6795 * dst_reg var_off to refine the result.
6797 dst_reg->umin_value = 0;
6798 dst_reg->umax_value = U64_MAX;
6800 /* Its not easy to operate on alu32 bounds here because it depends
6801 * on bits being shifted in from upper 32-bits. Take easy way out
6802 * and mark unbounded so we can recalculate later from tnum.
6804 __mark_reg32_unbounded(dst_reg);
6805 __update_reg_bounds(dst_reg);
6808 /* WARNING: This function does calculations on 64-bit values, but the actual
6809 * execution may occur on 32-bit values. Therefore, things like bitshifts
6810 * need extra checks in the 32-bit case.
6812 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
6813 struct bpf_insn *insn,
6814 struct bpf_reg_state *dst_reg,
6815 struct bpf_reg_state src_reg)
6817 struct bpf_reg_state *regs = cur_regs(env);
6818 u8 opcode = BPF_OP(insn->code);
6820 s64 smin_val, smax_val;
6821 u64 umin_val, umax_val;
6822 s32 s32_min_val, s32_max_val;
6823 u32 u32_min_val, u32_max_val;
6824 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
6825 u32 dst = insn->dst_reg;
6827 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
6829 smin_val = src_reg.smin_value;
6830 smax_val = src_reg.smax_value;
6831 umin_val = src_reg.umin_value;
6832 umax_val = src_reg.umax_value;
6834 s32_min_val = src_reg.s32_min_value;
6835 s32_max_val = src_reg.s32_max_value;
6836 u32_min_val = src_reg.u32_min_value;
6837 u32_max_val = src_reg.u32_max_value;
6840 src_known = tnum_subreg_is_const(src_reg.var_off);
6842 (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
6843 s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
6844 /* Taint dst register if offset had invalid bounds
6845 * derived from e.g. dead branches.
6847 __mark_reg_unknown(env, dst_reg);
6851 src_known = tnum_is_const(src_reg.var_off);
6853 (smin_val != smax_val || umin_val != umax_val)) ||
6854 smin_val > smax_val || umin_val > umax_val) {
6855 /* Taint dst register if offset had invalid bounds
6856 * derived from e.g. dead branches.
6858 __mark_reg_unknown(env, dst_reg);
6864 opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
6865 __mark_reg_unknown(env, dst_reg);
6869 /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
6870 * There are two classes of instructions: The first class we track both
6871 * alu32 and alu64 sign/unsigned bounds independently this provides the
6872 * greatest amount of precision when alu operations are mixed with jmp32
6873 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
6874 * and BPF_OR. This is possible because these ops have fairly easy to
6875 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
6876 * See alu32 verifier tests for examples. The second class of
6877 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
6878 * with regards to tracking sign/unsigned bounds because the bits may
6879 * cross subreg boundaries in the alu64 case. When this happens we mark
6880 * the reg unbounded in the subreg bound space and use the resulting
6881 * tnum to calculate an approximation of the sign/unsigned bounds.
6885 ret = sanitize_val_alu(env, insn);
6887 verbose(env, "R%d tried to add from different pointers or scalars\n", dst);
6890 scalar32_min_max_add(dst_reg, &src_reg);
6891 scalar_min_max_add(dst_reg, &src_reg);
6892 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
6895 ret = sanitize_val_alu(env, insn);
6897 verbose(env, "R%d tried to sub from different pointers or scalars\n", dst);
6900 scalar32_min_max_sub(dst_reg, &src_reg);
6901 scalar_min_max_sub(dst_reg, &src_reg);
6902 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
6905 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
6906 scalar32_min_max_mul(dst_reg, &src_reg);
6907 scalar_min_max_mul(dst_reg, &src_reg);
6910 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
6911 scalar32_min_max_and(dst_reg, &src_reg);
6912 scalar_min_max_and(dst_reg, &src_reg);
6915 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
6916 scalar32_min_max_or(dst_reg, &src_reg);
6917 scalar_min_max_or(dst_reg, &src_reg);
6920 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
6921 scalar32_min_max_xor(dst_reg, &src_reg);
6922 scalar_min_max_xor(dst_reg, &src_reg);
6925 if (umax_val >= insn_bitness) {
6926 /* Shifts greater than 31 or 63 are undefined.
6927 * This includes shifts by a negative number.
6929 mark_reg_unknown(env, regs, insn->dst_reg);
6933 scalar32_min_max_lsh(dst_reg, &src_reg);
6935 scalar_min_max_lsh(dst_reg, &src_reg);
6938 if (umax_val >= insn_bitness) {
6939 /* Shifts greater than 31 or 63 are undefined.
6940 * This includes shifts by a negative number.
6942 mark_reg_unknown(env, regs, insn->dst_reg);
6946 scalar32_min_max_rsh(dst_reg, &src_reg);
6948 scalar_min_max_rsh(dst_reg, &src_reg);
6951 if (umax_val >= insn_bitness) {
6952 /* Shifts greater than 31 or 63 are undefined.
6953 * This includes shifts by a negative number.
6955 mark_reg_unknown(env, regs, insn->dst_reg);
6959 scalar32_min_max_arsh(dst_reg, &src_reg);
6961 scalar_min_max_arsh(dst_reg, &src_reg);
6964 mark_reg_unknown(env, regs, insn->dst_reg);
6968 /* ALU32 ops are zero extended into 64bit register */
6970 zext_32_to_64(dst_reg);
6972 __update_reg_bounds(dst_reg);
6973 __reg_deduce_bounds(dst_reg);
6974 __reg_bound_offset(dst_reg);
6978 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
6981 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
6982 struct bpf_insn *insn)
6984 struct bpf_verifier_state *vstate = env->cur_state;
6985 struct bpf_func_state *state = vstate->frame[vstate->curframe];
6986 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
6987 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
6988 u8 opcode = BPF_OP(insn->code);
6991 dst_reg = ®s[insn->dst_reg];
6993 if (dst_reg->type != SCALAR_VALUE)
6996 /* Make sure ID is cleared otherwise dst_reg min/max could be
6997 * incorrectly propagated into other registers by find_equal_scalars()
7000 if (BPF_SRC(insn->code) == BPF_X) {
7001 src_reg = ®s[insn->src_reg];
7002 if (src_reg->type != SCALAR_VALUE) {
7003 if (dst_reg->type != SCALAR_VALUE) {
7004 /* Combining two pointers by any ALU op yields
7005 * an arbitrary scalar. Disallow all math except
7006 * pointer subtraction
7008 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
7009 mark_reg_unknown(env, regs, insn->dst_reg);
7012 verbose(env, "R%d pointer %s pointer prohibited\n",
7014 bpf_alu_string[opcode >> 4]);
7017 /* scalar += pointer
7018 * This is legal, but we have to reverse our
7019 * src/dest handling in computing the range
7021 err = mark_chain_precision(env, insn->dst_reg);
7024 return adjust_ptr_min_max_vals(env, insn,
7027 } else if (ptr_reg) {
7028 /* pointer += scalar */
7029 err = mark_chain_precision(env, insn->src_reg);
7032 return adjust_ptr_min_max_vals(env, insn,
7036 /* Pretend the src is a reg with a known value, since we only
7037 * need to be able to read from this state.
7039 off_reg.type = SCALAR_VALUE;
7040 __mark_reg_known(&off_reg, insn->imm);
7042 if (ptr_reg) /* pointer += K */
7043 return adjust_ptr_min_max_vals(env, insn,
7047 /* Got here implies adding two SCALAR_VALUEs */
7048 if (WARN_ON_ONCE(ptr_reg)) {
7049 print_verifier_state(env, state);
7050 verbose(env, "verifier internal error: unexpected ptr_reg\n");
7053 if (WARN_ON(!src_reg)) {
7054 print_verifier_state(env, state);
7055 verbose(env, "verifier internal error: no src_reg\n");
7058 return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
7061 /* check validity of 32-bit and 64-bit arithmetic operations */
7062 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
7064 struct bpf_reg_state *regs = cur_regs(env);
7065 u8 opcode = BPF_OP(insn->code);
7068 if (opcode == BPF_END || opcode == BPF_NEG) {
7069 if (opcode == BPF_NEG) {
7070 if (BPF_SRC(insn->code) != 0 ||
7071 insn->src_reg != BPF_REG_0 ||
7072 insn->off != 0 || insn->imm != 0) {
7073 verbose(env, "BPF_NEG uses reserved fields\n");
7077 if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
7078 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
7079 BPF_CLASS(insn->code) == BPF_ALU64) {
7080 verbose(env, "BPF_END uses reserved fields\n");
7085 /* check src operand */
7086 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
7090 if (is_pointer_value(env, insn->dst_reg)) {
7091 verbose(env, "R%d pointer arithmetic prohibited\n",
7096 /* check dest operand */
7097 err = check_reg_arg(env, insn->dst_reg, DST_OP);
7101 } else if (opcode == BPF_MOV) {
7103 if (BPF_SRC(insn->code) == BPF_X) {
7104 if (insn->imm != 0 || insn->off != 0) {
7105 verbose(env, "BPF_MOV uses reserved fields\n");
7109 /* check src operand */
7110 err = check_reg_arg(env, insn->src_reg, SRC_OP);
7114 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
7115 verbose(env, "BPF_MOV uses reserved fields\n");
7120 /* check dest operand, mark as required later */
7121 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
7125 if (BPF_SRC(insn->code) == BPF_X) {
7126 struct bpf_reg_state *src_reg = regs + insn->src_reg;
7127 struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
7129 if (BPF_CLASS(insn->code) == BPF_ALU64) {
7131 * copy register state to dest reg
7133 if (src_reg->type == SCALAR_VALUE && !src_reg->id)
7134 /* Assign src and dst registers the same ID
7135 * that will be used by find_equal_scalars()
7136 * to propagate min/max range.
7138 src_reg->id = ++env->id_gen;
7139 *dst_reg = *src_reg;
7140 dst_reg->live |= REG_LIVE_WRITTEN;
7141 dst_reg->subreg_def = DEF_NOT_SUBREG;
7144 if (is_pointer_value(env, insn->src_reg)) {
7146 "R%d partial copy of pointer\n",
7149 } else if (src_reg->type == SCALAR_VALUE) {
7150 *dst_reg = *src_reg;
7151 /* Make sure ID is cleared otherwise
7152 * dst_reg min/max could be incorrectly
7153 * propagated into src_reg by find_equal_scalars()
7156 dst_reg->live |= REG_LIVE_WRITTEN;
7157 dst_reg->subreg_def = env->insn_idx + 1;
7159 mark_reg_unknown(env, regs,
7162 zext_32_to_64(dst_reg);
7166 * remember the value we stored into this reg
7168 /* clear any state __mark_reg_known doesn't set */
7169 mark_reg_unknown(env, regs, insn->dst_reg);
7170 regs[insn->dst_reg].type = SCALAR_VALUE;
7171 if (BPF_CLASS(insn->code) == BPF_ALU64) {
7172 __mark_reg_known(regs + insn->dst_reg,
7175 __mark_reg_known(regs + insn->dst_reg,
7180 } else if (opcode > BPF_END) {
7181 verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
7184 } else { /* all other ALU ops: and, sub, xor, add, ... */
7186 if (BPF_SRC(insn->code) == BPF_X) {
7187 if (insn->imm != 0 || insn->off != 0) {
7188 verbose(env, "BPF_ALU uses reserved fields\n");
7191 /* check src1 operand */
7192 err = check_reg_arg(env, insn->src_reg, SRC_OP);
7196 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
7197 verbose(env, "BPF_ALU uses reserved fields\n");
7202 /* check src2 operand */
7203 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
7207 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
7208 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
7209 verbose(env, "div by zero\n");
7213 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
7214 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
7215 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
7217 if (insn->imm < 0 || insn->imm >= size) {
7218 verbose(env, "invalid shift %d\n", insn->imm);
7223 /* check dest operand */
7224 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
7228 return adjust_reg_min_max_vals(env, insn);
7234 static void __find_good_pkt_pointers(struct bpf_func_state *state,
7235 struct bpf_reg_state *dst_reg,
7236 enum bpf_reg_type type, int new_range)
7238 struct bpf_reg_state *reg;
7241 for (i = 0; i < MAX_BPF_REG; i++) {
7242 reg = &state->regs[i];
7243 if (reg->type == type && reg->id == dst_reg->id)
7244 /* keep the maximum range already checked */
7245 reg->range = max(reg->range, new_range);
7248 bpf_for_each_spilled_reg(i, state, reg) {
7251 if (reg->type == type && reg->id == dst_reg->id)
7252 reg->range = max(reg->range, new_range);
7256 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
7257 struct bpf_reg_state *dst_reg,
7258 enum bpf_reg_type type,
7259 bool range_right_open)
7263 if (dst_reg->off < 0 ||
7264 (dst_reg->off == 0 && range_right_open))
7265 /* This doesn't give us any range */
7268 if (dst_reg->umax_value > MAX_PACKET_OFF ||
7269 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
7270 /* Risk of overflow. For instance, ptr + (1<<63) may be less
7271 * than pkt_end, but that's because it's also less than pkt.
7275 new_range = dst_reg->off;
7276 if (range_right_open)
7279 /* Examples for register markings:
7281 * pkt_data in dst register:
7285 * if (r2 > pkt_end) goto <handle exception>
7290 * if (r2 < pkt_end) goto <access okay>
7291 * <handle exception>
7294 * r2 == dst_reg, pkt_end == src_reg
7295 * r2=pkt(id=n,off=8,r=0)
7296 * r3=pkt(id=n,off=0,r=0)
7298 * pkt_data in src register:
7302 * if (pkt_end >= r2) goto <access okay>
7303 * <handle exception>
7307 * if (pkt_end <= r2) goto <handle exception>
7311 * pkt_end == dst_reg, r2 == src_reg
7312 * r2=pkt(id=n,off=8,r=0)
7313 * r3=pkt(id=n,off=0,r=0)
7315 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
7316 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
7317 * and [r3, r3 + 8-1) respectively is safe to access depending on
7321 /* If our ids match, then we must have the same max_value. And we
7322 * don't care about the other reg's fixed offset, since if it's too big
7323 * the range won't allow anything.
7324 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
7326 for (i = 0; i <= vstate->curframe; i++)
7327 __find_good_pkt_pointers(vstate->frame[i], dst_reg, type,
7331 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
7333 struct tnum subreg = tnum_subreg(reg->var_off);
7334 s32 sval = (s32)val;
7338 if (tnum_is_const(subreg))
7339 return !!tnum_equals_const(subreg, val);
7342 if (tnum_is_const(subreg))
7343 return !tnum_equals_const(subreg, val);
7346 if ((~subreg.mask & subreg.value) & val)
7348 if (!((subreg.mask | subreg.value) & val))
7352 if (reg->u32_min_value > val)
7354 else if (reg->u32_max_value <= val)
7358 if (reg->s32_min_value > sval)
7360 else if (reg->s32_max_value <= sval)
7364 if (reg->u32_max_value < val)
7366 else if (reg->u32_min_value >= val)
7370 if (reg->s32_max_value < sval)
7372 else if (reg->s32_min_value >= sval)
7376 if (reg->u32_min_value >= val)
7378 else if (reg->u32_max_value < val)
7382 if (reg->s32_min_value >= sval)
7384 else if (reg->s32_max_value < sval)
7388 if (reg->u32_max_value <= val)
7390 else if (reg->u32_min_value > val)
7394 if (reg->s32_max_value <= sval)
7396 else if (reg->s32_min_value > sval)
7405 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
7407 s64 sval = (s64)val;
7411 if (tnum_is_const(reg->var_off))
7412 return !!tnum_equals_const(reg->var_off, val);
7415 if (tnum_is_const(reg->var_off))
7416 return !tnum_equals_const(reg->var_off, val);
7419 if ((~reg->var_off.mask & reg->var_off.value) & val)
7421 if (!((reg->var_off.mask | reg->var_off.value) & val))
7425 if (reg->umin_value > val)
7427 else if (reg->umax_value <= val)
7431 if (reg->smin_value > sval)
7433 else if (reg->smax_value <= sval)
7437 if (reg->umax_value < val)
7439 else if (reg->umin_value >= val)
7443 if (reg->smax_value < sval)
7445 else if (reg->smin_value >= sval)
7449 if (reg->umin_value >= val)
7451 else if (reg->umax_value < val)
7455 if (reg->smin_value >= sval)
7457 else if (reg->smax_value < sval)
7461 if (reg->umax_value <= val)
7463 else if (reg->umin_value > val)
7467 if (reg->smax_value <= sval)
7469 else if (reg->smin_value > sval)
7477 /* compute branch direction of the expression "if (reg opcode val) goto target;"
7479 * 1 - branch will be taken and "goto target" will be executed
7480 * 0 - branch will not be taken and fall-through to next insn
7481 * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
7484 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
7487 if (__is_pointer_value(false, reg)) {
7488 if (!reg_type_not_null(reg->type))
7491 /* If pointer is valid tests against zero will fail so we can
7492 * use this to direct branch taken.
7508 return is_branch32_taken(reg, val, opcode);
7509 return is_branch64_taken(reg, val, opcode);
7512 static int flip_opcode(u32 opcode)
7514 /* How can we transform "a <op> b" into "b <op> a"? */
7515 static const u8 opcode_flip[16] = {
7516 /* these stay the same */
7517 [BPF_JEQ >> 4] = BPF_JEQ,
7518 [BPF_JNE >> 4] = BPF_JNE,
7519 [BPF_JSET >> 4] = BPF_JSET,
7520 /* these swap "lesser" and "greater" (L and G in the opcodes) */
7521 [BPF_JGE >> 4] = BPF_JLE,
7522 [BPF_JGT >> 4] = BPF_JLT,
7523 [BPF_JLE >> 4] = BPF_JGE,
7524 [BPF_JLT >> 4] = BPF_JGT,
7525 [BPF_JSGE >> 4] = BPF_JSLE,
7526 [BPF_JSGT >> 4] = BPF_JSLT,
7527 [BPF_JSLE >> 4] = BPF_JSGE,
7528 [BPF_JSLT >> 4] = BPF_JSGT
7530 return opcode_flip[opcode >> 4];
7533 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
7534 struct bpf_reg_state *src_reg,
7537 struct bpf_reg_state *pkt;
7539 if (src_reg->type == PTR_TO_PACKET_END) {
7541 } else if (dst_reg->type == PTR_TO_PACKET_END) {
7543 opcode = flip_opcode(opcode);
7548 if (pkt->range >= 0)
7553 /* pkt <= pkt_end */
7557 if (pkt->range == BEYOND_PKT_END)
7558 /* pkt has at last one extra byte beyond pkt_end */
7559 return opcode == BPF_JGT;
7565 /* pkt >= pkt_end */
7566 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
7567 return opcode == BPF_JGE;
7573 /* Adjusts the register min/max values in the case that the dst_reg is the
7574 * variable register that we are working on, and src_reg is a constant or we're
7575 * simply doing a BPF_K check.
7576 * In JEQ/JNE cases we also adjust the var_off values.
7578 static void reg_set_min_max(struct bpf_reg_state *true_reg,
7579 struct bpf_reg_state *false_reg,
7581 u8 opcode, bool is_jmp32)
7583 struct tnum false_32off = tnum_subreg(false_reg->var_off);
7584 struct tnum false_64off = false_reg->var_off;
7585 struct tnum true_32off = tnum_subreg(true_reg->var_off);
7586 struct tnum true_64off = true_reg->var_off;
7587 s64 sval = (s64)val;
7588 s32 sval32 = (s32)val32;
7590 /* If the dst_reg is a pointer, we can't learn anything about its
7591 * variable offset from the compare (unless src_reg were a pointer into
7592 * the same object, but we don't bother with that.
7593 * Since false_reg and true_reg have the same type by construction, we
7594 * only need to check one of them for pointerness.
7596 if (__is_pointer_value(false, false_reg))
7603 struct bpf_reg_state *reg =
7604 opcode == BPF_JEQ ? true_reg : false_reg;
7606 /* JEQ/JNE comparison doesn't change the register equivalence.
7608 * if (r1 == 42) goto label;
7610 * label: // here both r1 and r2 are known to be 42.
7612 * Hence when marking register as known preserve it's ID.
7615 __mark_reg32_known(reg, val32);
7617 ___mark_reg_known(reg, val);
7622 false_32off = tnum_and(false_32off, tnum_const(~val32));
7623 if (is_power_of_2(val32))
7624 true_32off = tnum_or(true_32off,
7627 false_64off = tnum_and(false_64off, tnum_const(~val));
7628 if (is_power_of_2(val))
7629 true_64off = tnum_or(true_64off,
7637 u32 false_umax = opcode == BPF_JGT ? val32 : val32 - 1;
7638 u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
7640 false_reg->u32_max_value = min(false_reg->u32_max_value,
7642 true_reg->u32_min_value = max(true_reg->u32_min_value,
7645 u64 false_umax = opcode == BPF_JGT ? val : val - 1;
7646 u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
7648 false_reg->umax_value = min(false_reg->umax_value, false_umax);
7649 true_reg->umin_value = max(true_reg->umin_value, true_umin);
7657 s32 false_smax = opcode == BPF_JSGT ? sval32 : sval32 - 1;
7658 s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
7660 false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
7661 true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
7663 s64 false_smax = opcode == BPF_JSGT ? sval : sval - 1;
7664 s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
7666 false_reg->smax_value = min(false_reg->smax_value, false_smax);
7667 true_reg->smin_value = max(true_reg->smin_value, true_smin);
7675 u32 false_umin = opcode == BPF_JLT ? val32 : val32 + 1;
7676 u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
7678 false_reg->u32_min_value = max(false_reg->u32_min_value,
7680 true_reg->u32_max_value = min(true_reg->u32_max_value,
7683 u64 false_umin = opcode == BPF_JLT ? val : val + 1;
7684 u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
7686 false_reg->umin_value = max(false_reg->umin_value, false_umin);
7687 true_reg->umax_value = min(true_reg->umax_value, true_umax);
7695 s32 false_smin = opcode == BPF_JSLT ? sval32 : sval32 + 1;
7696 s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
7698 false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
7699 true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
7701 s64 false_smin = opcode == BPF_JSLT ? sval : sval + 1;
7702 s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
7704 false_reg->smin_value = max(false_reg->smin_value, false_smin);
7705 true_reg->smax_value = min(true_reg->smax_value, true_smax);
7714 false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
7715 tnum_subreg(false_32off));
7716 true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
7717 tnum_subreg(true_32off));
7718 __reg_combine_32_into_64(false_reg);
7719 __reg_combine_32_into_64(true_reg);
7721 false_reg->var_off = false_64off;
7722 true_reg->var_off = true_64off;
7723 __reg_combine_64_into_32(false_reg);
7724 __reg_combine_64_into_32(true_reg);
7728 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
7731 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
7732 struct bpf_reg_state *false_reg,
7734 u8 opcode, bool is_jmp32)
7736 opcode = flip_opcode(opcode);
7737 /* This uses zero as "not present in table"; luckily the zero opcode,
7738 * BPF_JA, can't get here.
7741 reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
7744 /* Regs are known to be equal, so intersect their min/max/var_off */
7745 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
7746 struct bpf_reg_state *dst_reg)
7748 src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
7749 dst_reg->umin_value);
7750 src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
7751 dst_reg->umax_value);
7752 src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
7753 dst_reg->smin_value);
7754 src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
7755 dst_reg->smax_value);
7756 src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
7758 /* We might have learned new bounds from the var_off. */
7759 __update_reg_bounds(src_reg);
7760 __update_reg_bounds(dst_reg);
7761 /* We might have learned something about the sign bit. */
7762 __reg_deduce_bounds(src_reg);
7763 __reg_deduce_bounds(dst_reg);
7764 /* We might have learned some bits from the bounds. */
7765 __reg_bound_offset(src_reg);
7766 __reg_bound_offset(dst_reg);
7767 /* Intersecting with the old var_off might have improved our bounds
7768 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
7769 * then new var_off is (0; 0x7f...fc) which improves our umax.
7771 __update_reg_bounds(src_reg);
7772 __update_reg_bounds(dst_reg);
7775 static void reg_combine_min_max(struct bpf_reg_state *true_src,
7776 struct bpf_reg_state *true_dst,
7777 struct bpf_reg_state *false_src,
7778 struct bpf_reg_state *false_dst,
7783 __reg_combine_min_max(true_src, true_dst);
7786 __reg_combine_min_max(false_src, false_dst);
7791 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
7792 struct bpf_reg_state *reg, u32 id,
7795 if (reg_type_may_be_null(reg->type) && reg->id == id &&
7796 !WARN_ON_ONCE(!reg->id)) {
7797 /* Old offset (both fixed and variable parts) should
7798 * have been known-zero, because we don't allow pointer
7799 * arithmetic on pointers that might be NULL.
7801 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value ||
7802 !tnum_equals_const(reg->var_off, 0) ||
7804 __mark_reg_known_zero(reg);
7808 reg->type = SCALAR_VALUE;
7809 /* We don't need id and ref_obj_id from this point
7810 * onwards anymore, thus we should better reset it,
7811 * so that state pruning has chances to take effect.
7814 reg->ref_obj_id = 0;
7819 mark_ptr_not_null_reg(reg);
7821 if (!reg_may_point_to_spin_lock(reg)) {
7822 /* For not-NULL ptr, reg->ref_obj_id will be reset
7823 * in release_reg_references().
7825 * reg->id is still used by spin_lock ptr. Other
7826 * than spin_lock ptr type, reg->id can be reset.
7833 static void __mark_ptr_or_null_regs(struct bpf_func_state *state, u32 id,
7836 struct bpf_reg_state *reg;
7839 for (i = 0; i < MAX_BPF_REG; i++)
7840 mark_ptr_or_null_reg(state, &state->regs[i], id, is_null);
7842 bpf_for_each_spilled_reg(i, state, reg) {
7845 mark_ptr_or_null_reg(state, reg, id, is_null);
7849 /* The logic is similar to find_good_pkt_pointers(), both could eventually
7850 * be folded together at some point.
7852 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
7855 struct bpf_func_state *state = vstate->frame[vstate->curframe];
7856 struct bpf_reg_state *regs = state->regs;
7857 u32 ref_obj_id = regs[regno].ref_obj_id;
7858 u32 id = regs[regno].id;
7861 if (ref_obj_id && ref_obj_id == id && is_null)
7862 /* regs[regno] is in the " == NULL" branch.
7863 * No one could have freed the reference state before
7864 * doing the NULL check.
7866 WARN_ON_ONCE(release_reference_state(state, id));
7868 for (i = 0; i <= vstate->curframe; i++)
7869 __mark_ptr_or_null_regs(vstate->frame[i], id, is_null);
7872 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
7873 struct bpf_reg_state *dst_reg,
7874 struct bpf_reg_state *src_reg,
7875 struct bpf_verifier_state *this_branch,
7876 struct bpf_verifier_state *other_branch)
7878 if (BPF_SRC(insn->code) != BPF_X)
7881 /* Pointers are always 64-bit. */
7882 if (BPF_CLASS(insn->code) == BPF_JMP32)
7885 switch (BPF_OP(insn->code)) {
7887 if ((dst_reg->type == PTR_TO_PACKET &&
7888 src_reg->type == PTR_TO_PACKET_END) ||
7889 (dst_reg->type == PTR_TO_PACKET_META &&
7890 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
7891 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
7892 find_good_pkt_pointers(this_branch, dst_reg,
7893 dst_reg->type, false);
7894 mark_pkt_end(other_branch, insn->dst_reg, true);
7895 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
7896 src_reg->type == PTR_TO_PACKET) ||
7897 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
7898 src_reg->type == PTR_TO_PACKET_META)) {
7899 /* pkt_end > pkt_data', pkt_data > pkt_meta' */
7900 find_good_pkt_pointers(other_branch, src_reg,
7901 src_reg->type, true);
7902 mark_pkt_end(this_branch, insn->src_reg, false);
7908 if ((dst_reg->type == PTR_TO_PACKET &&
7909 src_reg->type == PTR_TO_PACKET_END) ||
7910 (dst_reg->type == PTR_TO_PACKET_META &&
7911 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
7912 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
7913 find_good_pkt_pointers(other_branch, dst_reg,
7914 dst_reg->type, true);
7915 mark_pkt_end(this_branch, insn->dst_reg, false);
7916 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
7917 src_reg->type == PTR_TO_PACKET) ||
7918 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
7919 src_reg->type == PTR_TO_PACKET_META)) {
7920 /* pkt_end < pkt_data', pkt_data > pkt_meta' */
7921 find_good_pkt_pointers(this_branch, src_reg,
7922 src_reg->type, false);
7923 mark_pkt_end(other_branch, insn->src_reg, true);
7929 if ((dst_reg->type == PTR_TO_PACKET &&
7930 src_reg->type == PTR_TO_PACKET_END) ||
7931 (dst_reg->type == PTR_TO_PACKET_META &&
7932 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
7933 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
7934 find_good_pkt_pointers(this_branch, dst_reg,
7935 dst_reg->type, true);
7936 mark_pkt_end(other_branch, insn->dst_reg, false);
7937 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
7938 src_reg->type == PTR_TO_PACKET) ||
7939 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
7940 src_reg->type == PTR_TO_PACKET_META)) {
7941 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
7942 find_good_pkt_pointers(other_branch, src_reg,
7943 src_reg->type, false);
7944 mark_pkt_end(this_branch, insn->src_reg, true);
7950 if ((dst_reg->type == PTR_TO_PACKET &&
7951 src_reg->type == PTR_TO_PACKET_END) ||
7952 (dst_reg->type == PTR_TO_PACKET_META &&
7953 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
7954 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
7955 find_good_pkt_pointers(other_branch, dst_reg,
7956 dst_reg->type, false);
7957 mark_pkt_end(this_branch, insn->dst_reg, true);
7958 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
7959 src_reg->type == PTR_TO_PACKET) ||
7960 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
7961 src_reg->type == PTR_TO_PACKET_META)) {
7962 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
7963 find_good_pkt_pointers(this_branch, src_reg,
7964 src_reg->type, true);
7965 mark_pkt_end(other_branch, insn->src_reg, false);
7977 static void find_equal_scalars(struct bpf_verifier_state *vstate,
7978 struct bpf_reg_state *known_reg)
7980 struct bpf_func_state *state;
7981 struct bpf_reg_state *reg;
7984 for (i = 0; i <= vstate->curframe; i++) {
7985 state = vstate->frame[i];
7986 for (j = 0; j < MAX_BPF_REG; j++) {
7987 reg = &state->regs[j];
7988 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
7992 bpf_for_each_spilled_reg(j, state, reg) {
7995 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
8001 static int check_cond_jmp_op(struct bpf_verifier_env *env,
8002 struct bpf_insn *insn, int *insn_idx)
8004 struct bpf_verifier_state *this_branch = env->cur_state;
8005 struct bpf_verifier_state *other_branch;
8006 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
8007 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
8008 u8 opcode = BPF_OP(insn->code);
8013 /* Only conditional jumps are expected to reach here. */
8014 if (opcode == BPF_JA || opcode > BPF_JSLE) {
8015 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
8019 if (BPF_SRC(insn->code) == BPF_X) {
8020 if (insn->imm != 0) {
8021 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
8025 /* check src1 operand */
8026 err = check_reg_arg(env, insn->src_reg, SRC_OP);
8030 if (is_pointer_value(env, insn->src_reg)) {
8031 verbose(env, "R%d pointer comparison prohibited\n",
8035 src_reg = ®s[insn->src_reg];
8037 if (insn->src_reg != BPF_REG_0) {
8038 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
8043 /* check src2 operand */
8044 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
8048 dst_reg = ®s[insn->dst_reg];
8049 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
8051 if (BPF_SRC(insn->code) == BPF_K) {
8052 pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
8053 } else if (src_reg->type == SCALAR_VALUE &&
8054 is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
8055 pred = is_branch_taken(dst_reg,
8056 tnum_subreg(src_reg->var_off).value,
8059 } else if (src_reg->type == SCALAR_VALUE &&
8060 !is_jmp32 && tnum_is_const(src_reg->var_off)) {
8061 pred = is_branch_taken(dst_reg,
8062 src_reg->var_off.value,
8065 } else if (reg_is_pkt_pointer_any(dst_reg) &&
8066 reg_is_pkt_pointer_any(src_reg) &&
8068 pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
8072 /* If we get here with a dst_reg pointer type it is because
8073 * above is_branch_taken() special cased the 0 comparison.
8075 if (!__is_pointer_value(false, dst_reg))
8076 err = mark_chain_precision(env, insn->dst_reg);
8077 if (BPF_SRC(insn->code) == BPF_X && !err &&
8078 !__is_pointer_value(false, src_reg))
8079 err = mark_chain_precision(env, insn->src_reg);
8084 /* only follow the goto, ignore fall-through */
8085 *insn_idx += insn->off;
8087 } else if (pred == 0) {
8088 /* only follow fall-through branch, since
8089 * that's where the program will go
8094 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
8098 other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
8100 /* detect if we are comparing against a constant value so we can adjust
8101 * our min/max values for our dst register.
8102 * this is only legit if both are scalars (or pointers to the same
8103 * object, I suppose, but we don't support that right now), because
8104 * otherwise the different base pointers mean the offsets aren't
8107 if (BPF_SRC(insn->code) == BPF_X) {
8108 struct bpf_reg_state *src_reg = ®s[insn->src_reg];
8110 if (dst_reg->type == SCALAR_VALUE &&
8111 src_reg->type == SCALAR_VALUE) {
8112 if (tnum_is_const(src_reg->var_off) ||
8114 tnum_is_const(tnum_subreg(src_reg->var_off))))
8115 reg_set_min_max(&other_branch_regs[insn->dst_reg],
8117 src_reg->var_off.value,
8118 tnum_subreg(src_reg->var_off).value,
8120 else if (tnum_is_const(dst_reg->var_off) ||
8122 tnum_is_const(tnum_subreg(dst_reg->var_off))))
8123 reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
8125 dst_reg->var_off.value,
8126 tnum_subreg(dst_reg->var_off).value,
8128 else if (!is_jmp32 &&
8129 (opcode == BPF_JEQ || opcode == BPF_JNE))
8130 /* Comparing for equality, we can combine knowledge */
8131 reg_combine_min_max(&other_branch_regs[insn->src_reg],
8132 &other_branch_regs[insn->dst_reg],
8133 src_reg, dst_reg, opcode);
8135 !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
8136 find_equal_scalars(this_branch, src_reg);
8137 find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
8141 } else if (dst_reg->type == SCALAR_VALUE) {
8142 reg_set_min_max(&other_branch_regs[insn->dst_reg],
8143 dst_reg, insn->imm, (u32)insn->imm,
8147 if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
8148 !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
8149 find_equal_scalars(this_branch, dst_reg);
8150 find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
8153 /* detect if R == 0 where R is returned from bpf_map_lookup_elem().
8154 * NOTE: these optimizations below are related with pointer comparison
8155 * which will never be JMP32.
8157 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
8158 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
8159 reg_type_may_be_null(dst_reg->type)) {
8160 /* Mark all identical registers in each branch as either
8161 * safe or unknown depending R == 0 or R != 0 conditional.
8163 mark_ptr_or_null_regs(this_branch, insn->dst_reg,
8165 mark_ptr_or_null_regs(other_branch, insn->dst_reg,
8167 } else if (!try_match_pkt_pointers(insn, dst_reg, ®s[insn->src_reg],
8168 this_branch, other_branch) &&
8169 is_pointer_value(env, insn->dst_reg)) {
8170 verbose(env, "R%d pointer comparison prohibited\n",
8174 if (env->log.level & BPF_LOG_LEVEL)
8175 print_verifier_state(env, this_branch->frame[this_branch->curframe]);
8179 /* verify BPF_LD_IMM64 instruction */
8180 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
8182 struct bpf_insn_aux_data *aux = cur_aux(env);
8183 struct bpf_reg_state *regs = cur_regs(env);
8184 struct bpf_reg_state *dst_reg;
8185 struct bpf_map *map;
8188 if (BPF_SIZE(insn->code) != BPF_DW) {
8189 verbose(env, "invalid BPF_LD_IMM insn\n");
8192 if (insn->off != 0) {
8193 verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
8197 err = check_reg_arg(env, insn->dst_reg, DST_OP);
8201 dst_reg = ®s[insn->dst_reg];
8202 if (insn->src_reg == 0) {
8203 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
8205 dst_reg->type = SCALAR_VALUE;
8206 __mark_reg_known(®s[insn->dst_reg], imm);
8210 if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
8211 mark_reg_known_zero(env, regs, insn->dst_reg);
8213 dst_reg->type = aux->btf_var.reg_type;
8214 switch (dst_reg->type) {
8216 dst_reg->mem_size = aux->btf_var.mem_size;
8219 case PTR_TO_PERCPU_BTF_ID:
8220 dst_reg->btf = aux->btf_var.btf;
8221 dst_reg->btf_id = aux->btf_var.btf_id;
8224 verbose(env, "bpf verifier is misconfigured\n");
8230 map = env->used_maps[aux->map_index];
8231 mark_reg_known_zero(env, regs, insn->dst_reg);
8232 dst_reg->map_ptr = map;
8234 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE) {
8235 dst_reg->type = PTR_TO_MAP_VALUE;
8236 dst_reg->off = aux->map_off;
8237 if (map_value_has_spin_lock(map))
8238 dst_reg->id = ++env->id_gen;
8239 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD) {
8240 dst_reg->type = CONST_PTR_TO_MAP;
8242 verbose(env, "bpf verifier is misconfigured\n");
8249 static bool may_access_skb(enum bpf_prog_type type)
8252 case BPF_PROG_TYPE_SOCKET_FILTER:
8253 case BPF_PROG_TYPE_SCHED_CLS:
8254 case BPF_PROG_TYPE_SCHED_ACT:
8261 /* verify safety of LD_ABS|LD_IND instructions:
8262 * - they can only appear in the programs where ctx == skb
8263 * - since they are wrappers of function calls, they scratch R1-R5 registers,
8264 * preserve R6-R9, and store return value into R0
8267 * ctx == skb == R6 == CTX
8270 * SRC == any register
8271 * IMM == 32-bit immediate
8274 * R0 - 8/16/32-bit skb data converted to cpu endianness
8276 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
8278 struct bpf_reg_state *regs = cur_regs(env);
8279 static const int ctx_reg = BPF_REG_6;
8280 u8 mode = BPF_MODE(insn->code);
8283 if (!may_access_skb(resolve_prog_type(env->prog))) {
8284 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
8288 if (!env->ops->gen_ld_abs) {
8289 verbose(env, "bpf verifier is misconfigured\n");
8293 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
8294 BPF_SIZE(insn->code) == BPF_DW ||
8295 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
8296 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
8300 /* check whether implicit source operand (register R6) is readable */
8301 err = check_reg_arg(env, ctx_reg, SRC_OP);
8305 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
8306 * gen_ld_abs() may terminate the program at runtime, leading to
8309 err = check_reference_leak(env);
8311 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
8315 if (env->cur_state->active_spin_lock) {
8316 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
8320 if (regs[ctx_reg].type != PTR_TO_CTX) {
8322 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
8326 if (mode == BPF_IND) {
8327 /* check explicit source operand */
8328 err = check_reg_arg(env, insn->src_reg, SRC_OP);
8333 err = check_ctx_reg(env, ®s[ctx_reg], ctx_reg);
8337 /* reset caller saved regs to unreadable */
8338 for (i = 0; i < CALLER_SAVED_REGS; i++) {
8339 mark_reg_not_init(env, regs, caller_saved[i]);
8340 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
8343 /* mark destination R0 register as readable, since it contains
8344 * the value fetched from the packet.
8345 * Already marked as written above.
8347 mark_reg_unknown(env, regs, BPF_REG_0);
8348 /* ld_abs load up to 32-bit skb data. */
8349 regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
8353 static int check_return_code(struct bpf_verifier_env *env)
8355 struct tnum enforce_attach_type_range = tnum_unknown;
8356 const struct bpf_prog *prog = env->prog;
8357 struct bpf_reg_state *reg;
8358 struct tnum range = tnum_range(0, 1);
8359 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
8361 const bool is_subprog = env->cur_state->frame[0]->subprogno;
8363 /* LSM and struct_ops func-ptr's return type could be "void" */
8365 (prog_type == BPF_PROG_TYPE_STRUCT_OPS ||
8366 prog_type == BPF_PROG_TYPE_LSM) &&
8367 !prog->aux->attach_func_proto->type)
8370 /* eBPF calling convetion is such that R0 is used
8371 * to return the value from eBPF program.
8372 * Make sure that it's readable at this time
8373 * of bpf_exit, which means that program wrote
8374 * something into it earlier
8376 err = check_reg_arg(env, BPF_REG_0, SRC_OP);
8380 if (is_pointer_value(env, BPF_REG_0)) {
8381 verbose(env, "R0 leaks addr as return value\n");
8385 reg = cur_regs(env) + BPF_REG_0;
8387 if (reg->type != SCALAR_VALUE) {
8388 verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
8389 reg_type_str[reg->type]);
8395 switch (prog_type) {
8396 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
8397 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
8398 env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
8399 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
8400 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
8401 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
8402 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
8403 range = tnum_range(1, 1);
8404 if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
8405 env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
8406 range = tnum_range(0, 3);
8408 case BPF_PROG_TYPE_CGROUP_SKB:
8409 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
8410 range = tnum_range(0, 3);
8411 enforce_attach_type_range = tnum_range(2, 3);
8414 case BPF_PROG_TYPE_CGROUP_SOCK:
8415 case BPF_PROG_TYPE_SOCK_OPS:
8416 case BPF_PROG_TYPE_CGROUP_DEVICE:
8417 case BPF_PROG_TYPE_CGROUP_SYSCTL:
8418 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
8420 case BPF_PROG_TYPE_RAW_TRACEPOINT:
8421 if (!env->prog->aux->attach_btf_id)
8423 range = tnum_const(0);
8425 case BPF_PROG_TYPE_TRACING:
8426 switch (env->prog->expected_attach_type) {
8427 case BPF_TRACE_FENTRY:
8428 case BPF_TRACE_FEXIT:
8429 range = tnum_const(0);
8431 case BPF_TRACE_RAW_TP:
8432 case BPF_MODIFY_RETURN:
8434 case BPF_TRACE_ITER:
8440 case BPF_PROG_TYPE_SK_LOOKUP:
8441 range = tnum_range(SK_DROP, SK_PASS);
8443 case BPF_PROG_TYPE_EXT:
8444 /* freplace program can return anything as its return value
8445 * depends on the to-be-replaced kernel func or bpf program.
8451 if (reg->type != SCALAR_VALUE) {
8452 verbose(env, "At program exit the register R0 is not a known value (%s)\n",
8453 reg_type_str[reg->type]);
8457 if (!tnum_in(range, reg->var_off)) {
8460 verbose(env, "At program exit the register R0 ");
8461 if (!tnum_is_unknown(reg->var_off)) {
8462 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
8463 verbose(env, "has value %s", tn_buf);
8465 verbose(env, "has unknown scalar value");
8467 tnum_strn(tn_buf, sizeof(tn_buf), range);
8468 verbose(env, " should have been in %s\n", tn_buf);
8472 if (!tnum_is_unknown(enforce_attach_type_range) &&
8473 tnum_in(enforce_attach_type_range, reg->var_off))
8474 env->prog->enforce_expected_attach_type = 1;
8478 /* non-recursive DFS pseudo code
8479 * 1 procedure DFS-iterative(G,v):
8480 * 2 label v as discovered
8481 * 3 let S be a stack
8483 * 5 while S is not empty
8485 * 7 if t is what we're looking for:
8487 * 9 for all edges e in G.adjacentEdges(t) do
8488 * 10 if edge e is already labelled
8489 * 11 continue with the next edge
8490 * 12 w <- G.adjacentVertex(t,e)
8491 * 13 if vertex w is not discovered and not explored
8492 * 14 label e as tree-edge
8493 * 15 label w as discovered
8496 * 18 else if vertex w is discovered
8497 * 19 label e as back-edge
8499 * 21 // vertex w is explored
8500 * 22 label e as forward- or cross-edge
8501 * 23 label t as explored
8506 * 0x11 - discovered and fall-through edge labelled
8507 * 0x12 - discovered and fall-through and branch edges labelled
8518 static u32 state_htab_size(struct bpf_verifier_env *env)
8520 return env->prog->len;
8523 static struct bpf_verifier_state_list **explored_state(
8524 struct bpf_verifier_env *env,
8527 struct bpf_verifier_state *cur = env->cur_state;
8528 struct bpf_func_state *state = cur->frame[cur->curframe];
8530 return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
8533 static void init_explored_state(struct bpf_verifier_env *env, int idx)
8535 env->insn_aux_data[idx].prune_point = true;
8543 /* t, w, e - match pseudo-code above:
8544 * t - index of current instruction
8545 * w - next instruction
8548 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
8551 int *insn_stack = env->cfg.insn_stack;
8552 int *insn_state = env->cfg.insn_state;
8554 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
8555 return DONE_EXPLORING;
8557 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
8558 return DONE_EXPLORING;
8560 if (w < 0 || w >= env->prog->len) {
8561 verbose_linfo(env, t, "%d: ", t);
8562 verbose(env, "jump out of range from insn %d to %d\n", t, w);
8567 /* mark branch target for state pruning */
8568 init_explored_state(env, w);
8570 if (insn_state[w] == 0) {
8572 insn_state[t] = DISCOVERED | e;
8573 insn_state[w] = DISCOVERED;
8574 if (env->cfg.cur_stack >= env->prog->len)
8576 insn_stack[env->cfg.cur_stack++] = w;
8577 return KEEP_EXPLORING;
8578 } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
8579 if (loop_ok && env->bpf_capable)
8580 return DONE_EXPLORING;
8581 verbose_linfo(env, t, "%d: ", t);
8582 verbose_linfo(env, w, "%d: ", w);
8583 verbose(env, "back-edge from insn %d to %d\n", t, w);
8585 } else if (insn_state[w] == EXPLORED) {
8586 /* forward- or cross-edge */
8587 insn_state[t] = DISCOVERED | e;
8589 verbose(env, "insn state internal bug\n");
8592 return DONE_EXPLORING;
8595 /* Visits the instruction at index t and returns one of the following:
8596 * < 0 - an error occurred
8597 * DONE_EXPLORING - the instruction was fully explored
8598 * KEEP_EXPLORING - there is still work to be done before it is fully explored
8600 static int visit_insn(int t, int insn_cnt, struct bpf_verifier_env *env)
8602 struct bpf_insn *insns = env->prog->insnsi;
8605 /* All non-branch instructions have a single fall-through edge. */
8606 if (BPF_CLASS(insns[t].code) != BPF_JMP &&
8607 BPF_CLASS(insns[t].code) != BPF_JMP32)
8608 return push_insn(t, t + 1, FALLTHROUGH, env, false);
8610 switch (BPF_OP(insns[t].code)) {
8612 return DONE_EXPLORING;
8615 ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
8619 if (t + 1 < insn_cnt)
8620 init_explored_state(env, t + 1);
8621 if (insns[t].src_reg == BPF_PSEUDO_CALL) {
8622 init_explored_state(env, t);
8623 ret = push_insn(t, t + insns[t].imm + 1, BRANCH,
8629 if (BPF_SRC(insns[t].code) != BPF_K)
8632 /* unconditional jump with single edge */
8633 ret = push_insn(t, t + insns[t].off + 1, FALLTHROUGH, env,
8638 /* unconditional jmp is not a good pruning point,
8639 * but it's marked, since backtracking needs
8640 * to record jmp history in is_state_visited().
8642 init_explored_state(env, t + insns[t].off + 1);
8643 /* tell verifier to check for equivalent states
8644 * after every call and jump
8646 if (t + 1 < insn_cnt)
8647 init_explored_state(env, t + 1);
8652 /* conditional jump with two edges */
8653 init_explored_state(env, t);
8654 ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
8658 return push_insn(t, t + insns[t].off + 1, BRANCH, env, true);
8662 /* non-recursive depth-first-search to detect loops in BPF program
8663 * loop == back-edge in directed graph
8665 static int check_cfg(struct bpf_verifier_env *env)
8667 int insn_cnt = env->prog->len;
8668 int *insn_stack, *insn_state;
8672 insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
8676 insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
8682 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
8683 insn_stack[0] = 0; /* 0 is the first instruction */
8684 env->cfg.cur_stack = 1;
8686 while (env->cfg.cur_stack > 0) {
8687 int t = insn_stack[env->cfg.cur_stack - 1];
8689 ret = visit_insn(t, insn_cnt, env);
8691 case DONE_EXPLORING:
8692 insn_state[t] = EXPLORED;
8693 env->cfg.cur_stack--;
8695 case KEEP_EXPLORING:
8699 verbose(env, "visit_insn internal bug\n");
8706 if (env->cfg.cur_stack < 0) {
8707 verbose(env, "pop stack internal bug\n");
8712 for (i = 0; i < insn_cnt; i++) {
8713 if (insn_state[i] != EXPLORED) {
8714 verbose(env, "unreachable insn %d\n", i);
8719 ret = 0; /* cfg looks good */
8724 env->cfg.insn_state = env->cfg.insn_stack = NULL;
8728 static int check_abnormal_return(struct bpf_verifier_env *env)
8732 for (i = 1; i < env->subprog_cnt; i++) {
8733 if (env->subprog_info[i].has_ld_abs) {
8734 verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
8737 if (env->subprog_info[i].has_tail_call) {
8738 verbose(env, "tail_call is not allowed in subprogs without BTF\n");
8745 /* The minimum supported BTF func info size */
8746 #define MIN_BPF_FUNCINFO_SIZE 8
8747 #define MAX_FUNCINFO_REC_SIZE 252
8749 static int check_btf_func(struct bpf_verifier_env *env,
8750 const union bpf_attr *attr,
8751 union bpf_attr __user *uattr)
8753 const struct btf_type *type, *func_proto, *ret_type;
8754 u32 i, nfuncs, urec_size, min_size;
8755 u32 krec_size = sizeof(struct bpf_func_info);
8756 struct bpf_func_info *krecord;
8757 struct bpf_func_info_aux *info_aux = NULL;
8758 struct bpf_prog *prog;
8759 const struct btf *btf;
8760 void __user *urecord;
8761 u32 prev_offset = 0;
8765 nfuncs = attr->func_info_cnt;
8767 if (check_abnormal_return(env))
8772 if (nfuncs != env->subprog_cnt) {
8773 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
8777 urec_size = attr->func_info_rec_size;
8778 if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
8779 urec_size > MAX_FUNCINFO_REC_SIZE ||
8780 urec_size % sizeof(u32)) {
8781 verbose(env, "invalid func info rec size %u\n", urec_size);
8786 btf = prog->aux->btf;
8788 urecord = u64_to_user_ptr(attr->func_info);
8789 min_size = min_t(u32, krec_size, urec_size);
8791 krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
8794 info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
8798 for (i = 0; i < nfuncs; i++) {
8799 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
8801 if (ret == -E2BIG) {
8802 verbose(env, "nonzero tailing record in func info");
8803 /* set the size kernel expects so loader can zero
8804 * out the rest of the record.
8806 if (put_user(min_size, &uattr->func_info_rec_size))
8812 if (copy_from_user(&krecord[i], urecord, min_size)) {
8817 /* check insn_off */
8820 if (krecord[i].insn_off) {
8822 "nonzero insn_off %u for the first func info record",
8823 krecord[i].insn_off);
8826 } else if (krecord[i].insn_off <= prev_offset) {
8828 "same or smaller insn offset (%u) than previous func info record (%u)",
8829 krecord[i].insn_off, prev_offset);
8833 if (env->subprog_info[i].start != krecord[i].insn_off) {
8834 verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
8839 type = btf_type_by_id(btf, krecord[i].type_id);
8840 if (!type || !btf_type_is_func(type)) {
8841 verbose(env, "invalid type id %d in func info",
8842 krecord[i].type_id);
8845 info_aux[i].linkage = BTF_INFO_VLEN(type->info);
8847 func_proto = btf_type_by_id(btf, type->type);
8848 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
8849 /* btf_func_check() already verified it during BTF load */
8851 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
8853 btf_type_is_small_int(ret_type) || btf_type_is_enum(ret_type);
8854 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
8855 verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
8858 if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
8859 verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
8863 prev_offset = krecord[i].insn_off;
8864 urecord += urec_size;
8867 prog->aux->func_info = krecord;
8868 prog->aux->func_info_cnt = nfuncs;
8869 prog->aux->func_info_aux = info_aux;
8878 static void adjust_btf_func(struct bpf_verifier_env *env)
8880 struct bpf_prog_aux *aux = env->prog->aux;
8883 if (!aux->func_info)
8886 for (i = 0; i < env->subprog_cnt; i++)
8887 aux->func_info[i].insn_off = env->subprog_info[i].start;
8890 #define MIN_BPF_LINEINFO_SIZE (offsetof(struct bpf_line_info, line_col) + \
8891 sizeof(((struct bpf_line_info *)(0))->line_col))
8892 #define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE
8894 static int check_btf_line(struct bpf_verifier_env *env,
8895 const union bpf_attr *attr,
8896 union bpf_attr __user *uattr)
8898 u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
8899 struct bpf_subprog_info *sub;
8900 struct bpf_line_info *linfo;
8901 struct bpf_prog *prog;
8902 const struct btf *btf;
8903 void __user *ulinfo;
8906 nr_linfo = attr->line_info_cnt;
8910 rec_size = attr->line_info_rec_size;
8911 if (rec_size < MIN_BPF_LINEINFO_SIZE ||
8912 rec_size > MAX_LINEINFO_REC_SIZE ||
8913 rec_size & (sizeof(u32) - 1))
8916 /* Need to zero it in case the userspace may
8917 * pass in a smaller bpf_line_info object.
8919 linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
8920 GFP_KERNEL | __GFP_NOWARN);
8925 btf = prog->aux->btf;
8928 sub = env->subprog_info;
8929 ulinfo = u64_to_user_ptr(attr->line_info);
8930 expected_size = sizeof(struct bpf_line_info);
8931 ncopy = min_t(u32, expected_size, rec_size);
8932 for (i = 0; i < nr_linfo; i++) {
8933 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
8935 if (err == -E2BIG) {
8936 verbose(env, "nonzero tailing record in line_info");
8937 if (put_user(expected_size,
8938 &uattr->line_info_rec_size))
8944 if (copy_from_user(&linfo[i], ulinfo, ncopy)) {
8950 * Check insn_off to ensure
8951 * 1) strictly increasing AND
8952 * 2) bounded by prog->len
8954 * The linfo[0].insn_off == 0 check logically falls into
8955 * the later "missing bpf_line_info for func..." case
8956 * because the first linfo[0].insn_off must be the
8957 * first sub also and the first sub must have
8958 * subprog_info[0].start == 0.
8960 if ((i && linfo[i].insn_off <= prev_offset) ||
8961 linfo[i].insn_off >= prog->len) {
8962 verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
8963 i, linfo[i].insn_off, prev_offset,
8969 if (!prog->insnsi[linfo[i].insn_off].code) {
8971 "Invalid insn code at line_info[%u].insn_off\n",
8977 if (!btf_name_by_offset(btf, linfo[i].line_off) ||
8978 !btf_name_by_offset(btf, linfo[i].file_name_off)) {
8979 verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
8984 if (s != env->subprog_cnt) {
8985 if (linfo[i].insn_off == sub[s].start) {
8986 sub[s].linfo_idx = i;
8988 } else if (sub[s].start < linfo[i].insn_off) {
8989 verbose(env, "missing bpf_line_info for func#%u\n", s);
8995 prev_offset = linfo[i].insn_off;
8999 if (s != env->subprog_cnt) {
9000 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
9001 env->subprog_cnt - s, s);
9006 prog->aux->linfo = linfo;
9007 prog->aux->nr_linfo = nr_linfo;
9016 static int check_btf_info(struct bpf_verifier_env *env,
9017 const union bpf_attr *attr,
9018 union bpf_attr __user *uattr)
9023 if (!attr->func_info_cnt && !attr->line_info_cnt) {
9024 if (check_abnormal_return(env))
9029 btf = btf_get_by_fd(attr->prog_btf_fd);
9031 return PTR_ERR(btf);
9032 env->prog->aux->btf = btf;
9034 err = check_btf_func(env, attr, uattr);
9038 err = check_btf_line(env, attr, uattr);
9045 /* check %cur's range satisfies %old's */
9046 static bool range_within(struct bpf_reg_state *old,
9047 struct bpf_reg_state *cur)
9049 return old->umin_value <= cur->umin_value &&
9050 old->umax_value >= cur->umax_value &&
9051 old->smin_value <= cur->smin_value &&
9052 old->smax_value >= cur->smax_value &&
9053 old->u32_min_value <= cur->u32_min_value &&
9054 old->u32_max_value >= cur->u32_max_value &&
9055 old->s32_min_value <= cur->s32_min_value &&
9056 old->s32_max_value >= cur->s32_max_value;
9059 /* Maximum number of register states that can exist at once */
9060 #define ID_MAP_SIZE (MAX_BPF_REG + MAX_BPF_STACK / BPF_REG_SIZE)
9066 /* If in the old state two registers had the same id, then they need to have
9067 * the same id in the new state as well. But that id could be different from
9068 * the old state, so we need to track the mapping from old to new ids.
9069 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
9070 * regs with old id 5 must also have new id 9 for the new state to be safe. But
9071 * regs with a different old id could still have new id 9, we don't care about
9073 * So we look through our idmap to see if this old id has been seen before. If
9074 * so, we require the new id to match; otherwise, we add the id pair to the map.
9076 static bool check_ids(u32 old_id, u32 cur_id, struct idpair *idmap)
9080 for (i = 0; i < ID_MAP_SIZE; i++) {
9081 if (!idmap[i].old) {
9082 /* Reached an empty slot; haven't seen this id before */
9083 idmap[i].old = old_id;
9084 idmap[i].cur = cur_id;
9087 if (idmap[i].old == old_id)
9088 return idmap[i].cur == cur_id;
9090 /* We ran out of idmap slots, which should be impossible */
9095 static void clean_func_state(struct bpf_verifier_env *env,
9096 struct bpf_func_state *st)
9098 enum bpf_reg_liveness live;
9101 for (i = 0; i < BPF_REG_FP; i++) {
9102 live = st->regs[i].live;
9103 /* liveness must not touch this register anymore */
9104 st->regs[i].live |= REG_LIVE_DONE;
9105 if (!(live & REG_LIVE_READ))
9106 /* since the register is unused, clear its state
9107 * to make further comparison simpler
9109 __mark_reg_not_init(env, &st->regs[i]);
9112 for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
9113 live = st->stack[i].spilled_ptr.live;
9114 /* liveness must not touch this stack slot anymore */
9115 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
9116 if (!(live & REG_LIVE_READ)) {
9117 __mark_reg_not_init(env, &st->stack[i].spilled_ptr);
9118 for (j = 0; j < BPF_REG_SIZE; j++)
9119 st->stack[i].slot_type[j] = STACK_INVALID;
9124 static void clean_verifier_state(struct bpf_verifier_env *env,
9125 struct bpf_verifier_state *st)
9129 if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
9130 /* all regs in this state in all frames were already marked */
9133 for (i = 0; i <= st->curframe; i++)
9134 clean_func_state(env, st->frame[i]);
9137 /* the parentage chains form a tree.
9138 * the verifier states are added to state lists at given insn and
9139 * pushed into state stack for future exploration.
9140 * when the verifier reaches bpf_exit insn some of the verifer states
9141 * stored in the state lists have their final liveness state already,
9142 * but a lot of states will get revised from liveness point of view when
9143 * the verifier explores other branches.
9146 * 2: if r1 == 100 goto pc+1
9149 * when the verifier reaches exit insn the register r0 in the state list of
9150 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
9151 * of insn 2 and goes exploring further. At the insn 4 it will walk the
9152 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
9154 * Since the verifier pushes the branch states as it sees them while exploring
9155 * the program the condition of walking the branch instruction for the second
9156 * time means that all states below this branch were already explored and
9157 * their final liveness markes are already propagated.
9158 * Hence when the verifier completes the search of state list in is_state_visited()
9159 * we can call this clean_live_states() function to mark all liveness states
9160 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
9162 * This function also clears the registers and stack for states that !READ
9163 * to simplify state merging.
9165 * Important note here that walking the same branch instruction in the callee
9166 * doesn't meant that the states are DONE. The verifier has to compare
9169 static void clean_live_states(struct bpf_verifier_env *env, int insn,
9170 struct bpf_verifier_state *cur)
9172 struct bpf_verifier_state_list *sl;
9175 sl = *explored_state(env, insn);
9177 if (sl->state.branches)
9179 if (sl->state.insn_idx != insn ||
9180 sl->state.curframe != cur->curframe)
9182 for (i = 0; i <= cur->curframe; i++)
9183 if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
9185 clean_verifier_state(env, &sl->state);
9191 /* Returns true if (rold safe implies rcur safe) */
9192 static bool regsafe(struct bpf_reg_state *rold, struct bpf_reg_state *rcur,
9193 struct idpair *idmap)
9197 if (!(rold->live & REG_LIVE_READ))
9198 /* explored state didn't use this */
9201 equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, parent)) == 0;
9203 if (rold->type == PTR_TO_STACK)
9204 /* two stack pointers are equal only if they're pointing to
9205 * the same stack frame, since fp-8 in foo != fp-8 in bar
9207 return equal && rold->frameno == rcur->frameno;
9212 if (rold->type == NOT_INIT)
9213 /* explored state can't have used this */
9215 if (rcur->type == NOT_INIT)
9217 switch (rold->type) {
9219 if (rcur->type == SCALAR_VALUE) {
9220 if (!rold->precise && !rcur->precise)
9222 /* new val must satisfy old val knowledge */
9223 return range_within(rold, rcur) &&
9224 tnum_in(rold->var_off, rcur->var_off);
9226 /* We're trying to use a pointer in place of a scalar.
9227 * Even if the scalar was unbounded, this could lead to
9228 * pointer leaks because scalars are allowed to leak
9229 * while pointers are not. We could make this safe in
9230 * special cases if root is calling us, but it's
9231 * probably not worth the hassle.
9235 case PTR_TO_MAP_VALUE:
9236 /* If the new min/max/var_off satisfy the old ones and
9237 * everything else matches, we are OK.
9238 * 'id' is not compared, since it's only used for maps with
9239 * bpf_spin_lock inside map element and in such cases if
9240 * the rest of the prog is valid for one map element then
9241 * it's valid for all map elements regardless of the key
9242 * used in bpf_map_lookup()
9244 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
9245 range_within(rold, rcur) &&
9246 tnum_in(rold->var_off, rcur->var_off);
9247 case PTR_TO_MAP_VALUE_OR_NULL:
9248 /* a PTR_TO_MAP_VALUE could be safe to use as a
9249 * PTR_TO_MAP_VALUE_OR_NULL into the same map.
9250 * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
9251 * checked, doing so could have affected others with the same
9252 * id, and we can't check for that because we lost the id when
9253 * we converted to a PTR_TO_MAP_VALUE.
9255 if (rcur->type != PTR_TO_MAP_VALUE_OR_NULL)
9257 if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
9259 /* Check our ids match any regs they're supposed to */
9260 return check_ids(rold->id, rcur->id, idmap);
9261 case PTR_TO_PACKET_META:
9263 if (rcur->type != rold->type)
9265 /* We must have at least as much range as the old ptr
9266 * did, so that any accesses which were safe before are
9267 * still safe. This is true even if old range < old off,
9268 * since someone could have accessed through (ptr - k), or
9269 * even done ptr -= k in a register, to get a safe access.
9271 if (rold->range > rcur->range)
9273 /* If the offsets don't match, we can't trust our alignment;
9274 * nor can we be sure that we won't fall out of range.
9276 if (rold->off != rcur->off)
9278 /* id relations must be preserved */
9279 if (rold->id && !check_ids(rold->id, rcur->id, idmap))
9281 /* new val must satisfy old val knowledge */
9282 return range_within(rold, rcur) &&
9283 tnum_in(rold->var_off, rcur->var_off);
9285 case CONST_PTR_TO_MAP:
9286 case PTR_TO_PACKET_END:
9287 case PTR_TO_FLOW_KEYS:
9289 case PTR_TO_SOCKET_OR_NULL:
9290 case PTR_TO_SOCK_COMMON:
9291 case PTR_TO_SOCK_COMMON_OR_NULL:
9292 case PTR_TO_TCP_SOCK:
9293 case PTR_TO_TCP_SOCK_OR_NULL:
9294 case PTR_TO_XDP_SOCK:
9295 /* Only valid matches are exact, which memcmp() above
9296 * would have accepted
9299 /* Don't know what's going on, just say it's not safe */
9303 /* Shouldn't get here; if we do, say it's not safe */
9308 static bool stacksafe(struct bpf_func_state *old,
9309 struct bpf_func_state *cur,
9310 struct idpair *idmap)
9314 /* walk slots of the explored stack and ignore any additional
9315 * slots in the current stack, since explored(safe) state
9318 for (i = 0; i < old->allocated_stack; i++) {
9319 spi = i / BPF_REG_SIZE;
9321 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
9322 i += BPF_REG_SIZE - 1;
9323 /* explored state didn't use this */
9327 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
9330 /* explored stack has more populated slots than current stack
9331 * and these slots were used
9333 if (i >= cur->allocated_stack)
9336 /* if old state was safe with misc data in the stack
9337 * it will be safe with zero-initialized stack.
9338 * The opposite is not true
9340 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
9341 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
9343 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
9344 cur->stack[spi].slot_type[i % BPF_REG_SIZE])
9345 /* Ex: old explored (safe) state has STACK_SPILL in
9346 * this stack slot, but current has STACK_MISC ->
9347 * this verifier states are not equivalent,
9348 * return false to continue verification of this path
9351 if (i % BPF_REG_SIZE)
9353 if (old->stack[spi].slot_type[0] != STACK_SPILL)
9355 if (!regsafe(&old->stack[spi].spilled_ptr,
9356 &cur->stack[spi].spilled_ptr,
9358 /* when explored and current stack slot are both storing
9359 * spilled registers, check that stored pointers types
9360 * are the same as well.
9361 * Ex: explored safe path could have stored
9362 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
9363 * but current path has stored:
9364 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
9365 * such verifier states are not equivalent.
9366 * return false to continue verification of this path
9373 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur)
9375 if (old->acquired_refs != cur->acquired_refs)
9377 return !memcmp(old->refs, cur->refs,
9378 sizeof(*old->refs) * old->acquired_refs);
9381 /* compare two verifier states
9383 * all states stored in state_list are known to be valid, since
9384 * verifier reached 'bpf_exit' instruction through them
9386 * this function is called when verifier exploring different branches of
9387 * execution popped from the state stack. If it sees an old state that has
9388 * more strict register state and more strict stack state then this execution
9389 * branch doesn't need to be explored further, since verifier already
9390 * concluded that more strict state leads to valid finish.
9392 * Therefore two states are equivalent if register state is more conservative
9393 * and explored stack state is more conservative than the current one.
9396 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
9397 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
9399 * In other words if current stack state (one being explored) has more
9400 * valid slots than old one that already passed validation, it means
9401 * the verifier can stop exploring and conclude that current state is valid too
9403 * Similarly with registers. If explored state has register type as invalid
9404 * whereas register type in current state is meaningful, it means that
9405 * the current state will reach 'bpf_exit' instruction safely
9407 static bool func_states_equal(struct bpf_func_state *old,
9408 struct bpf_func_state *cur)
9410 struct idpair *idmap;
9414 idmap = kcalloc(ID_MAP_SIZE, sizeof(struct idpair), GFP_KERNEL);
9415 /* If we failed to allocate the idmap, just say it's not safe */
9419 for (i = 0; i < MAX_BPF_REG; i++) {
9420 if (!regsafe(&old->regs[i], &cur->regs[i], idmap))
9424 if (!stacksafe(old, cur, idmap))
9427 if (!refsafe(old, cur))
9435 static bool states_equal(struct bpf_verifier_env *env,
9436 struct bpf_verifier_state *old,
9437 struct bpf_verifier_state *cur)
9441 if (old->curframe != cur->curframe)
9444 /* Verification state from speculative execution simulation
9445 * must never prune a non-speculative execution one.
9447 if (old->speculative && !cur->speculative)
9450 if (old->active_spin_lock != cur->active_spin_lock)
9453 /* for states to be equal callsites have to be the same
9454 * and all frame states need to be equivalent
9456 for (i = 0; i <= old->curframe; i++) {
9457 if (old->frame[i]->callsite != cur->frame[i]->callsite)
9459 if (!func_states_equal(old->frame[i], cur->frame[i]))
9465 /* Return 0 if no propagation happened. Return negative error code if error
9466 * happened. Otherwise, return the propagated bit.
9468 static int propagate_liveness_reg(struct bpf_verifier_env *env,
9469 struct bpf_reg_state *reg,
9470 struct bpf_reg_state *parent_reg)
9472 u8 parent_flag = parent_reg->live & REG_LIVE_READ;
9473 u8 flag = reg->live & REG_LIVE_READ;
9476 /* When comes here, read flags of PARENT_REG or REG could be any of
9477 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
9478 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
9480 if (parent_flag == REG_LIVE_READ64 ||
9481 /* Or if there is no read flag from REG. */
9483 /* Or if the read flag from REG is the same as PARENT_REG. */
9484 parent_flag == flag)
9487 err = mark_reg_read(env, reg, parent_reg, flag);
9494 /* A write screens off any subsequent reads; but write marks come from the
9495 * straight-line code between a state and its parent. When we arrive at an
9496 * equivalent state (jump target or such) we didn't arrive by the straight-line
9497 * code, so read marks in the state must propagate to the parent regardless
9498 * of the state's write marks. That's what 'parent == state->parent' comparison
9499 * in mark_reg_read() is for.
9501 static int propagate_liveness(struct bpf_verifier_env *env,
9502 const struct bpf_verifier_state *vstate,
9503 struct bpf_verifier_state *vparent)
9505 struct bpf_reg_state *state_reg, *parent_reg;
9506 struct bpf_func_state *state, *parent;
9507 int i, frame, err = 0;
9509 if (vparent->curframe != vstate->curframe) {
9510 WARN(1, "propagate_live: parent frame %d current frame %d\n",
9511 vparent->curframe, vstate->curframe);
9514 /* Propagate read liveness of registers... */
9515 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
9516 for (frame = 0; frame <= vstate->curframe; frame++) {
9517 parent = vparent->frame[frame];
9518 state = vstate->frame[frame];
9519 parent_reg = parent->regs;
9520 state_reg = state->regs;
9521 /* We don't need to worry about FP liveness, it's read-only */
9522 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
9523 err = propagate_liveness_reg(env, &state_reg[i],
9527 if (err == REG_LIVE_READ64)
9528 mark_insn_zext(env, &parent_reg[i]);
9531 /* Propagate stack slots. */
9532 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
9533 i < parent->allocated_stack / BPF_REG_SIZE; i++) {
9534 parent_reg = &parent->stack[i].spilled_ptr;
9535 state_reg = &state->stack[i].spilled_ptr;
9536 err = propagate_liveness_reg(env, state_reg,
9545 /* find precise scalars in the previous equivalent state and
9546 * propagate them into the current state
9548 static int propagate_precision(struct bpf_verifier_env *env,
9549 const struct bpf_verifier_state *old)
9551 struct bpf_reg_state *state_reg;
9552 struct bpf_func_state *state;
9555 state = old->frame[old->curframe];
9556 state_reg = state->regs;
9557 for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
9558 if (state_reg->type != SCALAR_VALUE ||
9559 !state_reg->precise)
9561 if (env->log.level & BPF_LOG_LEVEL2)
9562 verbose(env, "propagating r%d\n", i);
9563 err = mark_chain_precision(env, i);
9568 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
9569 if (state->stack[i].slot_type[0] != STACK_SPILL)
9571 state_reg = &state->stack[i].spilled_ptr;
9572 if (state_reg->type != SCALAR_VALUE ||
9573 !state_reg->precise)
9575 if (env->log.level & BPF_LOG_LEVEL2)
9576 verbose(env, "propagating fp%d\n",
9577 (-i - 1) * BPF_REG_SIZE);
9578 err = mark_chain_precision_stack(env, i);
9585 static bool states_maybe_looping(struct bpf_verifier_state *old,
9586 struct bpf_verifier_state *cur)
9588 struct bpf_func_state *fold, *fcur;
9589 int i, fr = cur->curframe;
9591 if (old->curframe != fr)
9594 fold = old->frame[fr];
9595 fcur = cur->frame[fr];
9596 for (i = 0; i < MAX_BPF_REG; i++)
9597 if (memcmp(&fold->regs[i], &fcur->regs[i],
9598 offsetof(struct bpf_reg_state, parent)))
9604 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
9606 struct bpf_verifier_state_list *new_sl;
9607 struct bpf_verifier_state_list *sl, **pprev;
9608 struct bpf_verifier_state *cur = env->cur_state, *new;
9609 int i, j, err, states_cnt = 0;
9610 bool add_new_state = env->test_state_freq ? true : false;
9612 cur->last_insn_idx = env->prev_insn_idx;
9613 if (!env->insn_aux_data[insn_idx].prune_point)
9614 /* this 'insn_idx' instruction wasn't marked, so we will not
9615 * be doing state search here
9619 /* bpf progs typically have pruning point every 4 instructions
9620 * http://vger.kernel.org/bpfconf2019.html#session-1
9621 * Do not add new state for future pruning if the verifier hasn't seen
9622 * at least 2 jumps and at least 8 instructions.
9623 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
9624 * In tests that amounts to up to 50% reduction into total verifier
9625 * memory consumption and 20% verifier time speedup.
9627 if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
9628 env->insn_processed - env->prev_insn_processed >= 8)
9629 add_new_state = true;
9631 pprev = explored_state(env, insn_idx);
9634 clean_live_states(env, insn_idx, cur);
9638 if (sl->state.insn_idx != insn_idx)
9640 if (sl->state.branches) {
9641 if (states_maybe_looping(&sl->state, cur) &&
9642 states_equal(env, &sl->state, cur)) {
9643 verbose_linfo(env, insn_idx, "; ");
9644 verbose(env, "infinite loop detected at insn %d\n", insn_idx);
9647 /* if the verifier is processing a loop, avoid adding new state
9648 * too often, since different loop iterations have distinct
9649 * states and may not help future pruning.
9650 * This threshold shouldn't be too low to make sure that
9651 * a loop with large bound will be rejected quickly.
9652 * The most abusive loop will be:
9654 * if r1 < 1000000 goto pc-2
9655 * 1M insn_procssed limit / 100 == 10k peak states.
9656 * This threshold shouldn't be too high either, since states
9657 * at the end of the loop are likely to be useful in pruning.
9659 if (env->jmps_processed - env->prev_jmps_processed < 20 &&
9660 env->insn_processed - env->prev_insn_processed < 100)
9661 add_new_state = false;
9664 if (states_equal(env, &sl->state, cur)) {
9666 /* reached equivalent register/stack state,
9668 * Registers read by the continuation are read by us.
9669 * If we have any write marks in env->cur_state, they
9670 * will prevent corresponding reads in the continuation
9671 * from reaching our parent (an explored_state). Our
9672 * own state will get the read marks recorded, but
9673 * they'll be immediately forgotten as we're pruning
9674 * this state and will pop a new one.
9676 err = propagate_liveness(env, &sl->state, cur);
9678 /* if previous state reached the exit with precision and
9679 * current state is equivalent to it (except precsion marks)
9680 * the precision needs to be propagated back in
9681 * the current state.
9683 err = err ? : push_jmp_history(env, cur);
9684 err = err ? : propagate_precision(env, &sl->state);
9690 /* when new state is not going to be added do not increase miss count.
9691 * Otherwise several loop iterations will remove the state
9692 * recorded earlier. The goal of these heuristics is to have
9693 * states from some iterations of the loop (some in the beginning
9694 * and some at the end) to help pruning.
9698 /* heuristic to determine whether this state is beneficial
9699 * to keep checking from state equivalence point of view.
9700 * Higher numbers increase max_states_per_insn and verification time,
9701 * but do not meaningfully decrease insn_processed.
9703 if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
9704 /* the state is unlikely to be useful. Remove it to
9705 * speed up verification
9708 if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
9709 u32 br = sl->state.branches;
9712 "BUG live_done but branches_to_explore %d\n",
9714 free_verifier_state(&sl->state, false);
9718 /* cannot free this state, since parentage chain may
9719 * walk it later. Add it for free_list instead to
9720 * be freed at the end of verification
9722 sl->next = env->free_list;
9723 env->free_list = sl;
9733 if (env->max_states_per_insn < states_cnt)
9734 env->max_states_per_insn = states_cnt;
9736 if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
9737 return push_jmp_history(env, cur);
9740 return push_jmp_history(env, cur);
9742 /* There were no equivalent states, remember the current one.
9743 * Technically the current state is not proven to be safe yet,
9744 * but it will either reach outer most bpf_exit (which means it's safe)
9745 * or it will be rejected. When there are no loops the verifier won't be
9746 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
9747 * again on the way to bpf_exit.
9748 * When looping the sl->state.branches will be > 0 and this state
9749 * will not be considered for equivalence until branches == 0.
9751 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
9754 env->total_states++;
9756 env->prev_jmps_processed = env->jmps_processed;
9757 env->prev_insn_processed = env->insn_processed;
9759 /* add new state to the head of linked list */
9760 new = &new_sl->state;
9761 err = copy_verifier_state(new, cur);
9763 free_verifier_state(new, false);
9767 new->insn_idx = insn_idx;
9768 WARN_ONCE(new->branches != 1,
9769 "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
9772 cur->first_insn_idx = insn_idx;
9773 clear_jmp_history(cur);
9774 new_sl->next = *explored_state(env, insn_idx);
9775 *explored_state(env, insn_idx) = new_sl;
9776 /* connect new state to parentage chain. Current frame needs all
9777 * registers connected. Only r6 - r9 of the callers are alive (pushed
9778 * to the stack implicitly by JITs) so in callers' frames connect just
9779 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
9780 * the state of the call instruction (with WRITTEN set), and r0 comes
9781 * from callee with its full parentage chain, anyway.
9783 /* clear write marks in current state: the writes we did are not writes
9784 * our child did, so they don't screen off its reads from us.
9785 * (There are no read marks in current state, because reads always mark
9786 * their parent and current state never has children yet. Only
9787 * explored_states can get read marks.)
9789 for (j = 0; j <= cur->curframe; j++) {
9790 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
9791 cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
9792 for (i = 0; i < BPF_REG_FP; i++)
9793 cur->frame[j]->regs[i].live = REG_LIVE_NONE;
9796 /* all stack frames are accessible from callee, clear them all */
9797 for (j = 0; j <= cur->curframe; j++) {
9798 struct bpf_func_state *frame = cur->frame[j];
9799 struct bpf_func_state *newframe = new->frame[j];
9801 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
9802 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
9803 frame->stack[i].spilled_ptr.parent =
9804 &newframe->stack[i].spilled_ptr;
9810 /* Return true if it's OK to have the same insn return a different type. */
9811 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
9816 case PTR_TO_SOCKET_OR_NULL:
9817 case PTR_TO_SOCK_COMMON:
9818 case PTR_TO_SOCK_COMMON_OR_NULL:
9819 case PTR_TO_TCP_SOCK:
9820 case PTR_TO_TCP_SOCK_OR_NULL:
9821 case PTR_TO_XDP_SOCK:
9823 case PTR_TO_BTF_ID_OR_NULL:
9830 /* If an instruction was previously used with particular pointer types, then we
9831 * need to be careful to avoid cases such as the below, where it may be ok
9832 * for one branch accessing the pointer, but not ok for the other branch:
9837 * R1 = some_other_valid_ptr;
9840 * R2 = *(u32 *)(R1 + 0);
9842 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
9844 return src != prev && (!reg_type_mismatch_ok(src) ||
9845 !reg_type_mismatch_ok(prev));
9848 static int do_check(struct bpf_verifier_env *env)
9850 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
9851 struct bpf_verifier_state *state = env->cur_state;
9852 struct bpf_insn *insns = env->prog->insnsi;
9853 struct bpf_reg_state *regs;
9854 int insn_cnt = env->prog->len;
9855 bool do_print_state = false;
9856 int prev_insn_idx = -1;
9859 struct bpf_insn *insn;
9863 env->prev_insn_idx = prev_insn_idx;
9864 if (env->insn_idx >= insn_cnt) {
9865 verbose(env, "invalid insn idx %d insn_cnt %d\n",
9866 env->insn_idx, insn_cnt);
9870 insn = &insns[env->insn_idx];
9871 class = BPF_CLASS(insn->code);
9873 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
9875 "BPF program is too large. Processed %d insn\n",
9876 env->insn_processed);
9880 err = is_state_visited(env, env->insn_idx);
9884 /* found equivalent state, can prune the search */
9885 if (env->log.level & BPF_LOG_LEVEL) {
9887 verbose(env, "\nfrom %d to %d%s: safe\n",
9888 env->prev_insn_idx, env->insn_idx,
9889 env->cur_state->speculative ?
9890 " (speculative execution)" : "");
9892 verbose(env, "%d: safe\n", env->insn_idx);
9894 goto process_bpf_exit;
9897 if (signal_pending(current))
9903 if (env->log.level & BPF_LOG_LEVEL2 ||
9904 (env->log.level & BPF_LOG_LEVEL && do_print_state)) {
9905 if (env->log.level & BPF_LOG_LEVEL2)
9906 verbose(env, "%d:", env->insn_idx);
9908 verbose(env, "\nfrom %d to %d%s:",
9909 env->prev_insn_idx, env->insn_idx,
9910 env->cur_state->speculative ?
9911 " (speculative execution)" : "");
9912 print_verifier_state(env, state->frame[state->curframe]);
9913 do_print_state = false;
9916 if (env->log.level & BPF_LOG_LEVEL) {
9917 const struct bpf_insn_cbs cbs = {
9918 .cb_print = verbose,
9919 .private_data = env,
9922 verbose_linfo(env, env->insn_idx, "; ");
9923 verbose(env, "%d: ", env->insn_idx);
9924 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
9927 if (bpf_prog_is_dev_bound(env->prog->aux)) {
9928 err = bpf_prog_offload_verify_insn(env, env->insn_idx,
9929 env->prev_insn_idx);
9934 regs = cur_regs(env);
9935 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
9936 prev_insn_idx = env->insn_idx;
9938 if (class == BPF_ALU || class == BPF_ALU64) {
9939 err = check_alu_op(env, insn);
9943 } else if (class == BPF_LDX) {
9944 enum bpf_reg_type *prev_src_type, src_reg_type;
9946 /* check for reserved fields is already done */
9948 /* check src operand */
9949 err = check_reg_arg(env, insn->src_reg, SRC_OP);
9953 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
9957 src_reg_type = regs[insn->src_reg].type;
9959 /* check that memory (src_reg + off) is readable,
9960 * the state of dst_reg will be updated by this func
9962 err = check_mem_access(env, env->insn_idx, insn->src_reg,
9963 insn->off, BPF_SIZE(insn->code),
9964 BPF_READ, insn->dst_reg, false);
9968 prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type;
9970 if (*prev_src_type == NOT_INIT) {
9972 * dst_reg = *(u32 *)(src_reg + off)
9973 * save type to validate intersecting paths
9975 *prev_src_type = src_reg_type;
9977 } else if (reg_type_mismatch(src_reg_type, *prev_src_type)) {
9978 /* ABuser program is trying to use the same insn
9979 * dst_reg = *(u32*) (src_reg + off)
9980 * with different pointer types:
9981 * src_reg == ctx in one branch and
9982 * src_reg == stack|map in some other branch.
9985 verbose(env, "same insn cannot be used with different pointers\n");
9989 } else if (class == BPF_STX) {
9990 enum bpf_reg_type *prev_dst_type, dst_reg_type;
9992 if (BPF_MODE(insn->code) == BPF_ATOMIC) {
9993 err = check_atomic(env, env->insn_idx, insn);
10000 if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
10001 verbose(env, "BPF_STX uses reserved fields\n");
10005 /* check src1 operand */
10006 err = check_reg_arg(env, insn->src_reg, SRC_OP);
10009 /* check src2 operand */
10010 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
10014 dst_reg_type = regs[insn->dst_reg].type;
10016 /* check that memory (dst_reg + off) is writeable */
10017 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
10018 insn->off, BPF_SIZE(insn->code),
10019 BPF_WRITE, insn->src_reg, false);
10023 prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type;
10025 if (*prev_dst_type == NOT_INIT) {
10026 *prev_dst_type = dst_reg_type;
10027 } else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) {
10028 verbose(env, "same insn cannot be used with different pointers\n");
10032 } else if (class == BPF_ST) {
10033 if (BPF_MODE(insn->code) != BPF_MEM ||
10034 insn->src_reg != BPF_REG_0) {
10035 verbose(env, "BPF_ST uses reserved fields\n");
10038 /* check src operand */
10039 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
10043 if (is_ctx_reg(env, insn->dst_reg)) {
10044 verbose(env, "BPF_ST stores into R%d %s is not allowed\n",
10046 reg_type_str[reg_state(env, insn->dst_reg)->type]);
10050 /* check that memory (dst_reg + off) is writeable */
10051 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
10052 insn->off, BPF_SIZE(insn->code),
10053 BPF_WRITE, -1, false);
10057 } else if (class == BPF_JMP || class == BPF_JMP32) {
10058 u8 opcode = BPF_OP(insn->code);
10060 env->jmps_processed++;
10061 if (opcode == BPF_CALL) {
10062 if (BPF_SRC(insn->code) != BPF_K ||
10064 (insn->src_reg != BPF_REG_0 &&
10065 insn->src_reg != BPF_PSEUDO_CALL) ||
10066 insn->dst_reg != BPF_REG_0 ||
10067 class == BPF_JMP32) {
10068 verbose(env, "BPF_CALL uses reserved fields\n");
10072 if (env->cur_state->active_spin_lock &&
10073 (insn->src_reg == BPF_PSEUDO_CALL ||
10074 insn->imm != BPF_FUNC_spin_unlock)) {
10075 verbose(env, "function calls are not allowed while holding a lock\n");
10078 if (insn->src_reg == BPF_PSEUDO_CALL)
10079 err = check_func_call(env, insn, &env->insn_idx);
10081 err = check_helper_call(env, insn->imm, env->insn_idx);
10085 } else if (opcode == BPF_JA) {
10086 if (BPF_SRC(insn->code) != BPF_K ||
10088 insn->src_reg != BPF_REG_0 ||
10089 insn->dst_reg != BPF_REG_0 ||
10090 class == BPF_JMP32) {
10091 verbose(env, "BPF_JA uses reserved fields\n");
10095 env->insn_idx += insn->off + 1;
10098 } else if (opcode == BPF_EXIT) {
10099 if (BPF_SRC(insn->code) != BPF_K ||
10101 insn->src_reg != BPF_REG_0 ||
10102 insn->dst_reg != BPF_REG_0 ||
10103 class == BPF_JMP32) {
10104 verbose(env, "BPF_EXIT uses reserved fields\n");
10108 if (env->cur_state->active_spin_lock) {
10109 verbose(env, "bpf_spin_unlock is missing\n");
10113 if (state->curframe) {
10114 /* exit from nested function */
10115 err = prepare_func_exit(env, &env->insn_idx);
10118 do_print_state = true;
10122 err = check_reference_leak(env);
10126 err = check_return_code(env);
10130 update_branch_counts(env, env->cur_state);
10131 err = pop_stack(env, &prev_insn_idx,
10132 &env->insn_idx, pop_log);
10134 if (err != -ENOENT)
10138 do_print_state = true;
10142 err = check_cond_jmp_op(env, insn, &env->insn_idx);
10146 } else if (class == BPF_LD) {
10147 u8 mode = BPF_MODE(insn->code);
10149 if (mode == BPF_ABS || mode == BPF_IND) {
10150 err = check_ld_abs(env, insn);
10154 } else if (mode == BPF_IMM) {
10155 err = check_ld_imm(env, insn);
10160 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
10162 verbose(env, "invalid BPF_LD mode\n");
10166 verbose(env, "unknown insn class %d\n", class);
10176 static int find_btf_percpu_datasec(struct btf *btf)
10178 const struct btf_type *t;
10183 * Both vmlinux and module each have their own ".data..percpu"
10184 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
10185 * types to look at only module's own BTF types.
10187 n = btf_nr_types(btf);
10188 if (btf_is_module(btf))
10189 i = btf_nr_types(btf_vmlinux);
10193 for(; i < n; i++) {
10194 t = btf_type_by_id(btf, i);
10195 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
10198 tname = btf_name_by_offset(btf, t->name_off);
10199 if (!strcmp(tname, ".data..percpu"))
10206 /* replace pseudo btf_id with kernel symbol address */
10207 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
10208 struct bpf_insn *insn,
10209 struct bpf_insn_aux_data *aux)
10211 const struct btf_var_secinfo *vsi;
10212 const struct btf_type *datasec;
10213 struct btf_mod_pair *btf_mod;
10214 const struct btf_type *t;
10215 const char *sym_name;
10216 bool percpu = false;
10217 u32 type, id = insn->imm;
10221 int i, btf_fd, err;
10223 btf_fd = insn[1].imm;
10225 btf = btf_get_by_fd(btf_fd);
10227 verbose(env, "invalid module BTF object FD specified.\n");
10231 if (!btf_vmlinux) {
10232 verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
10239 t = btf_type_by_id(btf, id);
10241 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
10246 if (!btf_type_is_var(t)) {
10247 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR.\n", id);
10252 sym_name = btf_name_by_offset(btf, t->name_off);
10253 addr = kallsyms_lookup_name(sym_name);
10255 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
10261 datasec_id = find_btf_percpu_datasec(btf);
10262 if (datasec_id > 0) {
10263 datasec = btf_type_by_id(btf, datasec_id);
10264 for_each_vsi(i, datasec, vsi) {
10265 if (vsi->type == id) {
10272 insn[0].imm = (u32)addr;
10273 insn[1].imm = addr >> 32;
10276 t = btf_type_skip_modifiers(btf, type, NULL);
10278 aux->btf_var.reg_type = PTR_TO_PERCPU_BTF_ID;
10279 aux->btf_var.btf = btf;
10280 aux->btf_var.btf_id = type;
10281 } else if (!btf_type_is_struct(t)) {
10282 const struct btf_type *ret;
10286 /* resolve the type size of ksym. */
10287 ret = btf_resolve_size(btf, t, &tsize);
10289 tname = btf_name_by_offset(btf, t->name_off);
10290 verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
10291 tname, PTR_ERR(ret));
10295 aux->btf_var.reg_type = PTR_TO_MEM;
10296 aux->btf_var.mem_size = tsize;
10298 aux->btf_var.reg_type = PTR_TO_BTF_ID;
10299 aux->btf_var.btf = btf;
10300 aux->btf_var.btf_id = type;
10303 /* check whether we recorded this BTF (and maybe module) already */
10304 for (i = 0; i < env->used_btf_cnt; i++) {
10305 if (env->used_btfs[i].btf == btf) {
10311 if (env->used_btf_cnt >= MAX_USED_BTFS) {
10316 btf_mod = &env->used_btfs[env->used_btf_cnt];
10317 btf_mod->btf = btf;
10318 btf_mod->module = NULL;
10320 /* if we reference variables from kernel module, bump its refcount */
10321 if (btf_is_module(btf)) {
10322 btf_mod->module = btf_try_get_module(btf);
10323 if (!btf_mod->module) {
10329 env->used_btf_cnt++;
10337 static int check_map_prealloc(struct bpf_map *map)
10339 return (map->map_type != BPF_MAP_TYPE_HASH &&
10340 map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
10341 map->map_type != BPF_MAP_TYPE_HASH_OF_MAPS) ||
10342 !(map->map_flags & BPF_F_NO_PREALLOC);
10345 static bool is_tracing_prog_type(enum bpf_prog_type type)
10348 case BPF_PROG_TYPE_KPROBE:
10349 case BPF_PROG_TYPE_TRACEPOINT:
10350 case BPF_PROG_TYPE_PERF_EVENT:
10351 case BPF_PROG_TYPE_RAW_TRACEPOINT:
10358 static bool is_preallocated_map(struct bpf_map *map)
10360 if (!check_map_prealloc(map))
10362 if (map->inner_map_meta && !check_map_prealloc(map->inner_map_meta))
10367 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
10368 struct bpf_map *map,
10369 struct bpf_prog *prog)
10372 enum bpf_prog_type prog_type = resolve_prog_type(prog);
10374 * Validate that trace type programs use preallocated hash maps.
10376 * For programs attached to PERF events this is mandatory as the
10377 * perf NMI can hit any arbitrary code sequence.
10379 * All other trace types using preallocated hash maps are unsafe as
10380 * well because tracepoint or kprobes can be inside locked regions
10381 * of the memory allocator or at a place where a recursion into the
10382 * memory allocator would see inconsistent state.
10384 * On RT enabled kernels run-time allocation of all trace type
10385 * programs is strictly prohibited due to lock type constraints. On
10386 * !RT kernels it is allowed for backwards compatibility reasons for
10387 * now, but warnings are emitted so developers are made aware of
10388 * the unsafety and can fix their programs before this is enforced.
10390 if (is_tracing_prog_type(prog_type) && !is_preallocated_map(map)) {
10391 if (prog_type == BPF_PROG_TYPE_PERF_EVENT) {
10392 verbose(env, "perf_event programs can only use preallocated hash map\n");
10395 if (IS_ENABLED(CONFIG_PREEMPT_RT)) {
10396 verbose(env, "trace type programs can only use preallocated hash map\n");
10399 WARN_ONCE(1, "trace type BPF program uses run-time allocation\n");
10400 verbose(env, "trace type programs with run-time allocated hash maps are unsafe. Switch to preallocated hash maps.\n");
10403 if (map_value_has_spin_lock(map)) {
10404 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
10405 verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
10409 if (is_tracing_prog_type(prog_type)) {
10410 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
10414 if (prog->aux->sleepable) {
10415 verbose(env, "sleepable progs cannot use bpf_spin_lock yet\n");
10420 if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) &&
10421 !bpf_offload_prog_map_match(prog, map)) {
10422 verbose(env, "offload device mismatch between prog and map\n");
10426 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
10427 verbose(env, "bpf_struct_ops map cannot be used in prog\n");
10431 if (prog->aux->sleepable)
10432 switch (map->map_type) {
10433 case BPF_MAP_TYPE_HASH:
10434 case BPF_MAP_TYPE_LRU_HASH:
10435 case BPF_MAP_TYPE_ARRAY:
10436 case BPF_MAP_TYPE_PERCPU_HASH:
10437 case BPF_MAP_TYPE_PERCPU_ARRAY:
10438 case BPF_MAP_TYPE_LRU_PERCPU_HASH:
10439 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
10440 case BPF_MAP_TYPE_HASH_OF_MAPS:
10441 if (!is_preallocated_map(map)) {
10443 "Sleepable programs can only use preallocated maps\n");
10447 case BPF_MAP_TYPE_RINGBUF:
10451 "Sleepable programs can only use array, hash, and ringbuf maps\n");
10458 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
10460 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
10461 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
10464 /* find and rewrite pseudo imm in ld_imm64 instructions:
10466 * 1. if it accesses map FD, replace it with actual map pointer.
10467 * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
10469 * NOTE: btf_vmlinux is required for converting pseudo btf_id.
10471 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
10473 struct bpf_insn *insn = env->prog->insnsi;
10474 int insn_cnt = env->prog->len;
10477 err = bpf_prog_calc_tag(env->prog);
10481 for (i = 0; i < insn_cnt; i++, insn++) {
10482 if (BPF_CLASS(insn->code) == BPF_LDX &&
10483 (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
10484 verbose(env, "BPF_LDX uses reserved fields\n");
10488 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
10489 struct bpf_insn_aux_data *aux;
10490 struct bpf_map *map;
10494 if (i == insn_cnt - 1 || insn[1].code != 0 ||
10495 insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
10496 insn[1].off != 0) {
10497 verbose(env, "invalid bpf_ld_imm64 insn\n");
10501 if (insn[0].src_reg == 0)
10502 /* valid generic load 64-bit imm */
10505 if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
10506 aux = &env->insn_aux_data[i];
10507 err = check_pseudo_btf_id(env, insn, aux);
10513 /* In final convert_pseudo_ld_imm64() step, this is
10514 * converted into regular 64-bit imm load insn.
10516 if ((insn[0].src_reg != BPF_PSEUDO_MAP_FD &&
10517 insn[0].src_reg != BPF_PSEUDO_MAP_VALUE) ||
10518 (insn[0].src_reg == BPF_PSEUDO_MAP_FD &&
10519 insn[1].imm != 0)) {
10521 "unrecognized bpf_ld_imm64 insn\n");
10525 f = fdget(insn[0].imm);
10526 map = __bpf_map_get(f);
10528 verbose(env, "fd %d is not pointing to valid bpf_map\n",
10530 return PTR_ERR(map);
10533 err = check_map_prog_compatibility(env, map, env->prog);
10539 aux = &env->insn_aux_data[i];
10540 if (insn->src_reg == BPF_PSEUDO_MAP_FD) {
10541 addr = (unsigned long)map;
10543 u32 off = insn[1].imm;
10545 if (off >= BPF_MAX_VAR_OFF) {
10546 verbose(env, "direct value offset of %u is not allowed\n", off);
10551 if (!map->ops->map_direct_value_addr) {
10552 verbose(env, "no direct value access support for this map type\n");
10557 err = map->ops->map_direct_value_addr(map, &addr, off);
10559 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
10560 map->value_size, off);
10565 aux->map_off = off;
10569 insn[0].imm = (u32)addr;
10570 insn[1].imm = addr >> 32;
10572 /* check whether we recorded this map already */
10573 for (j = 0; j < env->used_map_cnt; j++) {
10574 if (env->used_maps[j] == map) {
10575 aux->map_index = j;
10581 if (env->used_map_cnt >= MAX_USED_MAPS) {
10586 /* hold the map. If the program is rejected by verifier,
10587 * the map will be released by release_maps() or it
10588 * will be used by the valid program until it's unloaded
10589 * and all maps are released in free_used_maps()
10593 aux->map_index = env->used_map_cnt;
10594 env->used_maps[env->used_map_cnt++] = map;
10596 if (bpf_map_is_cgroup_storage(map) &&
10597 bpf_cgroup_storage_assign(env->prog->aux, map)) {
10598 verbose(env, "only one cgroup storage of each type is allowed\n");
10610 /* Basic sanity check before we invest more work here. */
10611 if (!bpf_opcode_in_insntable(insn->code)) {
10612 verbose(env, "unknown opcode %02x\n", insn->code);
10617 /* now all pseudo BPF_LD_IMM64 instructions load valid
10618 * 'struct bpf_map *' into a register instead of user map_fd.
10619 * These pointers will be used later by verifier to validate map access.
10624 /* drop refcnt of maps used by the rejected program */
10625 static void release_maps(struct bpf_verifier_env *env)
10627 __bpf_free_used_maps(env->prog->aux, env->used_maps,
10628 env->used_map_cnt);
10631 /* drop refcnt of maps used by the rejected program */
10632 static void release_btfs(struct bpf_verifier_env *env)
10634 __bpf_free_used_btfs(env->prog->aux, env->used_btfs,
10635 env->used_btf_cnt);
10638 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
10639 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
10641 struct bpf_insn *insn = env->prog->insnsi;
10642 int insn_cnt = env->prog->len;
10645 for (i = 0; i < insn_cnt; i++, insn++)
10646 if (insn->code == (BPF_LD | BPF_IMM | BPF_DW))
10650 /* single env->prog->insni[off] instruction was replaced with the range
10651 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying
10652 * [0, off) and [off, end) to new locations, so the patched range stays zero
10654 static int adjust_insn_aux_data(struct bpf_verifier_env *env,
10655 struct bpf_prog *new_prog, u32 off, u32 cnt)
10657 struct bpf_insn_aux_data *new_data, *old_data = env->insn_aux_data;
10658 struct bpf_insn *insn = new_prog->insnsi;
10662 /* aux info at OFF always needs adjustment, no matter fast path
10663 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
10664 * original insn at old prog.
10666 old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
10670 prog_len = new_prog->len;
10671 new_data = vzalloc(array_size(prog_len,
10672 sizeof(struct bpf_insn_aux_data)));
10675 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
10676 memcpy(new_data + off + cnt - 1, old_data + off,
10677 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
10678 for (i = off; i < off + cnt - 1; i++) {
10679 new_data[i].seen = env->pass_cnt;
10680 new_data[i].zext_dst = insn_has_def32(env, insn + i);
10682 env->insn_aux_data = new_data;
10687 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
10693 /* NOTE: fake 'exit' subprog should be updated as well. */
10694 for (i = 0; i <= env->subprog_cnt; i++) {
10695 if (env->subprog_info[i].start <= off)
10697 env->subprog_info[i].start += len - 1;
10701 static void adjust_poke_descs(struct bpf_prog *prog, u32 len)
10703 struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
10704 int i, sz = prog->aux->size_poke_tab;
10705 struct bpf_jit_poke_descriptor *desc;
10707 for (i = 0; i < sz; i++) {
10709 desc->insn_idx += len - 1;
10713 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
10714 const struct bpf_insn *patch, u32 len)
10716 struct bpf_prog *new_prog;
10718 new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
10719 if (IS_ERR(new_prog)) {
10720 if (PTR_ERR(new_prog) == -ERANGE)
10722 "insn %d cannot be patched due to 16-bit range\n",
10723 env->insn_aux_data[off].orig_idx);
10726 if (adjust_insn_aux_data(env, new_prog, off, len))
10728 adjust_subprog_starts(env, off, len);
10729 adjust_poke_descs(new_prog, len);
10733 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
10738 /* find first prog starting at or after off (first to remove) */
10739 for (i = 0; i < env->subprog_cnt; i++)
10740 if (env->subprog_info[i].start >= off)
10742 /* find first prog starting at or after off + cnt (first to stay) */
10743 for (j = i; j < env->subprog_cnt; j++)
10744 if (env->subprog_info[j].start >= off + cnt)
10746 /* if j doesn't start exactly at off + cnt, we are just removing
10747 * the front of previous prog
10749 if (env->subprog_info[j].start != off + cnt)
10753 struct bpf_prog_aux *aux = env->prog->aux;
10756 /* move fake 'exit' subprog as well */
10757 move = env->subprog_cnt + 1 - j;
10759 memmove(env->subprog_info + i,
10760 env->subprog_info + j,
10761 sizeof(*env->subprog_info) * move);
10762 env->subprog_cnt -= j - i;
10764 /* remove func_info */
10765 if (aux->func_info) {
10766 move = aux->func_info_cnt - j;
10768 memmove(aux->func_info + i,
10769 aux->func_info + j,
10770 sizeof(*aux->func_info) * move);
10771 aux->func_info_cnt -= j - i;
10772 /* func_info->insn_off is set after all code rewrites,
10773 * in adjust_btf_func() - no need to adjust
10777 /* convert i from "first prog to remove" to "first to adjust" */
10778 if (env->subprog_info[i].start == off)
10782 /* update fake 'exit' subprog as well */
10783 for (; i <= env->subprog_cnt; i++)
10784 env->subprog_info[i].start -= cnt;
10789 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
10792 struct bpf_prog *prog = env->prog;
10793 u32 i, l_off, l_cnt, nr_linfo;
10794 struct bpf_line_info *linfo;
10796 nr_linfo = prog->aux->nr_linfo;
10800 linfo = prog->aux->linfo;
10802 /* find first line info to remove, count lines to be removed */
10803 for (i = 0; i < nr_linfo; i++)
10804 if (linfo[i].insn_off >= off)
10809 for (; i < nr_linfo; i++)
10810 if (linfo[i].insn_off < off + cnt)
10815 /* First live insn doesn't match first live linfo, it needs to "inherit"
10816 * last removed linfo. prog is already modified, so prog->len == off
10817 * means no live instructions after (tail of the program was removed).
10819 if (prog->len != off && l_cnt &&
10820 (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
10822 linfo[--i].insn_off = off + cnt;
10825 /* remove the line info which refer to the removed instructions */
10827 memmove(linfo + l_off, linfo + i,
10828 sizeof(*linfo) * (nr_linfo - i));
10830 prog->aux->nr_linfo -= l_cnt;
10831 nr_linfo = prog->aux->nr_linfo;
10834 /* pull all linfo[i].insn_off >= off + cnt in by cnt */
10835 for (i = l_off; i < nr_linfo; i++)
10836 linfo[i].insn_off -= cnt;
10838 /* fix up all subprogs (incl. 'exit') which start >= off */
10839 for (i = 0; i <= env->subprog_cnt; i++)
10840 if (env->subprog_info[i].linfo_idx > l_off) {
10841 /* program may have started in the removed region but
10842 * may not be fully removed
10844 if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
10845 env->subprog_info[i].linfo_idx -= l_cnt;
10847 env->subprog_info[i].linfo_idx = l_off;
10853 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
10855 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
10856 unsigned int orig_prog_len = env->prog->len;
10859 if (bpf_prog_is_dev_bound(env->prog->aux))
10860 bpf_prog_offload_remove_insns(env, off, cnt);
10862 err = bpf_remove_insns(env->prog, off, cnt);
10866 err = adjust_subprog_starts_after_remove(env, off, cnt);
10870 err = bpf_adj_linfo_after_remove(env, off, cnt);
10874 memmove(aux_data + off, aux_data + off + cnt,
10875 sizeof(*aux_data) * (orig_prog_len - off - cnt));
10880 /* The verifier does more data flow analysis than llvm and will not
10881 * explore branches that are dead at run time. Malicious programs can
10882 * have dead code too. Therefore replace all dead at-run-time code
10885 * Just nops are not optimal, e.g. if they would sit at the end of the
10886 * program and through another bug we would manage to jump there, then
10887 * we'd execute beyond program memory otherwise. Returning exception
10888 * code also wouldn't work since we can have subprogs where the dead
10889 * code could be located.
10891 static void sanitize_dead_code(struct bpf_verifier_env *env)
10893 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
10894 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
10895 struct bpf_insn *insn = env->prog->insnsi;
10896 const int insn_cnt = env->prog->len;
10899 for (i = 0; i < insn_cnt; i++) {
10900 if (aux_data[i].seen)
10902 memcpy(insn + i, &trap, sizeof(trap));
10906 static bool insn_is_cond_jump(u8 code)
10910 if (BPF_CLASS(code) == BPF_JMP32)
10913 if (BPF_CLASS(code) != BPF_JMP)
10917 return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
10920 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
10922 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
10923 struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
10924 struct bpf_insn *insn = env->prog->insnsi;
10925 const int insn_cnt = env->prog->len;
10928 for (i = 0; i < insn_cnt; i++, insn++) {
10929 if (!insn_is_cond_jump(insn->code))
10932 if (!aux_data[i + 1].seen)
10933 ja.off = insn->off;
10934 else if (!aux_data[i + 1 + insn->off].seen)
10939 if (bpf_prog_is_dev_bound(env->prog->aux))
10940 bpf_prog_offload_replace_insn(env, i, &ja);
10942 memcpy(insn, &ja, sizeof(ja));
10946 static int opt_remove_dead_code(struct bpf_verifier_env *env)
10948 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
10949 int insn_cnt = env->prog->len;
10952 for (i = 0; i < insn_cnt; i++) {
10956 while (i + j < insn_cnt && !aux_data[i + j].seen)
10961 err = verifier_remove_insns(env, i, j);
10964 insn_cnt = env->prog->len;
10970 static int opt_remove_nops(struct bpf_verifier_env *env)
10972 const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
10973 struct bpf_insn *insn = env->prog->insnsi;
10974 int insn_cnt = env->prog->len;
10977 for (i = 0; i < insn_cnt; i++) {
10978 if (memcmp(&insn[i], &ja, sizeof(ja)))
10981 err = verifier_remove_insns(env, i, 1);
10991 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
10992 const union bpf_attr *attr)
10994 struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
10995 struct bpf_insn_aux_data *aux = env->insn_aux_data;
10996 int i, patch_len, delta = 0, len = env->prog->len;
10997 struct bpf_insn *insns = env->prog->insnsi;
10998 struct bpf_prog *new_prog;
11001 rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
11002 zext_patch[1] = BPF_ZEXT_REG(0);
11003 rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
11004 rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
11005 rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
11006 for (i = 0; i < len; i++) {
11007 int adj_idx = i + delta;
11008 struct bpf_insn insn;
11011 insn = insns[adj_idx];
11012 if (!aux[adj_idx].zext_dst) {
11020 class = BPF_CLASS(code);
11021 if (insn_no_def(&insn))
11024 /* NOTE: arg "reg" (the fourth one) is only used for
11025 * BPF_STX which has been ruled out in above
11026 * check, it is safe to pass NULL here.
11028 if (is_reg64(env, &insn, insn.dst_reg, NULL, DST_OP)) {
11029 if (class == BPF_LD &&
11030 BPF_MODE(code) == BPF_IMM)
11035 /* ctx load could be transformed into wider load. */
11036 if (class == BPF_LDX &&
11037 aux[adj_idx].ptr_type == PTR_TO_CTX)
11040 imm_rnd = get_random_int();
11041 rnd_hi32_patch[0] = insn;
11042 rnd_hi32_patch[1].imm = imm_rnd;
11043 rnd_hi32_patch[3].dst_reg = insn.dst_reg;
11044 patch = rnd_hi32_patch;
11046 goto apply_patch_buffer;
11049 if (!bpf_jit_needs_zext())
11052 /* zext_dst means that we want to zero-extend whatever register
11053 * the insn defines, which is dst_reg most of the time, with
11054 * the notable exception of BPF_STX + BPF_ATOMIC + BPF_FETCH.
11056 if (BPF_CLASS(insn.code) == BPF_STX &&
11057 BPF_MODE(insn.code) == BPF_ATOMIC) {
11058 /* BPF_STX + BPF_ATOMIC insns without BPF_FETCH do not
11059 * define any registers, therefore zext_dst cannot be
11062 if (WARN_ON(!(insn.imm & BPF_FETCH)))
11064 load_reg = insn.imm == BPF_CMPXCHG ? BPF_REG_0
11067 load_reg = insn.dst_reg;
11070 zext_patch[0] = insn;
11071 zext_patch[1].dst_reg = load_reg;
11072 zext_patch[1].src_reg = load_reg;
11073 patch = zext_patch;
11075 apply_patch_buffer:
11076 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
11079 env->prog = new_prog;
11080 insns = new_prog->insnsi;
11081 aux = env->insn_aux_data;
11082 delta += patch_len - 1;
11088 /* convert load instructions that access fields of a context type into a
11089 * sequence of instructions that access fields of the underlying structure:
11090 * struct __sk_buff -> struct sk_buff
11091 * struct bpf_sock_ops -> struct sock
11093 static int convert_ctx_accesses(struct bpf_verifier_env *env)
11095 const struct bpf_verifier_ops *ops = env->ops;
11096 int i, cnt, size, ctx_field_size, delta = 0;
11097 const int insn_cnt = env->prog->len;
11098 struct bpf_insn insn_buf[16], *insn;
11099 u32 target_size, size_default, off;
11100 struct bpf_prog *new_prog;
11101 enum bpf_access_type type;
11102 bool is_narrower_load;
11104 if (ops->gen_prologue || env->seen_direct_write) {
11105 if (!ops->gen_prologue) {
11106 verbose(env, "bpf verifier is misconfigured\n");
11109 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
11111 if (cnt >= ARRAY_SIZE(insn_buf)) {
11112 verbose(env, "bpf verifier is misconfigured\n");
11115 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
11119 env->prog = new_prog;
11124 if (bpf_prog_is_dev_bound(env->prog->aux))
11127 insn = env->prog->insnsi + delta;
11129 for (i = 0; i < insn_cnt; i++, insn++) {
11130 bpf_convert_ctx_access_t convert_ctx_access;
11132 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
11133 insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
11134 insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
11135 insn->code == (BPF_LDX | BPF_MEM | BPF_DW))
11137 else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
11138 insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
11139 insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
11140 insn->code == (BPF_STX | BPF_MEM | BPF_DW))
11145 if (type == BPF_WRITE &&
11146 env->insn_aux_data[i + delta].sanitize_stack_off) {
11147 struct bpf_insn patch[] = {
11148 /* Sanitize suspicious stack slot with zero.
11149 * There are no memory dependencies for this store,
11150 * since it's only using frame pointer and immediate
11153 BPF_ST_MEM(BPF_DW, BPF_REG_FP,
11154 env->insn_aux_data[i + delta].sanitize_stack_off,
11156 /* the original STX instruction will immediately
11157 * overwrite the same stack slot with appropriate value
11162 cnt = ARRAY_SIZE(patch);
11163 new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
11168 env->prog = new_prog;
11169 insn = new_prog->insnsi + i + delta;
11173 switch (env->insn_aux_data[i + delta].ptr_type) {
11175 if (!ops->convert_ctx_access)
11177 convert_ctx_access = ops->convert_ctx_access;
11179 case PTR_TO_SOCKET:
11180 case PTR_TO_SOCK_COMMON:
11181 convert_ctx_access = bpf_sock_convert_ctx_access;
11183 case PTR_TO_TCP_SOCK:
11184 convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
11186 case PTR_TO_XDP_SOCK:
11187 convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
11189 case PTR_TO_BTF_ID:
11190 if (type == BPF_READ) {
11191 insn->code = BPF_LDX | BPF_PROBE_MEM |
11192 BPF_SIZE((insn)->code);
11193 env->prog->aux->num_exentries++;
11194 } else if (resolve_prog_type(env->prog) != BPF_PROG_TYPE_STRUCT_OPS) {
11195 verbose(env, "Writes through BTF pointers are not allowed\n");
11203 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
11204 size = BPF_LDST_BYTES(insn);
11206 /* If the read access is a narrower load of the field,
11207 * convert to a 4/8-byte load, to minimum program type specific
11208 * convert_ctx_access changes. If conversion is successful,
11209 * we will apply proper mask to the result.
11211 is_narrower_load = size < ctx_field_size;
11212 size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
11214 if (is_narrower_load) {
11217 if (type == BPF_WRITE) {
11218 verbose(env, "bpf verifier narrow ctx access misconfigured\n");
11223 if (ctx_field_size == 4)
11225 else if (ctx_field_size == 8)
11226 size_code = BPF_DW;
11228 insn->off = off & ~(size_default - 1);
11229 insn->code = BPF_LDX | BPF_MEM | size_code;
11233 cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
11235 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
11236 (ctx_field_size && !target_size)) {
11237 verbose(env, "bpf verifier is misconfigured\n");
11241 if (is_narrower_load && size < target_size) {
11242 u8 shift = bpf_ctx_narrow_access_offset(
11243 off, size, size_default) * 8;
11244 if (ctx_field_size <= 4) {
11246 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
11249 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
11250 (1 << size * 8) - 1);
11253 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
11256 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
11257 (1ULL << size * 8) - 1);
11261 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
11267 /* keep walking new program and skip insns we just inserted */
11268 env->prog = new_prog;
11269 insn = new_prog->insnsi + i + delta;
11275 static int jit_subprogs(struct bpf_verifier_env *env)
11277 struct bpf_prog *prog = env->prog, **func, *tmp;
11278 int i, j, subprog_start, subprog_end = 0, len, subprog;
11279 struct bpf_map *map_ptr;
11280 struct bpf_insn *insn;
11281 void *old_bpf_func;
11282 int err, num_exentries;
11284 if (env->subprog_cnt <= 1)
11287 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
11288 if (!bpf_pseudo_call(insn))
11290 /* Upon error here we cannot fall back to interpreter but
11291 * need a hard reject of the program. Thus -EFAULT is
11292 * propagated in any case.
11294 subprog = find_subprog(env, i + insn->imm + 1);
11296 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
11297 i + insn->imm + 1);
11300 /* temporarily remember subprog id inside insn instead of
11301 * aux_data, since next loop will split up all insns into funcs
11303 insn->off = subprog;
11304 /* remember original imm in case JIT fails and fallback
11305 * to interpreter will be needed
11307 env->insn_aux_data[i].call_imm = insn->imm;
11308 /* point imm to __bpf_call_base+1 from JITs point of view */
11312 err = bpf_prog_alloc_jited_linfo(prog);
11314 goto out_undo_insn;
11317 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
11319 goto out_undo_insn;
11321 for (i = 0; i < env->subprog_cnt; i++) {
11322 subprog_start = subprog_end;
11323 subprog_end = env->subprog_info[i + 1].start;
11325 len = subprog_end - subprog_start;
11326 /* BPF_PROG_RUN doesn't call subprogs directly,
11327 * hence main prog stats include the runtime of subprogs.
11328 * subprogs don't have IDs and not reachable via prog_get_next_id
11329 * func[i]->stats will never be accessed and stays NULL
11331 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
11334 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
11335 len * sizeof(struct bpf_insn));
11336 func[i]->type = prog->type;
11337 func[i]->len = len;
11338 if (bpf_prog_calc_tag(func[i]))
11340 func[i]->is_func = 1;
11341 func[i]->aux->func_idx = i;
11342 /* the btf and func_info will be freed only at prog->aux */
11343 func[i]->aux->btf = prog->aux->btf;
11344 func[i]->aux->func_info = prog->aux->func_info;
11346 for (j = 0; j < prog->aux->size_poke_tab; j++) {
11347 u32 insn_idx = prog->aux->poke_tab[j].insn_idx;
11350 if (!(insn_idx >= subprog_start &&
11351 insn_idx <= subprog_end))
11354 ret = bpf_jit_add_poke_descriptor(func[i],
11355 &prog->aux->poke_tab[j]);
11357 verbose(env, "adding tail call poke descriptor failed\n");
11361 func[i]->insnsi[insn_idx - subprog_start].imm = ret + 1;
11363 map_ptr = func[i]->aux->poke_tab[ret].tail_call.map;
11364 ret = map_ptr->ops->map_poke_track(map_ptr, func[i]->aux);
11366 verbose(env, "tracking tail call prog failed\n");
11371 /* Use bpf_prog_F_tag to indicate functions in stack traces.
11372 * Long term would need debug info to populate names
11374 func[i]->aux->name[0] = 'F';
11375 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
11376 func[i]->jit_requested = 1;
11377 func[i]->aux->linfo = prog->aux->linfo;
11378 func[i]->aux->nr_linfo = prog->aux->nr_linfo;
11379 func[i]->aux->jited_linfo = prog->aux->jited_linfo;
11380 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
11382 insn = func[i]->insnsi;
11383 for (j = 0; j < func[i]->len; j++, insn++) {
11384 if (BPF_CLASS(insn->code) == BPF_LDX &&
11385 BPF_MODE(insn->code) == BPF_PROBE_MEM)
11388 func[i]->aux->num_exentries = num_exentries;
11389 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
11390 func[i] = bpf_int_jit_compile(func[i]);
11391 if (!func[i]->jited) {
11398 /* Untrack main program's aux structs so that during map_poke_run()
11399 * we will not stumble upon the unfilled poke descriptors; each
11400 * of the main program's poke descs got distributed across subprogs
11401 * and got tracked onto map, so we are sure that none of them will
11402 * be missed after the operation below
11404 for (i = 0; i < prog->aux->size_poke_tab; i++) {
11405 map_ptr = prog->aux->poke_tab[i].tail_call.map;
11407 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
11410 /* at this point all bpf functions were successfully JITed
11411 * now populate all bpf_calls with correct addresses and
11412 * run last pass of JIT
11414 for (i = 0; i < env->subprog_cnt; i++) {
11415 insn = func[i]->insnsi;
11416 for (j = 0; j < func[i]->len; j++, insn++) {
11417 if (!bpf_pseudo_call(insn))
11419 subprog = insn->off;
11420 insn->imm = BPF_CAST_CALL(func[subprog]->bpf_func) -
11424 /* we use the aux data to keep a list of the start addresses
11425 * of the JITed images for each function in the program
11427 * for some architectures, such as powerpc64, the imm field
11428 * might not be large enough to hold the offset of the start
11429 * address of the callee's JITed image from __bpf_call_base
11431 * in such cases, we can lookup the start address of a callee
11432 * by using its subprog id, available from the off field of
11433 * the call instruction, as an index for this list
11435 func[i]->aux->func = func;
11436 func[i]->aux->func_cnt = env->subprog_cnt;
11438 for (i = 0; i < env->subprog_cnt; i++) {
11439 old_bpf_func = func[i]->bpf_func;
11440 tmp = bpf_int_jit_compile(func[i]);
11441 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
11442 verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
11449 /* finally lock prog and jit images for all functions and
11450 * populate kallsysm
11452 for (i = 0; i < env->subprog_cnt; i++) {
11453 bpf_prog_lock_ro(func[i]);
11454 bpf_prog_kallsyms_add(func[i]);
11457 /* Last step: make now unused interpreter insns from main
11458 * prog consistent for later dump requests, so they can
11459 * later look the same as if they were interpreted only.
11461 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
11462 if (!bpf_pseudo_call(insn))
11464 insn->off = env->insn_aux_data[i].call_imm;
11465 subprog = find_subprog(env, i + insn->off + 1);
11466 insn->imm = subprog;
11470 prog->bpf_func = func[0]->bpf_func;
11471 prog->aux->func = func;
11472 prog->aux->func_cnt = env->subprog_cnt;
11473 bpf_prog_free_unused_jited_linfo(prog);
11476 for (i = 0; i < env->subprog_cnt; i++) {
11480 for (j = 0; j < func[i]->aux->size_poke_tab; j++) {
11481 map_ptr = func[i]->aux->poke_tab[j].tail_call.map;
11482 map_ptr->ops->map_poke_untrack(map_ptr, func[i]->aux);
11484 bpf_jit_free(func[i]);
11488 /* cleanup main prog to be interpreted */
11489 prog->jit_requested = 0;
11490 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
11491 if (!bpf_pseudo_call(insn))
11494 insn->imm = env->insn_aux_data[i].call_imm;
11496 bpf_prog_free_jited_linfo(prog);
11500 static int fixup_call_args(struct bpf_verifier_env *env)
11502 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
11503 struct bpf_prog *prog = env->prog;
11504 struct bpf_insn *insn = prog->insnsi;
11509 if (env->prog->jit_requested &&
11510 !bpf_prog_is_dev_bound(env->prog->aux)) {
11511 err = jit_subprogs(env);
11514 if (err == -EFAULT)
11517 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
11518 if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
11519 /* When JIT fails the progs with bpf2bpf calls and tail_calls
11520 * have to be rejected, since interpreter doesn't support them yet.
11522 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
11525 for (i = 0; i < prog->len; i++, insn++) {
11526 if (!bpf_pseudo_call(insn))
11528 depth = get_callee_stack_depth(env, insn, i);
11531 bpf_patch_call_args(insn, depth);
11538 /* fixup insn->imm field of bpf_call instructions
11539 * and inline eligible helpers as explicit sequence of BPF instructions
11541 * this function is called after eBPF program passed verification
11543 static int fixup_bpf_calls(struct bpf_verifier_env *env)
11545 struct bpf_prog *prog = env->prog;
11546 bool expect_blinding = bpf_jit_blinding_enabled(prog);
11547 struct bpf_insn *insn = prog->insnsi;
11548 const struct bpf_func_proto *fn;
11549 const int insn_cnt = prog->len;
11550 const struct bpf_map_ops *ops;
11551 struct bpf_insn_aux_data *aux;
11552 struct bpf_insn insn_buf[16];
11553 struct bpf_prog *new_prog;
11554 struct bpf_map *map_ptr;
11555 int i, ret, cnt, delta = 0;
11557 for (i = 0; i < insn_cnt; i++, insn++) {
11558 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
11559 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
11560 insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
11561 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
11562 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
11563 bool isdiv = BPF_OP(insn->code) == BPF_DIV;
11564 struct bpf_insn *patchlet;
11565 struct bpf_insn chk_and_div[] = {
11566 /* [R,W]x div 0 -> 0 */
11567 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
11568 BPF_JNE | BPF_K, insn->src_reg,
11570 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
11571 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
11574 struct bpf_insn chk_and_mod[] = {
11575 /* [R,W]x mod 0 -> [R,W]x */
11576 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
11577 BPF_JEQ | BPF_K, insn->src_reg,
11578 0, 1 + (is64 ? 0 : 1), 0),
11580 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
11581 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
11584 patchlet = isdiv ? chk_and_div : chk_and_mod;
11585 cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
11586 ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
11588 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
11593 env->prog = prog = new_prog;
11594 insn = new_prog->insnsi + i + delta;
11598 if (BPF_CLASS(insn->code) == BPF_LD &&
11599 (BPF_MODE(insn->code) == BPF_ABS ||
11600 BPF_MODE(insn->code) == BPF_IND)) {
11601 cnt = env->ops->gen_ld_abs(insn, insn_buf);
11602 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
11603 verbose(env, "bpf verifier is misconfigured\n");
11607 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
11612 env->prog = prog = new_prog;
11613 insn = new_prog->insnsi + i + delta;
11617 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
11618 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
11619 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
11620 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
11621 struct bpf_insn insn_buf[16];
11622 struct bpf_insn *patch = &insn_buf[0];
11626 aux = &env->insn_aux_data[i + delta];
11627 if (!aux->alu_state ||
11628 aux->alu_state == BPF_ALU_NON_POINTER)
11631 isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
11632 issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
11633 BPF_ALU_SANITIZE_SRC;
11635 off_reg = issrc ? insn->src_reg : insn->dst_reg;
11637 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
11638 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit - 1);
11639 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
11640 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
11641 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
11642 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
11644 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX,
11646 insn->src_reg = BPF_REG_AX;
11648 *patch++ = BPF_ALU64_REG(BPF_AND, off_reg,
11652 insn->code = insn->code == code_add ?
11653 code_sub : code_add;
11655 if (issrc && isneg)
11656 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
11657 cnt = patch - insn_buf;
11659 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
11664 env->prog = prog = new_prog;
11665 insn = new_prog->insnsi + i + delta;
11669 if (insn->code != (BPF_JMP | BPF_CALL))
11671 if (insn->src_reg == BPF_PSEUDO_CALL)
11674 if (insn->imm == BPF_FUNC_get_route_realm)
11675 prog->dst_needed = 1;
11676 if (insn->imm == BPF_FUNC_get_prandom_u32)
11677 bpf_user_rnd_init_once();
11678 if (insn->imm == BPF_FUNC_override_return)
11679 prog->kprobe_override = 1;
11680 if (insn->imm == BPF_FUNC_tail_call) {
11681 /* If we tail call into other programs, we
11682 * cannot make any assumptions since they can
11683 * be replaced dynamically during runtime in
11684 * the program array.
11686 prog->cb_access = 1;
11687 if (!allow_tail_call_in_subprogs(env))
11688 prog->aux->stack_depth = MAX_BPF_STACK;
11689 prog->aux->max_pkt_offset = MAX_PACKET_OFF;
11691 /* mark bpf_tail_call as different opcode to avoid
11692 * conditional branch in the interpeter for every normal
11693 * call and to prevent accidental JITing by JIT compiler
11694 * that doesn't support bpf_tail_call yet
11697 insn->code = BPF_JMP | BPF_TAIL_CALL;
11699 aux = &env->insn_aux_data[i + delta];
11700 if (env->bpf_capable && !expect_blinding &&
11701 prog->jit_requested &&
11702 !bpf_map_key_poisoned(aux) &&
11703 !bpf_map_ptr_poisoned(aux) &&
11704 !bpf_map_ptr_unpriv(aux)) {
11705 struct bpf_jit_poke_descriptor desc = {
11706 .reason = BPF_POKE_REASON_TAIL_CALL,
11707 .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
11708 .tail_call.key = bpf_map_key_immediate(aux),
11709 .insn_idx = i + delta,
11712 ret = bpf_jit_add_poke_descriptor(prog, &desc);
11714 verbose(env, "adding tail call poke descriptor failed\n");
11718 insn->imm = ret + 1;
11722 if (!bpf_map_ptr_unpriv(aux))
11725 /* instead of changing every JIT dealing with tail_call
11726 * emit two extra insns:
11727 * if (index >= max_entries) goto out;
11728 * index &= array->index_mask;
11729 * to avoid out-of-bounds cpu speculation
11731 if (bpf_map_ptr_poisoned(aux)) {
11732 verbose(env, "tail_call abusing map_ptr\n");
11736 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
11737 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
11738 map_ptr->max_entries, 2);
11739 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
11740 container_of(map_ptr,
11743 insn_buf[2] = *insn;
11745 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
11750 env->prog = prog = new_prog;
11751 insn = new_prog->insnsi + i + delta;
11755 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
11756 * and other inlining handlers are currently limited to 64 bit
11759 if (prog->jit_requested && BITS_PER_LONG == 64 &&
11760 (insn->imm == BPF_FUNC_map_lookup_elem ||
11761 insn->imm == BPF_FUNC_map_update_elem ||
11762 insn->imm == BPF_FUNC_map_delete_elem ||
11763 insn->imm == BPF_FUNC_map_push_elem ||
11764 insn->imm == BPF_FUNC_map_pop_elem ||
11765 insn->imm == BPF_FUNC_map_peek_elem)) {
11766 aux = &env->insn_aux_data[i + delta];
11767 if (bpf_map_ptr_poisoned(aux))
11768 goto patch_call_imm;
11770 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
11771 ops = map_ptr->ops;
11772 if (insn->imm == BPF_FUNC_map_lookup_elem &&
11773 ops->map_gen_lookup) {
11774 cnt = ops->map_gen_lookup(map_ptr, insn_buf);
11775 if (cnt == -EOPNOTSUPP)
11776 goto patch_map_ops_generic;
11777 if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
11778 verbose(env, "bpf verifier is misconfigured\n");
11782 new_prog = bpf_patch_insn_data(env, i + delta,
11788 env->prog = prog = new_prog;
11789 insn = new_prog->insnsi + i + delta;
11793 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
11794 (void *(*)(struct bpf_map *map, void *key))NULL));
11795 BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
11796 (int (*)(struct bpf_map *map, void *key))NULL));
11797 BUILD_BUG_ON(!__same_type(ops->map_update_elem,
11798 (int (*)(struct bpf_map *map, void *key, void *value,
11800 BUILD_BUG_ON(!__same_type(ops->map_push_elem,
11801 (int (*)(struct bpf_map *map, void *value,
11803 BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
11804 (int (*)(struct bpf_map *map, void *value))NULL));
11805 BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
11806 (int (*)(struct bpf_map *map, void *value))NULL));
11807 patch_map_ops_generic:
11808 switch (insn->imm) {
11809 case BPF_FUNC_map_lookup_elem:
11810 insn->imm = BPF_CAST_CALL(ops->map_lookup_elem) -
11813 case BPF_FUNC_map_update_elem:
11814 insn->imm = BPF_CAST_CALL(ops->map_update_elem) -
11817 case BPF_FUNC_map_delete_elem:
11818 insn->imm = BPF_CAST_CALL(ops->map_delete_elem) -
11821 case BPF_FUNC_map_push_elem:
11822 insn->imm = BPF_CAST_CALL(ops->map_push_elem) -
11825 case BPF_FUNC_map_pop_elem:
11826 insn->imm = BPF_CAST_CALL(ops->map_pop_elem) -
11829 case BPF_FUNC_map_peek_elem:
11830 insn->imm = BPF_CAST_CALL(ops->map_peek_elem) -
11835 goto patch_call_imm;
11838 if (prog->jit_requested && BITS_PER_LONG == 64 &&
11839 insn->imm == BPF_FUNC_jiffies64) {
11840 struct bpf_insn ld_jiffies_addr[2] = {
11841 BPF_LD_IMM64(BPF_REG_0,
11842 (unsigned long)&jiffies),
11845 insn_buf[0] = ld_jiffies_addr[0];
11846 insn_buf[1] = ld_jiffies_addr[1];
11847 insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
11851 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
11857 env->prog = prog = new_prog;
11858 insn = new_prog->insnsi + i + delta;
11863 fn = env->ops->get_func_proto(insn->imm, env->prog);
11864 /* all functions that have prototype and verifier allowed
11865 * programs to call them, must be real in-kernel functions
11869 "kernel subsystem misconfigured func %s#%d\n",
11870 func_id_name(insn->imm), insn->imm);
11873 insn->imm = fn->func - __bpf_call_base;
11876 /* Since poke tab is now finalized, publish aux to tracker. */
11877 for (i = 0; i < prog->aux->size_poke_tab; i++) {
11878 map_ptr = prog->aux->poke_tab[i].tail_call.map;
11879 if (!map_ptr->ops->map_poke_track ||
11880 !map_ptr->ops->map_poke_untrack ||
11881 !map_ptr->ops->map_poke_run) {
11882 verbose(env, "bpf verifier is misconfigured\n");
11886 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
11888 verbose(env, "tracking tail call prog failed\n");
11896 static void free_states(struct bpf_verifier_env *env)
11898 struct bpf_verifier_state_list *sl, *sln;
11901 sl = env->free_list;
11904 free_verifier_state(&sl->state, false);
11908 env->free_list = NULL;
11910 if (!env->explored_states)
11913 for (i = 0; i < state_htab_size(env); i++) {
11914 sl = env->explored_states[i];
11918 free_verifier_state(&sl->state, false);
11922 env->explored_states[i] = NULL;
11926 /* The verifier is using insn_aux_data[] to store temporary data during
11927 * verification and to store information for passes that run after the
11928 * verification like dead code sanitization. do_check_common() for subprogram N
11929 * may analyze many other subprograms. sanitize_insn_aux_data() clears all
11930 * temporary data after do_check_common() finds that subprogram N cannot be
11931 * verified independently. pass_cnt counts the number of times
11932 * do_check_common() was run and insn->aux->seen tells the pass number
11933 * insn_aux_data was touched. These variables are compared to clear temporary
11934 * data from failed pass. For testing and experiments do_check_common() can be
11935 * run multiple times even when prior attempt to verify is unsuccessful.
11937 static void sanitize_insn_aux_data(struct bpf_verifier_env *env)
11939 struct bpf_insn *insn = env->prog->insnsi;
11940 struct bpf_insn_aux_data *aux;
11943 for (i = 0; i < env->prog->len; i++) {
11944 class = BPF_CLASS(insn[i].code);
11945 if (class != BPF_LDX && class != BPF_STX)
11947 aux = &env->insn_aux_data[i];
11948 if (aux->seen != env->pass_cnt)
11950 memset(aux, 0, offsetof(typeof(*aux), orig_idx));
11954 static int do_check_common(struct bpf_verifier_env *env, int subprog)
11956 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
11957 struct bpf_verifier_state *state;
11958 struct bpf_reg_state *regs;
11961 env->prev_linfo = NULL;
11964 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
11967 state->curframe = 0;
11968 state->speculative = false;
11969 state->branches = 1;
11970 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
11971 if (!state->frame[0]) {
11975 env->cur_state = state;
11976 init_func_state(env, state->frame[0],
11977 BPF_MAIN_FUNC /* callsite */,
11981 regs = state->frame[state->curframe]->regs;
11982 if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
11983 ret = btf_prepare_func_args(env, subprog, regs);
11986 for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
11987 if (regs[i].type == PTR_TO_CTX)
11988 mark_reg_known_zero(env, regs, i);
11989 else if (regs[i].type == SCALAR_VALUE)
11990 mark_reg_unknown(env, regs, i);
11991 else if (regs[i].type == PTR_TO_MEM_OR_NULL) {
11992 const u32 mem_size = regs[i].mem_size;
11994 mark_reg_known_zero(env, regs, i);
11995 regs[i].mem_size = mem_size;
11996 regs[i].id = ++env->id_gen;
12000 /* 1st arg to a function */
12001 regs[BPF_REG_1].type = PTR_TO_CTX;
12002 mark_reg_known_zero(env, regs, BPF_REG_1);
12003 ret = btf_check_func_arg_match(env, subprog, regs);
12004 if (ret == -EFAULT)
12005 /* unlikely verifier bug. abort.
12006 * ret == 0 and ret < 0 are sadly acceptable for
12007 * main() function due to backward compatibility.
12008 * Like socket filter program may be written as:
12009 * int bpf_prog(struct pt_regs *ctx)
12010 * and never dereference that ctx in the program.
12011 * 'struct pt_regs' is a type mismatch for socket
12012 * filter that should be using 'struct __sk_buff'.
12017 ret = do_check(env);
12019 /* check for NULL is necessary, since cur_state can be freed inside
12020 * do_check() under memory pressure.
12022 if (env->cur_state) {
12023 free_verifier_state(env->cur_state, true);
12024 env->cur_state = NULL;
12026 while (!pop_stack(env, NULL, NULL, false));
12027 if (!ret && pop_log)
12028 bpf_vlog_reset(&env->log, 0);
12031 /* clean aux data in case subprog was rejected */
12032 sanitize_insn_aux_data(env);
12036 /* Verify all global functions in a BPF program one by one based on their BTF.
12037 * All global functions must pass verification. Otherwise the whole program is rejected.
12048 * foo() will be verified first for R1=any_scalar_value. During verification it
12049 * will be assumed that bar() already verified successfully and call to bar()
12050 * from foo() will be checked for type match only. Later bar() will be verified
12051 * independently to check that it's safe for R1=any_scalar_value.
12053 static int do_check_subprogs(struct bpf_verifier_env *env)
12055 struct bpf_prog_aux *aux = env->prog->aux;
12058 if (!aux->func_info)
12061 for (i = 1; i < env->subprog_cnt; i++) {
12062 if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
12064 env->insn_idx = env->subprog_info[i].start;
12065 WARN_ON_ONCE(env->insn_idx == 0);
12066 ret = do_check_common(env, i);
12069 } else if (env->log.level & BPF_LOG_LEVEL) {
12071 "Func#%d is safe for any args that match its prototype\n",
12078 static int do_check_main(struct bpf_verifier_env *env)
12083 ret = do_check_common(env, 0);
12085 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
12090 static void print_verification_stats(struct bpf_verifier_env *env)
12094 if (env->log.level & BPF_LOG_STATS) {
12095 verbose(env, "verification time %lld usec\n",
12096 div_u64(env->verification_time, 1000));
12097 verbose(env, "stack depth ");
12098 for (i = 0; i < env->subprog_cnt; i++) {
12099 u32 depth = env->subprog_info[i].stack_depth;
12101 verbose(env, "%d", depth);
12102 if (i + 1 < env->subprog_cnt)
12105 verbose(env, "\n");
12107 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
12108 "total_states %d peak_states %d mark_read %d\n",
12109 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
12110 env->max_states_per_insn, env->total_states,
12111 env->peak_states, env->longest_mark_read_walk);
12114 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
12116 const struct btf_type *t, *func_proto;
12117 const struct bpf_struct_ops *st_ops;
12118 const struct btf_member *member;
12119 struct bpf_prog *prog = env->prog;
12120 u32 btf_id, member_idx;
12123 btf_id = prog->aux->attach_btf_id;
12124 st_ops = bpf_struct_ops_find(btf_id);
12126 verbose(env, "attach_btf_id %u is not a supported struct\n",
12132 member_idx = prog->expected_attach_type;
12133 if (member_idx >= btf_type_vlen(t)) {
12134 verbose(env, "attach to invalid member idx %u of struct %s\n",
12135 member_idx, st_ops->name);
12139 member = &btf_type_member(t)[member_idx];
12140 mname = btf_name_by_offset(btf_vmlinux, member->name_off);
12141 func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
12144 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
12145 mname, member_idx, st_ops->name);
12149 if (st_ops->check_member) {
12150 int err = st_ops->check_member(t, member);
12153 verbose(env, "attach to unsupported member %s of struct %s\n",
12154 mname, st_ops->name);
12159 prog->aux->attach_func_proto = func_proto;
12160 prog->aux->attach_func_name = mname;
12161 env->ops = st_ops->verifier_ops;
12165 #define SECURITY_PREFIX "security_"
12167 static int check_attach_modify_return(unsigned long addr, const char *func_name)
12169 if (within_error_injection_list(addr) ||
12170 !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
12176 /* list of non-sleepable functions that are otherwise on
12177 * ALLOW_ERROR_INJECTION list
12179 BTF_SET_START(btf_non_sleepable_error_inject)
12180 /* Three functions below can be called from sleepable and non-sleepable context.
12181 * Assume non-sleepable from bpf safety point of view.
12183 BTF_ID(func, __add_to_page_cache_locked)
12184 BTF_ID(func, should_fail_alloc_page)
12185 BTF_ID(func, should_failslab)
12186 BTF_SET_END(btf_non_sleepable_error_inject)
12188 static int check_non_sleepable_error_inject(u32 btf_id)
12190 return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
12193 int bpf_check_attach_target(struct bpf_verifier_log *log,
12194 const struct bpf_prog *prog,
12195 const struct bpf_prog *tgt_prog,
12197 struct bpf_attach_target_info *tgt_info)
12199 bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
12200 const char prefix[] = "btf_trace_";
12201 int ret = 0, subprog = -1, i;
12202 const struct btf_type *t;
12203 bool conservative = true;
12209 bpf_log(log, "Tracing programs must provide btf_id\n");
12212 btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
12215 "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
12218 t = btf_type_by_id(btf, btf_id);
12220 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
12223 tname = btf_name_by_offset(btf, t->name_off);
12225 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
12229 struct bpf_prog_aux *aux = tgt_prog->aux;
12231 for (i = 0; i < aux->func_info_cnt; i++)
12232 if (aux->func_info[i].type_id == btf_id) {
12236 if (subprog == -1) {
12237 bpf_log(log, "Subprog %s doesn't exist\n", tname);
12240 conservative = aux->func_info_aux[subprog].unreliable;
12241 if (prog_extension) {
12242 if (conservative) {
12244 "Cannot replace static functions\n");
12247 if (!prog->jit_requested) {
12249 "Extension programs should be JITed\n");
12253 if (!tgt_prog->jited) {
12254 bpf_log(log, "Can attach to only JITed progs\n");
12257 if (tgt_prog->type == prog->type) {
12258 /* Cannot fentry/fexit another fentry/fexit program.
12259 * Cannot attach program extension to another extension.
12260 * It's ok to attach fentry/fexit to extension program.
12262 bpf_log(log, "Cannot recursively attach\n");
12265 if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
12267 (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
12268 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
12269 /* Program extensions can extend all program types
12270 * except fentry/fexit. The reason is the following.
12271 * The fentry/fexit programs are used for performance
12272 * analysis, stats and can be attached to any program
12273 * type except themselves. When extension program is
12274 * replacing XDP function it is necessary to allow
12275 * performance analysis of all functions. Both original
12276 * XDP program and its program extension. Hence
12277 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
12278 * allowed. If extending of fentry/fexit was allowed it
12279 * would be possible to create long call chain
12280 * fentry->extension->fentry->extension beyond
12281 * reasonable stack size. Hence extending fentry is not
12284 bpf_log(log, "Cannot extend fentry/fexit\n");
12288 if (prog_extension) {
12289 bpf_log(log, "Cannot replace kernel functions\n");
12294 switch (prog->expected_attach_type) {
12295 case BPF_TRACE_RAW_TP:
12298 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
12301 if (!btf_type_is_typedef(t)) {
12302 bpf_log(log, "attach_btf_id %u is not a typedef\n",
12306 if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
12307 bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
12311 tname += sizeof(prefix) - 1;
12312 t = btf_type_by_id(btf, t->type);
12313 if (!btf_type_is_ptr(t))
12314 /* should never happen in valid vmlinux build */
12316 t = btf_type_by_id(btf, t->type);
12317 if (!btf_type_is_func_proto(t))
12318 /* should never happen in valid vmlinux build */
12322 case BPF_TRACE_ITER:
12323 if (!btf_type_is_func(t)) {
12324 bpf_log(log, "attach_btf_id %u is not a function\n",
12328 t = btf_type_by_id(btf, t->type);
12329 if (!btf_type_is_func_proto(t))
12331 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
12336 if (!prog_extension)
12339 case BPF_MODIFY_RETURN:
12341 case BPF_TRACE_FENTRY:
12342 case BPF_TRACE_FEXIT:
12343 if (!btf_type_is_func(t)) {
12344 bpf_log(log, "attach_btf_id %u is not a function\n",
12348 if (prog_extension &&
12349 btf_check_type_match(log, prog, btf, t))
12351 t = btf_type_by_id(btf, t->type);
12352 if (!btf_type_is_func_proto(t))
12355 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
12356 (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
12357 prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
12360 if (tgt_prog && conservative)
12363 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
12369 addr = (long) tgt_prog->bpf_func;
12371 addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
12373 addr = kallsyms_lookup_name(tname);
12376 "The address of function %s cannot be found\n",
12382 if (prog->aux->sleepable) {
12384 switch (prog->type) {
12385 case BPF_PROG_TYPE_TRACING:
12386 /* fentry/fexit/fmod_ret progs can be sleepable only if they are
12387 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
12389 if (!check_non_sleepable_error_inject(btf_id) &&
12390 within_error_injection_list(addr))
12393 case BPF_PROG_TYPE_LSM:
12394 /* LSM progs check that they are attached to bpf_lsm_*() funcs.
12395 * Only some of them are sleepable.
12397 if (bpf_lsm_is_sleepable_hook(btf_id))
12404 bpf_log(log, "%s is not sleepable\n", tname);
12407 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
12409 bpf_log(log, "can't modify return codes of BPF programs\n");
12412 ret = check_attach_modify_return(addr, tname);
12414 bpf_log(log, "%s() is not modifiable\n", tname);
12421 tgt_info->tgt_addr = addr;
12422 tgt_info->tgt_name = tname;
12423 tgt_info->tgt_type = t;
12427 static int check_attach_btf_id(struct bpf_verifier_env *env)
12429 struct bpf_prog *prog = env->prog;
12430 struct bpf_prog *tgt_prog = prog->aux->dst_prog;
12431 struct bpf_attach_target_info tgt_info = {};
12432 u32 btf_id = prog->aux->attach_btf_id;
12433 struct bpf_trampoline *tr;
12437 if (prog->aux->sleepable && prog->type != BPF_PROG_TYPE_TRACING &&
12438 prog->type != BPF_PROG_TYPE_LSM) {
12439 verbose(env, "Only fentry/fexit/fmod_ret and lsm programs can be sleepable\n");
12443 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
12444 return check_struct_ops_btf_id(env);
12446 if (prog->type != BPF_PROG_TYPE_TRACING &&
12447 prog->type != BPF_PROG_TYPE_LSM &&
12448 prog->type != BPF_PROG_TYPE_EXT)
12451 ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
12455 if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
12456 /* to make freplace equivalent to their targets, they need to
12457 * inherit env->ops and expected_attach_type for the rest of the
12460 env->ops = bpf_verifier_ops[tgt_prog->type];
12461 prog->expected_attach_type = tgt_prog->expected_attach_type;
12464 /* store info about the attachment target that will be used later */
12465 prog->aux->attach_func_proto = tgt_info.tgt_type;
12466 prog->aux->attach_func_name = tgt_info.tgt_name;
12469 prog->aux->saved_dst_prog_type = tgt_prog->type;
12470 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
12473 if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
12474 prog->aux->attach_btf_trace = true;
12476 } else if (prog->expected_attach_type == BPF_TRACE_ITER) {
12477 if (!bpf_iter_prog_supported(prog))
12482 if (prog->type == BPF_PROG_TYPE_LSM) {
12483 ret = bpf_lsm_verify_prog(&env->log, prog);
12488 key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
12489 tr = bpf_trampoline_get(key, &tgt_info);
12493 prog->aux->dst_trampoline = tr;
12497 struct btf *bpf_get_btf_vmlinux(void)
12499 if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
12500 mutex_lock(&bpf_verifier_lock);
12502 btf_vmlinux = btf_parse_vmlinux();
12503 mutex_unlock(&bpf_verifier_lock);
12505 return btf_vmlinux;
12508 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr,
12509 union bpf_attr __user *uattr)
12511 u64 start_time = ktime_get_ns();
12512 struct bpf_verifier_env *env;
12513 struct bpf_verifier_log *log;
12514 int i, len, ret = -EINVAL;
12517 /* no program is valid */
12518 if (ARRAY_SIZE(bpf_verifier_ops) == 0)
12521 /* 'struct bpf_verifier_env' can be global, but since it's not small,
12522 * allocate/free it every time bpf_check() is called
12524 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
12529 len = (*prog)->len;
12530 env->insn_aux_data =
12531 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
12533 if (!env->insn_aux_data)
12535 for (i = 0; i < len; i++)
12536 env->insn_aux_data[i].orig_idx = i;
12538 env->ops = bpf_verifier_ops[env->prog->type];
12539 is_priv = bpf_capable();
12541 bpf_get_btf_vmlinux();
12543 /* grab the mutex to protect few globals used by verifier */
12545 mutex_lock(&bpf_verifier_lock);
12547 if (attr->log_level || attr->log_buf || attr->log_size) {
12548 /* user requested verbose verifier output
12549 * and supplied buffer to store the verification trace
12551 log->level = attr->log_level;
12552 log->ubuf = (char __user *) (unsigned long) attr->log_buf;
12553 log->len_total = attr->log_size;
12556 /* log attributes have to be sane */
12557 if (log->len_total < 128 || log->len_total > UINT_MAX >> 2 ||
12558 !log->level || !log->ubuf || log->level & ~BPF_LOG_MASK)
12562 if (IS_ERR(btf_vmlinux)) {
12563 /* Either gcc or pahole or kernel are broken. */
12564 verbose(env, "in-kernel BTF is malformed\n");
12565 ret = PTR_ERR(btf_vmlinux);
12566 goto skip_full_check;
12569 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
12570 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
12571 env->strict_alignment = true;
12572 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
12573 env->strict_alignment = false;
12575 env->allow_ptr_leaks = bpf_allow_ptr_leaks();
12576 env->allow_uninit_stack = bpf_allow_uninit_stack();
12577 env->allow_ptr_to_map_access = bpf_allow_ptr_to_map_access();
12578 env->bypass_spec_v1 = bpf_bypass_spec_v1();
12579 env->bypass_spec_v4 = bpf_bypass_spec_v4();
12580 env->bpf_capable = bpf_capable();
12583 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
12585 if (bpf_prog_is_dev_bound(env->prog->aux)) {
12586 ret = bpf_prog_offload_verifier_prep(env->prog);
12588 goto skip_full_check;
12591 env->explored_states = kvcalloc(state_htab_size(env),
12592 sizeof(struct bpf_verifier_state_list *),
12595 if (!env->explored_states)
12596 goto skip_full_check;
12598 ret = check_subprogs(env);
12600 goto skip_full_check;
12602 ret = check_btf_info(env, attr, uattr);
12604 goto skip_full_check;
12606 ret = check_attach_btf_id(env);
12608 goto skip_full_check;
12610 ret = resolve_pseudo_ldimm64(env);
12612 goto skip_full_check;
12614 ret = check_cfg(env);
12616 goto skip_full_check;
12618 ret = do_check_subprogs(env);
12619 ret = ret ?: do_check_main(env);
12621 if (ret == 0 && bpf_prog_is_dev_bound(env->prog->aux))
12622 ret = bpf_prog_offload_finalize(env);
12625 kvfree(env->explored_states);
12628 ret = check_max_stack_depth(env);
12630 /* instruction rewrites happen after this point */
12633 opt_hard_wire_dead_code_branches(env);
12635 ret = opt_remove_dead_code(env);
12637 ret = opt_remove_nops(env);
12640 sanitize_dead_code(env);
12644 /* program is valid, convert *(u32*)(ctx + off) accesses */
12645 ret = convert_ctx_accesses(env);
12648 ret = fixup_bpf_calls(env);
12650 /* do 32-bit optimization after insn patching has done so those patched
12651 * insns could be handled correctly.
12653 if (ret == 0 && !bpf_prog_is_dev_bound(env->prog->aux)) {
12654 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
12655 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
12660 ret = fixup_call_args(env);
12662 env->verification_time = ktime_get_ns() - start_time;
12663 print_verification_stats(env);
12665 if (log->level && bpf_verifier_log_full(log))
12667 if (log->level && !log->ubuf) {
12669 goto err_release_maps;
12673 goto err_release_maps;
12675 if (env->used_map_cnt) {
12676 /* if program passed verifier, update used_maps in bpf_prog_info */
12677 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
12678 sizeof(env->used_maps[0]),
12681 if (!env->prog->aux->used_maps) {
12683 goto err_release_maps;
12686 memcpy(env->prog->aux->used_maps, env->used_maps,
12687 sizeof(env->used_maps[0]) * env->used_map_cnt);
12688 env->prog->aux->used_map_cnt = env->used_map_cnt;
12690 if (env->used_btf_cnt) {
12691 /* if program passed verifier, update used_btfs in bpf_prog_aux */
12692 env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
12693 sizeof(env->used_btfs[0]),
12695 if (!env->prog->aux->used_btfs) {
12697 goto err_release_maps;
12700 memcpy(env->prog->aux->used_btfs, env->used_btfs,
12701 sizeof(env->used_btfs[0]) * env->used_btf_cnt);
12702 env->prog->aux->used_btf_cnt = env->used_btf_cnt;
12704 if (env->used_map_cnt || env->used_btf_cnt) {
12705 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
12706 * bpf_ld_imm64 instructions
12708 convert_pseudo_ld_imm64(env);
12711 adjust_btf_func(env);
12714 if (!env->prog->aux->used_maps)
12715 /* if we didn't copy map pointers into bpf_prog_info, release
12716 * them now. Otherwise free_used_maps() will release them.
12719 if (!env->prog->aux->used_btfs)
12722 /* extension progs temporarily inherit the attach_type of their targets
12723 for verification purposes, so set it back to zero before returning
12725 if (env->prog->type == BPF_PROG_TYPE_EXT)
12726 env->prog->expected_attach_type = 0;
12731 mutex_unlock(&bpf_verifier_lock);
12732 vfree(env->insn_aux_data);