1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com
3 * Copyright (c) 2016 Facebook
4 * Copyright (c) 2018 Covalent IO, Inc. http://covalent.io
6 #include <uapi/linux/btf.h>
7 #include <linux/kernel.h>
8 #include <linux/types.h>
9 #include <linux/slab.h>
10 #include <linux/bpf.h>
11 #include <linux/btf.h>
12 #include <linux/bpf_verifier.h>
13 #include <linux/filter.h>
14 #include <net/netlink.h>
15 #include <linux/file.h>
16 #include <linux/vmalloc.h>
17 #include <linux/stringify.h>
18 #include <linux/bsearch.h>
19 #include <linux/sort.h>
20 #include <linux/perf_event.h>
21 #include <linux/ctype.h>
22 #include <linux/error-injection.h>
23 #include <linux/bpf_lsm.h>
24 #include <linux/btf_ids.h>
28 static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
29 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
30 [_id] = & _name ## _verifier_ops,
31 #define BPF_MAP_TYPE(_id, _ops)
32 #define BPF_LINK_TYPE(_id, _name)
33 #include <linux/bpf_types.h>
39 /* bpf_check() is a static code analyzer that walks eBPF program
40 * instruction by instruction and updates register/stack state.
41 * All paths of conditional branches are analyzed until 'bpf_exit' insn.
43 * The first pass is depth-first-search to check that the program is a DAG.
44 * It rejects the following programs:
45 * - larger than BPF_MAXINSNS insns
46 * - if loop is present (detected via back-edge)
47 * - unreachable insns exist (shouldn't be a forest. program = one function)
48 * - out of bounds or malformed jumps
49 * The second pass is all possible path descent from the 1st insn.
50 * Since it's analyzing all pathes through the program, the length of the
51 * analysis is limited to 64k insn, which may be hit even if total number of
52 * insn is less then 4K, but there are too many branches that change stack/regs.
53 * Number of 'branches to be analyzed' is limited to 1k
55 * On entry to each instruction, each register has a type, and the instruction
56 * changes the types of the registers depending on instruction semantics.
57 * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
60 * All registers are 64-bit.
61 * R0 - return register
62 * R1-R5 argument passing registers
63 * R6-R9 callee saved registers
64 * R10 - frame pointer read-only
66 * At the start of BPF program the register R1 contains a pointer to bpf_context
67 * and has type PTR_TO_CTX.
69 * Verifier tracks arithmetic operations on pointers in case:
70 * BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
71 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
72 * 1st insn copies R10 (which has FRAME_PTR) type into R1
73 * and 2nd arithmetic instruction is pattern matched to recognize
74 * that it wants to construct a pointer to some element within stack.
75 * So after 2nd insn, the register R1 has type PTR_TO_STACK
76 * (and -20 constant is saved for further stack bounds checking).
77 * Meaning that this reg is a pointer to stack plus known immediate constant.
79 * Most of the time the registers have SCALAR_VALUE type, which
80 * means the register has some value, but it's not a valid pointer.
81 * (like pointer plus pointer becomes SCALAR_VALUE type)
83 * When verifier sees load or store instructions the type of base register
84 * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are
85 * four pointer types recognized by check_mem_access() function.
87 * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
88 * and the range of [ptr, ptr + map's value_size) is accessible.
90 * registers used to pass values to function calls are checked against
91 * function argument constraints.
93 * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
94 * It means that the register type passed to this function must be
95 * PTR_TO_STACK and it will be used inside the function as
96 * 'pointer to map element key'
98 * For example the argument constraints for bpf_map_lookup_elem():
99 * .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
100 * .arg1_type = ARG_CONST_MAP_PTR,
101 * .arg2_type = ARG_PTR_TO_MAP_KEY,
103 * ret_type says that this function returns 'pointer to map elem value or null'
104 * function expects 1st argument to be a const pointer to 'struct bpf_map' and
105 * 2nd argument should be a pointer to stack, which will be used inside
106 * the helper function as a pointer to map element key.
108 * On the kernel side the helper function looks like:
109 * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
111 * struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
112 * void *key = (void *) (unsigned long) r2;
115 * here kernel can access 'key' and 'map' pointers safely, knowing that
116 * [key, key + map->key_size) bytes are valid and were initialized on
117 * the stack of eBPF program.
120 * Corresponding eBPF program may look like:
121 * BPF_MOV64_REG(BPF_REG_2, BPF_REG_10), // after this insn R2 type is FRAME_PTR
122 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
123 * BPF_LD_MAP_FD(BPF_REG_1, map_fd), // after this insn R1 type is CONST_PTR_TO_MAP
124 * BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
125 * here verifier looks at prototype of map_lookup_elem() and sees:
126 * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
127 * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
129 * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
130 * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
131 * and were initialized prior to this call.
132 * If it's ok, then verifier allows this BPF_CALL insn and looks at
133 * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
134 * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
135 * returns ether pointer to map value or NULL.
137 * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
138 * insn, the register holding that pointer in the true branch changes state to
139 * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
140 * branch. See check_cond_jmp_op().
142 * After the call R0 is set to return type of the function and registers R1-R5
143 * are set to NOT_INIT to indicate that they are no longer readable.
145 * The following reference types represent a potential reference to a kernel
146 * resource which, after first being allocated, must be checked and freed by
148 * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET
150 * When the verifier sees a helper call return a reference type, it allocates a
151 * pointer id for the reference and stores it in the current function state.
152 * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into
153 * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type
154 * passes through a NULL-check conditional. For the branch wherein the state is
155 * changed to CONST_IMM, the verifier releases the reference.
157 * For each helper function that allocates a reference, such as
158 * bpf_sk_lookup_tcp(), there is a corresponding release function, such as
159 * bpf_sk_release(). When a reference type passes into the release function,
160 * the verifier also releases the reference. If any unchecked or unreleased
161 * reference remains at the end of the program, the verifier rejects it.
164 /* verifier_state + insn_idx are pushed to stack when branch is encountered */
165 struct bpf_verifier_stack_elem {
166 /* verifer state is 'st'
167 * before processing instruction 'insn_idx'
168 * and after processing instruction 'prev_insn_idx'
170 struct bpf_verifier_state st;
173 struct bpf_verifier_stack_elem *next;
174 /* length of verifier log at the time this state was pushed on stack */
178 #define BPF_COMPLEXITY_LIMIT_JMP_SEQ 8192
179 #define BPF_COMPLEXITY_LIMIT_STATES 64
181 #define BPF_MAP_KEY_POISON (1ULL << 63)
182 #define BPF_MAP_KEY_SEEN (1ULL << 62)
184 #define BPF_MAP_PTR_UNPRIV 1UL
185 #define BPF_MAP_PTR_POISON ((void *)((0xeB9FUL << 1) + \
186 POISON_POINTER_DELTA))
187 #define BPF_MAP_PTR(X) ((struct bpf_map *)((X) & ~BPF_MAP_PTR_UNPRIV))
189 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux)
191 return BPF_MAP_PTR(aux->map_ptr_state) == BPF_MAP_PTR_POISON;
194 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux)
196 return aux->map_ptr_state & BPF_MAP_PTR_UNPRIV;
199 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
200 const struct bpf_map *map, bool unpriv)
202 BUILD_BUG_ON((unsigned long)BPF_MAP_PTR_POISON & BPF_MAP_PTR_UNPRIV);
203 unpriv |= bpf_map_ptr_unpriv(aux);
204 aux->map_ptr_state = (unsigned long)map |
205 (unpriv ? BPF_MAP_PTR_UNPRIV : 0UL);
208 static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux)
210 return aux->map_key_state & BPF_MAP_KEY_POISON;
213 static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux)
215 return !(aux->map_key_state & BPF_MAP_KEY_SEEN);
218 static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux)
220 return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON);
223 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state)
225 bool poisoned = bpf_map_key_poisoned(aux);
227 aux->map_key_state = state | BPF_MAP_KEY_SEEN |
228 (poisoned ? BPF_MAP_KEY_POISON : 0ULL);
231 struct bpf_call_arg_meta {
232 struct bpf_map *map_ptr;
245 struct btf *btf_vmlinux;
247 static DEFINE_MUTEX(bpf_verifier_lock);
249 static const struct bpf_line_info *
250 find_linfo(const struct bpf_verifier_env *env, u32 insn_off)
252 const struct bpf_line_info *linfo;
253 const struct bpf_prog *prog;
257 nr_linfo = prog->aux->nr_linfo;
259 if (!nr_linfo || insn_off >= prog->len)
262 linfo = prog->aux->linfo;
263 for (i = 1; i < nr_linfo; i++)
264 if (insn_off < linfo[i].insn_off)
267 return &linfo[i - 1];
270 void bpf_verifier_vlog(struct bpf_verifier_log *log, const char *fmt,
275 n = vscnprintf(log->kbuf, BPF_VERIFIER_TMP_LOG_SIZE, fmt, args);
277 WARN_ONCE(n >= BPF_VERIFIER_TMP_LOG_SIZE - 1,
278 "verifier log line truncated - local buffer too short\n");
280 n = min(log->len_total - log->len_used - 1, n);
283 if (log->level == BPF_LOG_KERNEL) {
284 pr_err("BPF:%s\n", log->kbuf);
287 if (!copy_to_user(log->ubuf + log->len_used, log->kbuf, n + 1))
293 static void bpf_vlog_reset(struct bpf_verifier_log *log, u32 new_pos)
297 if (!bpf_verifier_log_needed(log))
300 log->len_used = new_pos;
301 if (put_user(zero, log->ubuf + new_pos))
305 /* log_level controls verbosity level of eBPF verifier.
306 * bpf_verifier_log_write() is used to dump the verification trace to the log,
307 * so the user can figure out what's wrong with the program
309 __printf(2, 3) void bpf_verifier_log_write(struct bpf_verifier_env *env,
310 const char *fmt, ...)
314 if (!bpf_verifier_log_needed(&env->log))
318 bpf_verifier_vlog(&env->log, fmt, args);
321 EXPORT_SYMBOL_GPL(bpf_verifier_log_write);
323 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
325 struct bpf_verifier_env *env = private_data;
328 if (!bpf_verifier_log_needed(&env->log))
332 bpf_verifier_vlog(&env->log, fmt, args);
336 __printf(2, 3) void bpf_log(struct bpf_verifier_log *log,
337 const char *fmt, ...)
341 if (!bpf_verifier_log_needed(log))
345 bpf_verifier_vlog(log, fmt, args);
349 static const char *ltrim(const char *s)
357 __printf(3, 4) static void verbose_linfo(struct bpf_verifier_env *env,
359 const char *prefix_fmt, ...)
361 const struct bpf_line_info *linfo;
363 if (!bpf_verifier_log_needed(&env->log))
366 linfo = find_linfo(env, insn_off);
367 if (!linfo || linfo == env->prev_linfo)
373 va_start(args, prefix_fmt);
374 bpf_verifier_vlog(&env->log, prefix_fmt, args);
379 ltrim(btf_name_by_offset(env->prog->aux->btf,
382 env->prev_linfo = linfo;
385 static bool type_is_pkt_pointer(enum bpf_reg_type type)
387 return type == PTR_TO_PACKET ||
388 type == PTR_TO_PACKET_META;
391 static bool type_is_sk_pointer(enum bpf_reg_type type)
393 return type == PTR_TO_SOCKET ||
394 type == PTR_TO_SOCK_COMMON ||
395 type == PTR_TO_TCP_SOCK ||
396 type == PTR_TO_XDP_SOCK;
399 static bool reg_type_not_null(enum bpf_reg_type type)
401 return type == PTR_TO_SOCKET ||
402 type == PTR_TO_TCP_SOCK ||
403 type == PTR_TO_MAP_VALUE ||
404 type == PTR_TO_SOCK_COMMON;
407 static bool reg_type_may_be_null(enum bpf_reg_type type)
409 return type == PTR_TO_MAP_VALUE_OR_NULL ||
410 type == PTR_TO_SOCKET_OR_NULL ||
411 type == PTR_TO_SOCK_COMMON_OR_NULL ||
412 type == PTR_TO_TCP_SOCK_OR_NULL ||
413 type == PTR_TO_BTF_ID_OR_NULL ||
414 type == PTR_TO_MEM_OR_NULL ||
415 type == PTR_TO_RDONLY_BUF_OR_NULL ||
416 type == PTR_TO_RDWR_BUF_OR_NULL;
419 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
421 return reg->type == PTR_TO_MAP_VALUE &&
422 map_value_has_spin_lock(reg->map_ptr);
425 static bool reg_type_may_be_refcounted_or_null(enum bpf_reg_type type)
427 return type == PTR_TO_SOCKET ||
428 type == PTR_TO_SOCKET_OR_NULL ||
429 type == PTR_TO_TCP_SOCK ||
430 type == PTR_TO_TCP_SOCK_OR_NULL ||
431 type == PTR_TO_MEM ||
432 type == PTR_TO_MEM_OR_NULL;
435 static bool arg_type_may_be_refcounted(enum bpf_arg_type type)
437 return type == ARG_PTR_TO_SOCK_COMMON;
440 static bool arg_type_may_be_null(enum bpf_arg_type type)
442 return type == ARG_PTR_TO_MAP_VALUE_OR_NULL ||
443 type == ARG_PTR_TO_MEM_OR_NULL ||
444 type == ARG_PTR_TO_CTX_OR_NULL ||
445 type == ARG_PTR_TO_SOCKET_OR_NULL ||
446 type == ARG_PTR_TO_ALLOC_MEM_OR_NULL;
449 /* Determine whether the function releases some resources allocated by another
450 * function call. The first reference type argument will be assumed to be
451 * released by release_reference().
453 static bool is_release_function(enum bpf_func_id func_id)
455 return func_id == BPF_FUNC_sk_release ||
456 func_id == BPF_FUNC_ringbuf_submit ||
457 func_id == BPF_FUNC_ringbuf_discard;
460 static bool may_be_acquire_function(enum bpf_func_id func_id)
462 return func_id == BPF_FUNC_sk_lookup_tcp ||
463 func_id == BPF_FUNC_sk_lookup_udp ||
464 func_id == BPF_FUNC_skc_lookup_tcp ||
465 func_id == BPF_FUNC_map_lookup_elem ||
466 func_id == BPF_FUNC_ringbuf_reserve;
469 static bool is_acquire_function(enum bpf_func_id func_id,
470 const struct bpf_map *map)
472 enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
474 if (func_id == BPF_FUNC_sk_lookup_tcp ||
475 func_id == BPF_FUNC_sk_lookup_udp ||
476 func_id == BPF_FUNC_skc_lookup_tcp ||
477 func_id == BPF_FUNC_ringbuf_reserve)
480 if (func_id == BPF_FUNC_map_lookup_elem &&
481 (map_type == BPF_MAP_TYPE_SOCKMAP ||
482 map_type == BPF_MAP_TYPE_SOCKHASH))
488 static bool is_ptr_cast_function(enum bpf_func_id func_id)
490 return func_id == BPF_FUNC_tcp_sock ||
491 func_id == BPF_FUNC_sk_fullsock ||
492 func_id == BPF_FUNC_skc_to_tcp_sock ||
493 func_id == BPF_FUNC_skc_to_tcp6_sock ||
494 func_id == BPF_FUNC_skc_to_udp6_sock ||
495 func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
496 func_id == BPF_FUNC_skc_to_tcp_request_sock;
499 /* string representation of 'enum bpf_reg_type' */
500 static const char * const reg_type_str[] = {
502 [SCALAR_VALUE] = "inv",
503 [PTR_TO_CTX] = "ctx",
504 [CONST_PTR_TO_MAP] = "map_ptr",
505 [PTR_TO_MAP_VALUE] = "map_value",
506 [PTR_TO_MAP_VALUE_OR_NULL] = "map_value_or_null",
507 [PTR_TO_STACK] = "fp",
508 [PTR_TO_PACKET] = "pkt",
509 [PTR_TO_PACKET_META] = "pkt_meta",
510 [PTR_TO_PACKET_END] = "pkt_end",
511 [PTR_TO_FLOW_KEYS] = "flow_keys",
512 [PTR_TO_SOCKET] = "sock",
513 [PTR_TO_SOCKET_OR_NULL] = "sock_or_null",
514 [PTR_TO_SOCK_COMMON] = "sock_common",
515 [PTR_TO_SOCK_COMMON_OR_NULL] = "sock_common_or_null",
516 [PTR_TO_TCP_SOCK] = "tcp_sock",
517 [PTR_TO_TCP_SOCK_OR_NULL] = "tcp_sock_or_null",
518 [PTR_TO_TP_BUFFER] = "tp_buffer",
519 [PTR_TO_XDP_SOCK] = "xdp_sock",
520 [PTR_TO_BTF_ID] = "ptr_",
521 [PTR_TO_BTF_ID_OR_NULL] = "ptr_or_null_",
522 [PTR_TO_PERCPU_BTF_ID] = "percpu_ptr_",
523 [PTR_TO_MEM] = "mem",
524 [PTR_TO_MEM_OR_NULL] = "mem_or_null",
525 [PTR_TO_RDONLY_BUF] = "rdonly_buf",
526 [PTR_TO_RDONLY_BUF_OR_NULL] = "rdonly_buf_or_null",
527 [PTR_TO_RDWR_BUF] = "rdwr_buf",
528 [PTR_TO_RDWR_BUF_OR_NULL] = "rdwr_buf_or_null",
531 static char slot_type_char[] = {
532 [STACK_INVALID] = '?',
538 static void print_liveness(struct bpf_verifier_env *env,
539 enum bpf_reg_liveness live)
541 if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE))
543 if (live & REG_LIVE_READ)
545 if (live & REG_LIVE_WRITTEN)
547 if (live & REG_LIVE_DONE)
551 static struct bpf_func_state *func(struct bpf_verifier_env *env,
552 const struct bpf_reg_state *reg)
554 struct bpf_verifier_state *cur = env->cur_state;
556 return cur->frame[reg->frameno];
559 const char *kernel_type_name(u32 id)
561 return btf_name_by_offset(btf_vmlinux,
562 btf_type_by_id(btf_vmlinux, id)->name_off);
565 static void print_verifier_state(struct bpf_verifier_env *env,
566 const struct bpf_func_state *state)
568 const struct bpf_reg_state *reg;
573 verbose(env, " frame%d:", state->frameno);
574 for (i = 0; i < MAX_BPF_REG; i++) {
575 reg = &state->regs[i];
579 verbose(env, " R%d", i);
580 print_liveness(env, reg->live);
581 verbose(env, "=%s", reg_type_str[t]);
582 if (t == SCALAR_VALUE && reg->precise)
584 if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
585 tnum_is_const(reg->var_off)) {
586 /* reg->off should be 0 for SCALAR_VALUE */
587 verbose(env, "%lld", reg->var_off.value + reg->off);
589 if (t == PTR_TO_BTF_ID ||
590 t == PTR_TO_BTF_ID_OR_NULL ||
591 t == PTR_TO_PERCPU_BTF_ID)
592 verbose(env, "%s", kernel_type_name(reg->btf_id));
593 verbose(env, "(id=%d", reg->id);
594 if (reg_type_may_be_refcounted_or_null(t))
595 verbose(env, ",ref_obj_id=%d", reg->ref_obj_id);
596 if (t != SCALAR_VALUE)
597 verbose(env, ",off=%d", reg->off);
598 if (type_is_pkt_pointer(t))
599 verbose(env, ",r=%d", reg->range);
600 else if (t == CONST_PTR_TO_MAP ||
601 t == PTR_TO_MAP_VALUE ||
602 t == PTR_TO_MAP_VALUE_OR_NULL)
603 verbose(env, ",ks=%d,vs=%d",
604 reg->map_ptr->key_size,
605 reg->map_ptr->value_size);
606 if (tnum_is_const(reg->var_off)) {
607 /* Typically an immediate SCALAR_VALUE, but
608 * could be a pointer whose offset is too big
611 verbose(env, ",imm=%llx", reg->var_off.value);
613 if (reg->smin_value != reg->umin_value &&
614 reg->smin_value != S64_MIN)
615 verbose(env, ",smin_value=%lld",
616 (long long)reg->smin_value);
617 if (reg->smax_value != reg->umax_value &&
618 reg->smax_value != S64_MAX)
619 verbose(env, ",smax_value=%lld",
620 (long long)reg->smax_value);
621 if (reg->umin_value != 0)
622 verbose(env, ",umin_value=%llu",
623 (unsigned long long)reg->umin_value);
624 if (reg->umax_value != U64_MAX)
625 verbose(env, ",umax_value=%llu",
626 (unsigned long long)reg->umax_value);
627 if (!tnum_is_unknown(reg->var_off)) {
630 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
631 verbose(env, ",var_off=%s", tn_buf);
633 if (reg->s32_min_value != reg->smin_value &&
634 reg->s32_min_value != S32_MIN)
635 verbose(env, ",s32_min_value=%d",
636 (int)(reg->s32_min_value));
637 if (reg->s32_max_value != reg->smax_value &&
638 reg->s32_max_value != S32_MAX)
639 verbose(env, ",s32_max_value=%d",
640 (int)(reg->s32_max_value));
641 if (reg->u32_min_value != reg->umin_value &&
642 reg->u32_min_value != U32_MIN)
643 verbose(env, ",u32_min_value=%d",
644 (int)(reg->u32_min_value));
645 if (reg->u32_max_value != reg->umax_value &&
646 reg->u32_max_value != U32_MAX)
647 verbose(env, ",u32_max_value=%d",
648 (int)(reg->u32_max_value));
653 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
654 char types_buf[BPF_REG_SIZE + 1];
658 for (j = 0; j < BPF_REG_SIZE; j++) {
659 if (state->stack[i].slot_type[j] != STACK_INVALID)
661 types_buf[j] = slot_type_char[
662 state->stack[i].slot_type[j]];
664 types_buf[BPF_REG_SIZE] = 0;
667 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
668 print_liveness(env, state->stack[i].spilled_ptr.live);
669 if (state->stack[i].slot_type[0] == STACK_SPILL) {
670 reg = &state->stack[i].spilled_ptr;
672 verbose(env, "=%s", reg_type_str[t]);
673 if (t == SCALAR_VALUE && reg->precise)
675 if (t == SCALAR_VALUE && tnum_is_const(reg->var_off))
676 verbose(env, "%lld", reg->var_off.value + reg->off);
678 verbose(env, "=%s", types_buf);
681 if (state->acquired_refs && state->refs[0].id) {
682 verbose(env, " refs=%d", state->refs[0].id);
683 for (i = 1; i < state->acquired_refs; i++)
684 if (state->refs[i].id)
685 verbose(env, ",%d", state->refs[i].id);
690 #define COPY_STATE_FN(NAME, COUNT, FIELD, SIZE) \
691 static int copy_##NAME##_state(struct bpf_func_state *dst, \
692 const struct bpf_func_state *src) \
696 if (WARN_ON_ONCE(dst->COUNT < src->COUNT)) { \
697 /* internal bug, make state invalid to reject the program */ \
698 memset(dst, 0, sizeof(*dst)); \
701 memcpy(dst->FIELD, src->FIELD, \
702 sizeof(*src->FIELD) * (src->COUNT / SIZE)); \
705 /* copy_reference_state() */
706 COPY_STATE_FN(reference, acquired_refs, refs, 1)
707 /* copy_stack_state() */
708 COPY_STATE_FN(stack, allocated_stack, stack, BPF_REG_SIZE)
711 #define REALLOC_STATE_FN(NAME, COUNT, FIELD, SIZE) \
712 static int realloc_##NAME##_state(struct bpf_func_state *state, int size, \
715 u32 old_size = state->COUNT; \
716 struct bpf_##NAME##_state *new_##FIELD; \
717 int slot = size / SIZE; \
719 if (size <= old_size || !size) { \
722 state->COUNT = slot * SIZE; \
723 if (!size && old_size) { \
724 kfree(state->FIELD); \
725 state->FIELD = NULL; \
729 new_##FIELD = kmalloc_array(slot, sizeof(struct bpf_##NAME##_state), \
735 memcpy(new_##FIELD, state->FIELD, \
736 sizeof(*new_##FIELD) * (old_size / SIZE)); \
737 memset(new_##FIELD + old_size / SIZE, 0, \
738 sizeof(*new_##FIELD) * (size - old_size) / SIZE); \
740 state->COUNT = slot * SIZE; \
741 kfree(state->FIELD); \
742 state->FIELD = new_##FIELD; \
745 /* realloc_reference_state() */
746 REALLOC_STATE_FN(reference, acquired_refs, refs, 1)
747 /* realloc_stack_state() */
748 REALLOC_STATE_FN(stack, allocated_stack, stack, BPF_REG_SIZE)
749 #undef REALLOC_STATE_FN
751 /* do_check() starts with zero-sized stack in struct bpf_verifier_state to
752 * make it consume minimal amount of memory. check_stack_write() access from
753 * the program calls into realloc_func_state() to grow the stack size.
754 * Note there is a non-zero 'parent' pointer inside bpf_verifier_state
755 * which realloc_stack_state() copies over. It points to previous
756 * bpf_verifier_state which is never reallocated.
758 static int realloc_func_state(struct bpf_func_state *state, int stack_size,
759 int refs_size, bool copy_old)
761 int err = realloc_reference_state(state, refs_size, copy_old);
764 return realloc_stack_state(state, stack_size, copy_old);
767 /* Acquire a pointer id from the env and update the state->refs to include
768 * this new pointer reference.
769 * On success, returns a valid pointer id to associate with the register
770 * On failure, returns a negative errno.
772 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
774 struct bpf_func_state *state = cur_func(env);
775 int new_ofs = state->acquired_refs;
778 err = realloc_reference_state(state, state->acquired_refs + 1, true);
782 state->refs[new_ofs].id = id;
783 state->refs[new_ofs].insn_idx = insn_idx;
788 /* release function corresponding to acquire_reference_state(). Idempotent. */
789 static int release_reference_state(struct bpf_func_state *state, int ptr_id)
793 last_idx = state->acquired_refs - 1;
794 for (i = 0; i < state->acquired_refs; i++) {
795 if (state->refs[i].id == ptr_id) {
796 if (last_idx && i != last_idx)
797 memcpy(&state->refs[i], &state->refs[last_idx],
798 sizeof(*state->refs));
799 memset(&state->refs[last_idx], 0, sizeof(*state->refs));
800 state->acquired_refs--;
807 static int transfer_reference_state(struct bpf_func_state *dst,
808 struct bpf_func_state *src)
810 int err = realloc_reference_state(dst, src->acquired_refs, false);
813 err = copy_reference_state(dst, src);
819 static void free_func_state(struct bpf_func_state *state)
828 static void clear_jmp_history(struct bpf_verifier_state *state)
830 kfree(state->jmp_history);
831 state->jmp_history = NULL;
832 state->jmp_history_cnt = 0;
835 static void free_verifier_state(struct bpf_verifier_state *state,
840 for (i = 0; i <= state->curframe; i++) {
841 free_func_state(state->frame[i]);
842 state->frame[i] = NULL;
844 clear_jmp_history(state);
849 /* copy verifier state from src to dst growing dst stack space
850 * when necessary to accommodate larger src stack
852 static int copy_func_state(struct bpf_func_state *dst,
853 const struct bpf_func_state *src)
857 err = realloc_func_state(dst, src->allocated_stack, src->acquired_refs,
861 memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
862 err = copy_reference_state(dst, src);
865 return copy_stack_state(dst, src);
868 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
869 const struct bpf_verifier_state *src)
871 struct bpf_func_state *dst;
872 u32 jmp_sz = sizeof(struct bpf_idx_pair) * src->jmp_history_cnt;
875 if (dst_state->jmp_history_cnt < src->jmp_history_cnt) {
876 kfree(dst_state->jmp_history);
877 dst_state->jmp_history = kmalloc(jmp_sz, GFP_USER);
878 if (!dst_state->jmp_history)
881 memcpy(dst_state->jmp_history, src->jmp_history, jmp_sz);
882 dst_state->jmp_history_cnt = src->jmp_history_cnt;
884 /* if dst has more stack frames then src frame, free them */
885 for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
886 free_func_state(dst_state->frame[i]);
887 dst_state->frame[i] = NULL;
889 dst_state->speculative = src->speculative;
890 dst_state->curframe = src->curframe;
891 dst_state->active_spin_lock = src->active_spin_lock;
892 dst_state->branches = src->branches;
893 dst_state->parent = src->parent;
894 dst_state->first_insn_idx = src->first_insn_idx;
895 dst_state->last_insn_idx = src->last_insn_idx;
896 for (i = 0; i <= src->curframe; i++) {
897 dst = dst_state->frame[i];
899 dst = kzalloc(sizeof(*dst), GFP_KERNEL);
902 dst_state->frame[i] = dst;
904 err = copy_func_state(dst, src->frame[i]);
911 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
914 u32 br = --st->branches;
916 /* WARN_ON(br > 1) technically makes sense here,
917 * but see comment in push_stack(), hence:
919 WARN_ONCE((int)br < 0,
920 "BUG update_branch_counts:branches_to_explore=%d\n",
928 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
929 int *insn_idx, bool pop_log)
931 struct bpf_verifier_state *cur = env->cur_state;
932 struct bpf_verifier_stack_elem *elem, *head = env->head;
935 if (env->head == NULL)
939 err = copy_verifier_state(cur, &head->st);
944 bpf_vlog_reset(&env->log, head->log_pos);
946 *insn_idx = head->insn_idx;
948 *prev_insn_idx = head->prev_insn_idx;
950 free_verifier_state(&head->st, false);
957 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
958 int insn_idx, int prev_insn_idx,
961 struct bpf_verifier_state *cur = env->cur_state;
962 struct bpf_verifier_stack_elem *elem;
965 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
969 elem->insn_idx = insn_idx;
970 elem->prev_insn_idx = prev_insn_idx;
971 elem->next = env->head;
972 elem->log_pos = env->log.len_used;
975 err = copy_verifier_state(&elem->st, cur);
978 elem->st.speculative |= speculative;
979 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
980 verbose(env, "The sequence of %d jumps is too complex.\n",
984 if (elem->st.parent) {
985 ++elem->st.parent->branches;
986 /* WARN_ON(branches > 2) technically makes sense here,
988 * 1. speculative states will bump 'branches' for non-branch
990 * 2. is_state_visited() heuristics may decide not to create
991 * a new state for a sequence of branches and all such current
992 * and cloned states will be pointing to a single parent state
993 * which might have large 'branches' count.
998 free_verifier_state(env->cur_state, true);
999 env->cur_state = NULL;
1000 /* pop all elements and return */
1001 while (!pop_stack(env, NULL, NULL, false));
1005 #define CALLER_SAVED_REGS 6
1006 static const int caller_saved[CALLER_SAVED_REGS] = {
1007 BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
1010 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1011 struct bpf_reg_state *reg);
1013 /* This helper doesn't clear reg->id */
1014 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1016 reg->var_off = tnum_const(imm);
1017 reg->smin_value = (s64)imm;
1018 reg->smax_value = (s64)imm;
1019 reg->umin_value = imm;
1020 reg->umax_value = imm;
1022 reg->s32_min_value = (s32)imm;
1023 reg->s32_max_value = (s32)imm;
1024 reg->u32_min_value = (u32)imm;
1025 reg->u32_max_value = (u32)imm;
1028 /* Mark the unknown part of a register (variable offset or scalar value) as
1029 * known to have the value @imm.
1031 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1033 /* Clear id, off, and union(map_ptr, range) */
1034 memset(((u8 *)reg) + sizeof(reg->type), 0,
1035 offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
1036 ___mark_reg_known(reg, imm);
1039 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1041 reg->var_off = tnum_const_subreg(reg->var_off, imm);
1042 reg->s32_min_value = (s32)imm;
1043 reg->s32_max_value = (s32)imm;
1044 reg->u32_min_value = (u32)imm;
1045 reg->u32_max_value = (u32)imm;
1048 /* Mark the 'variable offset' part of a register as zero. This should be
1049 * used only on registers holding a pointer type.
1051 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
1053 __mark_reg_known(reg, 0);
1056 static void __mark_reg_const_zero(struct bpf_reg_state *reg)
1058 __mark_reg_known(reg, 0);
1059 reg->type = SCALAR_VALUE;
1062 static void mark_reg_known_zero(struct bpf_verifier_env *env,
1063 struct bpf_reg_state *regs, u32 regno)
1065 if (WARN_ON(regno >= MAX_BPF_REG)) {
1066 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
1067 /* Something bad happened, let's kill all regs */
1068 for (regno = 0; regno < MAX_BPF_REG; regno++)
1069 __mark_reg_not_init(env, regs + regno);
1072 __mark_reg_known_zero(regs + regno);
1075 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1077 return type_is_pkt_pointer(reg->type);
1080 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
1082 return reg_is_pkt_pointer(reg) ||
1083 reg->type == PTR_TO_PACKET_END;
1086 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
1087 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
1088 enum bpf_reg_type which)
1090 /* The register can already have a range from prior markings.
1091 * This is fine as long as it hasn't been advanced from its
1094 return reg->type == which &&
1097 tnum_equals_const(reg->var_off, 0);
1100 /* Reset the min/max bounds of a register */
1101 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
1103 reg->smin_value = S64_MIN;
1104 reg->smax_value = S64_MAX;
1105 reg->umin_value = 0;
1106 reg->umax_value = U64_MAX;
1108 reg->s32_min_value = S32_MIN;
1109 reg->s32_max_value = S32_MAX;
1110 reg->u32_min_value = 0;
1111 reg->u32_max_value = U32_MAX;
1114 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
1116 reg->smin_value = S64_MIN;
1117 reg->smax_value = S64_MAX;
1118 reg->umin_value = 0;
1119 reg->umax_value = U64_MAX;
1122 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
1124 reg->s32_min_value = S32_MIN;
1125 reg->s32_max_value = S32_MAX;
1126 reg->u32_min_value = 0;
1127 reg->u32_max_value = U32_MAX;
1130 static void __update_reg32_bounds(struct bpf_reg_state *reg)
1132 struct tnum var32_off = tnum_subreg(reg->var_off);
1134 /* min signed is max(sign bit) | min(other bits) */
1135 reg->s32_min_value = max_t(s32, reg->s32_min_value,
1136 var32_off.value | (var32_off.mask & S32_MIN));
1137 /* max signed is min(sign bit) | max(other bits) */
1138 reg->s32_max_value = min_t(s32, reg->s32_max_value,
1139 var32_off.value | (var32_off.mask & S32_MAX));
1140 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
1141 reg->u32_max_value = min(reg->u32_max_value,
1142 (u32)(var32_off.value | var32_off.mask));
1145 static void __update_reg64_bounds(struct bpf_reg_state *reg)
1147 /* min signed is max(sign bit) | min(other bits) */
1148 reg->smin_value = max_t(s64, reg->smin_value,
1149 reg->var_off.value | (reg->var_off.mask & S64_MIN));
1150 /* max signed is min(sign bit) | max(other bits) */
1151 reg->smax_value = min_t(s64, reg->smax_value,
1152 reg->var_off.value | (reg->var_off.mask & S64_MAX));
1153 reg->umin_value = max(reg->umin_value, reg->var_off.value);
1154 reg->umax_value = min(reg->umax_value,
1155 reg->var_off.value | reg->var_off.mask);
1158 static void __update_reg_bounds(struct bpf_reg_state *reg)
1160 __update_reg32_bounds(reg);
1161 __update_reg64_bounds(reg);
1164 /* Uses signed min/max values to inform unsigned, and vice-versa */
1165 static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
1167 /* Learn sign from signed bounds.
1168 * If we cannot cross the sign boundary, then signed and unsigned bounds
1169 * are the same, so combine. This works even in the negative case, e.g.
1170 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1172 if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) {
1173 reg->s32_min_value = reg->u32_min_value =
1174 max_t(u32, reg->s32_min_value, reg->u32_min_value);
1175 reg->s32_max_value = reg->u32_max_value =
1176 min_t(u32, reg->s32_max_value, reg->u32_max_value);
1179 /* Learn sign from unsigned bounds. Signed bounds cross the sign
1180 * boundary, so we must be careful.
1182 if ((s32)reg->u32_max_value >= 0) {
1183 /* Positive. We can't learn anything from the smin, but smax
1184 * is positive, hence safe.
1186 reg->s32_min_value = reg->u32_min_value;
1187 reg->s32_max_value = reg->u32_max_value =
1188 min_t(u32, reg->s32_max_value, reg->u32_max_value);
1189 } else if ((s32)reg->u32_min_value < 0) {
1190 /* Negative. We can't learn anything from the smax, but smin
1191 * is negative, hence safe.
1193 reg->s32_min_value = reg->u32_min_value =
1194 max_t(u32, reg->s32_min_value, reg->u32_min_value);
1195 reg->s32_max_value = reg->u32_max_value;
1199 static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
1201 /* Learn sign from signed bounds.
1202 * If we cannot cross the sign boundary, then signed and unsigned bounds
1203 * are the same, so combine. This works even in the negative case, e.g.
1204 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1206 if (reg->smin_value >= 0 || reg->smax_value < 0) {
1207 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1209 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1213 /* Learn sign from unsigned bounds. Signed bounds cross the sign
1214 * boundary, so we must be careful.
1216 if ((s64)reg->umax_value >= 0) {
1217 /* Positive. We can't learn anything from the smin, but smax
1218 * is positive, hence safe.
1220 reg->smin_value = reg->umin_value;
1221 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1223 } else if ((s64)reg->umin_value < 0) {
1224 /* Negative. We can't learn anything from the smax, but smin
1225 * is negative, hence safe.
1227 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1229 reg->smax_value = reg->umax_value;
1233 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
1235 __reg32_deduce_bounds(reg);
1236 __reg64_deduce_bounds(reg);
1239 /* Attempts to improve var_off based on unsigned min/max information */
1240 static void __reg_bound_offset(struct bpf_reg_state *reg)
1242 struct tnum var64_off = tnum_intersect(reg->var_off,
1243 tnum_range(reg->umin_value,
1245 struct tnum var32_off = tnum_intersect(tnum_subreg(reg->var_off),
1246 tnum_range(reg->u32_min_value,
1247 reg->u32_max_value));
1249 reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
1252 static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
1254 reg->umin_value = reg->u32_min_value;
1255 reg->umax_value = reg->u32_max_value;
1256 /* Attempt to pull 32-bit signed bounds into 64-bit bounds
1257 * but must be positive otherwise set to worse case bounds
1258 * and refine later from tnum.
1260 if (reg->s32_min_value >= 0 && reg->s32_max_value >= 0)
1261 reg->smax_value = reg->s32_max_value;
1263 reg->smax_value = U32_MAX;
1264 if (reg->s32_min_value >= 0)
1265 reg->smin_value = reg->s32_min_value;
1267 reg->smin_value = 0;
1270 static void __reg_combine_32_into_64(struct bpf_reg_state *reg)
1272 /* special case when 64-bit register has upper 32-bit register
1273 * zeroed. Typically happens after zext or <<32, >>32 sequence
1274 * allowing us to use 32-bit bounds directly,
1276 if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) {
1277 __reg_assign_32_into_64(reg);
1279 /* Otherwise the best we can do is push lower 32bit known and
1280 * unknown bits into register (var_off set from jmp logic)
1281 * then learn as much as possible from the 64-bit tnum
1282 * known and unknown bits. The previous smin/smax bounds are
1283 * invalid here because of jmp32 compare so mark them unknown
1284 * so they do not impact tnum bounds calculation.
1286 __mark_reg64_unbounded(reg);
1287 __update_reg_bounds(reg);
1290 /* Intersecting with the old var_off might have improved our bounds
1291 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1292 * then new var_off is (0; 0x7f...fc) which improves our umax.
1294 __reg_deduce_bounds(reg);
1295 __reg_bound_offset(reg);
1296 __update_reg_bounds(reg);
1299 static bool __reg64_bound_s32(s64 a)
1301 return a >= S32_MIN && a <= S32_MAX;
1304 static bool __reg64_bound_u32(u64 a)
1306 return a >= U32_MIN && a <= U32_MAX;
1309 static void __reg_combine_64_into_32(struct bpf_reg_state *reg)
1311 __mark_reg32_unbounded(reg);
1313 if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) {
1314 reg->s32_min_value = (s32)reg->smin_value;
1315 reg->s32_max_value = (s32)reg->smax_value;
1317 if (__reg64_bound_u32(reg->umin_value) && __reg64_bound_u32(reg->umax_value)) {
1318 reg->u32_min_value = (u32)reg->umin_value;
1319 reg->u32_max_value = (u32)reg->umax_value;
1322 /* Intersecting with the old var_off might have improved our bounds
1323 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1324 * then new var_off is (0; 0x7f...fc) which improves our umax.
1326 __reg_deduce_bounds(reg);
1327 __reg_bound_offset(reg);
1328 __update_reg_bounds(reg);
1331 /* Mark a register as having a completely unknown (scalar) value. */
1332 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
1333 struct bpf_reg_state *reg)
1336 * Clear type, id, off, and union(map_ptr, range) and
1337 * padding between 'type' and union
1339 memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
1340 reg->type = SCALAR_VALUE;
1341 reg->var_off = tnum_unknown;
1343 reg->precise = env->subprog_cnt > 1 || !env->bpf_capable;
1344 __mark_reg_unbounded(reg);
1347 static void mark_reg_unknown(struct bpf_verifier_env *env,
1348 struct bpf_reg_state *regs, u32 regno)
1350 if (WARN_ON(regno >= MAX_BPF_REG)) {
1351 verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
1352 /* Something bad happened, let's kill all regs except FP */
1353 for (regno = 0; regno < BPF_REG_FP; regno++)
1354 __mark_reg_not_init(env, regs + regno);
1357 __mark_reg_unknown(env, regs + regno);
1360 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1361 struct bpf_reg_state *reg)
1363 __mark_reg_unknown(env, reg);
1364 reg->type = NOT_INIT;
1367 static void mark_reg_not_init(struct bpf_verifier_env *env,
1368 struct bpf_reg_state *regs, u32 regno)
1370 if (WARN_ON(regno >= MAX_BPF_REG)) {
1371 verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
1372 /* Something bad happened, let's kill all regs except FP */
1373 for (regno = 0; regno < BPF_REG_FP; regno++)
1374 __mark_reg_not_init(env, regs + regno);
1377 __mark_reg_not_init(env, regs + regno);
1380 static void mark_btf_ld_reg(struct bpf_verifier_env *env,
1381 struct bpf_reg_state *regs, u32 regno,
1382 enum bpf_reg_type reg_type, u32 btf_id)
1384 if (reg_type == SCALAR_VALUE) {
1385 mark_reg_unknown(env, regs, regno);
1388 mark_reg_known_zero(env, regs, regno);
1389 regs[regno].type = PTR_TO_BTF_ID;
1390 regs[regno].btf_id = btf_id;
1393 #define DEF_NOT_SUBREG (0)
1394 static void init_reg_state(struct bpf_verifier_env *env,
1395 struct bpf_func_state *state)
1397 struct bpf_reg_state *regs = state->regs;
1400 for (i = 0; i < MAX_BPF_REG; i++) {
1401 mark_reg_not_init(env, regs, i);
1402 regs[i].live = REG_LIVE_NONE;
1403 regs[i].parent = NULL;
1404 regs[i].subreg_def = DEF_NOT_SUBREG;
1408 regs[BPF_REG_FP].type = PTR_TO_STACK;
1409 mark_reg_known_zero(env, regs, BPF_REG_FP);
1410 regs[BPF_REG_FP].frameno = state->frameno;
1413 #define BPF_MAIN_FUNC (-1)
1414 static void init_func_state(struct bpf_verifier_env *env,
1415 struct bpf_func_state *state,
1416 int callsite, int frameno, int subprogno)
1418 state->callsite = callsite;
1419 state->frameno = frameno;
1420 state->subprogno = subprogno;
1421 init_reg_state(env, state);
1425 SRC_OP, /* register is used as source operand */
1426 DST_OP, /* register is used as destination operand */
1427 DST_OP_NO_MARK /* same as above, check only, don't mark */
1430 static int cmp_subprogs(const void *a, const void *b)
1432 return ((struct bpf_subprog_info *)a)->start -
1433 ((struct bpf_subprog_info *)b)->start;
1436 static int find_subprog(struct bpf_verifier_env *env, int off)
1438 struct bpf_subprog_info *p;
1440 p = bsearch(&off, env->subprog_info, env->subprog_cnt,
1441 sizeof(env->subprog_info[0]), cmp_subprogs);
1444 return p - env->subprog_info;
1448 static int add_subprog(struct bpf_verifier_env *env, int off)
1450 int insn_cnt = env->prog->len;
1453 if (off >= insn_cnt || off < 0) {
1454 verbose(env, "call to invalid destination\n");
1457 ret = find_subprog(env, off);
1460 if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
1461 verbose(env, "too many subprograms\n");
1464 env->subprog_info[env->subprog_cnt++].start = off;
1465 sort(env->subprog_info, env->subprog_cnt,
1466 sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
1470 static int check_subprogs(struct bpf_verifier_env *env)
1472 int i, ret, subprog_start, subprog_end, off, cur_subprog = 0;
1473 struct bpf_subprog_info *subprog = env->subprog_info;
1474 struct bpf_insn *insn = env->prog->insnsi;
1475 int insn_cnt = env->prog->len;
1477 /* Add entry function. */
1478 ret = add_subprog(env, 0);
1482 /* determine subprog starts. The end is one before the next starts */
1483 for (i = 0; i < insn_cnt; i++) {
1484 if (insn[i].code != (BPF_JMP | BPF_CALL))
1486 if (insn[i].src_reg != BPF_PSEUDO_CALL)
1488 if (!env->bpf_capable) {
1490 "function calls to other bpf functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
1493 ret = add_subprog(env, i + insn[i].imm + 1);
1498 /* Add a fake 'exit' subprog which could simplify subprog iteration
1499 * logic. 'subprog_cnt' should not be increased.
1501 subprog[env->subprog_cnt].start = insn_cnt;
1503 if (env->log.level & BPF_LOG_LEVEL2)
1504 for (i = 0; i < env->subprog_cnt; i++)
1505 verbose(env, "func#%d @%d\n", i, subprog[i].start);
1507 /* now check that all jumps are within the same subprog */
1508 subprog_start = subprog[cur_subprog].start;
1509 subprog_end = subprog[cur_subprog + 1].start;
1510 for (i = 0; i < insn_cnt; i++) {
1511 u8 code = insn[i].code;
1513 if (code == (BPF_JMP | BPF_CALL) &&
1514 insn[i].imm == BPF_FUNC_tail_call &&
1515 insn[i].src_reg != BPF_PSEUDO_CALL)
1516 subprog[cur_subprog].has_tail_call = true;
1517 if (BPF_CLASS(code) == BPF_LD &&
1518 (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
1519 subprog[cur_subprog].has_ld_abs = true;
1520 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
1522 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
1524 off = i + insn[i].off + 1;
1525 if (off < subprog_start || off >= subprog_end) {
1526 verbose(env, "jump out of range from insn %d to %d\n", i, off);
1530 if (i == subprog_end - 1) {
1531 /* to avoid fall-through from one subprog into another
1532 * the last insn of the subprog should be either exit
1533 * or unconditional jump back
1535 if (code != (BPF_JMP | BPF_EXIT) &&
1536 code != (BPF_JMP | BPF_JA)) {
1537 verbose(env, "last insn is not an exit or jmp\n");
1540 subprog_start = subprog_end;
1542 if (cur_subprog < env->subprog_cnt)
1543 subprog_end = subprog[cur_subprog + 1].start;
1549 /* Parentage chain of this register (or stack slot) should take care of all
1550 * issues like callee-saved registers, stack slot allocation time, etc.
1552 static int mark_reg_read(struct bpf_verifier_env *env,
1553 const struct bpf_reg_state *state,
1554 struct bpf_reg_state *parent, u8 flag)
1556 bool writes = parent == state->parent; /* Observe write marks */
1560 /* if read wasn't screened by an earlier write ... */
1561 if (writes && state->live & REG_LIVE_WRITTEN)
1563 if (parent->live & REG_LIVE_DONE) {
1564 verbose(env, "verifier BUG type %s var_off %lld off %d\n",
1565 reg_type_str[parent->type],
1566 parent->var_off.value, parent->off);
1569 /* The first condition is more likely to be true than the
1570 * second, checked it first.
1572 if ((parent->live & REG_LIVE_READ) == flag ||
1573 parent->live & REG_LIVE_READ64)
1574 /* The parentage chain never changes and
1575 * this parent was already marked as LIVE_READ.
1576 * There is no need to keep walking the chain again and
1577 * keep re-marking all parents as LIVE_READ.
1578 * This case happens when the same register is read
1579 * multiple times without writes into it in-between.
1580 * Also, if parent has the stronger REG_LIVE_READ64 set,
1581 * then no need to set the weak REG_LIVE_READ32.
1584 /* ... then we depend on parent's value */
1585 parent->live |= flag;
1586 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
1587 if (flag == REG_LIVE_READ64)
1588 parent->live &= ~REG_LIVE_READ32;
1590 parent = state->parent;
1595 if (env->longest_mark_read_walk < cnt)
1596 env->longest_mark_read_walk = cnt;
1600 /* This function is supposed to be used by the following 32-bit optimization
1601 * code only. It returns TRUE if the source or destination register operates
1602 * on 64-bit, otherwise return FALSE.
1604 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
1605 u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
1610 class = BPF_CLASS(code);
1612 if (class == BPF_JMP) {
1613 /* BPF_EXIT for "main" will reach here. Return TRUE
1618 if (op == BPF_CALL) {
1619 /* BPF to BPF call will reach here because of marking
1620 * caller saved clobber with DST_OP_NO_MARK for which we
1621 * don't care the register def because they are anyway
1622 * marked as NOT_INIT already.
1624 if (insn->src_reg == BPF_PSEUDO_CALL)
1626 /* Helper call will reach here because of arg type
1627 * check, conservatively return TRUE.
1636 if (class == BPF_ALU64 || class == BPF_JMP ||
1637 /* BPF_END always use BPF_ALU class. */
1638 (class == BPF_ALU && op == BPF_END && insn->imm == 64))
1641 if (class == BPF_ALU || class == BPF_JMP32)
1644 if (class == BPF_LDX) {
1646 return BPF_SIZE(code) == BPF_DW;
1647 /* LDX source must be ptr. */
1651 if (class == BPF_STX) {
1652 if (reg->type != SCALAR_VALUE)
1654 return BPF_SIZE(code) == BPF_DW;
1657 if (class == BPF_LD) {
1658 u8 mode = BPF_MODE(code);
1661 if (mode == BPF_IMM)
1664 /* Both LD_IND and LD_ABS return 32-bit data. */
1668 /* Implicit ctx ptr. */
1669 if (regno == BPF_REG_6)
1672 /* Explicit source could be any width. */
1676 if (class == BPF_ST)
1677 /* The only source register for BPF_ST is a ptr. */
1680 /* Conservatively return true at default. */
1684 /* Return TRUE if INSN doesn't have explicit value define. */
1685 static bool insn_no_def(struct bpf_insn *insn)
1687 u8 class = BPF_CLASS(insn->code);
1689 return (class == BPF_JMP || class == BPF_JMP32 ||
1690 class == BPF_STX || class == BPF_ST);
1693 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
1694 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
1696 if (insn_no_def(insn))
1699 return !is_reg64(env, insn, insn->dst_reg, NULL, DST_OP);
1702 static void mark_insn_zext(struct bpf_verifier_env *env,
1703 struct bpf_reg_state *reg)
1705 s32 def_idx = reg->subreg_def;
1707 if (def_idx == DEF_NOT_SUBREG)
1710 env->insn_aux_data[def_idx - 1].zext_dst = true;
1711 /* The dst will be zero extended, so won't be sub-register anymore. */
1712 reg->subreg_def = DEF_NOT_SUBREG;
1715 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
1716 enum reg_arg_type t)
1718 struct bpf_verifier_state *vstate = env->cur_state;
1719 struct bpf_func_state *state = vstate->frame[vstate->curframe];
1720 struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
1721 struct bpf_reg_state *reg, *regs = state->regs;
1724 if (regno >= MAX_BPF_REG) {
1725 verbose(env, "R%d is invalid\n", regno);
1730 rw64 = is_reg64(env, insn, regno, reg, t);
1732 /* check whether register used as source operand can be read */
1733 if (reg->type == NOT_INIT) {
1734 verbose(env, "R%d !read_ok\n", regno);
1737 /* We don't need to worry about FP liveness because it's read-only */
1738 if (regno == BPF_REG_FP)
1742 mark_insn_zext(env, reg);
1744 return mark_reg_read(env, reg, reg->parent,
1745 rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
1747 /* check whether register used as dest operand can be written to */
1748 if (regno == BPF_REG_FP) {
1749 verbose(env, "frame pointer is read only\n");
1752 reg->live |= REG_LIVE_WRITTEN;
1753 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
1755 mark_reg_unknown(env, regs, regno);
1760 /* for any branch, call, exit record the history of jmps in the given state */
1761 static int push_jmp_history(struct bpf_verifier_env *env,
1762 struct bpf_verifier_state *cur)
1764 u32 cnt = cur->jmp_history_cnt;
1765 struct bpf_idx_pair *p;
1768 p = krealloc(cur->jmp_history, cnt * sizeof(*p), GFP_USER);
1771 p[cnt - 1].idx = env->insn_idx;
1772 p[cnt - 1].prev_idx = env->prev_insn_idx;
1773 cur->jmp_history = p;
1774 cur->jmp_history_cnt = cnt;
1778 /* Backtrack one insn at a time. If idx is not at the top of recorded
1779 * history then previous instruction came from straight line execution.
1781 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
1786 if (cnt && st->jmp_history[cnt - 1].idx == i) {
1787 i = st->jmp_history[cnt - 1].prev_idx;
1795 /* For given verifier state backtrack_insn() is called from the last insn to
1796 * the first insn. Its purpose is to compute a bitmask of registers and
1797 * stack slots that needs precision in the parent verifier state.
1799 static int backtrack_insn(struct bpf_verifier_env *env, int idx,
1800 u32 *reg_mask, u64 *stack_mask)
1802 const struct bpf_insn_cbs cbs = {
1803 .cb_print = verbose,
1804 .private_data = env,
1806 struct bpf_insn *insn = env->prog->insnsi + idx;
1807 u8 class = BPF_CLASS(insn->code);
1808 u8 opcode = BPF_OP(insn->code);
1809 u8 mode = BPF_MODE(insn->code);
1810 u32 dreg = 1u << insn->dst_reg;
1811 u32 sreg = 1u << insn->src_reg;
1814 if (insn->code == 0)
1816 if (env->log.level & BPF_LOG_LEVEL) {
1817 verbose(env, "regs=%x stack=%llx before ", *reg_mask, *stack_mask);
1818 verbose(env, "%d: ", idx);
1819 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
1822 if (class == BPF_ALU || class == BPF_ALU64) {
1823 if (!(*reg_mask & dreg))
1825 if (opcode == BPF_MOV) {
1826 if (BPF_SRC(insn->code) == BPF_X) {
1828 * dreg needs precision after this insn
1829 * sreg needs precision before this insn
1835 * dreg needs precision after this insn.
1836 * Corresponding register is already marked
1837 * as precise=true in this verifier state.
1838 * No further markings in parent are necessary
1843 if (BPF_SRC(insn->code) == BPF_X) {
1845 * both dreg and sreg need precision
1850 * dreg still needs precision before this insn
1853 } else if (class == BPF_LDX) {
1854 if (!(*reg_mask & dreg))
1858 /* scalars can only be spilled into stack w/o losing precision.
1859 * Load from any other memory can be zero extended.
1860 * The desire to keep that precision is already indicated
1861 * by 'precise' mark in corresponding register of this state.
1862 * No further tracking necessary.
1864 if (insn->src_reg != BPF_REG_FP)
1866 if (BPF_SIZE(insn->code) != BPF_DW)
1869 /* dreg = *(u64 *)[fp - off] was a fill from the stack.
1870 * that [fp - off] slot contains scalar that needs to be
1871 * tracked with precision
1873 spi = (-insn->off - 1) / BPF_REG_SIZE;
1875 verbose(env, "BUG spi %d\n", spi);
1876 WARN_ONCE(1, "verifier backtracking bug");
1879 *stack_mask |= 1ull << spi;
1880 } else if (class == BPF_STX || class == BPF_ST) {
1881 if (*reg_mask & dreg)
1882 /* stx & st shouldn't be using _scalar_ dst_reg
1883 * to access memory. It means backtracking
1884 * encountered a case of pointer subtraction.
1887 /* scalars can only be spilled into stack */
1888 if (insn->dst_reg != BPF_REG_FP)
1890 if (BPF_SIZE(insn->code) != BPF_DW)
1892 spi = (-insn->off - 1) / BPF_REG_SIZE;
1894 verbose(env, "BUG spi %d\n", spi);
1895 WARN_ONCE(1, "verifier backtracking bug");
1898 if (!(*stack_mask & (1ull << spi)))
1900 *stack_mask &= ~(1ull << spi);
1901 if (class == BPF_STX)
1903 } else if (class == BPF_JMP || class == BPF_JMP32) {
1904 if (opcode == BPF_CALL) {
1905 if (insn->src_reg == BPF_PSEUDO_CALL)
1907 /* regular helper call sets R0 */
1909 if (*reg_mask & 0x3f) {
1910 /* if backtracing was looking for registers R1-R5
1911 * they should have been found already.
1913 verbose(env, "BUG regs %x\n", *reg_mask);
1914 WARN_ONCE(1, "verifier backtracking bug");
1917 } else if (opcode == BPF_EXIT) {
1920 } else if (class == BPF_LD) {
1921 if (!(*reg_mask & dreg))
1924 /* It's ld_imm64 or ld_abs or ld_ind.
1925 * For ld_imm64 no further tracking of precision
1926 * into parent is necessary
1928 if (mode == BPF_IND || mode == BPF_ABS)
1929 /* to be analyzed */
1935 /* the scalar precision tracking algorithm:
1936 * . at the start all registers have precise=false.
1937 * . scalar ranges are tracked as normal through alu and jmp insns.
1938 * . once precise value of the scalar register is used in:
1939 * . ptr + scalar alu
1940 * . if (scalar cond K|scalar)
1941 * . helper_call(.., scalar, ...) where ARG_CONST is expected
1942 * backtrack through the verifier states and mark all registers and
1943 * stack slots with spilled constants that these scalar regisers
1944 * should be precise.
1945 * . during state pruning two registers (or spilled stack slots)
1946 * are equivalent if both are not precise.
1948 * Note the verifier cannot simply walk register parentage chain,
1949 * since many different registers and stack slots could have been
1950 * used to compute single precise scalar.
1952 * The approach of starting with precise=true for all registers and then
1953 * backtrack to mark a register as not precise when the verifier detects
1954 * that program doesn't care about specific value (e.g., when helper
1955 * takes register as ARG_ANYTHING parameter) is not safe.
1957 * It's ok to walk single parentage chain of the verifier states.
1958 * It's possible that this backtracking will go all the way till 1st insn.
1959 * All other branches will be explored for needing precision later.
1961 * The backtracking needs to deal with cases like:
1962 * 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)
1965 * if r5 > 0x79f goto pc+7
1966 * R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
1969 * call bpf_perf_event_output#25
1970 * where .arg5_type = ARG_CONST_SIZE_OR_ZERO
1974 * call foo // uses callee's r6 inside to compute r0
1978 * to track above reg_mask/stack_mask needs to be independent for each frame.
1980 * Also if parent's curframe > frame where backtracking started,
1981 * the verifier need to mark registers in both frames, otherwise callees
1982 * may incorrectly prune callers. This is similar to
1983 * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
1985 * For now backtracking falls back into conservative marking.
1987 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
1988 struct bpf_verifier_state *st)
1990 struct bpf_func_state *func;
1991 struct bpf_reg_state *reg;
1994 /* big hammer: mark all scalars precise in this path.
1995 * pop_stack may still get !precise scalars.
1997 for (; st; st = st->parent)
1998 for (i = 0; i <= st->curframe; i++) {
1999 func = st->frame[i];
2000 for (j = 0; j < BPF_REG_FP; j++) {
2001 reg = &func->regs[j];
2002 if (reg->type != SCALAR_VALUE)
2004 reg->precise = true;
2006 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
2007 if (func->stack[j].slot_type[0] != STACK_SPILL)
2009 reg = &func->stack[j].spilled_ptr;
2010 if (reg->type != SCALAR_VALUE)
2012 reg->precise = true;
2017 static int __mark_chain_precision(struct bpf_verifier_env *env, int regno,
2020 struct bpf_verifier_state *st = env->cur_state;
2021 int first_idx = st->first_insn_idx;
2022 int last_idx = env->insn_idx;
2023 struct bpf_func_state *func;
2024 struct bpf_reg_state *reg;
2025 u32 reg_mask = regno >= 0 ? 1u << regno : 0;
2026 u64 stack_mask = spi >= 0 ? 1ull << spi : 0;
2027 bool skip_first = true;
2028 bool new_marks = false;
2031 if (!env->bpf_capable)
2034 func = st->frame[st->curframe];
2036 reg = &func->regs[regno];
2037 if (reg->type != SCALAR_VALUE) {
2038 WARN_ONCE(1, "backtracing misuse");
2045 reg->precise = true;
2049 if (func->stack[spi].slot_type[0] != STACK_SPILL) {
2053 reg = &func->stack[spi].spilled_ptr;
2054 if (reg->type != SCALAR_VALUE) {
2062 reg->precise = true;
2068 if (!reg_mask && !stack_mask)
2071 DECLARE_BITMAP(mask, 64);
2072 u32 history = st->jmp_history_cnt;
2074 if (env->log.level & BPF_LOG_LEVEL)
2075 verbose(env, "last_idx %d first_idx %d\n", last_idx, first_idx);
2076 for (i = last_idx;;) {
2081 err = backtrack_insn(env, i, ®_mask, &stack_mask);
2083 if (err == -ENOTSUPP) {
2084 mark_all_scalars_precise(env, st);
2089 if (!reg_mask && !stack_mask)
2090 /* Found assignment(s) into tracked register in this state.
2091 * Since this state is already marked, just return.
2092 * Nothing to be tracked further in the parent state.
2097 i = get_prev_insn_idx(st, i, &history);
2098 if (i >= env->prog->len) {
2099 /* This can happen if backtracking reached insn 0
2100 * and there are still reg_mask or stack_mask
2102 * It means the backtracking missed the spot where
2103 * particular register was initialized with a constant.
2105 verbose(env, "BUG backtracking idx %d\n", i);
2106 WARN_ONCE(1, "verifier backtracking bug");
2115 func = st->frame[st->curframe];
2116 bitmap_from_u64(mask, reg_mask);
2117 for_each_set_bit(i, mask, 32) {
2118 reg = &func->regs[i];
2119 if (reg->type != SCALAR_VALUE) {
2120 reg_mask &= ~(1u << i);
2125 reg->precise = true;
2128 bitmap_from_u64(mask, stack_mask);
2129 for_each_set_bit(i, mask, 64) {
2130 if (i >= func->allocated_stack / BPF_REG_SIZE) {
2131 /* the sequence of instructions:
2133 * 3: (7b) *(u64 *)(r3 -8) = r0
2134 * 4: (79) r4 = *(u64 *)(r10 -8)
2135 * doesn't contain jmps. It's backtracked
2136 * as a single block.
2137 * During backtracking insn 3 is not recognized as
2138 * stack access, so at the end of backtracking
2139 * stack slot fp-8 is still marked in stack_mask.
2140 * However the parent state may not have accessed
2141 * fp-8 and it's "unallocated" stack space.
2142 * In such case fallback to conservative.
2144 mark_all_scalars_precise(env, st);
2148 if (func->stack[i].slot_type[0] != STACK_SPILL) {
2149 stack_mask &= ~(1ull << i);
2152 reg = &func->stack[i].spilled_ptr;
2153 if (reg->type != SCALAR_VALUE) {
2154 stack_mask &= ~(1ull << i);
2159 reg->precise = true;
2161 if (env->log.level & BPF_LOG_LEVEL) {
2162 print_verifier_state(env, func);
2163 verbose(env, "parent %s regs=%x stack=%llx marks\n",
2164 new_marks ? "didn't have" : "already had",
2165 reg_mask, stack_mask);
2168 if (!reg_mask && !stack_mask)
2173 last_idx = st->last_insn_idx;
2174 first_idx = st->first_insn_idx;
2179 static int mark_chain_precision(struct bpf_verifier_env *env, int regno)
2181 return __mark_chain_precision(env, regno, -1);
2184 static int mark_chain_precision_stack(struct bpf_verifier_env *env, int spi)
2186 return __mark_chain_precision(env, -1, spi);
2189 static bool is_spillable_regtype(enum bpf_reg_type type)
2192 case PTR_TO_MAP_VALUE:
2193 case PTR_TO_MAP_VALUE_OR_NULL:
2197 case PTR_TO_PACKET_META:
2198 case PTR_TO_PACKET_END:
2199 case PTR_TO_FLOW_KEYS:
2200 case CONST_PTR_TO_MAP:
2202 case PTR_TO_SOCKET_OR_NULL:
2203 case PTR_TO_SOCK_COMMON:
2204 case PTR_TO_SOCK_COMMON_OR_NULL:
2205 case PTR_TO_TCP_SOCK:
2206 case PTR_TO_TCP_SOCK_OR_NULL:
2207 case PTR_TO_XDP_SOCK:
2209 case PTR_TO_BTF_ID_OR_NULL:
2210 case PTR_TO_RDONLY_BUF:
2211 case PTR_TO_RDONLY_BUF_OR_NULL:
2212 case PTR_TO_RDWR_BUF:
2213 case PTR_TO_RDWR_BUF_OR_NULL:
2214 case PTR_TO_PERCPU_BTF_ID:
2216 case PTR_TO_MEM_OR_NULL:
2223 /* Does this register contain a constant zero? */
2224 static bool register_is_null(struct bpf_reg_state *reg)
2226 return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
2229 static bool register_is_const(struct bpf_reg_state *reg)
2231 return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
2234 static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
2236 return tnum_is_unknown(reg->var_off) &&
2237 reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
2238 reg->umin_value == 0 && reg->umax_value == U64_MAX &&
2239 reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
2240 reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
2243 static bool register_is_bounded(struct bpf_reg_state *reg)
2245 return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
2248 static bool __is_pointer_value(bool allow_ptr_leaks,
2249 const struct bpf_reg_state *reg)
2251 if (allow_ptr_leaks)
2254 return reg->type != SCALAR_VALUE;
2257 static void save_register_state(struct bpf_func_state *state,
2258 int spi, struct bpf_reg_state *reg)
2262 state->stack[spi].spilled_ptr = *reg;
2263 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
2265 for (i = 0; i < BPF_REG_SIZE; i++)
2266 state->stack[spi].slot_type[i] = STACK_SPILL;
2269 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
2270 * stack boundary and alignment are checked in check_mem_access()
2272 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
2273 /* stack frame we're writing to */
2274 struct bpf_func_state *state,
2275 int off, int size, int value_regno,
2278 struct bpf_func_state *cur; /* state of the current function */
2279 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
2280 u32 dst_reg = env->prog->insnsi[insn_idx].dst_reg;
2281 struct bpf_reg_state *reg = NULL;
2283 err = realloc_func_state(state, round_up(slot + 1, BPF_REG_SIZE),
2284 state->acquired_refs, true);
2287 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
2288 * so it's aligned access and [off, off + size) are within stack limits
2290 if (!env->allow_ptr_leaks &&
2291 state->stack[spi].slot_type[0] == STACK_SPILL &&
2292 size != BPF_REG_SIZE) {
2293 verbose(env, "attempt to corrupt spilled pointer on stack\n");
2297 cur = env->cur_state->frame[env->cur_state->curframe];
2298 if (value_regno >= 0)
2299 reg = &cur->regs[value_regno];
2300 if (!env->bypass_spec_v4) {
2301 bool sanitize = reg && is_spillable_regtype(reg->type);
2303 for (i = 0; i < size; i++) {
2304 if (state->stack[spi].slot_type[i] == STACK_INVALID) {
2311 env->insn_aux_data[insn_idx].sanitize_stack_spill = true;
2314 if (reg && size == BPF_REG_SIZE && register_is_bounded(reg) &&
2315 !register_is_null(reg) && env->bpf_capable) {
2316 if (dst_reg != BPF_REG_FP) {
2317 /* The backtracking logic can only recognize explicit
2318 * stack slot address like [fp - 8]. Other spill of
2319 * scalar via different register has to be conervative.
2320 * Backtrack from here and mark all registers as precise
2321 * that contributed into 'reg' being a constant.
2323 err = mark_chain_precision(env, value_regno);
2327 save_register_state(state, spi, reg);
2328 } else if (reg && is_spillable_regtype(reg->type)) {
2329 /* register containing pointer is being spilled into stack */
2330 if (size != BPF_REG_SIZE) {
2331 verbose_linfo(env, insn_idx, "; ");
2332 verbose(env, "invalid size of register spill\n");
2335 if (state != cur && reg->type == PTR_TO_STACK) {
2336 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
2339 save_register_state(state, spi, reg);
2341 u8 type = STACK_MISC;
2343 /* regular write of data into stack destroys any spilled ptr */
2344 state->stack[spi].spilled_ptr.type = NOT_INIT;
2345 /* Mark slots as STACK_MISC if they belonged to spilled ptr. */
2346 if (state->stack[spi].slot_type[0] == STACK_SPILL)
2347 for (i = 0; i < BPF_REG_SIZE; i++)
2348 state->stack[spi].slot_type[i] = STACK_MISC;
2350 /* only mark the slot as written if all 8 bytes were written
2351 * otherwise read propagation may incorrectly stop too soon
2352 * when stack slots are partially written.
2353 * This heuristic means that read propagation will be
2354 * conservative, since it will add reg_live_read marks
2355 * to stack slots all the way to first state when programs
2356 * writes+reads less than 8 bytes
2358 if (size == BPF_REG_SIZE)
2359 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
2361 /* when we zero initialize stack slots mark them as such */
2362 if (reg && register_is_null(reg)) {
2363 /* backtracking doesn't work for STACK_ZERO yet. */
2364 err = mark_chain_precision(env, value_regno);
2370 /* Mark slots affected by this stack write. */
2371 for (i = 0; i < size; i++)
2372 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
2378 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
2379 * known to contain a variable offset.
2380 * This function checks whether the write is permitted and conservatively
2381 * tracks the effects of the write, considering that each stack slot in the
2382 * dynamic range is potentially written to.
2384 * 'off' includes 'regno->off'.
2385 * 'value_regno' can be -1, meaning that an unknown value is being written to
2388 * Spilled pointers in range are not marked as written because we don't know
2389 * what's going to be actually written. This means that read propagation for
2390 * future reads cannot be terminated by this write.
2392 * For privileged programs, uninitialized stack slots are considered
2393 * initialized by this write (even though we don't know exactly what offsets
2394 * are going to be written to). The idea is that we don't want the verifier to
2395 * reject future reads that access slots written to through variable offsets.
2397 static int check_stack_write_var_off(struct bpf_verifier_env *env,
2398 /* func where register points to */
2399 struct bpf_func_state *state,
2400 int ptr_regno, int off, int size,
2401 int value_regno, int insn_idx)
2403 struct bpf_func_state *cur; /* state of the current function */
2404 int min_off, max_off;
2406 struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
2407 bool writing_zero = false;
2408 /* set if the fact that we're writing a zero is used to let any
2409 * stack slots remain STACK_ZERO
2411 bool zero_used = false;
2413 cur = env->cur_state->frame[env->cur_state->curframe];
2414 ptr_reg = &cur->regs[ptr_regno];
2415 min_off = ptr_reg->smin_value + off;
2416 max_off = ptr_reg->smax_value + off + size;
2417 if (value_regno >= 0)
2418 value_reg = &cur->regs[value_regno];
2419 if (value_reg && register_is_null(value_reg))
2420 writing_zero = true;
2422 err = realloc_func_state(state, round_up(-min_off, BPF_REG_SIZE),
2423 state->acquired_refs, true);
2428 /* Variable offset writes destroy any spilled pointers in range. */
2429 for (i = min_off; i < max_off; i++) {
2430 u8 new_type, *stype;
2434 spi = slot / BPF_REG_SIZE;
2435 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
2437 if (!env->allow_ptr_leaks
2438 && *stype != NOT_INIT
2439 && *stype != SCALAR_VALUE) {
2440 /* Reject the write if there's are spilled pointers in
2441 * range. If we didn't reject here, the ptr status
2442 * would be erased below (even though not all slots are
2443 * actually overwritten), possibly opening the door to
2446 verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
2451 /* Erase all spilled pointers. */
2452 state->stack[spi].spilled_ptr.type = NOT_INIT;
2454 /* Update the slot type. */
2455 new_type = STACK_MISC;
2456 if (writing_zero && *stype == STACK_ZERO) {
2457 new_type = STACK_ZERO;
2460 /* If the slot is STACK_INVALID, we check whether it's OK to
2461 * pretend that it will be initialized by this write. The slot
2462 * might not actually be written to, and so if we mark it as
2463 * initialized future reads might leak uninitialized memory.
2464 * For privileged programs, we will accept such reads to slots
2465 * that may or may not be written because, if we're reject
2466 * them, the error would be too confusing.
2468 if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
2469 verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
2476 /* backtracking doesn't work for STACK_ZERO yet. */
2477 err = mark_chain_precision(env, value_regno);
2484 /* When register 'dst_regno' is assigned some values from stack[min_off,
2485 * max_off), we set the register's type according to the types of the
2486 * respective stack slots. If all the stack values are known to be zeros, then
2487 * so is the destination reg. Otherwise, the register is considered to be
2488 * SCALAR. This function does not deal with register filling; the caller must
2489 * ensure that all spilled registers in the stack range have been marked as
2492 static void mark_reg_stack_read(struct bpf_verifier_env *env,
2493 /* func where src register points to */
2494 struct bpf_func_state *ptr_state,
2495 int min_off, int max_off, int dst_regno)
2497 struct bpf_verifier_state *vstate = env->cur_state;
2498 struct bpf_func_state *state = vstate->frame[vstate->curframe];
2503 for (i = min_off; i < max_off; i++) {
2505 spi = slot / BPF_REG_SIZE;
2506 stype = ptr_state->stack[spi].slot_type;
2507 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
2511 if (zeros == max_off - min_off) {
2512 /* any access_size read into register is zero extended,
2513 * so the whole register == const_zero
2515 __mark_reg_const_zero(&state->regs[dst_regno]);
2516 /* backtracking doesn't support STACK_ZERO yet,
2517 * so mark it precise here, so that later
2518 * backtracking can stop here.
2519 * Backtracking may not need this if this register
2520 * doesn't participate in pointer adjustment.
2521 * Forward propagation of precise flag is not
2522 * necessary either. This mark is only to stop
2523 * backtracking. Any register that contributed
2524 * to const 0 was marked precise before spill.
2526 state->regs[dst_regno].precise = true;
2528 /* have read misc data from the stack */
2529 mark_reg_unknown(env, state->regs, dst_regno);
2531 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
2534 /* Read the stack at 'off' and put the results into the register indicated by
2535 * 'dst_regno'. It handles reg filling if the addressed stack slot is a
2538 * 'dst_regno' can be -1, meaning that the read value is not going to a
2541 * The access is assumed to be within the current stack bounds.
2543 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
2544 /* func where src register points to */
2545 struct bpf_func_state *reg_state,
2546 int off, int size, int dst_regno)
2548 struct bpf_verifier_state *vstate = env->cur_state;
2549 struct bpf_func_state *state = vstate->frame[vstate->curframe];
2550 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
2551 struct bpf_reg_state *reg;
2554 stype = reg_state->stack[spi].slot_type;
2555 reg = ®_state->stack[spi].spilled_ptr;
2557 if (stype[0] == STACK_SPILL) {
2558 if (size != BPF_REG_SIZE) {
2559 if (reg->type != SCALAR_VALUE) {
2560 verbose_linfo(env, env->insn_idx, "; ");
2561 verbose(env, "invalid size of register fill\n");
2564 if (dst_regno >= 0) {
2565 mark_reg_unknown(env, state->regs, dst_regno);
2566 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
2568 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
2571 for (i = 1; i < BPF_REG_SIZE; i++) {
2572 if (stype[(slot - i) % BPF_REG_SIZE] != STACK_SPILL) {
2573 verbose(env, "corrupted spill memory\n");
2578 if (dst_regno >= 0) {
2579 /* restore register state from stack */
2580 state->regs[dst_regno] = *reg;
2581 /* mark reg as written since spilled pointer state likely
2582 * has its liveness marks cleared by is_state_visited()
2583 * which resets stack/reg liveness for state transitions
2585 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
2586 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
2587 /* If dst_regno==-1, the caller is asking us whether
2588 * it is acceptable to use this value as a SCALAR_VALUE
2590 * We must not allow unprivileged callers to do that
2591 * with spilled pointers.
2593 verbose(env, "leaking pointer from stack off %d\n",
2597 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
2601 for (i = 0; i < size; i++) {
2602 type = stype[(slot - i) % BPF_REG_SIZE];
2603 if (type == STACK_MISC)
2605 if (type == STACK_ZERO)
2607 verbose(env, "invalid read from stack off %d+%d size %d\n",
2611 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
2613 mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
2618 enum stack_access_src {
2619 ACCESS_DIRECT = 1, /* the access is performed by an instruction */
2620 ACCESS_HELPER = 2, /* the access is performed by a helper */
2623 static int check_stack_range_initialized(struct bpf_verifier_env *env,
2624 int regno, int off, int access_size,
2625 bool zero_size_allowed,
2626 enum stack_access_src type,
2627 struct bpf_call_arg_meta *meta);
2629 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
2631 return cur_regs(env) + regno;
2634 /* Read the stack at 'ptr_regno + off' and put the result into the register
2636 * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
2637 * but not its variable offset.
2638 * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
2640 * As opposed to check_stack_read_fixed_off, this function doesn't deal with
2641 * filling registers (i.e. reads of spilled register cannot be detected when
2642 * the offset is not fixed). We conservatively mark 'dst_regno' as containing
2643 * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
2644 * offset; for a fixed offset check_stack_read_fixed_off should be used
2647 static int check_stack_read_var_off(struct bpf_verifier_env *env,
2648 int ptr_regno, int off, int size, int dst_regno)
2650 /* The state of the source register. */
2651 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
2652 struct bpf_func_state *ptr_state = func(env, reg);
2654 int min_off, max_off;
2656 /* Note that we pass a NULL meta, so raw access will not be permitted.
2658 err = check_stack_range_initialized(env, ptr_regno, off, size,
2659 false, ACCESS_DIRECT, NULL);
2663 min_off = reg->smin_value + off;
2664 max_off = reg->smax_value + off;
2665 mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
2669 /* check_stack_read dispatches to check_stack_read_fixed_off or
2670 * check_stack_read_var_off.
2672 * The caller must ensure that the offset falls within the allocated stack
2675 * 'dst_regno' is a register which will receive the value from the stack. It
2676 * can be -1, meaning that the read value is not going to a register.
2678 static int check_stack_read(struct bpf_verifier_env *env,
2679 int ptr_regno, int off, int size,
2682 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
2683 struct bpf_func_state *state = func(env, reg);
2685 /* Some accesses are only permitted with a static offset. */
2686 bool var_off = !tnum_is_const(reg->var_off);
2688 /* The offset is required to be static when reads don't go to a
2689 * register, in order to not leak pointers (see
2690 * check_stack_read_fixed_off).
2692 if (dst_regno < 0 && var_off) {
2695 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
2696 verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
2700 /* Variable offset is prohibited for unprivileged mode for simplicity
2701 * since it requires corresponding support in Spectre masking for stack
2702 * ALU. See also retrieve_ptr_limit().
2704 if (!env->bypass_spec_v1 && var_off) {
2707 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
2708 verbose(env, "R%d variable offset stack access prohibited for !root, var_off=%s\n",
2714 off += reg->var_off.value;
2715 err = check_stack_read_fixed_off(env, state, off, size,
2718 /* Variable offset stack reads need more conservative handling
2719 * than fixed offset ones. Note that dst_regno >= 0 on this
2722 err = check_stack_read_var_off(env, ptr_regno, off, size,
2729 /* check_stack_write dispatches to check_stack_write_fixed_off or
2730 * check_stack_write_var_off.
2732 * 'ptr_regno' is the register used as a pointer into the stack.
2733 * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
2734 * 'value_regno' is the register whose value we're writing to the stack. It can
2735 * be -1, meaning that we're not writing from a register.
2737 * The caller must ensure that the offset falls within the maximum stack size.
2739 static int check_stack_write(struct bpf_verifier_env *env,
2740 int ptr_regno, int off, int size,
2741 int value_regno, int insn_idx)
2743 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
2744 struct bpf_func_state *state = func(env, reg);
2747 if (tnum_is_const(reg->var_off)) {
2748 off += reg->var_off.value;
2749 err = check_stack_write_fixed_off(env, state, off, size,
2750 value_regno, insn_idx);
2752 /* Variable offset stack reads need more conservative handling
2753 * than fixed offset ones.
2755 err = check_stack_write_var_off(env, state,
2756 ptr_regno, off, size,
2757 value_regno, insn_idx);
2762 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
2763 int off, int size, enum bpf_access_type type)
2765 struct bpf_reg_state *regs = cur_regs(env);
2766 struct bpf_map *map = regs[regno].map_ptr;
2767 u32 cap = bpf_map_flags_to_cap(map);
2769 if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
2770 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
2771 map->value_size, off, size);
2775 if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
2776 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
2777 map->value_size, off, size);
2784 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
2785 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
2786 int off, int size, u32 mem_size,
2787 bool zero_size_allowed)
2789 bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
2790 struct bpf_reg_state *reg;
2792 if (off >= 0 && size_ok && (u64)off + size <= mem_size)
2795 reg = &cur_regs(env)[regno];
2796 switch (reg->type) {
2797 case PTR_TO_MAP_VALUE:
2798 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
2799 mem_size, off, size);
2802 case PTR_TO_PACKET_META:
2803 case PTR_TO_PACKET_END:
2804 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
2805 off, size, regno, reg->id, off, mem_size);
2809 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
2810 mem_size, off, size);
2816 /* check read/write into a memory region with possible variable offset */
2817 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
2818 int off, int size, u32 mem_size,
2819 bool zero_size_allowed)
2821 struct bpf_verifier_state *vstate = env->cur_state;
2822 struct bpf_func_state *state = vstate->frame[vstate->curframe];
2823 struct bpf_reg_state *reg = &state->regs[regno];
2826 /* We may have adjusted the register pointing to memory region, so we
2827 * need to try adding each of min_value and max_value to off
2828 * to make sure our theoretical access will be safe.
2830 if (env->log.level & BPF_LOG_LEVEL)
2831 print_verifier_state(env, state);
2833 /* The minimum value is only important with signed
2834 * comparisons where we can't assume the floor of a
2835 * value is 0. If we are using signed variables for our
2836 * index'es we need to make sure that whatever we use
2837 * will have a set floor within our range.
2839 if (reg->smin_value < 0 &&
2840 (reg->smin_value == S64_MIN ||
2841 (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
2842 reg->smin_value + off < 0)) {
2843 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
2847 err = __check_mem_access(env, regno, reg->smin_value + off, size,
2848 mem_size, zero_size_allowed);
2850 verbose(env, "R%d min value is outside of the allowed memory range\n",
2855 /* If we haven't set a max value then we need to bail since we can't be
2856 * sure we won't do bad things.
2857 * If reg->umax_value + off could overflow, treat that as unbounded too.
2859 if (reg->umax_value >= BPF_MAX_VAR_OFF) {
2860 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
2864 err = __check_mem_access(env, regno, reg->umax_value + off, size,
2865 mem_size, zero_size_allowed);
2867 verbose(env, "R%d max value is outside of the allowed memory range\n",
2875 /* check read/write into a map element with possible variable offset */
2876 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
2877 int off, int size, bool zero_size_allowed)
2879 struct bpf_verifier_state *vstate = env->cur_state;
2880 struct bpf_func_state *state = vstate->frame[vstate->curframe];
2881 struct bpf_reg_state *reg = &state->regs[regno];
2882 struct bpf_map *map = reg->map_ptr;
2885 err = check_mem_region_access(env, regno, off, size, map->value_size,
2890 if (map_value_has_spin_lock(map)) {
2891 u32 lock = map->spin_lock_off;
2893 /* if any part of struct bpf_spin_lock can be touched by
2894 * load/store reject this program.
2895 * To check that [x1, x2) overlaps with [y1, y2)
2896 * it is sufficient to check x1 < y2 && y1 < x2.
2898 if (reg->smin_value + off < lock + sizeof(struct bpf_spin_lock) &&
2899 lock < reg->umax_value + off + size) {
2900 verbose(env, "bpf_spin_lock cannot be accessed directly by load/store\n");
2907 #define MAX_PACKET_OFF 0xffff
2909 static enum bpf_prog_type resolve_prog_type(struct bpf_prog *prog)
2911 return prog->aux->dst_prog ? prog->aux->dst_prog->type : prog->type;
2914 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
2915 const struct bpf_call_arg_meta *meta,
2916 enum bpf_access_type t)
2918 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
2920 switch (prog_type) {
2921 /* Program types only with direct read access go here! */
2922 case BPF_PROG_TYPE_LWT_IN:
2923 case BPF_PROG_TYPE_LWT_OUT:
2924 case BPF_PROG_TYPE_LWT_SEG6LOCAL:
2925 case BPF_PROG_TYPE_SK_REUSEPORT:
2926 case BPF_PROG_TYPE_FLOW_DISSECTOR:
2927 case BPF_PROG_TYPE_CGROUP_SKB:
2932 /* Program types with direct read + write access go here! */
2933 case BPF_PROG_TYPE_SCHED_CLS:
2934 case BPF_PROG_TYPE_SCHED_ACT:
2935 case BPF_PROG_TYPE_XDP:
2936 case BPF_PROG_TYPE_LWT_XMIT:
2937 case BPF_PROG_TYPE_SK_SKB:
2938 case BPF_PROG_TYPE_SK_MSG:
2940 return meta->pkt_access;
2942 env->seen_direct_write = true;
2945 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
2947 env->seen_direct_write = true;
2956 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
2957 int size, bool zero_size_allowed)
2959 struct bpf_reg_state *regs = cur_regs(env);
2960 struct bpf_reg_state *reg = ®s[regno];
2963 /* We may have added a variable offset to the packet pointer; but any
2964 * reg->range we have comes after that. We are only checking the fixed
2968 /* We don't allow negative numbers, because we aren't tracking enough
2969 * detail to prove they're safe.
2971 if (reg->smin_value < 0) {
2972 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
2976 err = __check_mem_access(env, regno, off, size, reg->range,
2979 verbose(env, "R%d offset is outside of the packet\n", regno);
2983 /* __check_mem_access has made sure "off + size - 1" is within u16.
2984 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
2985 * otherwise find_good_pkt_pointers would have refused to set range info
2986 * that __check_mem_access would have rejected this pkt access.
2987 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
2989 env->prog->aux->max_pkt_offset =
2990 max_t(u32, env->prog->aux->max_pkt_offset,
2991 off + reg->umax_value + size - 1);
2996 /* check access to 'struct bpf_context' fields. Supports fixed offsets only */
2997 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
2998 enum bpf_access_type t, enum bpf_reg_type *reg_type,
3001 struct bpf_insn_access_aux info = {
3002 .reg_type = *reg_type,
3006 if (env->ops->is_valid_access &&
3007 env->ops->is_valid_access(off, size, t, env->prog, &info)) {
3008 /* A non zero info.ctx_field_size indicates that this field is a
3009 * candidate for later verifier transformation to load the whole
3010 * field and then apply a mask when accessed with a narrower
3011 * access than actual ctx access size. A zero info.ctx_field_size
3012 * will only allow for whole field access and rejects any other
3013 * type of narrower access.
3015 *reg_type = info.reg_type;
3017 if (*reg_type == PTR_TO_BTF_ID || *reg_type == PTR_TO_BTF_ID_OR_NULL)
3018 *btf_id = info.btf_id;
3020 env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
3021 /* remember the offset of last byte accessed in ctx */
3022 if (env->prog->aux->max_ctx_offset < off + size)
3023 env->prog->aux->max_ctx_offset = off + size;
3027 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
3031 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
3034 if (size < 0 || off < 0 ||
3035 (u64)off + size > sizeof(struct bpf_flow_keys)) {
3036 verbose(env, "invalid access to flow keys off=%d size=%d\n",
3043 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
3044 u32 regno, int off, int size,
3045 enum bpf_access_type t)
3047 struct bpf_reg_state *regs = cur_regs(env);
3048 struct bpf_reg_state *reg = ®s[regno];
3049 struct bpf_insn_access_aux info = {};
3052 if (reg->smin_value < 0) {
3053 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3058 switch (reg->type) {
3059 case PTR_TO_SOCK_COMMON:
3060 valid = bpf_sock_common_is_valid_access(off, size, t, &info);
3063 valid = bpf_sock_is_valid_access(off, size, t, &info);
3065 case PTR_TO_TCP_SOCK:
3066 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
3068 case PTR_TO_XDP_SOCK:
3069 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
3077 env->insn_aux_data[insn_idx].ctx_field_size =
3078 info.ctx_field_size;
3082 verbose(env, "R%d invalid %s access off=%d size=%d\n",
3083 regno, reg_type_str[reg->type], off, size);
3088 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
3090 return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
3093 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
3095 const struct bpf_reg_state *reg = reg_state(env, regno);
3097 return reg->type == PTR_TO_CTX;
3100 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
3102 const struct bpf_reg_state *reg = reg_state(env, regno);
3104 return type_is_sk_pointer(reg->type);
3107 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
3109 const struct bpf_reg_state *reg = reg_state(env, regno);
3111 return type_is_pkt_pointer(reg->type);
3114 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
3116 const struct bpf_reg_state *reg = reg_state(env, regno);
3118 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
3119 return reg->type == PTR_TO_FLOW_KEYS;
3122 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
3123 const struct bpf_reg_state *reg,
3124 int off, int size, bool strict)
3126 struct tnum reg_off;
3129 /* Byte size accesses are always allowed. */
3130 if (!strict || size == 1)
3133 /* For platforms that do not have a Kconfig enabling
3134 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
3135 * NET_IP_ALIGN is universally set to '2'. And on platforms
3136 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
3137 * to this code only in strict mode where we want to emulate
3138 * the NET_IP_ALIGN==2 checking. Therefore use an
3139 * unconditional IP align value of '2'.
3143 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
3144 if (!tnum_is_aligned(reg_off, size)) {
3147 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3149 "misaligned packet access off %d+%s+%d+%d size %d\n",
3150 ip_align, tn_buf, reg->off, off, size);
3157 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
3158 const struct bpf_reg_state *reg,
3159 const char *pointer_desc,
3160 int off, int size, bool strict)
3162 struct tnum reg_off;
3164 /* Byte size accesses are always allowed. */
3165 if (!strict || size == 1)
3168 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
3169 if (!tnum_is_aligned(reg_off, size)) {
3172 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3173 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
3174 pointer_desc, tn_buf, reg->off, off, size);
3181 static int check_ptr_alignment(struct bpf_verifier_env *env,
3182 const struct bpf_reg_state *reg, int off,
3183 int size, bool strict_alignment_once)
3185 bool strict = env->strict_alignment || strict_alignment_once;
3186 const char *pointer_desc = "";
3188 switch (reg->type) {
3190 case PTR_TO_PACKET_META:
3191 /* Special case, because of NET_IP_ALIGN. Given metadata sits
3192 * right in front, treat it the very same way.
3194 return check_pkt_ptr_alignment(env, reg, off, size, strict);
3195 case PTR_TO_FLOW_KEYS:
3196 pointer_desc = "flow keys ";
3198 case PTR_TO_MAP_VALUE:
3199 pointer_desc = "value ";
3202 pointer_desc = "context ";
3205 pointer_desc = "stack ";
3206 /* The stack spill tracking logic in check_stack_write_fixed_off()
3207 * and check_stack_read_fixed_off() relies on stack accesses being
3213 pointer_desc = "sock ";
3215 case PTR_TO_SOCK_COMMON:
3216 pointer_desc = "sock_common ";
3218 case PTR_TO_TCP_SOCK:
3219 pointer_desc = "tcp_sock ";
3221 case PTR_TO_XDP_SOCK:
3222 pointer_desc = "xdp_sock ";
3227 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
3231 static int update_stack_depth(struct bpf_verifier_env *env,
3232 const struct bpf_func_state *func,
3235 u16 stack = env->subprog_info[func->subprogno].stack_depth;
3240 /* update known max for given subprogram */
3241 env->subprog_info[func->subprogno].stack_depth = -off;
3245 /* starting from main bpf function walk all instructions of the function
3246 * and recursively walk all callees that given function can call.
3247 * Ignore jump and exit insns.
3248 * Since recursion is prevented by check_cfg() this algorithm
3249 * only needs a local stack of MAX_CALL_FRAMES to remember callsites
3251 static int check_max_stack_depth(struct bpf_verifier_env *env)
3253 int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
3254 struct bpf_subprog_info *subprog = env->subprog_info;
3255 struct bpf_insn *insn = env->prog->insnsi;
3256 bool tail_call_reachable = false;
3257 int ret_insn[MAX_CALL_FRAMES];
3258 int ret_prog[MAX_CALL_FRAMES];
3262 /* protect against potential stack overflow that might happen when
3263 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
3264 * depth for such case down to 256 so that the worst case scenario
3265 * would result in 8k stack size (32 which is tailcall limit * 256 =
3268 * To get the idea what might happen, see an example:
3269 * func1 -> sub rsp, 128
3270 * subfunc1 -> sub rsp, 256
3271 * tailcall1 -> add rsp, 256
3272 * func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
3273 * subfunc2 -> sub rsp, 64
3274 * subfunc22 -> sub rsp, 128
3275 * tailcall2 -> add rsp, 128
3276 * func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
3278 * tailcall will unwind the current stack frame but it will not get rid
3279 * of caller's stack as shown on the example above.
3281 if (idx && subprog[idx].has_tail_call && depth >= 256) {
3283 "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
3287 /* round up to 32-bytes, since this is granularity
3288 * of interpreter stack size
3290 depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
3291 if (depth > MAX_BPF_STACK) {
3292 verbose(env, "combined stack size of %d calls is %d. Too large\n",
3297 subprog_end = subprog[idx + 1].start;
3298 for (; i < subprog_end; i++) {
3299 if (insn[i].code != (BPF_JMP | BPF_CALL))
3301 if (insn[i].src_reg != BPF_PSEUDO_CALL)
3303 /* remember insn and function to return to */
3304 ret_insn[frame] = i + 1;
3305 ret_prog[frame] = idx;
3307 /* find the callee */
3308 i = i + insn[i].imm + 1;
3309 idx = find_subprog(env, i);
3311 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
3316 if (subprog[idx].has_tail_call)
3317 tail_call_reachable = true;
3320 if (frame >= MAX_CALL_FRAMES) {
3321 verbose(env, "the call stack of %d frames is too deep !\n",
3327 /* if tail call got detected across bpf2bpf calls then mark each of the
3328 * currently present subprog frames as tail call reachable subprogs;
3329 * this info will be utilized by JIT so that we will be preserving the
3330 * tail call counter throughout bpf2bpf calls combined with tailcalls
3332 if (tail_call_reachable)
3333 for (j = 0; j < frame; j++)
3334 subprog[ret_prog[j]].tail_call_reachable = true;
3335 if (subprog[0].tail_call_reachable)
3336 env->prog->aux->tail_call_reachable = true;
3338 /* end of for() loop means the last insn of the 'subprog'
3339 * was reached. Doesn't matter whether it was JA or EXIT
3343 depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
3345 i = ret_insn[frame];
3346 idx = ret_prog[frame];
3350 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
3351 static int get_callee_stack_depth(struct bpf_verifier_env *env,
3352 const struct bpf_insn *insn, int idx)
3354 int start = idx + insn->imm + 1, subprog;
3356 subprog = find_subprog(env, start);
3358 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
3362 return env->subprog_info[subprog].stack_depth;
3366 int check_ctx_reg(struct bpf_verifier_env *env,
3367 const struct bpf_reg_state *reg, int regno)
3369 /* Access to ctx or passing it to a helper is only allowed in
3370 * its original, unmodified form.
3374 verbose(env, "dereference of modified ctx ptr R%d off=%d disallowed\n",
3379 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3382 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3383 verbose(env, "variable ctx access var_off=%s disallowed\n", tn_buf);
3390 static int __check_buffer_access(struct bpf_verifier_env *env,
3391 const char *buf_info,
3392 const struct bpf_reg_state *reg,
3393 int regno, int off, int size)
3397 "R%d invalid %s buffer access: off=%d, size=%d\n",
3398 regno, buf_info, off, size);
3401 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3404 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3406 "R%d invalid variable buffer offset: off=%d, var_off=%s\n",
3407 regno, off, tn_buf);
3414 static int check_tp_buffer_access(struct bpf_verifier_env *env,
3415 const struct bpf_reg_state *reg,
3416 int regno, int off, int size)
3420 err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
3424 if (off + size > env->prog->aux->max_tp_access)
3425 env->prog->aux->max_tp_access = off + size;
3430 static int check_buffer_access(struct bpf_verifier_env *env,
3431 const struct bpf_reg_state *reg,
3432 int regno, int off, int size,
3433 bool zero_size_allowed,
3434 const char *buf_info,
3439 err = __check_buffer_access(env, buf_info, reg, regno, off, size);
3443 if (off + size > *max_access)
3444 *max_access = off + size;
3449 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
3450 static void zext_32_to_64(struct bpf_reg_state *reg)
3452 reg->var_off = tnum_subreg(reg->var_off);
3453 __reg_assign_32_into_64(reg);
3456 /* truncate register to smaller size (in bytes)
3457 * must be called with size < BPF_REG_SIZE
3459 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
3463 /* clear high bits in bit representation */
3464 reg->var_off = tnum_cast(reg->var_off, size);
3466 /* fix arithmetic bounds */
3467 mask = ((u64)1 << (size * 8)) - 1;
3468 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
3469 reg->umin_value &= mask;
3470 reg->umax_value &= mask;
3472 reg->umin_value = 0;
3473 reg->umax_value = mask;
3475 reg->smin_value = reg->umin_value;
3476 reg->smax_value = reg->umax_value;
3478 /* If size is smaller than 32bit register the 32bit register
3479 * values are also truncated so we push 64-bit bounds into
3480 * 32-bit bounds. Above were truncated < 32-bits already.
3484 __reg_combine_64_into_32(reg);
3487 static bool bpf_map_is_rdonly(const struct bpf_map *map)
3489 /* A map is considered read-only if the following condition are true:
3491 * 1) BPF program side cannot change any of the map content. The
3492 * BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
3493 * and was set at map creation time.
3494 * 2) The map value(s) have been initialized from user space by a
3495 * loader and then "frozen", such that no new map update/delete
3496 * operations from syscall side are possible for the rest of
3497 * the map's lifetime from that point onwards.
3498 * 3) Any parallel/pending map update/delete operations from syscall
3499 * side have been completed. Only after that point, it's safe to
3500 * assume that map value(s) are immutable.
3502 return (map->map_flags & BPF_F_RDONLY_PROG) &&
3503 READ_ONCE(map->frozen) &&
3504 !bpf_map_write_active(map);
3507 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val)
3513 err = map->ops->map_direct_value_addr(map, &addr, off);
3516 ptr = (void *)(long)addr + off;
3520 *val = (u64)*(u8 *)ptr;
3523 *val = (u64)*(u16 *)ptr;
3526 *val = (u64)*(u32 *)ptr;
3537 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
3538 struct bpf_reg_state *regs,
3539 int regno, int off, int size,
3540 enum bpf_access_type atype,
3543 struct bpf_reg_state *reg = regs + regno;
3544 const struct btf_type *t = btf_type_by_id(btf_vmlinux, reg->btf_id);
3545 const char *tname = btf_name_by_offset(btf_vmlinux, t->name_off);
3551 "R%d is ptr_%s invalid negative access: off=%d\n",
3555 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3558 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3560 "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
3561 regno, tname, off, tn_buf);
3565 if (env->ops->btf_struct_access) {
3566 ret = env->ops->btf_struct_access(&env->log, t, off, size,
3569 if (atype != BPF_READ) {
3570 verbose(env, "only read is supported\n");
3574 ret = btf_struct_access(&env->log, t, off, size, atype,
3581 if (atype == BPF_READ && value_regno >= 0)
3582 mark_btf_ld_reg(env, regs, value_regno, ret, btf_id);
3587 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
3588 struct bpf_reg_state *regs,
3589 int regno, int off, int size,
3590 enum bpf_access_type atype,
3593 struct bpf_reg_state *reg = regs + regno;
3594 struct bpf_map *map = reg->map_ptr;
3595 const struct btf_type *t;
3601 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
3605 if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
3606 verbose(env, "map_ptr access not supported for map type %d\n",
3611 t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
3612 tname = btf_name_by_offset(btf_vmlinux, t->name_off);
3614 if (!env->allow_ptr_to_map_access) {
3616 "%s access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
3622 verbose(env, "R%d is %s invalid negative access: off=%d\n",
3627 if (atype != BPF_READ) {
3628 verbose(env, "only read from %s is supported\n", tname);
3632 ret = btf_struct_access(&env->log, t, off, size, atype, &btf_id);
3636 if (value_regno >= 0)
3637 mark_btf_ld_reg(env, regs, value_regno, ret, btf_id);
3642 /* Check that the stack access at the given offset is within bounds. The
3643 * maximum valid offset is -1.
3645 * The minimum valid offset is -MAX_BPF_STACK for writes, and
3646 * -state->allocated_stack for reads.
3648 static int check_stack_slot_within_bounds(int off,
3649 struct bpf_func_state *state,
3650 enum bpf_access_type t)
3655 min_valid_off = -MAX_BPF_STACK;
3657 min_valid_off = -state->allocated_stack;
3659 if (off < min_valid_off || off > -1)
3664 /* Check that the stack access at 'regno + off' falls within the maximum stack
3667 * 'off' includes `regno->offset`, but not its dynamic part (if any).
3669 static int check_stack_access_within_bounds(
3670 struct bpf_verifier_env *env,
3671 int regno, int off, int access_size,
3672 enum stack_access_src src, enum bpf_access_type type)
3674 struct bpf_reg_state *regs = cur_regs(env);
3675 struct bpf_reg_state *reg = regs + regno;
3676 struct bpf_func_state *state = func(env, reg);
3677 int min_off, max_off;
3681 if (src == ACCESS_HELPER)
3682 /* We don't know if helpers are reading or writing (or both). */
3683 err_extra = " indirect access to";
3684 else if (type == BPF_READ)
3685 err_extra = " read from";
3687 err_extra = " write to";
3689 if (tnum_is_const(reg->var_off)) {
3690 min_off = reg->var_off.value + off;
3691 if (access_size > 0)
3692 max_off = min_off + access_size - 1;
3696 if (reg->smax_value >= BPF_MAX_VAR_OFF ||
3697 reg->smin_value <= -BPF_MAX_VAR_OFF) {
3698 verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
3702 min_off = reg->smin_value + off;
3703 if (access_size > 0)
3704 max_off = reg->smax_value + off + access_size - 1;
3709 err = check_stack_slot_within_bounds(min_off, state, type);
3711 err = check_stack_slot_within_bounds(max_off, state, type);
3714 if (tnum_is_const(reg->var_off)) {
3715 verbose(env, "invalid%s stack R%d off=%d size=%d\n",
3716 err_extra, regno, off, access_size);
3720 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3721 verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
3722 err_extra, regno, tn_buf, access_size);
3728 /* check whether memory at (regno + off) is accessible for t = (read | write)
3729 * if t==write, value_regno is a register which value is stored into memory
3730 * if t==read, value_regno is a register which will receive the value from memory
3731 * if t==write && value_regno==-1, some unknown value is stored into memory
3732 * if t==read && value_regno==-1, don't care what we read from memory
3734 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
3735 int off, int bpf_size, enum bpf_access_type t,
3736 int value_regno, bool strict_alignment_once)
3738 struct bpf_reg_state *regs = cur_regs(env);
3739 struct bpf_reg_state *reg = regs + regno;
3740 struct bpf_func_state *state;
3743 size = bpf_size_to_bytes(bpf_size);
3747 /* alignment checks will add in reg->off themselves */
3748 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
3752 /* for access checks, reg->off is just part of off */
3755 if (reg->type == PTR_TO_MAP_VALUE) {
3756 if (t == BPF_WRITE && value_regno >= 0 &&
3757 is_pointer_value(env, value_regno)) {
3758 verbose(env, "R%d leaks addr into map\n", value_regno);
3761 err = check_map_access_type(env, regno, off, size, t);
3764 err = check_map_access(env, regno, off, size, false);
3765 if (!err && t == BPF_READ && value_regno >= 0) {
3766 struct bpf_map *map = reg->map_ptr;
3768 /* if map is read-only, track its contents as scalars */
3769 if (tnum_is_const(reg->var_off) &&
3770 bpf_map_is_rdonly(map) &&
3771 map->ops->map_direct_value_addr) {
3772 int map_off = off + reg->var_off.value;
3775 err = bpf_map_direct_read(map, map_off, size,
3780 regs[value_regno].type = SCALAR_VALUE;
3781 __mark_reg_known(®s[value_regno], val);
3783 mark_reg_unknown(env, regs, value_regno);
3786 } else if (reg->type == PTR_TO_MEM) {
3787 if (t == BPF_WRITE && value_regno >= 0 &&
3788 is_pointer_value(env, value_regno)) {
3789 verbose(env, "R%d leaks addr into mem\n", value_regno);
3792 err = check_mem_region_access(env, regno, off, size,
3793 reg->mem_size, false);
3794 if (!err && t == BPF_READ && value_regno >= 0)
3795 mark_reg_unknown(env, regs, value_regno);
3796 } else if (reg->type == PTR_TO_CTX) {
3797 enum bpf_reg_type reg_type = SCALAR_VALUE;
3800 if (t == BPF_WRITE && value_regno >= 0 &&
3801 is_pointer_value(env, value_regno)) {
3802 verbose(env, "R%d leaks addr into ctx\n", value_regno);
3806 err = check_ctx_reg(env, reg, regno);
3810 err = check_ctx_access(env, insn_idx, off, size, t, ®_type, &btf_id);
3812 verbose_linfo(env, insn_idx, "; ");
3813 if (!err && t == BPF_READ && value_regno >= 0) {
3814 /* ctx access returns either a scalar, or a
3815 * PTR_TO_PACKET[_META,_END]. In the latter
3816 * case, we know the offset is zero.
3818 if (reg_type == SCALAR_VALUE) {
3819 mark_reg_unknown(env, regs, value_regno);
3821 mark_reg_known_zero(env, regs,
3823 if (reg_type_may_be_null(reg_type))
3824 regs[value_regno].id = ++env->id_gen;
3825 /* A load of ctx field could have different
3826 * actual load size with the one encoded in the
3827 * insn. When the dst is PTR, it is for sure not
3830 regs[value_regno].subreg_def = DEF_NOT_SUBREG;
3831 if (reg_type == PTR_TO_BTF_ID ||
3832 reg_type == PTR_TO_BTF_ID_OR_NULL)
3833 regs[value_regno].btf_id = btf_id;
3835 regs[value_regno].type = reg_type;
3838 } else if (reg->type == PTR_TO_STACK) {
3839 /* Basic bounds checks. */
3840 err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
3844 state = func(env, reg);
3845 err = update_stack_depth(env, state, off);
3850 err = check_stack_read(env, regno, off, size,
3853 err = check_stack_write(env, regno, off, size,
3854 value_regno, insn_idx);
3855 } else if (reg_is_pkt_pointer(reg)) {
3856 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
3857 verbose(env, "cannot write into packet\n");
3860 if (t == BPF_WRITE && value_regno >= 0 &&
3861 is_pointer_value(env, value_regno)) {
3862 verbose(env, "R%d leaks addr into packet\n",
3866 err = check_packet_access(env, regno, off, size, false);
3867 if (!err && t == BPF_READ && value_regno >= 0)
3868 mark_reg_unknown(env, regs, value_regno);
3869 } else if (reg->type == PTR_TO_FLOW_KEYS) {
3870 if (t == BPF_WRITE && value_regno >= 0 &&
3871 is_pointer_value(env, value_regno)) {
3872 verbose(env, "R%d leaks addr into flow keys\n",
3877 err = check_flow_keys_access(env, off, size);
3878 if (!err && t == BPF_READ && value_regno >= 0)
3879 mark_reg_unknown(env, regs, value_regno);
3880 } else if (type_is_sk_pointer(reg->type)) {
3881 if (t == BPF_WRITE) {
3882 verbose(env, "R%d cannot write into %s\n",
3883 regno, reg_type_str[reg->type]);
3886 err = check_sock_access(env, insn_idx, regno, off, size, t);
3887 if (!err && value_regno >= 0)
3888 mark_reg_unknown(env, regs, value_regno);
3889 } else if (reg->type == PTR_TO_TP_BUFFER) {
3890 err = check_tp_buffer_access(env, reg, regno, off, size);
3891 if (!err && t == BPF_READ && value_regno >= 0)
3892 mark_reg_unknown(env, regs, value_regno);
3893 } else if (reg->type == PTR_TO_BTF_ID) {
3894 err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
3896 } else if (reg->type == CONST_PTR_TO_MAP) {
3897 err = check_ptr_to_map_access(env, regs, regno, off, size, t,
3899 } else if (reg->type == PTR_TO_RDONLY_BUF) {
3900 if (t == BPF_WRITE) {
3901 verbose(env, "R%d cannot write into %s\n",
3902 regno, reg_type_str[reg->type]);
3905 err = check_buffer_access(env, reg, regno, off, size, false,
3907 &env->prog->aux->max_rdonly_access);
3908 if (!err && value_regno >= 0)
3909 mark_reg_unknown(env, regs, value_regno);
3910 } else if (reg->type == PTR_TO_RDWR_BUF) {
3911 err = check_buffer_access(env, reg, regno, off, size, false,
3913 &env->prog->aux->max_rdwr_access);
3914 if (!err && t == BPF_READ && value_regno >= 0)
3915 mark_reg_unknown(env, regs, value_regno);
3917 verbose(env, "R%d invalid mem access '%s'\n", regno,
3918 reg_type_str[reg->type]);
3922 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
3923 regs[value_regno].type == SCALAR_VALUE) {
3924 /* b/h/w load zero-extends, mark upper bits as known 0 */
3925 coerce_reg_to_size(®s[value_regno], size);
3930 static int check_xadd(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
3934 if ((BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) ||
3936 verbose(env, "BPF_XADD uses reserved fields\n");
3940 /* check src1 operand */
3941 err = check_reg_arg(env, insn->src_reg, SRC_OP);
3945 /* check src2 operand */
3946 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
3950 if (is_pointer_value(env, insn->src_reg)) {
3951 verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
3955 if (is_ctx_reg(env, insn->dst_reg) ||
3956 is_pkt_reg(env, insn->dst_reg) ||
3957 is_flow_key_reg(env, insn->dst_reg) ||
3958 is_sk_reg(env, insn->dst_reg)) {
3959 verbose(env, "BPF_XADD stores into R%d %s is not allowed\n",
3961 reg_type_str[reg_state(env, insn->dst_reg)->type]);
3965 /* check whether atomic_add can read the memory */
3966 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
3967 BPF_SIZE(insn->code), BPF_READ, -1, true);
3971 /* check whether atomic_add can write into the same memory */
3972 return check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
3973 BPF_SIZE(insn->code), BPF_WRITE, -1, true);
3976 /* When register 'regno' is used to read the stack (either directly or through
3977 * a helper function) make sure that it's within stack boundary and, depending
3978 * on the access type, that all elements of the stack are initialized.
3980 * 'off' includes 'regno->off', but not its dynamic part (if any).
3982 * All registers that have been spilled on the stack in the slots within the
3983 * read offsets are marked as read.
3985 static int check_stack_range_initialized(
3986 struct bpf_verifier_env *env, int regno, int off,
3987 int access_size, bool zero_size_allowed,
3988 enum stack_access_src type, struct bpf_call_arg_meta *meta)
3990 struct bpf_reg_state *reg = reg_state(env, regno);
3991 struct bpf_func_state *state = func(env, reg);
3992 int err, min_off, max_off, i, j, slot, spi;
3993 char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
3994 enum bpf_access_type bounds_check_type;
3995 /* Some accesses can write anything into the stack, others are
3998 bool clobber = false;
4000 if (access_size == 0 && !zero_size_allowed) {
4001 verbose(env, "invalid zero-sized read\n");
4005 if (type == ACCESS_HELPER) {
4006 /* The bounds checks for writes are more permissive than for
4007 * reads. However, if raw_mode is not set, we'll do extra
4010 bounds_check_type = BPF_WRITE;
4013 bounds_check_type = BPF_READ;
4015 err = check_stack_access_within_bounds(env, regno, off, access_size,
4016 type, bounds_check_type);
4021 if (tnum_is_const(reg->var_off)) {
4022 min_off = max_off = reg->var_off.value + off;
4024 /* Variable offset is prohibited for unprivileged mode for
4025 * simplicity since it requires corresponding support in
4026 * Spectre masking for stack ALU.
4027 * See also retrieve_ptr_limit().
4029 if (!env->bypass_spec_v1) {
4032 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4033 verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
4034 regno, err_extra, tn_buf);
4037 /* Only initialized buffer on stack is allowed to be accessed
4038 * with variable offset. With uninitialized buffer it's hard to
4039 * guarantee that whole memory is marked as initialized on
4040 * helper return since specific bounds are unknown what may
4041 * cause uninitialized stack leaking.
4043 if (meta && meta->raw_mode)
4046 min_off = reg->smin_value + off;
4047 max_off = reg->smax_value + off;
4050 if (meta && meta->raw_mode) {
4051 meta->access_size = access_size;
4052 meta->regno = regno;
4056 for (i = min_off; i < max_off + access_size; i++) {
4060 spi = slot / BPF_REG_SIZE;
4061 if (state->allocated_stack <= slot)
4063 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
4064 if (*stype == STACK_MISC)
4066 if (*stype == STACK_ZERO) {
4068 /* helper can write anything into the stack */
4069 *stype = STACK_MISC;
4074 if (state->stack[spi].slot_type[0] == STACK_SPILL &&
4075 state->stack[spi].spilled_ptr.type == PTR_TO_BTF_ID)
4078 if (state->stack[spi].slot_type[0] == STACK_SPILL &&
4079 (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
4080 env->allow_ptr_leaks)) {
4082 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
4083 for (j = 0; j < BPF_REG_SIZE; j++)
4084 state->stack[spi].slot_type[j] = STACK_MISC;
4090 if (tnum_is_const(reg->var_off)) {
4091 verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
4092 err_extra, regno, min_off, i - min_off, access_size);
4096 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4097 verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
4098 err_extra, regno, tn_buf, i - min_off, access_size);
4102 /* reading any byte out of 8-byte 'spill_slot' will cause
4103 * the whole slot to be marked as 'read'
4105 mark_reg_read(env, &state->stack[spi].spilled_ptr,
4106 state->stack[spi].spilled_ptr.parent,
4109 return update_stack_depth(env, state, min_off);
4112 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
4113 int access_size, bool zero_size_allowed,
4114 struct bpf_call_arg_meta *meta)
4116 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
4118 switch (reg->type) {
4120 case PTR_TO_PACKET_META:
4121 return check_packet_access(env, regno, reg->off, access_size,
4123 case PTR_TO_MAP_VALUE:
4124 if (check_map_access_type(env, regno, reg->off, access_size,
4125 meta && meta->raw_mode ? BPF_WRITE :
4128 return check_map_access(env, regno, reg->off, access_size,
4131 return check_mem_region_access(env, regno, reg->off,
4132 access_size, reg->mem_size,
4134 case PTR_TO_RDONLY_BUF:
4135 if (meta && meta->raw_mode)
4137 return check_buffer_access(env, reg, regno, reg->off,
4138 access_size, zero_size_allowed,
4140 &env->prog->aux->max_rdonly_access);
4141 case PTR_TO_RDWR_BUF:
4142 return check_buffer_access(env, reg, regno, reg->off,
4143 access_size, zero_size_allowed,
4145 &env->prog->aux->max_rdwr_access);
4147 return check_stack_range_initialized(
4149 regno, reg->off, access_size,
4150 zero_size_allowed, ACCESS_HELPER, meta);
4151 default: /* scalar_value or invalid ptr */
4152 /* Allow zero-byte read from NULL, regardless of pointer type */
4153 if (zero_size_allowed && access_size == 0 &&
4154 register_is_null(reg))
4157 verbose(env, "R%d type=%s expected=%s\n", regno,
4158 reg_type_str[reg->type],
4159 reg_type_str[PTR_TO_STACK]);
4164 /* Implementation details:
4165 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL
4166 * Two bpf_map_lookups (even with the same key) will have different reg->id.
4167 * For traditional PTR_TO_MAP_VALUE the verifier clears reg->id after
4168 * value_or_null->value transition, since the verifier only cares about
4169 * the range of access to valid map value pointer and doesn't care about actual
4170 * address of the map element.
4171 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
4172 * reg->id > 0 after value_or_null->value transition. By doing so
4173 * two bpf_map_lookups will be considered two different pointers that
4174 * point to different bpf_spin_locks.
4175 * The verifier allows taking only one bpf_spin_lock at a time to avoid
4177 * Since only one bpf_spin_lock is allowed the checks are simpler than
4178 * reg_is_refcounted() logic. The verifier needs to remember only
4179 * one spin_lock instead of array of acquired_refs.
4180 * cur_state->active_spin_lock remembers which map value element got locked
4181 * and clears it after bpf_spin_unlock.
4183 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
4186 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
4187 struct bpf_verifier_state *cur = env->cur_state;
4188 bool is_const = tnum_is_const(reg->var_off);
4189 struct bpf_map *map = reg->map_ptr;
4190 u64 val = reg->var_off.value;
4194 "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
4200 "map '%s' has to have BTF in order to use bpf_spin_lock\n",
4204 if (!map_value_has_spin_lock(map)) {
4205 if (map->spin_lock_off == -E2BIG)
4207 "map '%s' has more than one 'struct bpf_spin_lock'\n",
4209 else if (map->spin_lock_off == -ENOENT)
4211 "map '%s' doesn't have 'struct bpf_spin_lock'\n",
4215 "map '%s' is not a struct type or bpf_spin_lock is mangled\n",
4219 if (map->spin_lock_off != val + reg->off) {
4220 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock'\n",
4225 if (cur->active_spin_lock) {
4227 "Locking two bpf_spin_locks are not allowed\n");
4230 cur->active_spin_lock = reg->id;
4232 if (!cur->active_spin_lock) {
4233 verbose(env, "bpf_spin_unlock without taking a lock\n");
4236 if (cur->active_spin_lock != reg->id) {
4237 verbose(env, "bpf_spin_unlock of different lock\n");
4240 cur->active_spin_lock = 0;
4245 static bool arg_type_is_mem_ptr(enum bpf_arg_type type)
4247 return type == ARG_PTR_TO_MEM ||
4248 type == ARG_PTR_TO_MEM_OR_NULL ||
4249 type == ARG_PTR_TO_UNINIT_MEM;
4252 static bool arg_type_is_mem_size(enum bpf_arg_type type)
4254 return type == ARG_CONST_SIZE ||
4255 type == ARG_CONST_SIZE_OR_ZERO;
4258 static bool arg_type_is_alloc_size(enum bpf_arg_type type)
4260 return type == ARG_CONST_ALLOC_SIZE_OR_ZERO;
4263 static bool arg_type_is_int_ptr(enum bpf_arg_type type)
4265 return type == ARG_PTR_TO_INT ||
4266 type == ARG_PTR_TO_LONG;
4269 static int int_ptr_type_to_size(enum bpf_arg_type type)
4271 if (type == ARG_PTR_TO_INT)
4273 else if (type == ARG_PTR_TO_LONG)
4279 static int resolve_map_arg_type(struct bpf_verifier_env *env,
4280 const struct bpf_call_arg_meta *meta,
4281 enum bpf_arg_type *arg_type)
4283 if (!meta->map_ptr) {
4284 /* kernel subsystem misconfigured verifier */
4285 verbose(env, "invalid map_ptr to access map->type\n");
4289 switch (meta->map_ptr->map_type) {
4290 case BPF_MAP_TYPE_SOCKMAP:
4291 case BPF_MAP_TYPE_SOCKHASH:
4292 if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
4293 *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
4295 verbose(env, "invalid arg_type for sockmap/sockhash\n");
4306 struct bpf_reg_types {
4307 const enum bpf_reg_type types[10];
4311 static const struct bpf_reg_types map_key_value_types = {
4320 static const struct bpf_reg_types sock_types = {
4330 static const struct bpf_reg_types btf_id_sock_common_types = {
4338 .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
4342 static const struct bpf_reg_types mem_types = {
4354 static const struct bpf_reg_types int_ptr_types = {
4363 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
4364 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
4365 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
4366 static const struct bpf_reg_types alloc_mem_types = { .types = { PTR_TO_MEM } };
4367 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
4368 static const struct bpf_reg_types btf_ptr_types = { .types = { PTR_TO_BTF_ID } };
4369 static const struct bpf_reg_types spin_lock_types = { .types = { PTR_TO_MAP_VALUE } };
4370 static const struct bpf_reg_types percpu_btf_ptr_types = { .types = { PTR_TO_PERCPU_BTF_ID } };
4372 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
4373 [ARG_PTR_TO_MAP_KEY] = &map_key_value_types,
4374 [ARG_PTR_TO_MAP_VALUE] = &map_key_value_types,
4375 [ARG_PTR_TO_UNINIT_MAP_VALUE] = &map_key_value_types,
4376 [ARG_PTR_TO_MAP_VALUE_OR_NULL] = &map_key_value_types,
4377 [ARG_CONST_SIZE] = &scalar_types,
4378 [ARG_CONST_SIZE_OR_ZERO] = &scalar_types,
4379 [ARG_CONST_ALLOC_SIZE_OR_ZERO] = &scalar_types,
4380 [ARG_CONST_MAP_PTR] = &const_map_ptr_types,
4381 [ARG_PTR_TO_CTX] = &context_types,
4382 [ARG_PTR_TO_CTX_OR_NULL] = &context_types,
4383 [ARG_PTR_TO_SOCK_COMMON] = &sock_types,
4385 [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types,
4387 [ARG_PTR_TO_SOCKET] = &fullsock_types,
4388 [ARG_PTR_TO_SOCKET_OR_NULL] = &fullsock_types,
4389 [ARG_PTR_TO_BTF_ID] = &btf_ptr_types,
4390 [ARG_PTR_TO_SPIN_LOCK] = &spin_lock_types,
4391 [ARG_PTR_TO_MEM] = &mem_types,
4392 [ARG_PTR_TO_MEM_OR_NULL] = &mem_types,
4393 [ARG_PTR_TO_UNINIT_MEM] = &mem_types,
4394 [ARG_PTR_TO_ALLOC_MEM] = &alloc_mem_types,
4395 [ARG_PTR_TO_ALLOC_MEM_OR_NULL] = &alloc_mem_types,
4396 [ARG_PTR_TO_INT] = &int_ptr_types,
4397 [ARG_PTR_TO_LONG] = &int_ptr_types,
4398 [ARG_PTR_TO_PERCPU_BTF_ID] = &percpu_btf_ptr_types,
4401 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
4402 enum bpf_arg_type arg_type,
4403 const u32 *arg_btf_id)
4405 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
4406 enum bpf_reg_type expected, type = reg->type;
4407 const struct bpf_reg_types *compatible;
4410 compatible = compatible_reg_types[arg_type];
4412 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
4416 for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
4417 expected = compatible->types[i];
4418 if (expected == NOT_INIT)
4421 if (type == expected)
4425 verbose(env, "R%d type=%s expected=", regno, reg_type_str[type]);
4426 for (j = 0; j + 1 < i; j++)
4427 verbose(env, "%s, ", reg_type_str[compatible->types[j]]);
4428 verbose(env, "%s\n", reg_type_str[compatible->types[j]]);
4432 if (type == PTR_TO_BTF_ID) {
4434 if (!compatible->btf_id) {
4435 verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
4438 arg_btf_id = compatible->btf_id;
4441 if (!btf_struct_ids_match(&env->log, reg->off, reg->btf_id,
4443 verbose(env, "R%d is of type %s but %s is expected\n",
4444 regno, kernel_type_name(reg->btf_id),
4445 kernel_type_name(*arg_btf_id));
4449 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4450 verbose(env, "R%d is a pointer to in-kernel struct with non-zero offset\n",
4459 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
4460 struct bpf_call_arg_meta *meta,
4461 const struct bpf_func_proto *fn)
4463 u32 regno = BPF_REG_1 + arg;
4464 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
4465 enum bpf_arg_type arg_type = fn->arg_type[arg];
4466 enum bpf_reg_type type = reg->type;
4469 if (arg_type == ARG_DONTCARE)
4472 err = check_reg_arg(env, regno, SRC_OP);
4476 if (arg_type == ARG_ANYTHING) {
4477 if (is_pointer_value(env, regno)) {
4478 verbose(env, "R%d leaks addr into helper function\n",
4485 if (type_is_pkt_pointer(type) &&
4486 !may_access_direct_pkt_data(env, meta, BPF_READ)) {
4487 verbose(env, "helper access to the packet is not allowed\n");
4491 if (arg_type == ARG_PTR_TO_MAP_VALUE ||
4492 arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE ||
4493 arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL) {
4494 err = resolve_map_arg_type(env, meta, &arg_type);
4499 if (register_is_null(reg) && arg_type_may_be_null(arg_type))
4500 /* A NULL register has a SCALAR_VALUE type, so skip
4503 goto skip_type_check;
4505 err = check_reg_type(env, regno, arg_type, fn->arg_btf_id[arg]);
4509 if (type == PTR_TO_CTX) {
4510 err = check_ctx_reg(env, reg, regno);
4516 if (reg->ref_obj_id) {
4517 if (meta->ref_obj_id) {
4518 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
4519 regno, reg->ref_obj_id,
4523 meta->ref_obj_id = reg->ref_obj_id;
4526 if (arg_type == ARG_CONST_MAP_PTR) {
4527 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
4528 meta->map_ptr = reg->map_ptr;
4529 } else if (arg_type == ARG_PTR_TO_MAP_KEY) {
4530 /* bpf_map_xxx(..., map_ptr, ..., key) call:
4531 * check that [key, key + map->key_size) are within
4532 * stack limits and initialized
4534 if (!meta->map_ptr) {
4535 /* in function declaration map_ptr must come before
4536 * map_key, so that it's verified and known before
4537 * we have to check map_key here. Otherwise it means
4538 * that kernel subsystem misconfigured verifier
4540 verbose(env, "invalid map_ptr to access map->key\n");
4543 err = check_helper_mem_access(env, regno,
4544 meta->map_ptr->key_size, false,
4546 } else if (arg_type == ARG_PTR_TO_MAP_VALUE ||
4547 (arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL &&
4548 !register_is_null(reg)) ||
4549 arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE) {
4550 /* bpf_map_xxx(..., map_ptr, ..., value) call:
4551 * check [value, value + map->value_size) validity
4553 if (!meta->map_ptr) {
4554 /* kernel subsystem misconfigured verifier */
4555 verbose(env, "invalid map_ptr to access map->value\n");
4558 meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE);
4559 err = check_helper_mem_access(env, regno,
4560 meta->map_ptr->value_size, false,
4562 } else if (arg_type == ARG_PTR_TO_PERCPU_BTF_ID) {
4564 verbose(env, "Helper has invalid btf_id in R%d\n", regno);
4567 meta->ret_btf_id = reg->btf_id;
4568 } else if (arg_type == ARG_PTR_TO_SPIN_LOCK) {
4569 if (meta->func_id == BPF_FUNC_spin_lock) {
4570 if (process_spin_lock(env, regno, true))
4572 } else if (meta->func_id == BPF_FUNC_spin_unlock) {
4573 if (process_spin_lock(env, regno, false))
4576 verbose(env, "verifier internal error\n");
4579 } else if (arg_type_is_mem_ptr(arg_type)) {
4580 /* The access to this pointer is only checked when we hit the
4581 * next is_mem_size argument below.
4583 meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MEM);
4584 } else if (arg_type_is_mem_size(arg_type)) {
4585 bool zero_size_allowed = (arg_type == ARG_CONST_SIZE_OR_ZERO);
4587 /* This is used to refine r0 return value bounds for helpers
4588 * that enforce this value as an upper bound on return values.
4589 * See do_refine_retval_range() for helpers that can refine
4590 * the return value. C type of helper is u32 so we pull register
4591 * bound from umax_value however, if negative verifier errors
4592 * out. Only upper bounds can be learned because retval is an
4593 * int type and negative retvals are allowed.
4595 meta->msize_max_value = reg->umax_value;
4597 /* The register is SCALAR_VALUE; the access check
4598 * happens using its boundaries.
4600 if (!tnum_is_const(reg->var_off))
4601 /* For unprivileged variable accesses, disable raw
4602 * mode so that the program is required to
4603 * initialize all the memory that the helper could
4604 * just partially fill up.
4608 if (reg->smin_value < 0) {
4609 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
4614 if (reg->umin_value == 0) {
4615 err = check_helper_mem_access(env, regno - 1, 0,
4622 if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
4623 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
4627 err = check_helper_mem_access(env, regno - 1,
4629 zero_size_allowed, meta);
4631 err = mark_chain_precision(env, regno);
4632 } else if (arg_type_is_alloc_size(arg_type)) {
4633 if (!tnum_is_const(reg->var_off)) {
4634 verbose(env, "R%d unbounded size, use 'var &= const' or 'if (var < const)'\n",
4638 meta->mem_size = reg->var_off.value;
4639 } else if (arg_type_is_int_ptr(arg_type)) {
4640 int size = int_ptr_type_to_size(arg_type);
4642 err = check_helper_mem_access(env, regno, size, false, meta);
4645 err = check_ptr_alignment(env, reg, 0, size, true);
4651 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
4653 enum bpf_attach_type eatype = env->prog->expected_attach_type;
4654 enum bpf_prog_type type = resolve_prog_type(env->prog);
4656 if (func_id != BPF_FUNC_map_update_elem)
4659 /* It's not possible to get access to a locked struct sock in these
4660 * contexts, so updating is safe.
4663 case BPF_PROG_TYPE_TRACING:
4664 if (eatype == BPF_TRACE_ITER)
4667 case BPF_PROG_TYPE_SOCKET_FILTER:
4668 case BPF_PROG_TYPE_SCHED_CLS:
4669 case BPF_PROG_TYPE_SCHED_ACT:
4670 case BPF_PROG_TYPE_XDP:
4671 case BPF_PROG_TYPE_SK_REUSEPORT:
4672 case BPF_PROG_TYPE_FLOW_DISSECTOR:
4673 case BPF_PROG_TYPE_SK_LOOKUP:
4679 verbose(env, "cannot update sockmap in this context\n");
4683 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
4685 return env->prog->jit_requested && IS_ENABLED(CONFIG_X86_64);
4688 static int check_map_func_compatibility(struct bpf_verifier_env *env,
4689 struct bpf_map *map, int func_id)
4694 /* We need a two way check, first is from map perspective ... */
4695 switch (map->map_type) {
4696 case BPF_MAP_TYPE_PROG_ARRAY:
4697 if (func_id != BPF_FUNC_tail_call)
4700 case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
4701 if (func_id != BPF_FUNC_perf_event_read &&
4702 func_id != BPF_FUNC_perf_event_output &&
4703 func_id != BPF_FUNC_skb_output &&
4704 func_id != BPF_FUNC_perf_event_read_value &&
4705 func_id != BPF_FUNC_xdp_output)
4708 case BPF_MAP_TYPE_RINGBUF:
4709 if (func_id != BPF_FUNC_ringbuf_output &&
4710 func_id != BPF_FUNC_ringbuf_reserve &&
4711 func_id != BPF_FUNC_ringbuf_query)
4714 case BPF_MAP_TYPE_STACK_TRACE:
4715 if (func_id != BPF_FUNC_get_stackid)
4718 case BPF_MAP_TYPE_CGROUP_ARRAY:
4719 if (func_id != BPF_FUNC_skb_under_cgroup &&
4720 func_id != BPF_FUNC_current_task_under_cgroup)
4723 case BPF_MAP_TYPE_CGROUP_STORAGE:
4724 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
4725 if (func_id != BPF_FUNC_get_local_storage)
4728 case BPF_MAP_TYPE_DEVMAP:
4729 case BPF_MAP_TYPE_DEVMAP_HASH:
4730 if (func_id != BPF_FUNC_redirect_map &&
4731 func_id != BPF_FUNC_map_lookup_elem)
4734 /* Restrict bpf side of cpumap and xskmap, open when use-cases
4737 case BPF_MAP_TYPE_CPUMAP:
4738 if (func_id != BPF_FUNC_redirect_map)
4741 case BPF_MAP_TYPE_XSKMAP:
4742 if (func_id != BPF_FUNC_redirect_map &&
4743 func_id != BPF_FUNC_map_lookup_elem)
4746 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
4747 case BPF_MAP_TYPE_HASH_OF_MAPS:
4748 if (func_id != BPF_FUNC_map_lookup_elem)
4751 case BPF_MAP_TYPE_SOCKMAP:
4752 if (func_id != BPF_FUNC_sk_redirect_map &&
4753 func_id != BPF_FUNC_sock_map_update &&
4754 func_id != BPF_FUNC_map_delete_elem &&
4755 func_id != BPF_FUNC_msg_redirect_map &&
4756 func_id != BPF_FUNC_sk_select_reuseport &&
4757 func_id != BPF_FUNC_map_lookup_elem &&
4758 !may_update_sockmap(env, func_id))
4761 case BPF_MAP_TYPE_SOCKHASH:
4762 if (func_id != BPF_FUNC_sk_redirect_hash &&
4763 func_id != BPF_FUNC_sock_hash_update &&
4764 func_id != BPF_FUNC_map_delete_elem &&
4765 func_id != BPF_FUNC_msg_redirect_hash &&
4766 func_id != BPF_FUNC_sk_select_reuseport &&
4767 func_id != BPF_FUNC_map_lookup_elem &&
4768 !may_update_sockmap(env, func_id))
4771 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
4772 if (func_id != BPF_FUNC_sk_select_reuseport)
4775 case BPF_MAP_TYPE_QUEUE:
4776 case BPF_MAP_TYPE_STACK:
4777 if (func_id != BPF_FUNC_map_peek_elem &&
4778 func_id != BPF_FUNC_map_pop_elem &&
4779 func_id != BPF_FUNC_map_push_elem)
4782 case BPF_MAP_TYPE_SK_STORAGE:
4783 if (func_id != BPF_FUNC_sk_storage_get &&
4784 func_id != BPF_FUNC_sk_storage_delete)
4787 case BPF_MAP_TYPE_INODE_STORAGE:
4788 if (func_id != BPF_FUNC_inode_storage_get &&
4789 func_id != BPF_FUNC_inode_storage_delete)
4796 /* ... and second from the function itself. */
4798 case BPF_FUNC_tail_call:
4799 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
4801 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
4802 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
4806 case BPF_FUNC_perf_event_read:
4807 case BPF_FUNC_perf_event_output:
4808 case BPF_FUNC_perf_event_read_value:
4809 case BPF_FUNC_skb_output:
4810 case BPF_FUNC_xdp_output:
4811 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
4814 case BPF_FUNC_ringbuf_output:
4815 case BPF_FUNC_ringbuf_reserve:
4816 case BPF_FUNC_ringbuf_query:
4817 if (map->map_type != BPF_MAP_TYPE_RINGBUF)
4820 case BPF_FUNC_get_stackid:
4821 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
4824 case BPF_FUNC_current_task_under_cgroup:
4825 case BPF_FUNC_skb_under_cgroup:
4826 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
4829 case BPF_FUNC_redirect_map:
4830 if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
4831 map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
4832 map->map_type != BPF_MAP_TYPE_CPUMAP &&
4833 map->map_type != BPF_MAP_TYPE_XSKMAP)
4836 case BPF_FUNC_sk_redirect_map:
4837 case BPF_FUNC_msg_redirect_map:
4838 case BPF_FUNC_sock_map_update:
4839 if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
4842 case BPF_FUNC_sk_redirect_hash:
4843 case BPF_FUNC_msg_redirect_hash:
4844 case BPF_FUNC_sock_hash_update:
4845 if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
4848 case BPF_FUNC_get_local_storage:
4849 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
4850 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
4853 case BPF_FUNC_sk_select_reuseport:
4854 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
4855 map->map_type != BPF_MAP_TYPE_SOCKMAP &&
4856 map->map_type != BPF_MAP_TYPE_SOCKHASH)
4859 case BPF_FUNC_map_peek_elem:
4860 case BPF_FUNC_map_pop_elem:
4861 case BPF_FUNC_map_push_elem:
4862 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
4863 map->map_type != BPF_MAP_TYPE_STACK)
4866 case BPF_FUNC_sk_storage_get:
4867 case BPF_FUNC_sk_storage_delete:
4868 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
4871 case BPF_FUNC_inode_storage_get:
4872 case BPF_FUNC_inode_storage_delete:
4873 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
4882 verbose(env, "cannot pass map_type %d into func %s#%d\n",
4883 map->map_type, func_id_name(func_id), func_id);
4887 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
4891 if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
4893 if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
4895 if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
4897 if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
4899 if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
4902 /* We only support one arg being in raw mode at the moment,
4903 * which is sufficient for the helper functions we have
4909 static bool check_args_pair_invalid(enum bpf_arg_type arg_curr,
4910 enum bpf_arg_type arg_next)
4912 return (arg_type_is_mem_ptr(arg_curr) &&
4913 !arg_type_is_mem_size(arg_next)) ||
4914 (!arg_type_is_mem_ptr(arg_curr) &&
4915 arg_type_is_mem_size(arg_next));
4918 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
4920 /* bpf_xxx(..., buf, len) call will access 'len'
4921 * bytes from memory 'buf'. Both arg types need
4922 * to be paired, so make sure there's no buggy
4923 * helper function specification.
4925 if (arg_type_is_mem_size(fn->arg1_type) ||
4926 arg_type_is_mem_ptr(fn->arg5_type) ||
4927 check_args_pair_invalid(fn->arg1_type, fn->arg2_type) ||
4928 check_args_pair_invalid(fn->arg2_type, fn->arg3_type) ||
4929 check_args_pair_invalid(fn->arg3_type, fn->arg4_type) ||
4930 check_args_pair_invalid(fn->arg4_type, fn->arg5_type))
4936 static bool check_refcount_ok(const struct bpf_func_proto *fn, int func_id)
4940 if (arg_type_may_be_refcounted(fn->arg1_type))
4942 if (arg_type_may_be_refcounted(fn->arg2_type))
4944 if (arg_type_may_be_refcounted(fn->arg3_type))
4946 if (arg_type_may_be_refcounted(fn->arg4_type))
4948 if (arg_type_may_be_refcounted(fn->arg5_type))
4951 /* A reference acquiring function cannot acquire
4952 * another refcounted ptr.
4954 if (may_be_acquire_function(func_id) && count)
4957 /* We only support one arg being unreferenced at the moment,
4958 * which is sufficient for the helper functions we have right now.
4963 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
4967 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
4968 if (fn->arg_type[i] == ARG_PTR_TO_BTF_ID && !fn->arg_btf_id[i])
4971 if (fn->arg_type[i] != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i])
4978 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
4980 return check_raw_mode_ok(fn) &&
4981 check_arg_pair_ok(fn) &&
4982 check_btf_id_ok(fn) &&
4983 check_refcount_ok(fn, func_id) ? 0 : -EINVAL;
4986 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
4987 * are now invalid, so turn them into unknown SCALAR_VALUE.
4989 static void __clear_all_pkt_pointers(struct bpf_verifier_env *env,
4990 struct bpf_func_state *state)
4992 struct bpf_reg_state *regs = state->regs, *reg;
4995 for (i = 0; i < MAX_BPF_REG; i++)
4996 if (reg_is_pkt_pointer_any(®s[i]))
4997 mark_reg_unknown(env, regs, i);
4999 bpf_for_each_spilled_reg(i, state, reg) {
5002 if (reg_is_pkt_pointer_any(reg))
5003 __mark_reg_unknown(env, reg);
5007 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
5009 struct bpf_verifier_state *vstate = env->cur_state;
5012 for (i = 0; i <= vstate->curframe; i++)
5013 __clear_all_pkt_pointers(env, vstate->frame[i]);
5016 static void release_reg_references(struct bpf_verifier_env *env,
5017 struct bpf_func_state *state,
5020 struct bpf_reg_state *regs = state->regs, *reg;
5023 for (i = 0; i < MAX_BPF_REG; i++)
5024 if (regs[i].ref_obj_id == ref_obj_id)
5025 mark_reg_unknown(env, regs, i);
5027 bpf_for_each_spilled_reg(i, state, reg) {
5030 if (reg->ref_obj_id == ref_obj_id)
5031 __mark_reg_unknown(env, reg);
5035 /* The pointer with the specified id has released its reference to kernel
5036 * resources. Identify all copies of the same pointer and clear the reference.
5038 static int release_reference(struct bpf_verifier_env *env,
5041 struct bpf_verifier_state *vstate = env->cur_state;
5045 err = release_reference_state(cur_func(env), ref_obj_id);
5049 for (i = 0; i <= vstate->curframe; i++)
5050 release_reg_references(env, vstate->frame[i], ref_obj_id);
5055 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
5056 struct bpf_reg_state *regs)
5060 /* after the call registers r0 - r5 were scratched */
5061 for (i = 0; i < CALLER_SAVED_REGS; i++) {
5062 mark_reg_not_init(env, regs, caller_saved[i]);
5063 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
5067 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
5070 struct bpf_verifier_state *state = env->cur_state;
5071 struct bpf_func_info_aux *func_info_aux;
5072 struct bpf_func_state *caller, *callee;
5073 int i, err, subprog, target_insn;
5074 bool is_global = false;
5076 if (state->curframe + 1 >= MAX_CALL_FRAMES) {
5077 verbose(env, "the call stack of %d frames is too deep\n",
5078 state->curframe + 2);
5082 target_insn = *insn_idx + insn->imm;
5083 subprog = find_subprog(env, target_insn + 1);
5085 verbose(env, "verifier bug. No program starts at insn %d\n",
5090 caller = state->frame[state->curframe];
5091 if (state->frame[state->curframe + 1]) {
5092 verbose(env, "verifier bug. Frame %d already allocated\n",
5093 state->curframe + 1);
5097 func_info_aux = env->prog->aux->func_info_aux;
5099 is_global = func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
5100 err = btf_check_func_arg_match(env, subprog, caller->regs);
5105 verbose(env, "Caller passes invalid args into func#%d\n",
5109 if (env->log.level & BPF_LOG_LEVEL)
5111 "Func#%d is global and valid. Skipping.\n",
5113 clear_caller_saved_regs(env, caller->regs);
5115 /* All global functions return a 64-bit SCALAR_VALUE */
5116 mark_reg_unknown(env, caller->regs, BPF_REG_0);
5117 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
5119 /* continue with next insn after call */
5124 callee = kzalloc(sizeof(*callee), GFP_KERNEL);
5127 state->frame[state->curframe + 1] = callee;
5129 /* callee cannot access r0, r6 - r9 for reading and has to write
5130 * into its own stack before reading from it.
5131 * callee can read/write into caller's stack
5133 init_func_state(env, callee,
5134 /* remember the callsite, it will be used by bpf_exit */
5135 *insn_idx /* callsite */,
5136 state->curframe + 1 /* frameno within this callchain */,
5137 subprog /* subprog number within this prog */);
5139 /* Transfer references to the callee */
5140 err = transfer_reference_state(callee, caller);
5144 /* copy r1 - r5 args that callee can access. The copy includes parent
5145 * pointers, which connects us up to the liveness chain
5147 for (i = BPF_REG_1; i <= BPF_REG_5; i++)
5148 callee->regs[i] = caller->regs[i];
5150 clear_caller_saved_regs(env, caller->regs);
5152 /* only increment it after check_reg_arg() finished */
5155 /* and go analyze first insn of the callee */
5156 *insn_idx = target_insn;
5158 if (env->log.level & BPF_LOG_LEVEL) {
5159 verbose(env, "caller:\n");
5160 print_verifier_state(env, caller);
5161 verbose(env, "callee:\n");
5162 print_verifier_state(env, callee);
5167 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
5169 struct bpf_verifier_state *state = env->cur_state;
5170 struct bpf_func_state *caller, *callee;
5171 struct bpf_reg_state *r0;
5174 callee = state->frame[state->curframe];
5175 r0 = &callee->regs[BPF_REG_0];
5176 if (r0->type == PTR_TO_STACK) {
5177 /* technically it's ok to return caller's stack pointer
5178 * (or caller's caller's pointer) back to the caller,
5179 * since these pointers are valid. Only current stack
5180 * pointer will be invalid as soon as function exits,
5181 * but let's be conservative
5183 verbose(env, "cannot return stack pointer to the caller\n");
5188 caller = state->frame[state->curframe];
5189 /* return to the caller whatever r0 had in the callee */
5190 caller->regs[BPF_REG_0] = *r0;
5192 /* Transfer references to the caller */
5193 err = transfer_reference_state(caller, callee);
5197 *insn_idx = callee->callsite + 1;
5198 if (env->log.level & BPF_LOG_LEVEL) {
5199 verbose(env, "returning from callee:\n");
5200 print_verifier_state(env, callee);
5201 verbose(env, "to caller at %d:\n", *insn_idx);
5202 print_verifier_state(env, caller);
5204 /* clear everything in the callee */
5205 free_func_state(callee);
5206 state->frame[state->curframe + 1] = NULL;
5210 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
5212 struct bpf_call_arg_meta *meta)
5214 struct bpf_reg_state *ret_reg = ®s[BPF_REG_0];
5216 if (ret_type != RET_INTEGER ||
5217 (func_id != BPF_FUNC_get_stack &&
5218 func_id != BPF_FUNC_probe_read_str &&
5219 func_id != BPF_FUNC_probe_read_kernel_str &&
5220 func_id != BPF_FUNC_probe_read_user_str))
5223 ret_reg->smax_value = meta->msize_max_value;
5224 ret_reg->s32_max_value = meta->msize_max_value;
5225 ret_reg->smin_value = -MAX_ERRNO;
5226 ret_reg->s32_min_value = -MAX_ERRNO;
5227 __reg_deduce_bounds(ret_reg);
5228 __reg_bound_offset(ret_reg);
5229 __update_reg_bounds(ret_reg);
5233 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
5234 int func_id, int insn_idx)
5236 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
5237 struct bpf_map *map = meta->map_ptr;
5239 if (func_id != BPF_FUNC_tail_call &&
5240 func_id != BPF_FUNC_map_lookup_elem &&
5241 func_id != BPF_FUNC_map_update_elem &&
5242 func_id != BPF_FUNC_map_delete_elem &&
5243 func_id != BPF_FUNC_map_push_elem &&
5244 func_id != BPF_FUNC_map_pop_elem &&
5245 func_id != BPF_FUNC_map_peek_elem)
5249 verbose(env, "kernel subsystem misconfigured verifier\n");
5253 /* In case of read-only, some additional restrictions
5254 * need to be applied in order to prevent altering the
5255 * state of the map from program side.
5257 if ((map->map_flags & BPF_F_RDONLY_PROG) &&
5258 (func_id == BPF_FUNC_map_delete_elem ||
5259 func_id == BPF_FUNC_map_update_elem ||
5260 func_id == BPF_FUNC_map_push_elem ||
5261 func_id == BPF_FUNC_map_pop_elem)) {
5262 verbose(env, "write into map forbidden\n");
5266 if (!BPF_MAP_PTR(aux->map_ptr_state))
5267 bpf_map_ptr_store(aux, meta->map_ptr,
5268 !meta->map_ptr->bypass_spec_v1);
5269 else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
5270 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
5271 !meta->map_ptr->bypass_spec_v1);
5276 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
5277 int func_id, int insn_idx)
5279 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
5280 struct bpf_reg_state *regs = cur_regs(env), *reg;
5281 struct bpf_map *map = meta->map_ptr;
5286 if (func_id != BPF_FUNC_tail_call)
5288 if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
5289 verbose(env, "kernel subsystem misconfigured verifier\n");
5293 range = tnum_range(0, map->max_entries - 1);
5294 reg = ®s[BPF_REG_3];
5296 if (!register_is_const(reg) || !tnum_in(range, reg->var_off)) {
5297 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
5301 err = mark_chain_precision(env, BPF_REG_3);
5305 val = reg->var_off.value;
5306 if (bpf_map_key_unseen(aux))
5307 bpf_map_key_store(aux, val);
5308 else if (!bpf_map_key_poisoned(aux) &&
5309 bpf_map_key_immediate(aux) != val)
5310 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
5314 static int check_reference_leak(struct bpf_verifier_env *env)
5316 struct bpf_func_state *state = cur_func(env);
5319 for (i = 0; i < state->acquired_refs; i++) {
5320 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
5321 state->refs[i].id, state->refs[i].insn_idx);
5323 return state->acquired_refs ? -EINVAL : 0;
5326 static int check_helper_call(struct bpf_verifier_env *env, int func_id, int insn_idx)
5328 const struct bpf_func_proto *fn = NULL;
5329 struct bpf_reg_state *regs;
5330 struct bpf_call_arg_meta meta;
5334 /* find function prototype */
5335 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
5336 verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
5341 if (env->ops->get_func_proto)
5342 fn = env->ops->get_func_proto(func_id, env->prog);
5344 verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
5349 /* eBPF programs must be GPL compatible to use GPL-ed functions */
5350 if (!env->prog->gpl_compatible && fn->gpl_only) {
5351 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
5355 if (fn->allowed && !fn->allowed(env->prog)) {
5356 verbose(env, "helper call is not allowed in probe\n");
5360 /* With LD_ABS/IND some JITs save/restore skb from r1. */
5361 changes_data = bpf_helper_changes_pkt_data(fn->func);
5362 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
5363 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
5364 func_id_name(func_id), func_id);
5368 memset(&meta, 0, sizeof(meta));
5369 meta.pkt_access = fn->pkt_access;
5371 err = check_func_proto(fn, func_id);
5373 verbose(env, "kernel subsystem misconfigured func %s#%d\n",
5374 func_id_name(func_id), func_id);
5378 meta.func_id = func_id;
5380 for (i = 0; i < 5; i++) {
5381 err = check_func_arg(env, i, &meta, fn);
5386 err = record_func_map(env, &meta, func_id, insn_idx);
5390 err = record_func_key(env, &meta, func_id, insn_idx);
5394 /* Mark slots with STACK_MISC in case of raw mode, stack offset
5395 * is inferred from register state.
5397 for (i = 0; i < meta.access_size; i++) {
5398 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
5399 BPF_WRITE, -1, false);
5404 if (func_id == BPF_FUNC_tail_call) {
5405 err = check_reference_leak(env);
5407 verbose(env, "tail_call would lead to reference leak\n");
5410 } else if (is_release_function(func_id)) {
5411 err = release_reference(env, meta.ref_obj_id);
5413 verbose(env, "func %s#%d reference has not been acquired before\n",
5414 func_id_name(func_id), func_id);
5419 regs = cur_regs(env);
5421 /* check that flags argument in get_local_storage(map, flags) is 0,
5422 * this is required because get_local_storage() can't return an error.
5424 if (func_id == BPF_FUNC_get_local_storage &&
5425 !register_is_null(®s[BPF_REG_2])) {
5426 verbose(env, "get_local_storage() doesn't support non-zero flags\n");
5430 /* reset caller saved regs */
5431 for (i = 0; i < CALLER_SAVED_REGS; i++) {
5432 mark_reg_not_init(env, regs, caller_saved[i]);
5433 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
5436 /* helper call returns 64-bit value. */
5437 regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
5439 /* update return register (already marked as written above) */
5440 if (fn->ret_type == RET_INTEGER) {
5441 /* sets type to SCALAR_VALUE */
5442 mark_reg_unknown(env, regs, BPF_REG_0);
5443 } else if (fn->ret_type == RET_VOID) {
5444 regs[BPF_REG_0].type = NOT_INIT;
5445 } else if (fn->ret_type == RET_PTR_TO_MAP_VALUE_OR_NULL ||
5446 fn->ret_type == RET_PTR_TO_MAP_VALUE) {
5447 /* There is no offset yet applied, variable or fixed */
5448 mark_reg_known_zero(env, regs, BPF_REG_0);
5449 /* remember map_ptr, so that check_map_access()
5450 * can check 'value_size' boundary of memory access
5451 * to map element returned from bpf_map_lookup_elem()
5453 if (meta.map_ptr == NULL) {
5455 "kernel subsystem misconfigured verifier\n");
5458 regs[BPF_REG_0].map_ptr = meta.map_ptr;
5459 if (fn->ret_type == RET_PTR_TO_MAP_VALUE) {
5460 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE;
5461 if (map_value_has_spin_lock(meta.map_ptr))
5462 regs[BPF_REG_0].id = ++env->id_gen;
5464 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE_OR_NULL;
5466 } else if (fn->ret_type == RET_PTR_TO_SOCKET_OR_NULL) {
5467 mark_reg_known_zero(env, regs, BPF_REG_0);
5468 regs[BPF_REG_0].type = PTR_TO_SOCKET_OR_NULL;
5469 } else if (fn->ret_type == RET_PTR_TO_SOCK_COMMON_OR_NULL) {
5470 mark_reg_known_zero(env, regs, BPF_REG_0);
5471 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON_OR_NULL;
5472 } else if (fn->ret_type == RET_PTR_TO_TCP_SOCK_OR_NULL) {
5473 mark_reg_known_zero(env, regs, BPF_REG_0);
5474 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK_OR_NULL;
5475 } else if (fn->ret_type == RET_PTR_TO_ALLOC_MEM_OR_NULL) {
5476 mark_reg_known_zero(env, regs, BPF_REG_0);
5477 regs[BPF_REG_0].type = PTR_TO_MEM_OR_NULL;
5478 regs[BPF_REG_0].mem_size = meta.mem_size;
5479 } else if (fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID_OR_NULL ||
5480 fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID) {
5481 const struct btf_type *t;
5483 mark_reg_known_zero(env, regs, BPF_REG_0);
5484 t = btf_type_skip_modifiers(btf_vmlinux, meta.ret_btf_id, NULL);
5485 if (!btf_type_is_struct(t)) {
5487 const struct btf_type *ret;
5490 /* resolve the type size of ksym. */
5491 ret = btf_resolve_size(btf_vmlinux, t, &tsize);
5493 tname = btf_name_by_offset(btf_vmlinux, t->name_off);
5494 verbose(env, "unable to resolve the size of type '%s': %ld\n",
5495 tname, PTR_ERR(ret));
5498 regs[BPF_REG_0].type =
5499 fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID ?
5500 PTR_TO_MEM : PTR_TO_MEM_OR_NULL;
5501 regs[BPF_REG_0].mem_size = tsize;
5503 regs[BPF_REG_0].type =
5504 fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID ?
5505 PTR_TO_BTF_ID : PTR_TO_BTF_ID_OR_NULL;
5506 regs[BPF_REG_0].btf_id = meta.ret_btf_id;
5508 } else if (fn->ret_type == RET_PTR_TO_BTF_ID_OR_NULL) {
5511 mark_reg_known_zero(env, regs, BPF_REG_0);
5512 regs[BPF_REG_0].type = PTR_TO_BTF_ID_OR_NULL;
5513 ret_btf_id = *fn->ret_btf_id;
5514 if (ret_btf_id == 0) {
5515 verbose(env, "invalid return type %d of func %s#%d\n",
5516 fn->ret_type, func_id_name(func_id), func_id);
5519 regs[BPF_REG_0].btf_id = ret_btf_id;
5521 verbose(env, "unknown return type %d of func %s#%d\n",
5522 fn->ret_type, func_id_name(func_id), func_id);
5526 if (reg_type_may_be_null(regs[BPF_REG_0].type))
5527 regs[BPF_REG_0].id = ++env->id_gen;
5529 if (is_ptr_cast_function(func_id)) {
5530 /* For release_reference() */
5531 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
5532 } else if (is_acquire_function(func_id, meta.map_ptr)) {
5533 int id = acquire_reference_state(env, insn_idx);
5537 /* For mark_ptr_or_null_reg() */
5538 regs[BPF_REG_0].id = id;
5539 /* For release_reference() */
5540 regs[BPF_REG_0].ref_obj_id = id;
5543 do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
5545 err = check_map_func_compatibility(env, meta.map_ptr, func_id);
5549 if ((func_id == BPF_FUNC_get_stack ||
5550 func_id == BPF_FUNC_get_task_stack) &&
5551 !env->prog->has_callchain_buf) {
5552 const char *err_str;
5554 #ifdef CONFIG_PERF_EVENTS
5555 err = get_callchain_buffers(sysctl_perf_event_max_stack);
5556 err_str = "cannot get callchain buffer for func %s#%d\n";
5559 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
5562 verbose(env, err_str, func_id_name(func_id), func_id);
5566 env->prog->has_callchain_buf = true;
5569 if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
5570 env->prog->call_get_stack = true;
5573 clear_all_pkt_pointers(env);
5577 static bool signed_add_overflows(s64 a, s64 b)
5579 /* Do the add in u64, where overflow is well-defined */
5580 s64 res = (s64)((u64)a + (u64)b);
5587 static bool signed_add32_overflows(s32 a, s32 b)
5589 /* Do the add in u32, where overflow is well-defined */
5590 s32 res = (s32)((u32)a + (u32)b);
5597 static bool signed_sub_overflows(s64 a, s64 b)
5599 /* Do the sub in u64, where overflow is well-defined */
5600 s64 res = (s64)((u64)a - (u64)b);
5607 static bool signed_sub32_overflows(s32 a, s32 b)
5609 /* Do the sub in u32, where overflow is well-defined */
5610 s32 res = (s32)((u32)a - (u32)b);
5617 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
5618 const struct bpf_reg_state *reg,
5619 enum bpf_reg_type type)
5621 bool known = tnum_is_const(reg->var_off);
5622 s64 val = reg->var_off.value;
5623 s64 smin = reg->smin_value;
5625 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
5626 verbose(env, "math between %s pointer and %lld is not allowed\n",
5627 reg_type_str[type], val);
5631 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
5632 verbose(env, "%s pointer offset %d is not allowed\n",
5633 reg_type_str[type], reg->off);
5637 if (smin == S64_MIN) {
5638 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
5639 reg_type_str[type]);
5643 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
5644 verbose(env, "value %lld makes %s pointer be out of bounds\n",
5645 smin, reg_type_str[type]);
5652 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
5654 return &env->insn_aux_data[env->insn_idx];
5665 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
5666 u32 *alu_limit, bool mask_to_left)
5668 u32 max = 0, ptr_limit = 0;
5670 switch (ptr_reg->type) {
5672 /* Offset 0 is out-of-bounds, but acceptable start for the
5673 * left direction, see BPF_REG_FP. Also, unknown scalar
5674 * offset where we would need to deal with min/max bounds is
5675 * currently prohibited for unprivileged.
5677 max = MAX_BPF_STACK + mask_to_left;
5678 ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
5680 case PTR_TO_MAP_VALUE:
5681 max = ptr_reg->map_ptr->value_size;
5682 ptr_limit = (mask_to_left ?
5683 ptr_reg->smin_value :
5684 ptr_reg->umax_value) + ptr_reg->off;
5690 if (ptr_limit >= max)
5691 return REASON_LIMIT;
5692 *alu_limit = ptr_limit;
5696 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
5697 const struct bpf_insn *insn)
5699 return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
5702 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
5703 u32 alu_state, u32 alu_limit)
5705 /* If we arrived here from different branches with different
5706 * state or limits to sanitize, then this won't work.
5708 if (aux->alu_state &&
5709 (aux->alu_state != alu_state ||
5710 aux->alu_limit != alu_limit))
5711 return REASON_PATHS;
5713 /* Corresponding fixup done in fixup_bpf_calls(). */
5714 aux->alu_state = alu_state;
5715 aux->alu_limit = alu_limit;
5719 static int sanitize_val_alu(struct bpf_verifier_env *env,
5720 struct bpf_insn *insn)
5722 struct bpf_insn_aux_data *aux = cur_aux(env);
5724 if (can_skip_alu_sanitation(env, insn))
5727 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
5730 static bool sanitize_needed(u8 opcode)
5732 return opcode == BPF_ADD || opcode == BPF_SUB;
5735 struct bpf_sanitize_info {
5736 struct bpf_insn_aux_data aux;
5740 static struct bpf_verifier_state *
5741 sanitize_speculative_path(struct bpf_verifier_env *env,
5742 const struct bpf_insn *insn,
5743 u32 next_idx, u32 curr_idx)
5745 struct bpf_verifier_state *branch;
5746 struct bpf_reg_state *regs;
5748 branch = push_stack(env, next_idx, curr_idx, true);
5749 if (branch && insn) {
5750 regs = branch->frame[branch->curframe]->regs;
5751 if (BPF_SRC(insn->code) == BPF_K) {
5752 mark_reg_unknown(env, regs, insn->dst_reg);
5753 } else if (BPF_SRC(insn->code) == BPF_X) {
5754 mark_reg_unknown(env, regs, insn->dst_reg);
5755 mark_reg_unknown(env, regs, insn->src_reg);
5761 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
5762 struct bpf_insn *insn,
5763 const struct bpf_reg_state *ptr_reg,
5764 const struct bpf_reg_state *off_reg,
5765 struct bpf_reg_state *dst_reg,
5766 struct bpf_sanitize_info *info,
5767 const bool commit_window)
5769 struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
5770 struct bpf_verifier_state *vstate = env->cur_state;
5771 bool off_is_imm = tnum_is_const(off_reg->var_off);
5772 bool off_is_neg = off_reg->smin_value < 0;
5773 bool ptr_is_dst_reg = ptr_reg == dst_reg;
5774 u8 opcode = BPF_OP(insn->code);
5775 u32 alu_state, alu_limit;
5776 struct bpf_reg_state tmp;
5780 if (can_skip_alu_sanitation(env, insn))
5783 /* We already marked aux for masking from non-speculative
5784 * paths, thus we got here in the first place. We only care
5785 * to explore bad access from here.
5787 if (vstate->speculative)
5790 if (!commit_window) {
5791 if (!tnum_is_const(off_reg->var_off) &&
5792 (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
5793 return REASON_BOUNDS;
5795 info->mask_to_left = (opcode == BPF_ADD && off_is_neg) ||
5796 (opcode == BPF_SUB && !off_is_neg);
5799 err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
5803 if (commit_window) {
5804 /* In commit phase we narrow the masking window based on
5805 * the observed pointer move after the simulated operation.
5807 alu_state = info->aux.alu_state;
5808 alu_limit = abs(info->aux.alu_limit - alu_limit);
5810 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
5811 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
5812 alu_state |= ptr_is_dst_reg ?
5813 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
5815 /* Limit pruning on unknown scalars to enable deep search for
5816 * potential masking differences from other program paths.
5819 env->explore_alu_limits = true;
5822 err = update_alu_sanitation_state(aux, alu_state, alu_limit);
5826 /* If we're in commit phase, we're done here given we already
5827 * pushed the truncated dst_reg into the speculative verification
5830 * Also, when register is a known constant, we rewrite register-based
5831 * operation to immediate-based, and thus do not need masking (and as
5832 * a consequence, do not need to simulate the zero-truncation either).
5834 if (commit_window || off_is_imm)
5837 /* Simulate and find potential out-of-bounds access under
5838 * speculative execution from truncation as a result of
5839 * masking when off was not within expected range. If off
5840 * sits in dst, then we temporarily need to move ptr there
5841 * to simulate dst (== 0) +/-= ptr. Needed, for example,
5842 * for cases where we use K-based arithmetic in one direction
5843 * and truncated reg-based in the other in order to explore
5846 if (!ptr_is_dst_reg) {
5848 *dst_reg = *ptr_reg;
5850 ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
5852 if (!ptr_is_dst_reg && ret)
5854 return !ret ? REASON_STACK : 0;
5857 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
5859 struct bpf_verifier_state *vstate = env->cur_state;
5861 /* If we simulate paths under speculation, we don't update the
5862 * insn as 'seen' such that when we verify unreachable paths in
5863 * the non-speculative domain, sanitize_dead_code() can still
5864 * rewrite/sanitize them.
5866 if (!vstate->speculative)
5867 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
5870 static int sanitize_err(struct bpf_verifier_env *env,
5871 const struct bpf_insn *insn, int reason,
5872 const struct bpf_reg_state *off_reg,
5873 const struct bpf_reg_state *dst_reg)
5875 static const char *err = "pointer arithmetic with it prohibited for !root";
5876 const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
5877 u32 dst = insn->dst_reg, src = insn->src_reg;
5881 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
5882 off_reg == dst_reg ? dst : src, err);
5885 verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
5886 off_reg == dst_reg ? src : dst, err);
5889 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
5893 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
5897 verbose(env, "R%d could not be pushed for speculative verification, %s\n",
5901 verbose(env, "verifier internal error: unknown reason (%d)\n",
5909 /* check that stack access falls within stack limits and that 'reg' doesn't
5910 * have a variable offset.
5912 * Variable offset is prohibited for unprivileged mode for simplicity since it
5913 * requires corresponding support in Spectre masking for stack ALU. See also
5914 * retrieve_ptr_limit().
5917 * 'off' includes 'reg->off'.
5919 static int check_stack_access_for_ptr_arithmetic(
5920 struct bpf_verifier_env *env,
5922 const struct bpf_reg_state *reg,
5925 if (!tnum_is_const(reg->var_off)) {
5928 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5929 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
5930 regno, tn_buf, off);
5934 if (off >= 0 || off < -MAX_BPF_STACK) {
5935 verbose(env, "R%d stack pointer arithmetic goes out of range, "
5936 "prohibited for !root; off=%d\n", regno, off);
5943 static int sanitize_check_bounds(struct bpf_verifier_env *env,
5944 const struct bpf_insn *insn,
5945 const struct bpf_reg_state *dst_reg)
5947 u32 dst = insn->dst_reg;
5949 /* For unprivileged we require that resulting offset must be in bounds
5950 * in order to be able to sanitize access later on.
5952 if (env->bypass_spec_v1)
5955 switch (dst_reg->type) {
5957 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
5958 dst_reg->off + dst_reg->var_off.value))
5961 case PTR_TO_MAP_VALUE:
5962 if (check_map_access(env, dst, dst_reg->off, 1, false)) {
5963 verbose(env, "R%d pointer arithmetic of map value goes out of range, "
5964 "prohibited for !root\n", dst);
5975 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
5976 * Caller should also handle BPF_MOV case separately.
5977 * If we return -EACCES, caller may want to try again treating pointer as a
5978 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks.
5980 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
5981 struct bpf_insn *insn,
5982 const struct bpf_reg_state *ptr_reg,
5983 const struct bpf_reg_state *off_reg)
5985 struct bpf_verifier_state *vstate = env->cur_state;
5986 struct bpf_func_state *state = vstate->frame[vstate->curframe];
5987 struct bpf_reg_state *regs = state->regs, *dst_reg;
5988 bool known = tnum_is_const(off_reg->var_off);
5989 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
5990 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
5991 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
5992 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
5993 struct bpf_sanitize_info info = {};
5994 u8 opcode = BPF_OP(insn->code);
5995 u32 dst = insn->dst_reg;
5998 dst_reg = ®s[dst];
6000 if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
6001 smin_val > smax_val || umin_val > umax_val) {
6002 /* Taint dst register if offset had invalid bounds derived from
6003 * e.g. dead branches.
6005 __mark_reg_unknown(env, dst_reg);
6009 if (BPF_CLASS(insn->code) != BPF_ALU64) {
6010 /* 32-bit ALU ops on pointers produce (meaningless) scalars */
6011 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
6012 __mark_reg_unknown(env, dst_reg);
6017 "R%d 32-bit pointer arithmetic prohibited\n",
6022 switch (ptr_reg->type) {
6023 case PTR_TO_MAP_VALUE_OR_NULL:
6024 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
6025 dst, reg_type_str[ptr_reg->type]);
6027 case CONST_PTR_TO_MAP:
6028 /* smin_val represents the known value */
6029 if (known && smin_val == 0 && opcode == BPF_ADD)
6032 case PTR_TO_PACKET_END:
6034 case PTR_TO_SOCKET_OR_NULL:
6035 case PTR_TO_SOCK_COMMON:
6036 case PTR_TO_SOCK_COMMON_OR_NULL:
6037 case PTR_TO_TCP_SOCK:
6038 case PTR_TO_TCP_SOCK_OR_NULL:
6039 case PTR_TO_XDP_SOCK:
6040 verbose(env, "R%d pointer arithmetic on %s prohibited\n",
6041 dst, reg_type_str[ptr_reg->type]);
6047 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
6048 * The id may be overwritten later if we create a new variable offset.
6050 dst_reg->type = ptr_reg->type;
6051 dst_reg->id = ptr_reg->id;
6053 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
6054 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
6057 /* pointer types do not carry 32-bit bounds at the moment. */
6058 __mark_reg32_unbounded(dst_reg);
6060 if (sanitize_needed(opcode)) {
6061 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
6064 return sanitize_err(env, insn, ret, off_reg, dst_reg);
6069 /* We can take a fixed offset as long as it doesn't overflow
6070 * the s32 'off' field
6072 if (known && (ptr_reg->off + smin_val ==
6073 (s64)(s32)(ptr_reg->off + smin_val))) {
6074 /* pointer += K. Accumulate it into fixed offset */
6075 dst_reg->smin_value = smin_ptr;
6076 dst_reg->smax_value = smax_ptr;
6077 dst_reg->umin_value = umin_ptr;
6078 dst_reg->umax_value = umax_ptr;
6079 dst_reg->var_off = ptr_reg->var_off;
6080 dst_reg->off = ptr_reg->off + smin_val;
6081 dst_reg->raw = ptr_reg->raw;
6084 /* A new variable offset is created. Note that off_reg->off
6085 * == 0, since it's a scalar.
6086 * dst_reg gets the pointer type and since some positive
6087 * integer value was added to the pointer, give it a new 'id'
6088 * if it's a PTR_TO_PACKET.
6089 * this creates a new 'base' pointer, off_reg (variable) gets
6090 * added into the variable offset, and we copy the fixed offset
6093 if (signed_add_overflows(smin_ptr, smin_val) ||
6094 signed_add_overflows(smax_ptr, smax_val)) {
6095 dst_reg->smin_value = S64_MIN;
6096 dst_reg->smax_value = S64_MAX;
6098 dst_reg->smin_value = smin_ptr + smin_val;
6099 dst_reg->smax_value = smax_ptr + smax_val;
6101 if (umin_ptr + umin_val < umin_ptr ||
6102 umax_ptr + umax_val < umax_ptr) {
6103 dst_reg->umin_value = 0;
6104 dst_reg->umax_value = U64_MAX;
6106 dst_reg->umin_value = umin_ptr + umin_val;
6107 dst_reg->umax_value = umax_ptr + umax_val;
6109 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
6110 dst_reg->off = ptr_reg->off;
6111 dst_reg->raw = ptr_reg->raw;
6112 if (reg_is_pkt_pointer(ptr_reg)) {
6113 dst_reg->id = ++env->id_gen;
6114 /* something was added to pkt_ptr, set range to zero */
6119 if (dst_reg == off_reg) {
6120 /* scalar -= pointer. Creates an unknown scalar */
6121 verbose(env, "R%d tried to subtract pointer from scalar\n",
6125 /* We don't allow subtraction from FP, because (according to
6126 * test_verifier.c test "invalid fp arithmetic", JITs might not
6127 * be able to deal with it.
6129 if (ptr_reg->type == PTR_TO_STACK) {
6130 verbose(env, "R%d subtraction from stack pointer prohibited\n",
6134 if (known && (ptr_reg->off - smin_val ==
6135 (s64)(s32)(ptr_reg->off - smin_val))) {
6136 /* pointer -= K. Subtract it from fixed offset */
6137 dst_reg->smin_value = smin_ptr;
6138 dst_reg->smax_value = smax_ptr;
6139 dst_reg->umin_value = umin_ptr;
6140 dst_reg->umax_value = umax_ptr;
6141 dst_reg->var_off = ptr_reg->var_off;
6142 dst_reg->id = ptr_reg->id;
6143 dst_reg->off = ptr_reg->off - smin_val;
6144 dst_reg->raw = ptr_reg->raw;
6147 /* A new variable offset is created. If the subtrahend is known
6148 * nonnegative, then any reg->range we had before is still good.
6150 if (signed_sub_overflows(smin_ptr, smax_val) ||
6151 signed_sub_overflows(smax_ptr, smin_val)) {
6152 /* Overflow possible, we know nothing */
6153 dst_reg->smin_value = S64_MIN;
6154 dst_reg->smax_value = S64_MAX;
6156 dst_reg->smin_value = smin_ptr - smax_val;
6157 dst_reg->smax_value = smax_ptr - smin_val;
6159 if (umin_ptr < umax_val) {
6160 /* Overflow possible, we know nothing */
6161 dst_reg->umin_value = 0;
6162 dst_reg->umax_value = U64_MAX;
6164 /* Cannot overflow (as long as bounds are consistent) */
6165 dst_reg->umin_value = umin_ptr - umax_val;
6166 dst_reg->umax_value = umax_ptr - umin_val;
6168 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
6169 dst_reg->off = ptr_reg->off;
6170 dst_reg->raw = ptr_reg->raw;
6171 if (reg_is_pkt_pointer(ptr_reg)) {
6172 dst_reg->id = ++env->id_gen;
6173 /* something was added to pkt_ptr, set range to zero */
6181 /* bitwise ops on pointers are troublesome, prohibit. */
6182 verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
6183 dst, bpf_alu_string[opcode >> 4]);
6186 /* other operators (e.g. MUL,LSH) produce non-pointer results */
6187 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
6188 dst, bpf_alu_string[opcode >> 4]);
6192 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
6195 __update_reg_bounds(dst_reg);
6196 __reg_deduce_bounds(dst_reg);
6197 __reg_bound_offset(dst_reg);
6199 if (sanitize_check_bounds(env, insn, dst_reg) < 0)
6201 if (sanitize_needed(opcode)) {
6202 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
6205 return sanitize_err(env, insn, ret, off_reg, dst_reg);
6211 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
6212 struct bpf_reg_state *src_reg)
6214 s32 smin_val = src_reg->s32_min_value;
6215 s32 smax_val = src_reg->s32_max_value;
6216 u32 umin_val = src_reg->u32_min_value;
6217 u32 umax_val = src_reg->u32_max_value;
6219 if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
6220 signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
6221 dst_reg->s32_min_value = S32_MIN;
6222 dst_reg->s32_max_value = S32_MAX;
6224 dst_reg->s32_min_value += smin_val;
6225 dst_reg->s32_max_value += smax_val;
6227 if (dst_reg->u32_min_value + umin_val < umin_val ||
6228 dst_reg->u32_max_value + umax_val < umax_val) {
6229 dst_reg->u32_min_value = 0;
6230 dst_reg->u32_max_value = U32_MAX;
6232 dst_reg->u32_min_value += umin_val;
6233 dst_reg->u32_max_value += umax_val;
6237 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
6238 struct bpf_reg_state *src_reg)
6240 s64 smin_val = src_reg->smin_value;
6241 s64 smax_val = src_reg->smax_value;
6242 u64 umin_val = src_reg->umin_value;
6243 u64 umax_val = src_reg->umax_value;
6245 if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
6246 signed_add_overflows(dst_reg->smax_value, smax_val)) {
6247 dst_reg->smin_value = S64_MIN;
6248 dst_reg->smax_value = S64_MAX;
6250 dst_reg->smin_value += smin_val;
6251 dst_reg->smax_value += smax_val;
6253 if (dst_reg->umin_value + umin_val < umin_val ||
6254 dst_reg->umax_value + umax_val < umax_val) {
6255 dst_reg->umin_value = 0;
6256 dst_reg->umax_value = U64_MAX;
6258 dst_reg->umin_value += umin_val;
6259 dst_reg->umax_value += umax_val;
6263 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
6264 struct bpf_reg_state *src_reg)
6266 s32 smin_val = src_reg->s32_min_value;
6267 s32 smax_val = src_reg->s32_max_value;
6268 u32 umin_val = src_reg->u32_min_value;
6269 u32 umax_val = src_reg->u32_max_value;
6271 if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
6272 signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
6273 /* Overflow possible, we know nothing */
6274 dst_reg->s32_min_value = S32_MIN;
6275 dst_reg->s32_max_value = S32_MAX;
6277 dst_reg->s32_min_value -= smax_val;
6278 dst_reg->s32_max_value -= smin_val;
6280 if (dst_reg->u32_min_value < umax_val) {
6281 /* Overflow possible, we know nothing */
6282 dst_reg->u32_min_value = 0;
6283 dst_reg->u32_max_value = U32_MAX;
6285 /* Cannot overflow (as long as bounds are consistent) */
6286 dst_reg->u32_min_value -= umax_val;
6287 dst_reg->u32_max_value -= umin_val;
6291 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
6292 struct bpf_reg_state *src_reg)
6294 s64 smin_val = src_reg->smin_value;
6295 s64 smax_val = src_reg->smax_value;
6296 u64 umin_val = src_reg->umin_value;
6297 u64 umax_val = src_reg->umax_value;
6299 if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
6300 signed_sub_overflows(dst_reg->smax_value, smin_val)) {
6301 /* Overflow possible, we know nothing */
6302 dst_reg->smin_value = S64_MIN;
6303 dst_reg->smax_value = S64_MAX;
6305 dst_reg->smin_value -= smax_val;
6306 dst_reg->smax_value -= smin_val;
6308 if (dst_reg->umin_value < umax_val) {
6309 /* Overflow possible, we know nothing */
6310 dst_reg->umin_value = 0;
6311 dst_reg->umax_value = U64_MAX;
6313 /* Cannot overflow (as long as bounds are consistent) */
6314 dst_reg->umin_value -= umax_val;
6315 dst_reg->umax_value -= umin_val;
6319 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
6320 struct bpf_reg_state *src_reg)
6322 s32 smin_val = src_reg->s32_min_value;
6323 u32 umin_val = src_reg->u32_min_value;
6324 u32 umax_val = src_reg->u32_max_value;
6326 if (smin_val < 0 || dst_reg->s32_min_value < 0) {
6327 /* Ain't nobody got time to multiply that sign */
6328 __mark_reg32_unbounded(dst_reg);
6331 /* Both values are positive, so we can work with unsigned and
6332 * copy the result to signed (unless it exceeds S32_MAX).
6334 if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
6335 /* Potential overflow, we know nothing */
6336 __mark_reg32_unbounded(dst_reg);
6339 dst_reg->u32_min_value *= umin_val;
6340 dst_reg->u32_max_value *= umax_val;
6341 if (dst_reg->u32_max_value > S32_MAX) {
6342 /* Overflow possible, we know nothing */
6343 dst_reg->s32_min_value = S32_MIN;
6344 dst_reg->s32_max_value = S32_MAX;
6346 dst_reg->s32_min_value = dst_reg->u32_min_value;
6347 dst_reg->s32_max_value = dst_reg->u32_max_value;
6351 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
6352 struct bpf_reg_state *src_reg)
6354 s64 smin_val = src_reg->smin_value;
6355 u64 umin_val = src_reg->umin_value;
6356 u64 umax_val = src_reg->umax_value;
6358 if (smin_val < 0 || dst_reg->smin_value < 0) {
6359 /* Ain't nobody got time to multiply that sign */
6360 __mark_reg64_unbounded(dst_reg);
6363 /* Both values are positive, so we can work with unsigned and
6364 * copy the result to signed (unless it exceeds S64_MAX).
6366 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
6367 /* Potential overflow, we know nothing */
6368 __mark_reg64_unbounded(dst_reg);
6371 dst_reg->umin_value *= umin_val;
6372 dst_reg->umax_value *= umax_val;
6373 if (dst_reg->umax_value > S64_MAX) {
6374 /* Overflow possible, we know nothing */
6375 dst_reg->smin_value = S64_MIN;
6376 dst_reg->smax_value = S64_MAX;
6378 dst_reg->smin_value = dst_reg->umin_value;
6379 dst_reg->smax_value = dst_reg->umax_value;
6383 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
6384 struct bpf_reg_state *src_reg)
6386 bool src_known = tnum_subreg_is_const(src_reg->var_off);
6387 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
6388 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
6389 s32 smin_val = src_reg->s32_min_value;
6390 u32 umax_val = src_reg->u32_max_value;
6392 if (src_known && dst_known) {
6393 __mark_reg32_known(dst_reg, var32_off.value);
6397 /* We get our minimum from the var_off, since that's inherently
6398 * bitwise. Our maximum is the minimum of the operands' maxima.
6400 dst_reg->u32_min_value = var32_off.value;
6401 dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
6402 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
6403 /* Lose signed bounds when ANDing negative numbers,
6404 * ain't nobody got time for that.
6406 dst_reg->s32_min_value = S32_MIN;
6407 dst_reg->s32_max_value = S32_MAX;
6409 /* ANDing two positives gives a positive, so safe to
6410 * cast result into s64.
6412 dst_reg->s32_min_value = dst_reg->u32_min_value;
6413 dst_reg->s32_max_value = dst_reg->u32_max_value;
6417 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
6418 struct bpf_reg_state *src_reg)
6420 bool src_known = tnum_is_const(src_reg->var_off);
6421 bool dst_known = tnum_is_const(dst_reg->var_off);
6422 s64 smin_val = src_reg->smin_value;
6423 u64 umax_val = src_reg->umax_value;
6425 if (src_known && dst_known) {
6426 __mark_reg_known(dst_reg, dst_reg->var_off.value);
6430 /* We get our minimum from the var_off, since that's inherently
6431 * bitwise. Our maximum is the minimum of the operands' maxima.
6433 dst_reg->umin_value = dst_reg->var_off.value;
6434 dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
6435 if (dst_reg->smin_value < 0 || smin_val < 0) {
6436 /* Lose signed bounds when ANDing negative numbers,
6437 * ain't nobody got time for that.
6439 dst_reg->smin_value = S64_MIN;
6440 dst_reg->smax_value = S64_MAX;
6442 /* ANDing two positives gives a positive, so safe to
6443 * cast result into s64.
6445 dst_reg->smin_value = dst_reg->umin_value;
6446 dst_reg->smax_value = dst_reg->umax_value;
6448 /* We may learn something more from the var_off */
6449 __update_reg_bounds(dst_reg);
6452 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
6453 struct bpf_reg_state *src_reg)
6455 bool src_known = tnum_subreg_is_const(src_reg->var_off);
6456 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
6457 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
6458 s32 smin_val = src_reg->s32_min_value;
6459 u32 umin_val = src_reg->u32_min_value;
6461 if (src_known && dst_known) {
6462 __mark_reg32_known(dst_reg, var32_off.value);
6466 /* We get our maximum from the var_off, and our minimum is the
6467 * maximum of the operands' minima
6469 dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
6470 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
6471 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
6472 /* Lose signed bounds when ORing negative numbers,
6473 * ain't nobody got time for that.
6475 dst_reg->s32_min_value = S32_MIN;
6476 dst_reg->s32_max_value = S32_MAX;
6478 /* ORing two positives gives a positive, so safe to
6479 * cast result into s64.
6481 dst_reg->s32_min_value = dst_reg->u32_min_value;
6482 dst_reg->s32_max_value = dst_reg->u32_max_value;
6486 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
6487 struct bpf_reg_state *src_reg)
6489 bool src_known = tnum_is_const(src_reg->var_off);
6490 bool dst_known = tnum_is_const(dst_reg->var_off);
6491 s64 smin_val = src_reg->smin_value;
6492 u64 umin_val = src_reg->umin_value;
6494 if (src_known && dst_known) {
6495 __mark_reg_known(dst_reg, dst_reg->var_off.value);
6499 /* We get our maximum from the var_off, and our minimum is the
6500 * maximum of the operands' minima
6502 dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
6503 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
6504 if (dst_reg->smin_value < 0 || smin_val < 0) {
6505 /* Lose signed bounds when ORing negative numbers,
6506 * ain't nobody got time for that.
6508 dst_reg->smin_value = S64_MIN;
6509 dst_reg->smax_value = S64_MAX;
6511 /* ORing two positives gives a positive, so safe to
6512 * cast result into s64.
6514 dst_reg->smin_value = dst_reg->umin_value;
6515 dst_reg->smax_value = dst_reg->umax_value;
6517 /* We may learn something more from the var_off */
6518 __update_reg_bounds(dst_reg);
6521 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
6522 struct bpf_reg_state *src_reg)
6524 bool src_known = tnum_subreg_is_const(src_reg->var_off);
6525 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
6526 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
6527 s32 smin_val = src_reg->s32_min_value;
6529 if (src_known && dst_known) {
6530 __mark_reg32_known(dst_reg, var32_off.value);
6534 /* We get both minimum and maximum from the var32_off. */
6535 dst_reg->u32_min_value = var32_off.value;
6536 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
6538 if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
6539 /* XORing two positive sign numbers gives a positive,
6540 * so safe to cast u32 result into s32.
6542 dst_reg->s32_min_value = dst_reg->u32_min_value;
6543 dst_reg->s32_max_value = dst_reg->u32_max_value;
6545 dst_reg->s32_min_value = S32_MIN;
6546 dst_reg->s32_max_value = S32_MAX;
6550 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
6551 struct bpf_reg_state *src_reg)
6553 bool src_known = tnum_is_const(src_reg->var_off);
6554 bool dst_known = tnum_is_const(dst_reg->var_off);
6555 s64 smin_val = src_reg->smin_value;
6557 if (src_known && dst_known) {
6558 /* dst_reg->var_off.value has been updated earlier */
6559 __mark_reg_known(dst_reg, dst_reg->var_off.value);
6563 /* We get both minimum and maximum from the var_off. */
6564 dst_reg->umin_value = dst_reg->var_off.value;
6565 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
6567 if (dst_reg->smin_value >= 0 && smin_val >= 0) {
6568 /* XORing two positive sign numbers gives a positive,
6569 * so safe to cast u64 result into s64.
6571 dst_reg->smin_value = dst_reg->umin_value;
6572 dst_reg->smax_value = dst_reg->umax_value;
6574 dst_reg->smin_value = S64_MIN;
6575 dst_reg->smax_value = S64_MAX;
6578 __update_reg_bounds(dst_reg);
6581 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
6582 u64 umin_val, u64 umax_val)
6584 /* We lose all sign bit information (except what we can pick
6587 dst_reg->s32_min_value = S32_MIN;
6588 dst_reg->s32_max_value = S32_MAX;
6589 /* If we might shift our top bit out, then we know nothing */
6590 if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
6591 dst_reg->u32_min_value = 0;
6592 dst_reg->u32_max_value = U32_MAX;
6594 dst_reg->u32_min_value <<= umin_val;
6595 dst_reg->u32_max_value <<= umax_val;
6599 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
6600 struct bpf_reg_state *src_reg)
6602 u32 umax_val = src_reg->u32_max_value;
6603 u32 umin_val = src_reg->u32_min_value;
6604 /* u32 alu operation will zext upper bits */
6605 struct tnum subreg = tnum_subreg(dst_reg->var_off);
6607 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
6608 dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
6609 /* Not required but being careful mark reg64 bounds as unknown so
6610 * that we are forced to pick them up from tnum and zext later and
6611 * if some path skips this step we are still safe.
6613 __mark_reg64_unbounded(dst_reg);
6614 __update_reg32_bounds(dst_reg);
6617 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
6618 u64 umin_val, u64 umax_val)
6620 /* Special case <<32 because it is a common compiler pattern to sign
6621 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
6622 * positive we know this shift will also be positive so we can track
6623 * bounds correctly. Otherwise we lose all sign bit information except
6624 * what we can pick up from var_off. Perhaps we can generalize this
6625 * later to shifts of any length.
6627 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
6628 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
6630 dst_reg->smax_value = S64_MAX;
6632 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
6633 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
6635 dst_reg->smin_value = S64_MIN;
6637 /* If we might shift our top bit out, then we know nothing */
6638 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
6639 dst_reg->umin_value = 0;
6640 dst_reg->umax_value = U64_MAX;
6642 dst_reg->umin_value <<= umin_val;
6643 dst_reg->umax_value <<= umax_val;
6647 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
6648 struct bpf_reg_state *src_reg)
6650 u64 umax_val = src_reg->umax_value;
6651 u64 umin_val = src_reg->umin_value;
6653 /* scalar64 calc uses 32bit unshifted bounds so must be called first */
6654 __scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
6655 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
6657 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
6658 /* We may learn something more from the var_off */
6659 __update_reg_bounds(dst_reg);
6662 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
6663 struct bpf_reg_state *src_reg)
6665 struct tnum subreg = tnum_subreg(dst_reg->var_off);
6666 u32 umax_val = src_reg->u32_max_value;
6667 u32 umin_val = src_reg->u32_min_value;
6669 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
6670 * be negative, then either:
6671 * 1) src_reg might be zero, so the sign bit of the result is
6672 * unknown, so we lose our signed bounds
6673 * 2) it's known negative, thus the unsigned bounds capture the
6675 * 3) the signed bounds cross zero, so they tell us nothing
6677 * If the value in dst_reg is known nonnegative, then again the
6678 * unsigned bounts capture the signed bounds.
6679 * Thus, in all cases it suffices to blow away our signed bounds
6680 * and rely on inferring new ones from the unsigned bounds and
6681 * var_off of the result.
6683 dst_reg->s32_min_value = S32_MIN;
6684 dst_reg->s32_max_value = S32_MAX;
6686 dst_reg->var_off = tnum_rshift(subreg, umin_val);
6687 dst_reg->u32_min_value >>= umax_val;
6688 dst_reg->u32_max_value >>= umin_val;
6690 __mark_reg64_unbounded(dst_reg);
6691 __update_reg32_bounds(dst_reg);
6694 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
6695 struct bpf_reg_state *src_reg)
6697 u64 umax_val = src_reg->umax_value;
6698 u64 umin_val = src_reg->umin_value;
6700 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
6701 * be negative, then either:
6702 * 1) src_reg might be zero, so the sign bit of the result is
6703 * unknown, so we lose our signed bounds
6704 * 2) it's known negative, thus the unsigned bounds capture the
6706 * 3) the signed bounds cross zero, so they tell us nothing
6708 * If the value in dst_reg is known nonnegative, then again the
6709 * unsigned bounts capture the signed bounds.
6710 * Thus, in all cases it suffices to blow away our signed bounds
6711 * and rely on inferring new ones from the unsigned bounds and
6712 * var_off of the result.
6714 dst_reg->smin_value = S64_MIN;
6715 dst_reg->smax_value = S64_MAX;
6716 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
6717 dst_reg->umin_value >>= umax_val;
6718 dst_reg->umax_value >>= umin_val;
6720 /* Its not easy to operate on alu32 bounds here because it depends
6721 * on bits being shifted in. Take easy way out and mark unbounded
6722 * so we can recalculate later from tnum.
6724 __mark_reg32_unbounded(dst_reg);
6725 __update_reg_bounds(dst_reg);
6728 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
6729 struct bpf_reg_state *src_reg)
6731 u64 umin_val = src_reg->u32_min_value;
6733 /* Upon reaching here, src_known is true and
6734 * umax_val is equal to umin_val.
6736 dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
6737 dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
6739 dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
6741 /* blow away the dst_reg umin_value/umax_value and rely on
6742 * dst_reg var_off to refine the result.
6744 dst_reg->u32_min_value = 0;
6745 dst_reg->u32_max_value = U32_MAX;
6747 __mark_reg64_unbounded(dst_reg);
6748 __update_reg32_bounds(dst_reg);
6751 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
6752 struct bpf_reg_state *src_reg)
6754 u64 umin_val = src_reg->umin_value;
6756 /* Upon reaching here, src_known is true and umax_val is equal
6759 dst_reg->smin_value >>= umin_val;
6760 dst_reg->smax_value >>= umin_val;
6762 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
6764 /* blow away the dst_reg umin_value/umax_value and rely on
6765 * dst_reg var_off to refine the result.
6767 dst_reg->umin_value = 0;
6768 dst_reg->umax_value = U64_MAX;
6770 /* Its not easy to operate on alu32 bounds here because it depends
6771 * on bits being shifted in from upper 32-bits. Take easy way out
6772 * and mark unbounded so we can recalculate later from tnum.
6774 __mark_reg32_unbounded(dst_reg);
6775 __update_reg_bounds(dst_reg);
6778 /* WARNING: This function does calculations on 64-bit values, but the actual
6779 * execution may occur on 32-bit values. Therefore, things like bitshifts
6780 * need extra checks in the 32-bit case.
6782 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
6783 struct bpf_insn *insn,
6784 struct bpf_reg_state *dst_reg,
6785 struct bpf_reg_state src_reg)
6787 struct bpf_reg_state *regs = cur_regs(env);
6788 u8 opcode = BPF_OP(insn->code);
6790 s64 smin_val, smax_val;
6791 u64 umin_val, umax_val;
6792 s32 s32_min_val, s32_max_val;
6793 u32 u32_min_val, u32_max_val;
6794 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
6795 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
6798 smin_val = src_reg.smin_value;
6799 smax_val = src_reg.smax_value;
6800 umin_val = src_reg.umin_value;
6801 umax_val = src_reg.umax_value;
6803 s32_min_val = src_reg.s32_min_value;
6804 s32_max_val = src_reg.s32_max_value;
6805 u32_min_val = src_reg.u32_min_value;
6806 u32_max_val = src_reg.u32_max_value;
6809 src_known = tnum_subreg_is_const(src_reg.var_off);
6811 (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
6812 s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
6813 /* Taint dst register if offset had invalid bounds
6814 * derived from e.g. dead branches.
6816 __mark_reg_unknown(env, dst_reg);
6820 src_known = tnum_is_const(src_reg.var_off);
6822 (smin_val != smax_val || umin_val != umax_val)) ||
6823 smin_val > smax_val || umin_val > umax_val) {
6824 /* Taint dst register if offset had invalid bounds
6825 * derived from e.g. dead branches.
6827 __mark_reg_unknown(env, dst_reg);
6833 opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
6834 __mark_reg_unknown(env, dst_reg);
6838 if (sanitize_needed(opcode)) {
6839 ret = sanitize_val_alu(env, insn);
6841 return sanitize_err(env, insn, ret, NULL, NULL);
6844 /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
6845 * There are two classes of instructions: The first class we track both
6846 * alu32 and alu64 sign/unsigned bounds independently this provides the
6847 * greatest amount of precision when alu operations are mixed with jmp32
6848 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
6849 * and BPF_OR. This is possible because these ops have fairly easy to
6850 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
6851 * See alu32 verifier tests for examples. The second class of
6852 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
6853 * with regards to tracking sign/unsigned bounds because the bits may
6854 * cross subreg boundaries in the alu64 case. When this happens we mark
6855 * the reg unbounded in the subreg bound space and use the resulting
6856 * tnum to calculate an approximation of the sign/unsigned bounds.
6860 scalar32_min_max_add(dst_reg, &src_reg);
6861 scalar_min_max_add(dst_reg, &src_reg);
6862 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
6865 scalar32_min_max_sub(dst_reg, &src_reg);
6866 scalar_min_max_sub(dst_reg, &src_reg);
6867 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
6870 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
6871 scalar32_min_max_mul(dst_reg, &src_reg);
6872 scalar_min_max_mul(dst_reg, &src_reg);
6875 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
6876 scalar32_min_max_and(dst_reg, &src_reg);
6877 scalar_min_max_and(dst_reg, &src_reg);
6880 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
6881 scalar32_min_max_or(dst_reg, &src_reg);
6882 scalar_min_max_or(dst_reg, &src_reg);
6885 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
6886 scalar32_min_max_xor(dst_reg, &src_reg);
6887 scalar_min_max_xor(dst_reg, &src_reg);
6890 if (umax_val >= insn_bitness) {
6891 /* Shifts greater than 31 or 63 are undefined.
6892 * This includes shifts by a negative number.
6894 mark_reg_unknown(env, regs, insn->dst_reg);
6898 scalar32_min_max_lsh(dst_reg, &src_reg);
6900 scalar_min_max_lsh(dst_reg, &src_reg);
6903 if (umax_val >= insn_bitness) {
6904 /* Shifts greater than 31 or 63 are undefined.
6905 * This includes shifts by a negative number.
6907 mark_reg_unknown(env, regs, insn->dst_reg);
6911 scalar32_min_max_rsh(dst_reg, &src_reg);
6913 scalar_min_max_rsh(dst_reg, &src_reg);
6916 if (umax_val >= insn_bitness) {
6917 /* Shifts greater than 31 or 63 are undefined.
6918 * This includes shifts by a negative number.
6920 mark_reg_unknown(env, regs, insn->dst_reg);
6924 scalar32_min_max_arsh(dst_reg, &src_reg);
6926 scalar_min_max_arsh(dst_reg, &src_reg);
6929 mark_reg_unknown(env, regs, insn->dst_reg);
6933 /* ALU32 ops are zero extended into 64bit register */
6935 zext_32_to_64(dst_reg);
6937 __update_reg_bounds(dst_reg);
6938 __reg_deduce_bounds(dst_reg);
6939 __reg_bound_offset(dst_reg);
6943 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
6946 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
6947 struct bpf_insn *insn)
6949 struct bpf_verifier_state *vstate = env->cur_state;
6950 struct bpf_func_state *state = vstate->frame[vstate->curframe];
6951 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
6952 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
6953 u8 opcode = BPF_OP(insn->code);
6956 dst_reg = ®s[insn->dst_reg];
6958 if (dst_reg->type != SCALAR_VALUE)
6961 /* Make sure ID is cleared otherwise dst_reg min/max could be
6962 * incorrectly propagated into other registers by find_equal_scalars()
6965 if (BPF_SRC(insn->code) == BPF_X) {
6966 src_reg = ®s[insn->src_reg];
6967 if (src_reg->type != SCALAR_VALUE) {
6968 if (dst_reg->type != SCALAR_VALUE) {
6969 /* Combining two pointers by any ALU op yields
6970 * an arbitrary scalar. Disallow all math except
6971 * pointer subtraction
6973 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
6974 mark_reg_unknown(env, regs, insn->dst_reg);
6977 verbose(env, "R%d pointer %s pointer prohibited\n",
6979 bpf_alu_string[opcode >> 4]);
6982 /* scalar += pointer
6983 * This is legal, but we have to reverse our
6984 * src/dest handling in computing the range
6986 err = mark_chain_precision(env, insn->dst_reg);
6989 return adjust_ptr_min_max_vals(env, insn,
6992 } else if (ptr_reg) {
6993 /* pointer += scalar */
6994 err = mark_chain_precision(env, insn->src_reg);
6997 return adjust_ptr_min_max_vals(env, insn,
7001 /* Pretend the src is a reg with a known value, since we only
7002 * need to be able to read from this state.
7004 off_reg.type = SCALAR_VALUE;
7005 __mark_reg_known(&off_reg, insn->imm);
7007 if (ptr_reg) /* pointer += K */
7008 return adjust_ptr_min_max_vals(env, insn,
7012 /* Got here implies adding two SCALAR_VALUEs */
7013 if (WARN_ON_ONCE(ptr_reg)) {
7014 print_verifier_state(env, state);
7015 verbose(env, "verifier internal error: unexpected ptr_reg\n");
7018 if (WARN_ON(!src_reg)) {
7019 print_verifier_state(env, state);
7020 verbose(env, "verifier internal error: no src_reg\n");
7023 return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
7026 /* check validity of 32-bit and 64-bit arithmetic operations */
7027 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
7029 struct bpf_reg_state *regs = cur_regs(env);
7030 u8 opcode = BPF_OP(insn->code);
7033 if (opcode == BPF_END || opcode == BPF_NEG) {
7034 if (opcode == BPF_NEG) {
7035 if (BPF_SRC(insn->code) != 0 ||
7036 insn->src_reg != BPF_REG_0 ||
7037 insn->off != 0 || insn->imm != 0) {
7038 verbose(env, "BPF_NEG uses reserved fields\n");
7042 if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
7043 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
7044 BPF_CLASS(insn->code) == BPF_ALU64) {
7045 verbose(env, "BPF_END uses reserved fields\n");
7050 /* check src operand */
7051 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
7055 if (is_pointer_value(env, insn->dst_reg)) {
7056 verbose(env, "R%d pointer arithmetic prohibited\n",
7061 /* check dest operand */
7062 err = check_reg_arg(env, insn->dst_reg, DST_OP);
7066 } else if (opcode == BPF_MOV) {
7068 if (BPF_SRC(insn->code) == BPF_X) {
7069 if (insn->imm != 0 || insn->off != 0) {
7070 verbose(env, "BPF_MOV uses reserved fields\n");
7074 /* check src operand */
7075 err = check_reg_arg(env, insn->src_reg, SRC_OP);
7079 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
7080 verbose(env, "BPF_MOV uses reserved fields\n");
7085 /* check dest operand, mark as required later */
7086 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
7090 if (BPF_SRC(insn->code) == BPF_X) {
7091 struct bpf_reg_state *src_reg = regs + insn->src_reg;
7092 struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
7094 if (BPF_CLASS(insn->code) == BPF_ALU64) {
7096 * copy register state to dest reg
7098 if (src_reg->type == SCALAR_VALUE && !src_reg->id)
7099 /* Assign src and dst registers the same ID
7100 * that will be used by find_equal_scalars()
7101 * to propagate min/max range.
7103 src_reg->id = ++env->id_gen;
7104 *dst_reg = *src_reg;
7105 dst_reg->live |= REG_LIVE_WRITTEN;
7106 dst_reg->subreg_def = DEF_NOT_SUBREG;
7109 if (is_pointer_value(env, insn->src_reg)) {
7111 "R%d partial copy of pointer\n",
7114 } else if (src_reg->type == SCALAR_VALUE) {
7115 *dst_reg = *src_reg;
7116 /* Make sure ID is cleared otherwise
7117 * dst_reg min/max could be incorrectly
7118 * propagated into src_reg by find_equal_scalars()
7121 dst_reg->live |= REG_LIVE_WRITTEN;
7122 dst_reg->subreg_def = env->insn_idx + 1;
7124 mark_reg_unknown(env, regs,
7127 zext_32_to_64(dst_reg);
7131 * remember the value we stored into this reg
7133 /* clear any state __mark_reg_known doesn't set */
7134 mark_reg_unknown(env, regs, insn->dst_reg);
7135 regs[insn->dst_reg].type = SCALAR_VALUE;
7136 if (BPF_CLASS(insn->code) == BPF_ALU64) {
7137 __mark_reg_known(regs + insn->dst_reg,
7140 __mark_reg_known(regs + insn->dst_reg,
7145 } else if (opcode > BPF_END) {
7146 verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
7149 } else { /* all other ALU ops: and, sub, xor, add, ... */
7151 if (BPF_SRC(insn->code) == BPF_X) {
7152 if (insn->imm != 0 || insn->off != 0) {
7153 verbose(env, "BPF_ALU uses reserved fields\n");
7156 /* check src1 operand */
7157 err = check_reg_arg(env, insn->src_reg, SRC_OP);
7161 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
7162 verbose(env, "BPF_ALU uses reserved fields\n");
7167 /* check src2 operand */
7168 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
7172 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
7173 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
7174 verbose(env, "div by zero\n");
7178 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
7179 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
7180 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
7182 if (insn->imm < 0 || insn->imm >= size) {
7183 verbose(env, "invalid shift %d\n", insn->imm);
7188 /* check dest operand */
7189 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
7193 return adjust_reg_min_max_vals(env, insn);
7199 static void __find_good_pkt_pointers(struct bpf_func_state *state,
7200 struct bpf_reg_state *dst_reg,
7201 enum bpf_reg_type type, u16 new_range)
7203 struct bpf_reg_state *reg;
7206 for (i = 0; i < MAX_BPF_REG; i++) {
7207 reg = &state->regs[i];
7208 if (reg->type == type && reg->id == dst_reg->id)
7209 /* keep the maximum range already checked */
7210 reg->range = max(reg->range, new_range);
7213 bpf_for_each_spilled_reg(i, state, reg) {
7216 if (reg->type == type && reg->id == dst_reg->id)
7217 reg->range = max(reg->range, new_range);
7221 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
7222 struct bpf_reg_state *dst_reg,
7223 enum bpf_reg_type type,
7224 bool range_right_open)
7229 if (dst_reg->off < 0 ||
7230 (dst_reg->off == 0 && range_right_open))
7231 /* This doesn't give us any range */
7234 if (dst_reg->umax_value > MAX_PACKET_OFF ||
7235 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
7236 /* Risk of overflow. For instance, ptr + (1<<63) may be less
7237 * than pkt_end, but that's because it's also less than pkt.
7241 new_range = dst_reg->off;
7242 if (range_right_open)
7245 /* Examples for register markings:
7247 * pkt_data in dst register:
7251 * if (r2 > pkt_end) goto <handle exception>
7256 * if (r2 < pkt_end) goto <access okay>
7257 * <handle exception>
7260 * r2 == dst_reg, pkt_end == src_reg
7261 * r2=pkt(id=n,off=8,r=0)
7262 * r3=pkt(id=n,off=0,r=0)
7264 * pkt_data in src register:
7268 * if (pkt_end >= r2) goto <access okay>
7269 * <handle exception>
7273 * if (pkt_end <= r2) goto <handle exception>
7277 * pkt_end == dst_reg, r2 == src_reg
7278 * r2=pkt(id=n,off=8,r=0)
7279 * r3=pkt(id=n,off=0,r=0)
7281 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
7282 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
7283 * and [r3, r3 + 8-1) respectively is safe to access depending on
7287 /* If our ids match, then we must have the same max_value. And we
7288 * don't care about the other reg's fixed offset, since if it's too big
7289 * the range won't allow anything.
7290 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
7292 for (i = 0; i <= vstate->curframe; i++)
7293 __find_good_pkt_pointers(vstate->frame[i], dst_reg, type,
7297 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
7299 struct tnum subreg = tnum_subreg(reg->var_off);
7300 s32 sval = (s32)val;
7304 if (tnum_is_const(subreg))
7305 return !!tnum_equals_const(subreg, val);
7308 if (tnum_is_const(subreg))
7309 return !tnum_equals_const(subreg, val);
7312 if ((~subreg.mask & subreg.value) & val)
7314 if (!((subreg.mask | subreg.value) & val))
7318 if (reg->u32_min_value > val)
7320 else if (reg->u32_max_value <= val)
7324 if (reg->s32_min_value > sval)
7326 else if (reg->s32_max_value <= sval)
7330 if (reg->u32_max_value < val)
7332 else if (reg->u32_min_value >= val)
7336 if (reg->s32_max_value < sval)
7338 else if (reg->s32_min_value >= sval)
7342 if (reg->u32_min_value >= val)
7344 else if (reg->u32_max_value < val)
7348 if (reg->s32_min_value >= sval)
7350 else if (reg->s32_max_value < sval)
7354 if (reg->u32_max_value <= val)
7356 else if (reg->u32_min_value > val)
7360 if (reg->s32_max_value <= sval)
7362 else if (reg->s32_min_value > sval)
7371 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
7373 s64 sval = (s64)val;
7377 if (tnum_is_const(reg->var_off))
7378 return !!tnum_equals_const(reg->var_off, val);
7381 if (tnum_is_const(reg->var_off))
7382 return !tnum_equals_const(reg->var_off, val);
7385 if ((~reg->var_off.mask & reg->var_off.value) & val)
7387 if (!((reg->var_off.mask | reg->var_off.value) & val))
7391 if (reg->umin_value > val)
7393 else if (reg->umax_value <= val)
7397 if (reg->smin_value > sval)
7399 else if (reg->smax_value <= sval)
7403 if (reg->umax_value < val)
7405 else if (reg->umin_value >= val)
7409 if (reg->smax_value < sval)
7411 else if (reg->smin_value >= sval)
7415 if (reg->umin_value >= val)
7417 else if (reg->umax_value < val)
7421 if (reg->smin_value >= sval)
7423 else if (reg->smax_value < sval)
7427 if (reg->umax_value <= val)
7429 else if (reg->umin_value > val)
7433 if (reg->smax_value <= sval)
7435 else if (reg->smin_value > sval)
7443 /* compute branch direction of the expression "if (reg opcode val) goto target;"
7445 * 1 - branch will be taken and "goto target" will be executed
7446 * 0 - branch will not be taken and fall-through to next insn
7447 * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
7450 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
7453 if (__is_pointer_value(false, reg)) {
7454 if (!reg_type_not_null(reg->type))
7457 /* If pointer is valid tests against zero will fail so we can
7458 * use this to direct branch taken.
7474 return is_branch32_taken(reg, val, opcode);
7475 return is_branch64_taken(reg, val, opcode);
7478 /* Adjusts the register min/max values in the case that the dst_reg is the
7479 * variable register that we are working on, and src_reg is a constant or we're
7480 * simply doing a BPF_K check.
7481 * In JEQ/JNE cases we also adjust the var_off values.
7483 static void reg_set_min_max(struct bpf_reg_state *true_reg,
7484 struct bpf_reg_state *false_reg,
7486 u8 opcode, bool is_jmp32)
7488 struct tnum false_32off = tnum_subreg(false_reg->var_off);
7489 struct tnum false_64off = false_reg->var_off;
7490 struct tnum true_32off = tnum_subreg(true_reg->var_off);
7491 struct tnum true_64off = true_reg->var_off;
7492 s64 sval = (s64)val;
7493 s32 sval32 = (s32)val32;
7495 /* If the dst_reg is a pointer, we can't learn anything about its
7496 * variable offset from the compare (unless src_reg were a pointer into
7497 * the same object, but we don't bother with that.
7498 * Since false_reg and true_reg have the same type by construction, we
7499 * only need to check one of them for pointerness.
7501 if (__is_pointer_value(false, false_reg))
7508 struct bpf_reg_state *reg =
7509 opcode == BPF_JEQ ? true_reg : false_reg;
7511 /* JEQ/JNE comparison doesn't change the register equivalence.
7513 * if (r1 == 42) goto label;
7515 * label: // here both r1 and r2 are known to be 42.
7517 * Hence when marking register as known preserve it's ID.
7520 __mark_reg32_known(reg, val32);
7522 ___mark_reg_known(reg, val);
7527 false_32off = tnum_and(false_32off, tnum_const(~val32));
7528 if (is_power_of_2(val32))
7529 true_32off = tnum_or(true_32off,
7532 false_64off = tnum_and(false_64off, tnum_const(~val));
7533 if (is_power_of_2(val))
7534 true_64off = tnum_or(true_64off,
7542 u32 false_umax = opcode == BPF_JGT ? val32 : val32 - 1;
7543 u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
7545 false_reg->u32_max_value = min(false_reg->u32_max_value,
7547 true_reg->u32_min_value = max(true_reg->u32_min_value,
7550 u64 false_umax = opcode == BPF_JGT ? val : val - 1;
7551 u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
7553 false_reg->umax_value = min(false_reg->umax_value, false_umax);
7554 true_reg->umin_value = max(true_reg->umin_value, true_umin);
7562 s32 false_smax = opcode == BPF_JSGT ? sval32 : sval32 - 1;
7563 s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
7565 false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
7566 true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
7568 s64 false_smax = opcode == BPF_JSGT ? sval : sval - 1;
7569 s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
7571 false_reg->smax_value = min(false_reg->smax_value, false_smax);
7572 true_reg->smin_value = max(true_reg->smin_value, true_smin);
7580 u32 false_umin = opcode == BPF_JLT ? val32 : val32 + 1;
7581 u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
7583 false_reg->u32_min_value = max(false_reg->u32_min_value,
7585 true_reg->u32_max_value = min(true_reg->u32_max_value,
7588 u64 false_umin = opcode == BPF_JLT ? val : val + 1;
7589 u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
7591 false_reg->umin_value = max(false_reg->umin_value, false_umin);
7592 true_reg->umax_value = min(true_reg->umax_value, true_umax);
7600 s32 false_smin = opcode == BPF_JSLT ? sval32 : sval32 + 1;
7601 s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
7603 false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
7604 true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
7606 s64 false_smin = opcode == BPF_JSLT ? sval : sval + 1;
7607 s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
7609 false_reg->smin_value = max(false_reg->smin_value, false_smin);
7610 true_reg->smax_value = min(true_reg->smax_value, true_smax);
7619 false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
7620 tnum_subreg(false_32off));
7621 true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
7622 tnum_subreg(true_32off));
7623 __reg_combine_32_into_64(false_reg);
7624 __reg_combine_32_into_64(true_reg);
7626 false_reg->var_off = false_64off;
7627 true_reg->var_off = true_64off;
7628 __reg_combine_64_into_32(false_reg);
7629 __reg_combine_64_into_32(true_reg);
7633 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
7636 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
7637 struct bpf_reg_state *false_reg,
7639 u8 opcode, bool is_jmp32)
7641 /* How can we transform "a <op> b" into "b <op> a"? */
7642 static const u8 opcode_flip[16] = {
7643 /* these stay the same */
7644 [BPF_JEQ >> 4] = BPF_JEQ,
7645 [BPF_JNE >> 4] = BPF_JNE,
7646 [BPF_JSET >> 4] = BPF_JSET,
7647 /* these swap "lesser" and "greater" (L and G in the opcodes) */
7648 [BPF_JGE >> 4] = BPF_JLE,
7649 [BPF_JGT >> 4] = BPF_JLT,
7650 [BPF_JLE >> 4] = BPF_JGE,
7651 [BPF_JLT >> 4] = BPF_JGT,
7652 [BPF_JSGE >> 4] = BPF_JSLE,
7653 [BPF_JSGT >> 4] = BPF_JSLT,
7654 [BPF_JSLE >> 4] = BPF_JSGE,
7655 [BPF_JSLT >> 4] = BPF_JSGT
7657 opcode = opcode_flip[opcode >> 4];
7658 /* This uses zero as "not present in table"; luckily the zero opcode,
7659 * BPF_JA, can't get here.
7662 reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
7665 /* Regs are known to be equal, so intersect their min/max/var_off */
7666 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
7667 struct bpf_reg_state *dst_reg)
7669 src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
7670 dst_reg->umin_value);
7671 src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
7672 dst_reg->umax_value);
7673 src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
7674 dst_reg->smin_value);
7675 src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
7676 dst_reg->smax_value);
7677 src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
7679 /* We might have learned new bounds from the var_off. */
7680 __update_reg_bounds(src_reg);
7681 __update_reg_bounds(dst_reg);
7682 /* We might have learned something about the sign bit. */
7683 __reg_deduce_bounds(src_reg);
7684 __reg_deduce_bounds(dst_reg);
7685 /* We might have learned some bits from the bounds. */
7686 __reg_bound_offset(src_reg);
7687 __reg_bound_offset(dst_reg);
7688 /* Intersecting with the old var_off might have improved our bounds
7689 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
7690 * then new var_off is (0; 0x7f...fc) which improves our umax.
7692 __update_reg_bounds(src_reg);
7693 __update_reg_bounds(dst_reg);
7696 static void reg_combine_min_max(struct bpf_reg_state *true_src,
7697 struct bpf_reg_state *true_dst,
7698 struct bpf_reg_state *false_src,
7699 struct bpf_reg_state *false_dst,
7704 __reg_combine_min_max(true_src, true_dst);
7707 __reg_combine_min_max(false_src, false_dst);
7712 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
7713 struct bpf_reg_state *reg, u32 id,
7716 if (reg_type_may_be_null(reg->type) && reg->id == id &&
7717 !WARN_ON_ONCE(!reg->id)) {
7718 /* Old offset (both fixed and variable parts) should
7719 * have been known-zero, because we don't allow pointer
7720 * arithmetic on pointers that might be NULL.
7722 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value ||
7723 !tnum_equals_const(reg->var_off, 0) ||
7725 __mark_reg_known_zero(reg);
7729 reg->type = SCALAR_VALUE;
7730 } else if (reg->type == PTR_TO_MAP_VALUE_OR_NULL) {
7731 const struct bpf_map *map = reg->map_ptr;
7733 if (map->inner_map_meta) {
7734 reg->type = CONST_PTR_TO_MAP;
7735 reg->map_ptr = map->inner_map_meta;
7736 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
7737 reg->type = PTR_TO_XDP_SOCK;
7738 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
7739 map->map_type == BPF_MAP_TYPE_SOCKHASH) {
7740 reg->type = PTR_TO_SOCKET;
7742 reg->type = PTR_TO_MAP_VALUE;
7744 } else if (reg->type == PTR_TO_SOCKET_OR_NULL) {
7745 reg->type = PTR_TO_SOCKET;
7746 } else if (reg->type == PTR_TO_SOCK_COMMON_OR_NULL) {
7747 reg->type = PTR_TO_SOCK_COMMON;
7748 } else if (reg->type == PTR_TO_TCP_SOCK_OR_NULL) {
7749 reg->type = PTR_TO_TCP_SOCK;
7750 } else if (reg->type == PTR_TO_BTF_ID_OR_NULL) {
7751 reg->type = PTR_TO_BTF_ID;
7752 } else if (reg->type == PTR_TO_MEM_OR_NULL) {
7753 reg->type = PTR_TO_MEM;
7754 } else if (reg->type == PTR_TO_RDONLY_BUF_OR_NULL) {
7755 reg->type = PTR_TO_RDONLY_BUF;
7756 } else if (reg->type == PTR_TO_RDWR_BUF_OR_NULL) {
7757 reg->type = PTR_TO_RDWR_BUF;
7760 /* We don't need id and ref_obj_id from this point
7761 * onwards anymore, thus we should better reset it,
7762 * so that state pruning has chances to take effect.
7765 reg->ref_obj_id = 0;
7766 } else if (!reg_may_point_to_spin_lock(reg)) {
7767 /* For not-NULL ptr, reg->ref_obj_id will be reset
7768 * in release_reg_references().
7770 * reg->id is still used by spin_lock ptr. Other
7771 * than spin_lock ptr type, reg->id can be reset.
7778 static void __mark_ptr_or_null_regs(struct bpf_func_state *state, u32 id,
7781 struct bpf_reg_state *reg;
7784 for (i = 0; i < MAX_BPF_REG; i++)
7785 mark_ptr_or_null_reg(state, &state->regs[i], id, is_null);
7787 bpf_for_each_spilled_reg(i, state, reg) {
7790 mark_ptr_or_null_reg(state, reg, id, is_null);
7794 /* The logic is similar to find_good_pkt_pointers(), both could eventually
7795 * be folded together at some point.
7797 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
7800 struct bpf_func_state *state = vstate->frame[vstate->curframe];
7801 struct bpf_reg_state *regs = state->regs;
7802 u32 ref_obj_id = regs[regno].ref_obj_id;
7803 u32 id = regs[regno].id;
7806 if (ref_obj_id && ref_obj_id == id && is_null)
7807 /* regs[regno] is in the " == NULL" branch.
7808 * No one could have freed the reference state before
7809 * doing the NULL check.
7811 WARN_ON_ONCE(release_reference_state(state, id));
7813 for (i = 0; i <= vstate->curframe; i++)
7814 __mark_ptr_or_null_regs(vstate->frame[i], id, is_null);
7817 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
7818 struct bpf_reg_state *dst_reg,
7819 struct bpf_reg_state *src_reg,
7820 struct bpf_verifier_state *this_branch,
7821 struct bpf_verifier_state *other_branch)
7823 if (BPF_SRC(insn->code) != BPF_X)
7826 /* Pointers are always 64-bit. */
7827 if (BPF_CLASS(insn->code) == BPF_JMP32)
7830 switch (BPF_OP(insn->code)) {
7832 if ((dst_reg->type == PTR_TO_PACKET &&
7833 src_reg->type == PTR_TO_PACKET_END) ||
7834 (dst_reg->type == PTR_TO_PACKET_META &&
7835 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
7836 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
7837 find_good_pkt_pointers(this_branch, dst_reg,
7838 dst_reg->type, false);
7839 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
7840 src_reg->type == PTR_TO_PACKET) ||
7841 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
7842 src_reg->type == PTR_TO_PACKET_META)) {
7843 /* pkt_end > pkt_data', pkt_data > pkt_meta' */
7844 find_good_pkt_pointers(other_branch, src_reg,
7845 src_reg->type, true);
7851 if ((dst_reg->type == PTR_TO_PACKET &&
7852 src_reg->type == PTR_TO_PACKET_END) ||
7853 (dst_reg->type == PTR_TO_PACKET_META &&
7854 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
7855 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
7856 find_good_pkt_pointers(other_branch, dst_reg,
7857 dst_reg->type, true);
7858 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
7859 src_reg->type == PTR_TO_PACKET) ||
7860 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
7861 src_reg->type == PTR_TO_PACKET_META)) {
7862 /* pkt_end < pkt_data', pkt_data > pkt_meta' */
7863 find_good_pkt_pointers(this_branch, src_reg,
7864 src_reg->type, false);
7870 if ((dst_reg->type == PTR_TO_PACKET &&
7871 src_reg->type == PTR_TO_PACKET_END) ||
7872 (dst_reg->type == PTR_TO_PACKET_META &&
7873 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
7874 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
7875 find_good_pkt_pointers(this_branch, dst_reg,
7876 dst_reg->type, true);
7877 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
7878 src_reg->type == PTR_TO_PACKET) ||
7879 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
7880 src_reg->type == PTR_TO_PACKET_META)) {
7881 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
7882 find_good_pkt_pointers(other_branch, src_reg,
7883 src_reg->type, false);
7889 if ((dst_reg->type == PTR_TO_PACKET &&
7890 src_reg->type == PTR_TO_PACKET_END) ||
7891 (dst_reg->type == PTR_TO_PACKET_META &&
7892 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
7893 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
7894 find_good_pkt_pointers(other_branch, dst_reg,
7895 dst_reg->type, false);
7896 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
7897 src_reg->type == PTR_TO_PACKET) ||
7898 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
7899 src_reg->type == PTR_TO_PACKET_META)) {
7900 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
7901 find_good_pkt_pointers(this_branch, src_reg,
7902 src_reg->type, true);
7914 static void find_equal_scalars(struct bpf_verifier_state *vstate,
7915 struct bpf_reg_state *known_reg)
7917 struct bpf_func_state *state;
7918 struct bpf_reg_state *reg;
7921 for (i = 0; i <= vstate->curframe; i++) {
7922 state = vstate->frame[i];
7923 for (j = 0; j < MAX_BPF_REG; j++) {
7924 reg = &state->regs[j];
7925 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
7929 bpf_for_each_spilled_reg(j, state, reg) {
7932 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
7938 static int check_cond_jmp_op(struct bpf_verifier_env *env,
7939 struct bpf_insn *insn, int *insn_idx)
7941 struct bpf_verifier_state *this_branch = env->cur_state;
7942 struct bpf_verifier_state *other_branch;
7943 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
7944 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
7945 u8 opcode = BPF_OP(insn->code);
7950 /* Only conditional jumps are expected to reach here. */
7951 if (opcode == BPF_JA || opcode > BPF_JSLE) {
7952 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
7956 if (BPF_SRC(insn->code) == BPF_X) {
7957 if (insn->imm != 0) {
7958 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
7962 /* check src1 operand */
7963 err = check_reg_arg(env, insn->src_reg, SRC_OP);
7967 if (is_pointer_value(env, insn->src_reg)) {
7968 verbose(env, "R%d pointer comparison prohibited\n",
7972 src_reg = ®s[insn->src_reg];
7974 if (insn->src_reg != BPF_REG_0) {
7975 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
7980 /* check src2 operand */
7981 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
7985 dst_reg = ®s[insn->dst_reg];
7986 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
7988 if (BPF_SRC(insn->code) == BPF_K) {
7989 pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
7990 } else if (src_reg->type == SCALAR_VALUE &&
7991 is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
7992 pred = is_branch_taken(dst_reg,
7993 tnum_subreg(src_reg->var_off).value,
7996 } else if (src_reg->type == SCALAR_VALUE &&
7997 !is_jmp32 && tnum_is_const(src_reg->var_off)) {
7998 pred = is_branch_taken(dst_reg,
7999 src_reg->var_off.value,
8005 /* If we get here with a dst_reg pointer type it is because
8006 * above is_branch_taken() special cased the 0 comparison.
8008 if (!__is_pointer_value(false, dst_reg))
8009 err = mark_chain_precision(env, insn->dst_reg);
8010 if (BPF_SRC(insn->code) == BPF_X && !err)
8011 err = mark_chain_precision(env, insn->src_reg);
8017 /* Only follow the goto, ignore fall-through. If needed, push
8018 * the fall-through branch for simulation under speculative
8021 if (!env->bypass_spec_v1 &&
8022 !sanitize_speculative_path(env, insn, *insn_idx + 1,
8025 *insn_idx += insn->off;
8027 } else if (pred == 0) {
8028 /* Only follow the fall-through branch, since that's where the
8029 * program will go. If needed, push the goto branch for
8030 * simulation under speculative execution.
8032 if (!env->bypass_spec_v1 &&
8033 !sanitize_speculative_path(env, insn,
8034 *insn_idx + insn->off + 1,
8040 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
8044 other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
8046 /* detect if we are comparing against a constant value so we can adjust
8047 * our min/max values for our dst register.
8048 * this is only legit if both are scalars (or pointers to the same
8049 * object, I suppose, but we don't support that right now), because
8050 * otherwise the different base pointers mean the offsets aren't
8053 if (BPF_SRC(insn->code) == BPF_X) {
8054 struct bpf_reg_state *src_reg = ®s[insn->src_reg];
8056 if (dst_reg->type == SCALAR_VALUE &&
8057 src_reg->type == SCALAR_VALUE) {
8058 if (tnum_is_const(src_reg->var_off) ||
8060 tnum_is_const(tnum_subreg(src_reg->var_off))))
8061 reg_set_min_max(&other_branch_regs[insn->dst_reg],
8063 src_reg->var_off.value,
8064 tnum_subreg(src_reg->var_off).value,
8066 else if (tnum_is_const(dst_reg->var_off) ||
8068 tnum_is_const(tnum_subreg(dst_reg->var_off))))
8069 reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
8071 dst_reg->var_off.value,
8072 tnum_subreg(dst_reg->var_off).value,
8074 else if (!is_jmp32 &&
8075 (opcode == BPF_JEQ || opcode == BPF_JNE))
8076 /* Comparing for equality, we can combine knowledge */
8077 reg_combine_min_max(&other_branch_regs[insn->src_reg],
8078 &other_branch_regs[insn->dst_reg],
8079 src_reg, dst_reg, opcode);
8081 !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
8082 find_equal_scalars(this_branch, src_reg);
8083 find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
8087 } else if (dst_reg->type == SCALAR_VALUE) {
8088 reg_set_min_max(&other_branch_regs[insn->dst_reg],
8089 dst_reg, insn->imm, (u32)insn->imm,
8093 if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
8094 !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
8095 find_equal_scalars(this_branch, dst_reg);
8096 find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
8099 /* detect if R == 0 where R is returned from bpf_map_lookup_elem().
8100 * NOTE: these optimizations below are related with pointer comparison
8101 * which will never be JMP32.
8103 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
8104 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
8105 reg_type_may_be_null(dst_reg->type)) {
8106 /* Mark all identical registers in each branch as either
8107 * safe or unknown depending R == 0 or R != 0 conditional.
8109 mark_ptr_or_null_regs(this_branch, insn->dst_reg,
8111 mark_ptr_or_null_regs(other_branch, insn->dst_reg,
8113 } else if (!try_match_pkt_pointers(insn, dst_reg, ®s[insn->src_reg],
8114 this_branch, other_branch) &&
8115 is_pointer_value(env, insn->dst_reg)) {
8116 verbose(env, "R%d pointer comparison prohibited\n",
8120 if (env->log.level & BPF_LOG_LEVEL)
8121 print_verifier_state(env, this_branch->frame[this_branch->curframe]);
8125 /* verify BPF_LD_IMM64 instruction */
8126 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
8128 struct bpf_insn_aux_data *aux = cur_aux(env);
8129 struct bpf_reg_state *regs = cur_regs(env);
8130 struct bpf_reg_state *dst_reg;
8131 struct bpf_map *map;
8134 if (BPF_SIZE(insn->code) != BPF_DW) {
8135 verbose(env, "invalid BPF_LD_IMM insn\n");
8138 if (insn->off != 0) {
8139 verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
8143 err = check_reg_arg(env, insn->dst_reg, DST_OP);
8147 dst_reg = ®s[insn->dst_reg];
8148 if (insn->src_reg == 0) {
8149 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
8151 dst_reg->type = SCALAR_VALUE;
8152 __mark_reg_known(®s[insn->dst_reg], imm);
8156 if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
8157 mark_reg_known_zero(env, regs, insn->dst_reg);
8159 dst_reg->type = aux->btf_var.reg_type;
8160 switch (dst_reg->type) {
8162 dst_reg->mem_size = aux->btf_var.mem_size;
8165 case PTR_TO_PERCPU_BTF_ID:
8166 dst_reg->btf_id = aux->btf_var.btf_id;
8169 verbose(env, "bpf verifier is misconfigured\n");
8175 map = env->used_maps[aux->map_index];
8176 mark_reg_known_zero(env, regs, insn->dst_reg);
8177 dst_reg->map_ptr = map;
8179 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE) {
8180 dst_reg->type = PTR_TO_MAP_VALUE;
8181 dst_reg->off = aux->map_off;
8182 if (map_value_has_spin_lock(map))
8183 dst_reg->id = ++env->id_gen;
8184 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD) {
8185 dst_reg->type = CONST_PTR_TO_MAP;
8187 verbose(env, "bpf verifier is misconfigured\n");
8194 static bool may_access_skb(enum bpf_prog_type type)
8197 case BPF_PROG_TYPE_SOCKET_FILTER:
8198 case BPF_PROG_TYPE_SCHED_CLS:
8199 case BPF_PROG_TYPE_SCHED_ACT:
8206 /* verify safety of LD_ABS|LD_IND instructions:
8207 * - they can only appear in the programs where ctx == skb
8208 * - since they are wrappers of function calls, they scratch R1-R5 registers,
8209 * preserve R6-R9, and store return value into R0
8212 * ctx == skb == R6 == CTX
8215 * SRC == any register
8216 * IMM == 32-bit immediate
8219 * R0 - 8/16/32-bit skb data converted to cpu endianness
8221 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
8223 struct bpf_reg_state *regs = cur_regs(env);
8224 static const int ctx_reg = BPF_REG_6;
8225 u8 mode = BPF_MODE(insn->code);
8228 if (!may_access_skb(resolve_prog_type(env->prog))) {
8229 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
8233 if (!env->ops->gen_ld_abs) {
8234 verbose(env, "bpf verifier is misconfigured\n");
8238 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
8239 BPF_SIZE(insn->code) == BPF_DW ||
8240 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
8241 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
8245 /* check whether implicit source operand (register R6) is readable */
8246 err = check_reg_arg(env, ctx_reg, SRC_OP);
8250 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
8251 * gen_ld_abs() may terminate the program at runtime, leading to
8254 err = check_reference_leak(env);
8256 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
8260 if (env->cur_state->active_spin_lock) {
8261 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
8265 if (regs[ctx_reg].type != PTR_TO_CTX) {
8267 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
8271 if (mode == BPF_IND) {
8272 /* check explicit source operand */
8273 err = check_reg_arg(env, insn->src_reg, SRC_OP);
8278 err = check_ctx_reg(env, ®s[ctx_reg], ctx_reg);
8282 /* reset caller saved regs to unreadable */
8283 for (i = 0; i < CALLER_SAVED_REGS; i++) {
8284 mark_reg_not_init(env, regs, caller_saved[i]);
8285 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
8288 /* mark destination R0 register as readable, since it contains
8289 * the value fetched from the packet.
8290 * Already marked as written above.
8292 mark_reg_unknown(env, regs, BPF_REG_0);
8293 /* ld_abs load up to 32-bit skb data. */
8294 regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
8298 static int check_return_code(struct bpf_verifier_env *env)
8300 struct tnum enforce_attach_type_range = tnum_unknown;
8301 const struct bpf_prog *prog = env->prog;
8302 struct bpf_reg_state *reg;
8303 struct tnum range = tnum_range(0, 1);
8304 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
8306 const bool is_subprog = env->cur_state->frame[0]->subprogno;
8308 /* LSM and struct_ops func-ptr's return type could be "void" */
8310 (prog_type == BPF_PROG_TYPE_STRUCT_OPS ||
8311 prog_type == BPF_PROG_TYPE_LSM) &&
8312 !prog->aux->attach_func_proto->type)
8315 /* eBPF calling convetion is such that R0 is used
8316 * to return the value from eBPF program.
8317 * Make sure that it's readable at this time
8318 * of bpf_exit, which means that program wrote
8319 * something into it earlier
8321 err = check_reg_arg(env, BPF_REG_0, SRC_OP);
8325 if (is_pointer_value(env, BPF_REG_0)) {
8326 verbose(env, "R0 leaks addr as return value\n");
8330 reg = cur_regs(env) + BPF_REG_0;
8332 if (reg->type != SCALAR_VALUE) {
8333 verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
8334 reg_type_str[reg->type]);
8340 switch (prog_type) {
8341 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
8342 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
8343 env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
8344 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
8345 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
8346 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
8347 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
8348 range = tnum_range(1, 1);
8350 case BPF_PROG_TYPE_CGROUP_SKB:
8351 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
8352 range = tnum_range(0, 3);
8353 enforce_attach_type_range = tnum_range(2, 3);
8356 case BPF_PROG_TYPE_CGROUP_SOCK:
8357 case BPF_PROG_TYPE_SOCK_OPS:
8358 case BPF_PROG_TYPE_CGROUP_DEVICE:
8359 case BPF_PROG_TYPE_CGROUP_SYSCTL:
8360 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
8362 case BPF_PROG_TYPE_RAW_TRACEPOINT:
8363 if (!env->prog->aux->attach_btf_id)
8365 range = tnum_const(0);
8367 case BPF_PROG_TYPE_TRACING:
8368 switch (env->prog->expected_attach_type) {
8369 case BPF_TRACE_FENTRY:
8370 case BPF_TRACE_FEXIT:
8371 range = tnum_const(0);
8373 case BPF_TRACE_RAW_TP:
8374 case BPF_MODIFY_RETURN:
8376 case BPF_TRACE_ITER:
8382 case BPF_PROG_TYPE_SK_LOOKUP:
8383 range = tnum_range(SK_DROP, SK_PASS);
8385 case BPF_PROG_TYPE_EXT:
8386 /* freplace program can return anything as its return value
8387 * depends on the to-be-replaced kernel func or bpf program.
8393 if (reg->type != SCALAR_VALUE) {
8394 verbose(env, "At program exit the register R0 is not a known value (%s)\n",
8395 reg_type_str[reg->type]);
8399 if (!tnum_in(range, reg->var_off)) {
8402 verbose(env, "At program exit the register R0 ");
8403 if (!tnum_is_unknown(reg->var_off)) {
8404 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
8405 verbose(env, "has value %s", tn_buf);
8407 verbose(env, "has unknown scalar value");
8409 tnum_strn(tn_buf, sizeof(tn_buf), range);
8410 verbose(env, " should have been in %s\n", tn_buf);
8414 if (!tnum_is_unknown(enforce_attach_type_range) &&
8415 tnum_in(enforce_attach_type_range, reg->var_off))
8416 env->prog->enforce_expected_attach_type = 1;
8420 /* non-recursive DFS pseudo code
8421 * 1 procedure DFS-iterative(G,v):
8422 * 2 label v as discovered
8423 * 3 let S be a stack
8425 * 5 while S is not empty
8427 * 7 if t is what we're looking for:
8429 * 9 for all edges e in G.adjacentEdges(t) do
8430 * 10 if edge e is already labelled
8431 * 11 continue with the next edge
8432 * 12 w <- G.adjacentVertex(t,e)
8433 * 13 if vertex w is not discovered and not explored
8434 * 14 label e as tree-edge
8435 * 15 label w as discovered
8438 * 18 else if vertex w is discovered
8439 * 19 label e as back-edge
8441 * 21 // vertex w is explored
8442 * 22 label e as forward- or cross-edge
8443 * 23 label t as explored
8448 * 0x11 - discovered and fall-through edge labelled
8449 * 0x12 - discovered and fall-through and branch edges labelled
8460 static u32 state_htab_size(struct bpf_verifier_env *env)
8462 return env->prog->len;
8465 static struct bpf_verifier_state_list **explored_state(
8466 struct bpf_verifier_env *env,
8469 struct bpf_verifier_state *cur = env->cur_state;
8470 struct bpf_func_state *state = cur->frame[cur->curframe];
8472 return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
8475 static void init_explored_state(struct bpf_verifier_env *env, int idx)
8477 env->insn_aux_data[idx].prune_point = true;
8480 /* t, w, e - match pseudo-code above:
8481 * t - index of current instruction
8482 * w - next instruction
8485 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
8488 int *insn_stack = env->cfg.insn_stack;
8489 int *insn_state = env->cfg.insn_state;
8491 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
8494 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
8497 if (w < 0 || w >= env->prog->len) {
8498 verbose_linfo(env, t, "%d: ", t);
8499 verbose(env, "jump out of range from insn %d to %d\n", t, w);
8504 /* mark branch target for state pruning */
8505 init_explored_state(env, w);
8507 if (insn_state[w] == 0) {
8509 insn_state[t] = DISCOVERED | e;
8510 insn_state[w] = DISCOVERED;
8511 if (env->cfg.cur_stack >= env->prog->len)
8513 insn_stack[env->cfg.cur_stack++] = w;
8515 } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
8516 if (loop_ok && env->bpf_capable)
8518 verbose_linfo(env, t, "%d: ", t);
8519 verbose_linfo(env, w, "%d: ", w);
8520 verbose(env, "back-edge from insn %d to %d\n", t, w);
8522 } else if (insn_state[w] == EXPLORED) {
8523 /* forward- or cross-edge */
8524 insn_state[t] = DISCOVERED | e;
8526 verbose(env, "insn state internal bug\n");
8532 /* non-recursive depth-first-search to detect loops in BPF program
8533 * loop == back-edge in directed graph
8535 static int check_cfg(struct bpf_verifier_env *env)
8537 struct bpf_insn *insns = env->prog->insnsi;
8538 int insn_cnt = env->prog->len;
8539 int *insn_stack, *insn_state;
8543 insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
8547 insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
8553 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
8554 insn_stack[0] = 0; /* 0 is the first instruction */
8555 env->cfg.cur_stack = 1;
8558 if (env->cfg.cur_stack == 0)
8560 t = insn_stack[env->cfg.cur_stack - 1];
8562 if (BPF_CLASS(insns[t].code) == BPF_JMP ||
8563 BPF_CLASS(insns[t].code) == BPF_JMP32) {
8564 u8 opcode = BPF_OP(insns[t].code);
8566 if (opcode == BPF_EXIT) {
8568 } else if (opcode == BPF_CALL) {
8569 ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
8574 if (t + 1 < insn_cnt)
8575 init_explored_state(env, t + 1);
8576 if (insns[t].src_reg == BPF_PSEUDO_CALL) {
8577 init_explored_state(env, t);
8578 ret = push_insn(t, t + insns[t].imm + 1, BRANCH,
8585 } else if (opcode == BPF_JA) {
8586 if (BPF_SRC(insns[t].code) != BPF_K) {
8590 /* unconditional jump with single edge */
8591 ret = push_insn(t, t + insns[t].off + 1,
8592 FALLTHROUGH, env, true);
8597 /* unconditional jmp is not a good pruning point,
8598 * but it's marked, since backtracking needs
8599 * to record jmp history in is_state_visited().
8601 init_explored_state(env, t + insns[t].off + 1);
8602 /* tell verifier to check for equivalent states
8603 * after every call and jump
8605 if (t + 1 < insn_cnt)
8606 init_explored_state(env, t + 1);
8608 /* conditional jump with two edges */
8609 init_explored_state(env, t);
8610 ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
8616 ret = push_insn(t, t + insns[t].off + 1, BRANCH, env, true);
8623 /* all other non-branch instructions with single
8626 ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
8634 insn_state[t] = EXPLORED;
8635 if (env->cfg.cur_stack-- <= 0) {
8636 verbose(env, "pop stack internal bug\n");
8643 for (i = 0; i < insn_cnt; i++) {
8644 if (insn_state[i] != EXPLORED) {
8645 verbose(env, "unreachable insn %d\n", i);
8650 ret = 0; /* cfg looks good */
8655 env->cfg.insn_state = env->cfg.insn_stack = NULL;
8659 static int check_abnormal_return(struct bpf_verifier_env *env)
8663 for (i = 1; i < env->subprog_cnt; i++) {
8664 if (env->subprog_info[i].has_ld_abs) {
8665 verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
8668 if (env->subprog_info[i].has_tail_call) {
8669 verbose(env, "tail_call is not allowed in subprogs without BTF\n");
8676 /* The minimum supported BTF func info size */
8677 #define MIN_BPF_FUNCINFO_SIZE 8
8678 #define MAX_FUNCINFO_REC_SIZE 252
8680 static int check_btf_func(struct bpf_verifier_env *env,
8681 const union bpf_attr *attr,
8682 union bpf_attr __user *uattr)
8684 const struct btf_type *type, *func_proto, *ret_type;
8685 u32 i, nfuncs, urec_size, min_size;
8686 u32 krec_size = sizeof(struct bpf_func_info);
8687 struct bpf_func_info *krecord;
8688 struct bpf_func_info_aux *info_aux = NULL;
8689 struct bpf_prog *prog;
8690 const struct btf *btf;
8691 void __user *urecord;
8692 u32 prev_offset = 0;
8696 nfuncs = attr->func_info_cnt;
8698 if (check_abnormal_return(env))
8703 if (nfuncs != env->subprog_cnt) {
8704 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
8708 urec_size = attr->func_info_rec_size;
8709 if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
8710 urec_size > MAX_FUNCINFO_REC_SIZE ||
8711 urec_size % sizeof(u32)) {
8712 verbose(env, "invalid func info rec size %u\n", urec_size);
8717 btf = prog->aux->btf;
8719 urecord = u64_to_user_ptr(attr->func_info);
8720 min_size = min_t(u32, krec_size, urec_size);
8722 krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
8725 info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
8729 for (i = 0; i < nfuncs; i++) {
8730 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
8732 if (ret == -E2BIG) {
8733 verbose(env, "nonzero tailing record in func info");
8734 /* set the size kernel expects so loader can zero
8735 * out the rest of the record.
8737 if (put_user(min_size, &uattr->func_info_rec_size))
8743 if (copy_from_user(&krecord[i], urecord, min_size)) {
8748 /* check insn_off */
8751 if (krecord[i].insn_off) {
8753 "nonzero insn_off %u for the first func info record",
8754 krecord[i].insn_off);
8757 } else if (krecord[i].insn_off <= prev_offset) {
8759 "same or smaller insn offset (%u) than previous func info record (%u)",
8760 krecord[i].insn_off, prev_offset);
8764 if (env->subprog_info[i].start != krecord[i].insn_off) {
8765 verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
8770 type = btf_type_by_id(btf, krecord[i].type_id);
8771 if (!type || !btf_type_is_func(type)) {
8772 verbose(env, "invalid type id %d in func info",
8773 krecord[i].type_id);
8776 info_aux[i].linkage = BTF_INFO_VLEN(type->info);
8778 func_proto = btf_type_by_id(btf, type->type);
8779 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
8780 /* btf_func_check() already verified it during BTF load */
8782 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
8784 btf_type_is_small_int(ret_type) || btf_type_is_enum(ret_type);
8785 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
8786 verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
8789 if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
8790 verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
8794 prev_offset = krecord[i].insn_off;
8795 urecord += urec_size;
8798 prog->aux->func_info = krecord;
8799 prog->aux->func_info_cnt = nfuncs;
8800 prog->aux->func_info_aux = info_aux;
8809 static void adjust_btf_func(struct bpf_verifier_env *env)
8811 struct bpf_prog_aux *aux = env->prog->aux;
8814 if (!aux->func_info)
8817 for (i = 0; i < env->subprog_cnt; i++)
8818 aux->func_info[i].insn_off = env->subprog_info[i].start;
8821 #define MIN_BPF_LINEINFO_SIZE (offsetof(struct bpf_line_info, line_col) + \
8822 sizeof(((struct bpf_line_info *)(0))->line_col))
8823 #define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE
8825 static int check_btf_line(struct bpf_verifier_env *env,
8826 const union bpf_attr *attr,
8827 union bpf_attr __user *uattr)
8829 u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
8830 struct bpf_subprog_info *sub;
8831 struct bpf_line_info *linfo;
8832 struct bpf_prog *prog;
8833 const struct btf *btf;
8834 void __user *ulinfo;
8837 nr_linfo = attr->line_info_cnt;
8840 if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
8843 rec_size = attr->line_info_rec_size;
8844 if (rec_size < MIN_BPF_LINEINFO_SIZE ||
8845 rec_size > MAX_LINEINFO_REC_SIZE ||
8846 rec_size & (sizeof(u32) - 1))
8849 /* Need to zero it in case the userspace may
8850 * pass in a smaller bpf_line_info object.
8852 linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
8853 GFP_KERNEL | __GFP_NOWARN);
8858 btf = prog->aux->btf;
8861 sub = env->subprog_info;
8862 ulinfo = u64_to_user_ptr(attr->line_info);
8863 expected_size = sizeof(struct bpf_line_info);
8864 ncopy = min_t(u32, expected_size, rec_size);
8865 for (i = 0; i < nr_linfo; i++) {
8866 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
8868 if (err == -E2BIG) {
8869 verbose(env, "nonzero tailing record in line_info");
8870 if (put_user(expected_size,
8871 &uattr->line_info_rec_size))
8877 if (copy_from_user(&linfo[i], ulinfo, ncopy)) {
8883 * Check insn_off to ensure
8884 * 1) strictly increasing AND
8885 * 2) bounded by prog->len
8887 * The linfo[0].insn_off == 0 check logically falls into
8888 * the later "missing bpf_line_info for func..." case
8889 * because the first linfo[0].insn_off must be the
8890 * first sub also and the first sub must have
8891 * subprog_info[0].start == 0.
8893 if ((i && linfo[i].insn_off <= prev_offset) ||
8894 linfo[i].insn_off >= prog->len) {
8895 verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
8896 i, linfo[i].insn_off, prev_offset,
8902 if (!prog->insnsi[linfo[i].insn_off].code) {
8904 "Invalid insn code at line_info[%u].insn_off\n",
8910 if (!btf_name_by_offset(btf, linfo[i].line_off) ||
8911 !btf_name_by_offset(btf, linfo[i].file_name_off)) {
8912 verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
8917 if (s != env->subprog_cnt) {
8918 if (linfo[i].insn_off == sub[s].start) {
8919 sub[s].linfo_idx = i;
8921 } else if (sub[s].start < linfo[i].insn_off) {
8922 verbose(env, "missing bpf_line_info for func#%u\n", s);
8928 prev_offset = linfo[i].insn_off;
8932 if (s != env->subprog_cnt) {
8933 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
8934 env->subprog_cnt - s, s);
8939 prog->aux->linfo = linfo;
8940 prog->aux->nr_linfo = nr_linfo;
8949 static int check_btf_info(struct bpf_verifier_env *env,
8950 const union bpf_attr *attr,
8951 union bpf_attr __user *uattr)
8956 if (!attr->func_info_cnt && !attr->line_info_cnt) {
8957 if (check_abnormal_return(env))
8962 btf = btf_get_by_fd(attr->prog_btf_fd);
8964 return PTR_ERR(btf);
8965 env->prog->aux->btf = btf;
8967 err = check_btf_func(env, attr, uattr);
8971 err = check_btf_line(env, attr, uattr);
8978 /* check %cur's range satisfies %old's */
8979 static bool range_within(struct bpf_reg_state *old,
8980 struct bpf_reg_state *cur)
8982 return old->umin_value <= cur->umin_value &&
8983 old->umax_value >= cur->umax_value &&
8984 old->smin_value <= cur->smin_value &&
8985 old->smax_value >= cur->smax_value &&
8986 old->u32_min_value <= cur->u32_min_value &&
8987 old->u32_max_value >= cur->u32_max_value &&
8988 old->s32_min_value <= cur->s32_min_value &&
8989 old->s32_max_value >= cur->s32_max_value;
8992 /* If in the old state two registers had the same id, then they need to have
8993 * the same id in the new state as well. But that id could be different from
8994 * the old state, so we need to track the mapping from old to new ids.
8995 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
8996 * regs with old id 5 must also have new id 9 for the new state to be safe. But
8997 * regs with a different old id could still have new id 9, we don't care about
8999 * So we look through our idmap to see if this old id has been seen before. If
9000 * so, we require the new id to match; otherwise, we add the id pair to the map.
9002 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_id_pair *idmap)
9006 for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
9007 if (!idmap[i].old) {
9008 /* Reached an empty slot; haven't seen this id before */
9009 idmap[i].old = old_id;
9010 idmap[i].cur = cur_id;
9013 if (idmap[i].old == old_id)
9014 return idmap[i].cur == cur_id;
9016 /* We ran out of idmap slots, which should be impossible */
9021 static void clean_func_state(struct bpf_verifier_env *env,
9022 struct bpf_func_state *st)
9024 enum bpf_reg_liveness live;
9027 for (i = 0; i < BPF_REG_FP; i++) {
9028 live = st->regs[i].live;
9029 /* liveness must not touch this register anymore */
9030 st->regs[i].live |= REG_LIVE_DONE;
9031 if (!(live & REG_LIVE_READ))
9032 /* since the register is unused, clear its state
9033 * to make further comparison simpler
9035 __mark_reg_not_init(env, &st->regs[i]);
9038 for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
9039 live = st->stack[i].spilled_ptr.live;
9040 /* liveness must not touch this stack slot anymore */
9041 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
9042 if (!(live & REG_LIVE_READ)) {
9043 __mark_reg_not_init(env, &st->stack[i].spilled_ptr);
9044 for (j = 0; j < BPF_REG_SIZE; j++)
9045 st->stack[i].slot_type[j] = STACK_INVALID;
9050 static void clean_verifier_state(struct bpf_verifier_env *env,
9051 struct bpf_verifier_state *st)
9055 if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
9056 /* all regs in this state in all frames were already marked */
9059 for (i = 0; i <= st->curframe; i++)
9060 clean_func_state(env, st->frame[i]);
9063 /* the parentage chains form a tree.
9064 * the verifier states are added to state lists at given insn and
9065 * pushed into state stack for future exploration.
9066 * when the verifier reaches bpf_exit insn some of the verifer states
9067 * stored in the state lists have their final liveness state already,
9068 * but a lot of states will get revised from liveness point of view when
9069 * the verifier explores other branches.
9072 * 2: if r1 == 100 goto pc+1
9075 * when the verifier reaches exit insn the register r0 in the state list of
9076 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
9077 * of insn 2 and goes exploring further. At the insn 4 it will walk the
9078 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
9080 * Since the verifier pushes the branch states as it sees them while exploring
9081 * the program the condition of walking the branch instruction for the second
9082 * time means that all states below this branch were already explored and
9083 * their final liveness markes are already propagated.
9084 * Hence when the verifier completes the search of state list in is_state_visited()
9085 * we can call this clean_live_states() function to mark all liveness states
9086 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
9088 * This function also clears the registers and stack for states that !READ
9089 * to simplify state merging.
9091 * Important note here that walking the same branch instruction in the callee
9092 * doesn't meant that the states are DONE. The verifier has to compare
9095 static void clean_live_states(struct bpf_verifier_env *env, int insn,
9096 struct bpf_verifier_state *cur)
9098 struct bpf_verifier_state_list *sl;
9101 sl = *explored_state(env, insn);
9103 if (sl->state.branches)
9105 if (sl->state.insn_idx != insn ||
9106 sl->state.curframe != cur->curframe)
9108 for (i = 0; i <= cur->curframe; i++)
9109 if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
9111 clean_verifier_state(env, &sl->state);
9117 /* Returns true if (rold safe implies rcur safe) */
9118 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
9119 struct bpf_reg_state *rcur, struct bpf_id_pair *idmap)
9123 if (!(rold->live & REG_LIVE_READ))
9124 /* explored state didn't use this */
9127 equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, parent)) == 0;
9129 if (rold->type == PTR_TO_STACK)
9130 /* two stack pointers are equal only if they're pointing to
9131 * the same stack frame, since fp-8 in foo != fp-8 in bar
9133 return equal && rold->frameno == rcur->frameno;
9138 if (rold->type == NOT_INIT)
9139 /* explored state can't have used this */
9141 if (rcur->type == NOT_INIT)
9143 switch (rold->type) {
9145 if (env->explore_alu_limits)
9147 if (rcur->type == SCALAR_VALUE) {
9148 if (!rold->precise && !rcur->precise)
9150 /* new val must satisfy old val knowledge */
9151 return range_within(rold, rcur) &&
9152 tnum_in(rold->var_off, rcur->var_off);
9154 /* We're trying to use a pointer in place of a scalar.
9155 * Even if the scalar was unbounded, this could lead to
9156 * pointer leaks because scalars are allowed to leak
9157 * while pointers are not. We could make this safe in
9158 * special cases if root is calling us, but it's
9159 * probably not worth the hassle.
9163 case PTR_TO_MAP_VALUE:
9164 /* If the new min/max/var_off satisfy the old ones and
9165 * everything else matches, we are OK.
9166 * 'id' is not compared, since it's only used for maps with
9167 * bpf_spin_lock inside map element and in such cases if
9168 * the rest of the prog is valid for one map element then
9169 * it's valid for all map elements regardless of the key
9170 * used in bpf_map_lookup()
9172 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
9173 range_within(rold, rcur) &&
9174 tnum_in(rold->var_off, rcur->var_off);
9175 case PTR_TO_MAP_VALUE_OR_NULL:
9176 /* a PTR_TO_MAP_VALUE could be safe to use as a
9177 * PTR_TO_MAP_VALUE_OR_NULL into the same map.
9178 * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
9179 * checked, doing so could have affected others with the same
9180 * id, and we can't check for that because we lost the id when
9181 * we converted to a PTR_TO_MAP_VALUE.
9183 if (rcur->type != PTR_TO_MAP_VALUE_OR_NULL)
9185 if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
9187 /* Check our ids match any regs they're supposed to */
9188 return check_ids(rold->id, rcur->id, idmap);
9189 case PTR_TO_PACKET_META:
9191 if (rcur->type != rold->type)
9193 /* We must have at least as much range as the old ptr
9194 * did, so that any accesses which were safe before are
9195 * still safe. This is true even if old range < old off,
9196 * since someone could have accessed through (ptr - k), or
9197 * even done ptr -= k in a register, to get a safe access.
9199 if (rold->range > rcur->range)
9201 /* If the offsets don't match, we can't trust our alignment;
9202 * nor can we be sure that we won't fall out of range.
9204 if (rold->off != rcur->off)
9206 /* id relations must be preserved */
9207 if (rold->id && !check_ids(rold->id, rcur->id, idmap))
9209 /* new val must satisfy old val knowledge */
9210 return range_within(rold, rcur) &&
9211 tnum_in(rold->var_off, rcur->var_off);
9213 case CONST_PTR_TO_MAP:
9214 case PTR_TO_PACKET_END:
9215 case PTR_TO_FLOW_KEYS:
9217 case PTR_TO_SOCKET_OR_NULL:
9218 case PTR_TO_SOCK_COMMON:
9219 case PTR_TO_SOCK_COMMON_OR_NULL:
9220 case PTR_TO_TCP_SOCK:
9221 case PTR_TO_TCP_SOCK_OR_NULL:
9222 case PTR_TO_XDP_SOCK:
9223 /* Only valid matches are exact, which memcmp() above
9224 * would have accepted
9227 /* Don't know what's going on, just say it's not safe */
9231 /* Shouldn't get here; if we do, say it's not safe */
9236 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
9237 struct bpf_func_state *cur, struct bpf_id_pair *idmap)
9241 /* walk slots of the explored stack and ignore any additional
9242 * slots in the current stack, since explored(safe) state
9245 for (i = 0; i < old->allocated_stack; i++) {
9246 spi = i / BPF_REG_SIZE;
9248 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
9249 i += BPF_REG_SIZE - 1;
9250 /* explored state didn't use this */
9254 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
9257 /* explored stack has more populated slots than current stack
9258 * and these slots were used
9260 if (i >= cur->allocated_stack)
9263 /* if old state was safe with misc data in the stack
9264 * it will be safe with zero-initialized stack.
9265 * The opposite is not true
9267 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
9268 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
9270 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
9271 cur->stack[spi].slot_type[i % BPF_REG_SIZE])
9272 /* Ex: old explored (safe) state has STACK_SPILL in
9273 * this stack slot, but current has STACK_MISC ->
9274 * this verifier states are not equivalent,
9275 * return false to continue verification of this path
9278 if (i % BPF_REG_SIZE)
9280 if (old->stack[spi].slot_type[0] != STACK_SPILL)
9282 if (!regsafe(env, &old->stack[spi].spilled_ptr,
9283 &cur->stack[spi].spilled_ptr, idmap))
9284 /* when explored and current stack slot are both storing
9285 * spilled registers, check that stored pointers types
9286 * are the same as well.
9287 * Ex: explored safe path could have stored
9288 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
9289 * but current path has stored:
9290 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
9291 * such verifier states are not equivalent.
9292 * return false to continue verification of this path
9299 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur)
9301 if (old->acquired_refs != cur->acquired_refs)
9303 return !memcmp(old->refs, cur->refs,
9304 sizeof(*old->refs) * old->acquired_refs);
9307 /* compare two verifier states
9309 * all states stored in state_list are known to be valid, since
9310 * verifier reached 'bpf_exit' instruction through them
9312 * this function is called when verifier exploring different branches of
9313 * execution popped from the state stack. If it sees an old state that has
9314 * more strict register state and more strict stack state then this execution
9315 * branch doesn't need to be explored further, since verifier already
9316 * concluded that more strict state leads to valid finish.
9318 * Therefore two states are equivalent if register state is more conservative
9319 * and explored stack state is more conservative than the current one.
9322 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
9323 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
9325 * In other words if current stack state (one being explored) has more
9326 * valid slots than old one that already passed validation, it means
9327 * the verifier can stop exploring and conclude that current state is valid too
9329 * Similarly with registers. If explored state has register type as invalid
9330 * whereas register type in current state is meaningful, it means that
9331 * the current state will reach 'bpf_exit' instruction safely
9333 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
9334 struct bpf_func_state *cur)
9338 memset(env->idmap_scratch, 0, sizeof(env->idmap_scratch));
9339 for (i = 0; i < MAX_BPF_REG; i++)
9340 if (!regsafe(env, &old->regs[i], &cur->regs[i],
9341 env->idmap_scratch))
9344 if (!stacksafe(env, old, cur, env->idmap_scratch))
9347 if (!refsafe(old, cur))
9353 static bool states_equal(struct bpf_verifier_env *env,
9354 struct bpf_verifier_state *old,
9355 struct bpf_verifier_state *cur)
9359 if (old->curframe != cur->curframe)
9362 /* Verification state from speculative execution simulation
9363 * must never prune a non-speculative execution one.
9365 if (old->speculative && !cur->speculative)
9368 if (old->active_spin_lock != cur->active_spin_lock)
9371 /* for states to be equal callsites have to be the same
9372 * and all frame states need to be equivalent
9374 for (i = 0; i <= old->curframe; i++) {
9375 if (old->frame[i]->callsite != cur->frame[i]->callsite)
9377 if (!func_states_equal(env, old->frame[i], cur->frame[i]))
9383 /* Return 0 if no propagation happened. Return negative error code if error
9384 * happened. Otherwise, return the propagated bit.
9386 static int propagate_liveness_reg(struct bpf_verifier_env *env,
9387 struct bpf_reg_state *reg,
9388 struct bpf_reg_state *parent_reg)
9390 u8 parent_flag = parent_reg->live & REG_LIVE_READ;
9391 u8 flag = reg->live & REG_LIVE_READ;
9394 /* When comes here, read flags of PARENT_REG or REG could be any of
9395 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
9396 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
9398 if (parent_flag == REG_LIVE_READ64 ||
9399 /* Or if there is no read flag from REG. */
9401 /* Or if the read flag from REG is the same as PARENT_REG. */
9402 parent_flag == flag)
9405 err = mark_reg_read(env, reg, parent_reg, flag);
9412 /* A write screens off any subsequent reads; but write marks come from the
9413 * straight-line code between a state and its parent. When we arrive at an
9414 * equivalent state (jump target or such) we didn't arrive by the straight-line
9415 * code, so read marks in the state must propagate to the parent regardless
9416 * of the state's write marks. That's what 'parent == state->parent' comparison
9417 * in mark_reg_read() is for.
9419 static int propagate_liveness(struct bpf_verifier_env *env,
9420 const struct bpf_verifier_state *vstate,
9421 struct bpf_verifier_state *vparent)
9423 struct bpf_reg_state *state_reg, *parent_reg;
9424 struct bpf_func_state *state, *parent;
9425 int i, frame, err = 0;
9427 if (vparent->curframe != vstate->curframe) {
9428 WARN(1, "propagate_live: parent frame %d current frame %d\n",
9429 vparent->curframe, vstate->curframe);
9432 /* Propagate read liveness of registers... */
9433 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
9434 for (frame = 0; frame <= vstate->curframe; frame++) {
9435 parent = vparent->frame[frame];
9436 state = vstate->frame[frame];
9437 parent_reg = parent->regs;
9438 state_reg = state->regs;
9439 /* We don't need to worry about FP liveness, it's read-only */
9440 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
9441 err = propagate_liveness_reg(env, &state_reg[i],
9445 if (err == REG_LIVE_READ64)
9446 mark_insn_zext(env, &parent_reg[i]);
9449 /* Propagate stack slots. */
9450 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
9451 i < parent->allocated_stack / BPF_REG_SIZE; i++) {
9452 parent_reg = &parent->stack[i].spilled_ptr;
9453 state_reg = &state->stack[i].spilled_ptr;
9454 err = propagate_liveness_reg(env, state_reg,
9463 /* find precise scalars in the previous equivalent state and
9464 * propagate them into the current state
9466 static int propagate_precision(struct bpf_verifier_env *env,
9467 const struct bpf_verifier_state *old)
9469 struct bpf_reg_state *state_reg;
9470 struct bpf_func_state *state;
9473 state = old->frame[old->curframe];
9474 state_reg = state->regs;
9475 for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
9476 if (state_reg->type != SCALAR_VALUE ||
9477 !state_reg->precise)
9479 if (env->log.level & BPF_LOG_LEVEL2)
9480 verbose(env, "propagating r%d\n", i);
9481 err = mark_chain_precision(env, i);
9486 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
9487 if (state->stack[i].slot_type[0] != STACK_SPILL)
9489 state_reg = &state->stack[i].spilled_ptr;
9490 if (state_reg->type != SCALAR_VALUE ||
9491 !state_reg->precise)
9493 if (env->log.level & BPF_LOG_LEVEL2)
9494 verbose(env, "propagating fp%d\n",
9495 (-i - 1) * BPF_REG_SIZE);
9496 err = mark_chain_precision_stack(env, i);
9503 static bool states_maybe_looping(struct bpf_verifier_state *old,
9504 struct bpf_verifier_state *cur)
9506 struct bpf_func_state *fold, *fcur;
9507 int i, fr = cur->curframe;
9509 if (old->curframe != fr)
9512 fold = old->frame[fr];
9513 fcur = cur->frame[fr];
9514 for (i = 0; i < MAX_BPF_REG; i++)
9515 if (memcmp(&fold->regs[i], &fcur->regs[i],
9516 offsetof(struct bpf_reg_state, parent)))
9522 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
9524 struct bpf_verifier_state_list *new_sl;
9525 struct bpf_verifier_state_list *sl, **pprev;
9526 struct bpf_verifier_state *cur = env->cur_state, *new;
9527 int i, j, err, states_cnt = 0;
9528 bool add_new_state = env->test_state_freq ? true : false;
9530 cur->last_insn_idx = env->prev_insn_idx;
9531 if (!env->insn_aux_data[insn_idx].prune_point)
9532 /* this 'insn_idx' instruction wasn't marked, so we will not
9533 * be doing state search here
9537 /* bpf progs typically have pruning point every 4 instructions
9538 * http://vger.kernel.org/bpfconf2019.html#session-1
9539 * Do not add new state for future pruning if the verifier hasn't seen
9540 * at least 2 jumps and at least 8 instructions.
9541 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
9542 * In tests that amounts to up to 50% reduction into total verifier
9543 * memory consumption and 20% verifier time speedup.
9545 if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
9546 env->insn_processed - env->prev_insn_processed >= 8)
9547 add_new_state = true;
9549 pprev = explored_state(env, insn_idx);
9552 clean_live_states(env, insn_idx, cur);
9556 if (sl->state.insn_idx != insn_idx)
9558 if (sl->state.branches) {
9559 if (states_maybe_looping(&sl->state, cur) &&
9560 states_equal(env, &sl->state, cur)) {
9561 verbose_linfo(env, insn_idx, "; ");
9562 verbose(env, "infinite loop detected at insn %d\n", insn_idx);
9565 /* if the verifier is processing a loop, avoid adding new state
9566 * too often, since different loop iterations have distinct
9567 * states and may not help future pruning.
9568 * This threshold shouldn't be too low to make sure that
9569 * a loop with large bound will be rejected quickly.
9570 * The most abusive loop will be:
9572 * if r1 < 1000000 goto pc-2
9573 * 1M insn_procssed limit / 100 == 10k peak states.
9574 * This threshold shouldn't be too high either, since states
9575 * at the end of the loop are likely to be useful in pruning.
9577 if (env->jmps_processed - env->prev_jmps_processed < 20 &&
9578 env->insn_processed - env->prev_insn_processed < 100)
9579 add_new_state = false;
9582 if (states_equal(env, &sl->state, cur)) {
9584 /* reached equivalent register/stack state,
9586 * Registers read by the continuation are read by us.
9587 * If we have any write marks in env->cur_state, they
9588 * will prevent corresponding reads in the continuation
9589 * from reaching our parent (an explored_state). Our
9590 * own state will get the read marks recorded, but
9591 * they'll be immediately forgotten as we're pruning
9592 * this state and will pop a new one.
9594 err = propagate_liveness(env, &sl->state, cur);
9596 /* if previous state reached the exit with precision and
9597 * current state is equivalent to it (except precsion marks)
9598 * the precision needs to be propagated back in
9599 * the current state.
9601 err = err ? : push_jmp_history(env, cur);
9602 err = err ? : propagate_precision(env, &sl->state);
9608 /* when new state is not going to be added do not increase miss count.
9609 * Otherwise several loop iterations will remove the state
9610 * recorded earlier. The goal of these heuristics is to have
9611 * states from some iterations of the loop (some in the beginning
9612 * and some at the end) to help pruning.
9616 /* heuristic to determine whether this state is beneficial
9617 * to keep checking from state equivalence point of view.
9618 * Higher numbers increase max_states_per_insn and verification time,
9619 * but do not meaningfully decrease insn_processed.
9621 if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
9622 /* the state is unlikely to be useful. Remove it to
9623 * speed up verification
9626 if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
9627 u32 br = sl->state.branches;
9630 "BUG live_done but branches_to_explore %d\n",
9632 free_verifier_state(&sl->state, false);
9636 /* cannot free this state, since parentage chain may
9637 * walk it later. Add it for free_list instead to
9638 * be freed at the end of verification
9640 sl->next = env->free_list;
9641 env->free_list = sl;
9651 if (env->max_states_per_insn < states_cnt)
9652 env->max_states_per_insn = states_cnt;
9654 if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
9655 return push_jmp_history(env, cur);
9658 return push_jmp_history(env, cur);
9660 /* There were no equivalent states, remember the current one.
9661 * Technically the current state is not proven to be safe yet,
9662 * but it will either reach outer most bpf_exit (which means it's safe)
9663 * or it will be rejected. When there are no loops the verifier won't be
9664 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
9665 * again on the way to bpf_exit.
9666 * When looping the sl->state.branches will be > 0 and this state
9667 * will not be considered for equivalence until branches == 0.
9669 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
9672 env->total_states++;
9674 env->prev_jmps_processed = env->jmps_processed;
9675 env->prev_insn_processed = env->insn_processed;
9677 /* add new state to the head of linked list */
9678 new = &new_sl->state;
9679 err = copy_verifier_state(new, cur);
9681 free_verifier_state(new, false);
9685 new->insn_idx = insn_idx;
9686 WARN_ONCE(new->branches != 1,
9687 "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
9690 cur->first_insn_idx = insn_idx;
9691 clear_jmp_history(cur);
9692 new_sl->next = *explored_state(env, insn_idx);
9693 *explored_state(env, insn_idx) = new_sl;
9694 /* connect new state to parentage chain. Current frame needs all
9695 * registers connected. Only r6 - r9 of the callers are alive (pushed
9696 * to the stack implicitly by JITs) so in callers' frames connect just
9697 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
9698 * the state of the call instruction (with WRITTEN set), and r0 comes
9699 * from callee with its full parentage chain, anyway.
9701 /* clear write marks in current state: the writes we did are not writes
9702 * our child did, so they don't screen off its reads from us.
9703 * (There are no read marks in current state, because reads always mark
9704 * their parent and current state never has children yet. Only
9705 * explored_states can get read marks.)
9707 for (j = 0; j <= cur->curframe; j++) {
9708 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
9709 cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
9710 for (i = 0; i < BPF_REG_FP; i++)
9711 cur->frame[j]->regs[i].live = REG_LIVE_NONE;
9714 /* all stack frames are accessible from callee, clear them all */
9715 for (j = 0; j <= cur->curframe; j++) {
9716 struct bpf_func_state *frame = cur->frame[j];
9717 struct bpf_func_state *newframe = new->frame[j];
9719 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
9720 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
9721 frame->stack[i].spilled_ptr.parent =
9722 &newframe->stack[i].spilled_ptr;
9728 /* Return true if it's OK to have the same insn return a different type. */
9729 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
9734 case PTR_TO_SOCKET_OR_NULL:
9735 case PTR_TO_SOCK_COMMON:
9736 case PTR_TO_SOCK_COMMON_OR_NULL:
9737 case PTR_TO_TCP_SOCK:
9738 case PTR_TO_TCP_SOCK_OR_NULL:
9739 case PTR_TO_XDP_SOCK:
9741 case PTR_TO_BTF_ID_OR_NULL:
9748 /* If an instruction was previously used with particular pointer types, then we
9749 * need to be careful to avoid cases such as the below, where it may be ok
9750 * for one branch accessing the pointer, but not ok for the other branch:
9755 * R1 = some_other_valid_ptr;
9758 * R2 = *(u32 *)(R1 + 0);
9760 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
9762 return src != prev && (!reg_type_mismatch_ok(src) ||
9763 !reg_type_mismatch_ok(prev));
9766 static int do_check(struct bpf_verifier_env *env)
9768 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
9769 struct bpf_verifier_state *state = env->cur_state;
9770 struct bpf_insn *insns = env->prog->insnsi;
9771 struct bpf_reg_state *regs;
9772 int insn_cnt = env->prog->len;
9773 bool do_print_state = false;
9774 int prev_insn_idx = -1;
9777 struct bpf_insn *insn;
9781 env->prev_insn_idx = prev_insn_idx;
9782 if (env->insn_idx >= insn_cnt) {
9783 verbose(env, "invalid insn idx %d insn_cnt %d\n",
9784 env->insn_idx, insn_cnt);
9788 insn = &insns[env->insn_idx];
9789 class = BPF_CLASS(insn->code);
9791 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
9793 "BPF program is too large. Processed %d insn\n",
9794 env->insn_processed);
9798 err = is_state_visited(env, env->insn_idx);
9802 /* found equivalent state, can prune the search */
9803 if (env->log.level & BPF_LOG_LEVEL) {
9805 verbose(env, "\nfrom %d to %d%s: safe\n",
9806 env->prev_insn_idx, env->insn_idx,
9807 env->cur_state->speculative ?
9808 " (speculative execution)" : "");
9810 verbose(env, "%d: safe\n", env->insn_idx);
9812 goto process_bpf_exit;
9815 if (signal_pending(current))
9821 if (env->log.level & BPF_LOG_LEVEL2 ||
9822 (env->log.level & BPF_LOG_LEVEL && do_print_state)) {
9823 if (env->log.level & BPF_LOG_LEVEL2)
9824 verbose(env, "%d:", env->insn_idx);
9826 verbose(env, "\nfrom %d to %d%s:",
9827 env->prev_insn_idx, env->insn_idx,
9828 env->cur_state->speculative ?
9829 " (speculative execution)" : "");
9830 print_verifier_state(env, state->frame[state->curframe]);
9831 do_print_state = false;
9834 if (env->log.level & BPF_LOG_LEVEL) {
9835 const struct bpf_insn_cbs cbs = {
9836 .cb_print = verbose,
9837 .private_data = env,
9840 verbose_linfo(env, env->insn_idx, "; ");
9841 verbose(env, "%d: ", env->insn_idx);
9842 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
9845 if (bpf_prog_is_dev_bound(env->prog->aux)) {
9846 err = bpf_prog_offload_verify_insn(env, env->insn_idx,
9847 env->prev_insn_idx);
9852 regs = cur_regs(env);
9853 sanitize_mark_insn_seen(env);
9854 prev_insn_idx = env->insn_idx;
9856 if (class == BPF_ALU || class == BPF_ALU64) {
9857 err = check_alu_op(env, insn);
9861 } else if (class == BPF_LDX) {
9862 enum bpf_reg_type *prev_src_type, src_reg_type;
9864 /* check for reserved fields is already done */
9866 /* check src operand */
9867 err = check_reg_arg(env, insn->src_reg, SRC_OP);
9871 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
9875 src_reg_type = regs[insn->src_reg].type;
9877 /* check that memory (src_reg + off) is readable,
9878 * the state of dst_reg will be updated by this func
9880 err = check_mem_access(env, env->insn_idx, insn->src_reg,
9881 insn->off, BPF_SIZE(insn->code),
9882 BPF_READ, insn->dst_reg, false);
9886 prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type;
9888 if (*prev_src_type == NOT_INIT) {
9890 * dst_reg = *(u32 *)(src_reg + off)
9891 * save type to validate intersecting paths
9893 *prev_src_type = src_reg_type;
9895 } else if (reg_type_mismatch(src_reg_type, *prev_src_type)) {
9896 /* ABuser program is trying to use the same insn
9897 * dst_reg = *(u32*) (src_reg + off)
9898 * with different pointer types:
9899 * src_reg == ctx in one branch and
9900 * src_reg == stack|map in some other branch.
9903 verbose(env, "same insn cannot be used with different pointers\n");
9907 } else if (class == BPF_STX) {
9908 enum bpf_reg_type *prev_dst_type, dst_reg_type;
9910 if (BPF_MODE(insn->code) == BPF_XADD) {
9911 err = check_xadd(env, env->insn_idx, insn);
9918 /* check src1 operand */
9919 err = check_reg_arg(env, insn->src_reg, SRC_OP);
9922 /* check src2 operand */
9923 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
9927 dst_reg_type = regs[insn->dst_reg].type;
9929 /* check that memory (dst_reg + off) is writeable */
9930 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
9931 insn->off, BPF_SIZE(insn->code),
9932 BPF_WRITE, insn->src_reg, false);
9936 prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type;
9938 if (*prev_dst_type == NOT_INIT) {
9939 *prev_dst_type = dst_reg_type;
9940 } else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) {
9941 verbose(env, "same insn cannot be used with different pointers\n");
9945 } else if (class == BPF_ST) {
9946 if (BPF_MODE(insn->code) != BPF_MEM ||
9947 insn->src_reg != BPF_REG_0) {
9948 verbose(env, "BPF_ST uses reserved fields\n");
9951 /* check src operand */
9952 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
9956 if (is_ctx_reg(env, insn->dst_reg)) {
9957 verbose(env, "BPF_ST stores into R%d %s is not allowed\n",
9959 reg_type_str[reg_state(env, insn->dst_reg)->type]);
9963 /* check that memory (dst_reg + off) is writeable */
9964 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
9965 insn->off, BPF_SIZE(insn->code),
9966 BPF_WRITE, -1, false);
9970 } else if (class == BPF_JMP || class == BPF_JMP32) {
9971 u8 opcode = BPF_OP(insn->code);
9973 env->jmps_processed++;
9974 if (opcode == BPF_CALL) {
9975 if (BPF_SRC(insn->code) != BPF_K ||
9977 (insn->src_reg != BPF_REG_0 &&
9978 insn->src_reg != BPF_PSEUDO_CALL) ||
9979 insn->dst_reg != BPF_REG_0 ||
9980 class == BPF_JMP32) {
9981 verbose(env, "BPF_CALL uses reserved fields\n");
9985 if (env->cur_state->active_spin_lock &&
9986 (insn->src_reg == BPF_PSEUDO_CALL ||
9987 insn->imm != BPF_FUNC_spin_unlock)) {
9988 verbose(env, "function calls are not allowed while holding a lock\n");
9991 if (insn->src_reg == BPF_PSEUDO_CALL)
9992 err = check_func_call(env, insn, &env->insn_idx);
9994 err = check_helper_call(env, insn->imm, env->insn_idx);
9998 } else if (opcode == BPF_JA) {
9999 if (BPF_SRC(insn->code) != BPF_K ||
10001 insn->src_reg != BPF_REG_0 ||
10002 insn->dst_reg != BPF_REG_0 ||
10003 class == BPF_JMP32) {
10004 verbose(env, "BPF_JA uses reserved fields\n");
10008 env->insn_idx += insn->off + 1;
10011 } else if (opcode == BPF_EXIT) {
10012 if (BPF_SRC(insn->code) != BPF_K ||
10014 insn->src_reg != BPF_REG_0 ||
10015 insn->dst_reg != BPF_REG_0 ||
10016 class == BPF_JMP32) {
10017 verbose(env, "BPF_EXIT uses reserved fields\n");
10021 if (env->cur_state->active_spin_lock) {
10022 verbose(env, "bpf_spin_unlock is missing\n");
10026 if (state->curframe) {
10027 /* exit from nested function */
10028 err = prepare_func_exit(env, &env->insn_idx);
10031 do_print_state = true;
10035 err = check_reference_leak(env);
10039 err = check_return_code(env);
10043 update_branch_counts(env, env->cur_state);
10044 err = pop_stack(env, &prev_insn_idx,
10045 &env->insn_idx, pop_log);
10047 if (err != -ENOENT)
10051 do_print_state = true;
10055 err = check_cond_jmp_op(env, insn, &env->insn_idx);
10059 } else if (class == BPF_LD) {
10060 u8 mode = BPF_MODE(insn->code);
10062 if (mode == BPF_ABS || mode == BPF_IND) {
10063 err = check_ld_abs(env, insn);
10067 } else if (mode == BPF_IMM) {
10068 err = check_ld_imm(env, insn);
10073 sanitize_mark_insn_seen(env);
10075 verbose(env, "invalid BPF_LD mode\n");
10079 verbose(env, "unknown insn class %d\n", class);
10089 /* replace pseudo btf_id with kernel symbol address */
10090 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
10091 struct bpf_insn *insn,
10092 struct bpf_insn_aux_data *aux)
10094 const struct btf_var_secinfo *vsi;
10095 const struct btf_type *datasec;
10096 const struct btf_type *t;
10097 const char *sym_name;
10098 bool percpu = false;
10099 u32 type, id = insn->imm;
10104 if (!btf_vmlinux) {
10105 verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
10109 if (insn[1].imm != 0) {
10110 verbose(env, "reserved field (insn[1].imm) is used in pseudo_btf_id ldimm64 insn.\n");
10114 t = btf_type_by_id(btf_vmlinux, id);
10116 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
10120 if (!btf_type_is_var(t)) {
10121 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR.\n",
10126 sym_name = btf_name_by_offset(btf_vmlinux, t->name_off);
10127 addr = kallsyms_lookup_name(sym_name);
10129 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
10134 datasec_id = btf_find_by_name_kind(btf_vmlinux, ".data..percpu",
10136 if (datasec_id > 0) {
10137 datasec = btf_type_by_id(btf_vmlinux, datasec_id);
10138 for_each_vsi(i, datasec, vsi) {
10139 if (vsi->type == id) {
10146 insn[0].imm = (u32)addr;
10147 insn[1].imm = addr >> 32;
10150 t = btf_type_skip_modifiers(btf_vmlinux, type, NULL);
10152 aux->btf_var.reg_type = PTR_TO_PERCPU_BTF_ID;
10153 aux->btf_var.btf_id = type;
10154 } else if (!btf_type_is_struct(t)) {
10155 const struct btf_type *ret;
10159 /* resolve the type size of ksym. */
10160 ret = btf_resolve_size(btf_vmlinux, t, &tsize);
10162 tname = btf_name_by_offset(btf_vmlinux, t->name_off);
10163 verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
10164 tname, PTR_ERR(ret));
10167 aux->btf_var.reg_type = PTR_TO_MEM;
10168 aux->btf_var.mem_size = tsize;
10170 aux->btf_var.reg_type = PTR_TO_BTF_ID;
10171 aux->btf_var.btf_id = type;
10176 static int check_map_prealloc(struct bpf_map *map)
10178 return (map->map_type != BPF_MAP_TYPE_HASH &&
10179 map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
10180 map->map_type != BPF_MAP_TYPE_HASH_OF_MAPS) ||
10181 !(map->map_flags & BPF_F_NO_PREALLOC);
10184 static bool is_tracing_prog_type(enum bpf_prog_type type)
10187 case BPF_PROG_TYPE_KPROBE:
10188 case BPF_PROG_TYPE_TRACEPOINT:
10189 case BPF_PROG_TYPE_PERF_EVENT:
10190 case BPF_PROG_TYPE_RAW_TRACEPOINT:
10197 static bool is_preallocated_map(struct bpf_map *map)
10199 if (!check_map_prealloc(map))
10201 if (map->inner_map_meta && !check_map_prealloc(map->inner_map_meta))
10206 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
10207 struct bpf_map *map,
10208 struct bpf_prog *prog)
10211 enum bpf_prog_type prog_type = resolve_prog_type(prog);
10213 * Validate that trace type programs use preallocated hash maps.
10215 * For programs attached to PERF events this is mandatory as the
10216 * perf NMI can hit any arbitrary code sequence.
10218 * All other trace types using preallocated hash maps are unsafe as
10219 * well because tracepoint or kprobes can be inside locked regions
10220 * of the memory allocator or at a place where a recursion into the
10221 * memory allocator would see inconsistent state.
10223 * On RT enabled kernels run-time allocation of all trace type
10224 * programs is strictly prohibited due to lock type constraints. On
10225 * !RT kernels it is allowed for backwards compatibility reasons for
10226 * now, but warnings are emitted so developers are made aware of
10227 * the unsafety and can fix their programs before this is enforced.
10229 if (is_tracing_prog_type(prog_type) && !is_preallocated_map(map)) {
10230 if (prog_type == BPF_PROG_TYPE_PERF_EVENT) {
10231 verbose(env, "perf_event programs can only use preallocated hash map\n");
10234 if (IS_ENABLED(CONFIG_PREEMPT_RT)) {
10235 verbose(env, "trace type programs can only use preallocated hash map\n");
10238 WARN_ONCE(1, "trace type BPF program uses run-time allocation\n");
10239 verbose(env, "trace type programs with run-time allocated hash maps are unsafe. Switch to preallocated hash maps.\n");
10242 if ((is_tracing_prog_type(prog_type) ||
10243 prog_type == BPF_PROG_TYPE_SOCKET_FILTER) &&
10244 map_value_has_spin_lock(map)) {
10245 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
10249 if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) &&
10250 !bpf_offload_prog_map_match(prog, map)) {
10251 verbose(env, "offload device mismatch between prog and map\n");
10255 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
10256 verbose(env, "bpf_struct_ops map cannot be used in prog\n");
10260 if (prog->aux->sleepable)
10261 switch (map->map_type) {
10262 case BPF_MAP_TYPE_HASH:
10263 case BPF_MAP_TYPE_LRU_HASH:
10264 case BPF_MAP_TYPE_ARRAY:
10265 if (!is_preallocated_map(map)) {
10267 "Sleepable programs can only use preallocated hash maps\n");
10273 "Sleepable programs can only use array and hash maps\n");
10280 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
10282 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
10283 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
10286 /* find and rewrite pseudo imm in ld_imm64 instructions:
10288 * 1. if it accesses map FD, replace it with actual map pointer.
10289 * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
10291 * NOTE: btf_vmlinux is required for converting pseudo btf_id.
10293 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
10295 struct bpf_insn *insn = env->prog->insnsi;
10296 int insn_cnt = env->prog->len;
10299 err = bpf_prog_calc_tag(env->prog);
10303 for (i = 0; i < insn_cnt; i++, insn++) {
10304 if (BPF_CLASS(insn->code) == BPF_LDX &&
10305 (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
10306 verbose(env, "BPF_LDX uses reserved fields\n");
10310 if (BPF_CLASS(insn->code) == BPF_STX &&
10311 ((BPF_MODE(insn->code) != BPF_MEM &&
10312 BPF_MODE(insn->code) != BPF_XADD) || insn->imm != 0)) {
10313 verbose(env, "BPF_STX uses reserved fields\n");
10317 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
10318 struct bpf_insn_aux_data *aux;
10319 struct bpf_map *map;
10323 if (i == insn_cnt - 1 || insn[1].code != 0 ||
10324 insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
10325 insn[1].off != 0) {
10326 verbose(env, "invalid bpf_ld_imm64 insn\n");
10330 if (insn[0].src_reg == 0)
10331 /* valid generic load 64-bit imm */
10334 if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
10335 aux = &env->insn_aux_data[i];
10336 err = check_pseudo_btf_id(env, insn, aux);
10342 /* In final convert_pseudo_ld_imm64() step, this is
10343 * converted into regular 64-bit imm load insn.
10345 if ((insn[0].src_reg != BPF_PSEUDO_MAP_FD &&
10346 insn[0].src_reg != BPF_PSEUDO_MAP_VALUE) ||
10347 (insn[0].src_reg == BPF_PSEUDO_MAP_FD &&
10348 insn[1].imm != 0)) {
10350 "unrecognized bpf_ld_imm64 insn\n");
10354 f = fdget(insn[0].imm);
10355 map = __bpf_map_get(f);
10357 verbose(env, "fd %d is not pointing to valid bpf_map\n",
10359 return PTR_ERR(map);
10362 err = check_map_prog_compatibility(env, map, env->prog);
10368 aux = &env->insn_aux_data[i];
10369 if (insn->src_reg == BPF_PSEUDO_MAP_FD) {
10370 addr = (unsigned long)map;
10372 u32 off = insn[1].imm;
10374 if (off >= BPF_MAX_VAR_OFF) {
10375 verbose(env, "direct value offset of %u is not allowed\n", off);
10380 if (!map->ops->map_direct_value_addr) {
10381 verbose(env, "no direct value access support for this map type\n");
10386 err = map->ops->map_direct_value_addr(map, &addr, off);
10388 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
10389 map->value_size, off);
10394 aux->map_off = off;
10398 insn[0].imm = (u32)addr;
10399 insn[1].imm = addr >> 32;
10401 /* check whether we recorded this map already */
10402 for (j = 0; j < env->used_map_cnt; j++) {
10403 if (env->used_maps[j] == map) {
10404 aux->map_index = j;
10410 if (env->used_map_cnt >= MAX_USED_MAPS) {
10415 /* hold the map. If the program is rejected by verifier,
10416 * the map will be released by release_maps() or it
10417 * will be used by the valid program until it's unloaded
10418 * and all maps are released in free_used_maps()
10422 aux->map_index = env->used_map_cnt;
10423 env->used_maps[env->used_map_cnt++] = map;
10425 if (bpf_map_is_cgroup_storage(map) &&
10426 bpf_cgroup_storage_assign(env->prog->aux, map)) {
10427 verbose(env, "only one cgroup storage of each type is allowed\n");
10439 /* Basic sanity check before we invest more work here. */
10440 if (!bpf_opcode_in_insntable(insn->code)) {
10441 verbose(env, "unknown opcode %02x\n", insn->code);
10446 /* now all pseudo BPF_LD_IMM64 instructions load valid
10447 * 'struct bpf_map *' into a register instead of user map_fd.
10448 * These pointers will be used later by verifier to validate map access.
10453 /* drop refcnt of maps used by the rejected program */
10454 static void release_maps(struct bpf_verifier_env *env)
10456 __bpf_free_used_maps(env->prog->aux, env->used_maps,
10457 env->used_map_cnt);
10460 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
10461 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
10463 struct bpf_insn *insn = env->prog->insnsi;
10464 int insn_cnt = env->prog->len;
10467 for (i = 0; i < insn_cnt; i++, insn++)
10468 if (insn->code == (BPF_LD | BPF_IMM | BPF_DW))
10472 /* single env->prog->insni[off] instruction was replaced with the range
10473 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying
10474 * [0, off) and [off, end) to new locations, so the patched range stays zero
10476 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
10477 struct bpf_insn_aux_data *new_data,
10478 struct bpf_prog *new_prog, u32 off, u32 cnt)
10480 struct bpf_insn_aux_data *old_data = env->insn_aux_data;
10481 struct bpf_insn *insn = new_prog->insnsi;
10482 u32 old_seen = old_data[off].seen;
10486 /* aux info at OFF always needs adjustment, no matter fast path
10487 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
10488 * original insn at old prog.
10490 old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
10494 prog_len = new_prog->len;
10496 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
10497 memcpy(new_data + off + cnt - 1, old_data + off,
10498 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
10499 for (i = off; i < off + cnt - 1; i++) {
10500 /* Expand insni[off]'s seen count to the patched range. */
10501 new_data[i].seen = old_seen;
10502 new_data[i].zext_dst = insn_has_def32(env, insn + i);
10504 env->insn_aux_data = new_data;
10508 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
10514 /* NOTE: fake 'exit' subprog should be updated as well. */
10515 for (i = 0; i <= env->subprog_cnt; i++) {
10516 if (env->subprog_info[i].start <= off)
10518 env->subprog_info[i].start += len - 1;
10522 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
10524 struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
10525 int i, sz = prog->aux->size_poke_tab;
10526 struct bpf_jit_poke_descriptor *desc;
10528 for (i = 0; i < sz; i++) {
10530 if (desc->insn_idx <= off)
10532 desc->insn_idx += len - 1;
10536 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
10537 const struct bpf_insn *patch, u32 len)
10539 struct bpf_prog *new_prog;
10540 struct bpf_insn_aux_data *new_data = NULL;
10543 new_data = vzalloc(array_size(env->prog->len + len - 1,
10544 sizeof(struct bpf_insn_aux_data)));
10549 new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
10550 if (IS_ERR(new_prog)) {
10551 if (PTR_ERR(new_prog) == -ERANGE)
10553 "insn %d cannot be patched due to 16-bit range\n",
10554 env->insn_aux_data[off].orig_idx);
10558 adjust_insn_aux_data(env, new_data, new_prog, off, len);
10559 adjust_subprog_starts(env, off, len);
10560 adjust_poke_descs(new_prog, off, len);
10564 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
10569 /* find first prog starting at or after off (first to remove) */
10570 for (i = 0; i < env->subprog_cnt; i++)
10571 if (env->subprog_info[i].start >= off)
10573 /* find first prog starting at or after off + cnt (first to stay) */
10574 for (j = i; j < env->subprog_cnt; j++)
10575 if (env->subprog_info[j].start >= off + cnt)
10577 /* if j doesn't start exactly at off + cnt, we are just removing
10578 * the front of previous prog
10580 if (env->subprog_info[j].start != off + cnt)
10584 struct bpf_prog_aux *aux = env->prog->aux;
10587 /* move fake 'exit' subprog as well */
10588 move = env->subprog_cnt + 1 - j;
10590 memmove(env->subprog_info + i,
10591 env->subprog_info + j,
10592 sizeof(*env->subprog_info) * move);
10593 env->subprog_cnt -= j - i;
10595 /* remove func_info */
10596 if (aux->func_info) {
10597 move = aux->func_info_cnt - j;
10599 memmove(aux->func_info + i,
10600 aux->func_info + j,
10601 sizeof(*aux->func_info) * move);
10602 aux->func_info_cnt -= j - i;
10603 /* func_info->insn_off is set after all code rewrites,
10604 * in adjust_btf_func() - no need to adjust
10608 /* convert i from "first prog to remove" to "first to adjust" */
10609 if (env->subprog_info[i].start == off)
10613 /* update fake 'exit' subprog as well */
10614 for (; i <= env->subprog_cnt; i++)
10615 env->subprog_info[i].start -= cnt;
10620 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
10623 struct bpf_prog *prog = env->prog;
10624 u32 i, l_off, l_cnt, nr_linfo;
10625 struct bpf_line_info *linfo;
10627 nr_linfo = prog->aux->nr_linfo;
10631 linfo = prog->aux->linfo;
10633 /* find first line info to remove, count lines to be removed */
10634 for (i = 0; i < nr_linfo; i++)
10635 if (linfo[i].insn_off >= off)
10640 for (; i < nr_linfo; i++)
10641 if (linfo[i].insn_off < off + cnt)
10646 /* First live insn doesn't match first live linfo, it needs to "inherit"
10647 * last removed linfo. prog is already modified, so prog->len == off
10648 * means no live instructions after (tail of the program was removed).
10650 if (prog->len != off && l_cnt &&
10651 (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
10653 linfo[--i].insn_off = off + cnt;
10656 /* remove the line info which refer to the removed instructions */
10658 memmove(linfo + l_off, linfo + i,
10659 sizeof(*linfo) * (nr_linfo - i));
10661 prog->aux->nr_linfo -= l_cnt;
10662 nr_linfo = prog->aux->nr_linfo;
10665 /* pull all linfo[i].insn_off >= off + cnt in by cnt */
10666 for (i = l_off; i < nr_linfo; i++)
10667 linfo[i].insn_off -= cnt;
10669 /* fix up all subprogs (incl. 'exit') which start >= off */
10670 for (i = 0; i <= env->subprog_cnt; i++)
10671 if (env->subprog_info[i].linfo_idx > l_off) {
10672 /* program may have started in the removed region but
10673 * may not be fully removed
10675 if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
10676 env->subprog_info[i].linfo_idx -= l_cnt;
10678 env->subprog_info[i].linfo_idx = l_off;
10684 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
10686 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
10687 unsigned int orig_prog_len = env->prog->len;
10690 if (bpf_prog_is_dev_bound(env->prog->aux))
10691 bpf_prog_offload_remove_insns(env, off, cnt);
10693 err = bpf_remove_insns(env->prog, off, cnt);
10697 err = adjust_subprog_starts_after_remove(env, off, cnt);
10701 err = bpf_adj_linfo_after_remove(env, off, cnt);
10705 memmove(aux_data + off, aux_data + off + cnt,
10706 sizeof(*aux_data) * (orig_prog_len - off - cnt));
10711 /* The verifier does more data flow analysis than llvm and will not
10712 * explore branches that are dead at run time. Malicious programs can
10713 * have dead code too. Therefore replace all dead at-run-time code
10716 * Just nops are not optimal, e.g. if they would sit at the end of the
10717 * program and through another bug we would manage to jump there, then
10718 * we'd execute beyond program memory otherwise. Returning exception
10719 * code also wouldn't work since we can have subprogs where the dead
10720 * code could be located.
10722 static void sanitize_dead_code(struct bpf_verifier_env *env)
10724 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
10725 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
10726 struct bpf_insn *insn = env->prog->insnsi;
10727 const int insn_cnt = env->prog->len;
10730 for (i = 0; i < insn_cnt; i++) {
10731 if (aux_data[i].seen)
10733 memcpy(insn + i, &trap, sizeof(trap));
10734 aux_data[i].zext_dst = false;
10738 static bool insn_is_cond_jump(u8 code)
10742 if (BPF_CLASS(code) == BPF_JMP32)
10745 if (BPF_CLASS(code) != BPF_JMP)
10749 return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
10752 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
10754 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
10755 struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
10756 struct bpf_insn *insn = env->prog->insnsi;
10757 const int insn_cnt = env->prog->len;
10760 for (i = 0; i < insn_cnt; i++, insn++) {
10761 if (!insn_is_cond_jump(insn->code))
10764 if (!aux_data[i + 1].seen)
10765 ja.off = insn->off;
10766 else if (!aux_data[i + 1 + insn->off].seen)
10771 if (bpf_prog_is_dev_bound(env->prog->aux))
10772 bpf_prog_offload_replace_insn(env, i, &ja);
10774 memcpy(insn, &ja, sizeof(ja));
10778 static int opt_remove_dead_code(struct bpf_verifier_env *env)
10780 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
10781 int insn_cnt = env->prog->len;
10784 for (i = 0; i < insn_cnt; i++) {
10788 while (i + j < insn_cnt && !aux_data[i + j].seen)
10793 err = verifier_remove_insns(env, i, j);
10796 insn_cnt = env->prog->len;
10802 static int opt_remove_nops(struct bpf_verifier_env *env)
10804 const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
10805 struct bpf_insn *insn = env->prog->insnsi;
10806 int insn_cnt = env->prog->len;
10809 for (i = 0; i < insn_cnt; i++) {
10810 if (memcmp(&insn[i], &ja, sizeof(ja)))
10813 err = verifier_remove_insns(env, i, 1);
10823 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
10824 const union bpf_attr *attr)
10826 struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
10827 struct bpf_insn_aux_data *aux = env->insn_aux_data;
10828 int i, patch_len, delta = 0, len = env->prog->len;
10829 struct bpf_insn *insns = env->prog->insnsi;
10830 struct bpf_prog *new_prog;
10833 rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
10834 zext_patch[1] = BPF_ZEXT_REG(0);
10835 rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
10836 rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
10837 rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
10838 for (i = 0; i < len; i++) {
10839 int adj_idx = i + delta;
10840 struct bpf_insn insn;
10842 insn = insns[adj_idx];
10843 if (!aux[adj_idx].zext_dst) {
10851 class = BPF_CLASS(code);
10852 if (insn_no_def(&insn))
10855 /* NOTE: arg "reg" (the fourth one) is only used for
10856 * BPF_STX which has been ruled out in above
10857 * check, it is safe to pass NULL here.
10859 if (is_reg64(env, &insn, insn.dst_reg, NULL, DST_OP)) {
10860 if (class == BPF_LD &&
10861 BPF_MODE(code) == BPF_IMM)
10866 /* ctx load could be transformed into wider load. */
10867 if (class == BPF_LDX &&
10868 aux[adj_idx].ptr_type == PTR_TO_CTX)
10871 imm_rnd = get_random_int();
10872 rnd_hi32_patch[0] = insn;
10873 rnd_hi32_patch[1].imm = imm_rnd;
10874 rnd_hi32_patch[3].dst_reg = insn.dst_reg;
10875 patch = rnd_hi32_patch;
10877 goto apply_patch_buffer;
10880 if (!bpf_jit_needs_zext())
10883 zext_patch[0] = insn;
10884 zext_patch[1].dst_reg = insn.dst_reg;
10885 zext_patch[1].src_reg = insn.dst_reg;
10886 patch = zext_patch;
10888 apply_patch_buffer:
10889 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
10892 env->prog = new_prog;
10893 insns = new_prog->insnsi;
10894 aux = env->insn_aux_data;
10895 delta += patch_len - 1;
10901 /* convert load instructions that access fields of a context type into a
10902 * sequence of instructions that access fields of the underlying structure:
10903 * struct __sk_buff -> struct sk_buff
10904 * struct bpf_sock_ops -> struct sock
10906 static int convert_ctx_accesses(struct bpf_verifier_env *env)
10908 const struct bpf_verifier_ops *ops = env->ops;
10909 int i, cnt, size, ctx_field_size, delta = 0;
10910 const int insn_cnt = env->prog->len;
10911 struct bpf_insn insn_buf[16], *insn;
10912 u32 target_size, size_default, off;
10913 struct bpf_prog *new_prog;
10914 enum bpf_access_type type;
10915 bool is_narrower_load;
10917 if (ops->gen_prologue || env->seen_direct_write) {
10918 if (!ops->gen_prologue) {
10919 verbose(env, "bpf verifier is misconfigured\n");
10922 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
10924 if (cnt >= ARRAY_SIZE(insn_buf)) {
10925 verbose(env, "bpf verifier is misconfigured\n");
10928 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
10932 env->prog = new_prog;
10937 if (bpf_prog_is_dev_bound(env->prog->aux))
10940 insn = env->prog->insnsi + delta;
10942 for (i = 0; i < insn_cnt; i++, insn++) {
10943 bpf_convert_ctx_access_t convert_ctx_access;
10946 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
10947 insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
10948 insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
10949 insn->code == (BPF_LDX | BPF_MEM | BPF_DW)) {
10952 } else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
10953 insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
10954 insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
10955 insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
10956 insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
10957 insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
10958 insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
10959 insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
10961 ctx_access = BPF_CLASS(insn->code) == BPF_STX;
10966 if (type == BPF_WRITE &&
10967 env->insn_aux_data[i + delta].sanitize_stack_spill) {
10968 struct bpf_insn patch[] = {
10973 cnt = ARRAY_SIZE(patch);
10974 new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
10979 env->prog = new_prog;
10980 insn = new_prog->insnsi + i + delta;
10987 switch (env->insn_aux_data[i + delta].ptr_type) {
10989 if (!ops->convert_ctx_access)
10991 convert_ctx_access = ops->convert_ctx_access;
10993 case PTR_TO_SOCKET:
10994 case PTR_TO_SOCK_COMMON:
10995 convert_ctx_access = bpf_sock_convert_ctx_access;
10997 case PTR_TO_TCP_SOCK:
10998 convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
11000 case PTR_TO_XDP_SOCK:
11001 convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
11003 case PTR_TO_BTF_ID:
11004 if (type == BPF_READ) {
11005 insn->code = BPF_LDX | BPF_PROBE_MEM |
11006 BPF_SIZE((insn)->code);
11007 env->prog->aux->num_exentries++;
11008 } else if (resolve_prog_type(env->prog) != BPF_PROG_TYPE_STRUCT_OPS) {
11009 verbose(env, "Writes through BTF pointers are not allowed\n");
11017 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
11018 size = BPF_LDST_BYTES(insn);
11020 /* If the read access is a narrower load of the field,
11021 * convert to a 4/8-byte load, to minimum program type specific
11022 * convert_ctx_access changes. If conversion is successful,
11023 * we will apply proper mask to the result.
11025 is_narrower_load = size < ctx_field_size;
11026 size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
11028 if (is_narrower_load) {
11031 if (type == BPF_WRITE) {
11032 verbose(env, "bpf verifier narrow ctx access misconfigured\n");
11037 if (ctx_field_size == 4)
11039 else if (ctx_field_size == 8)
11040 size_code = BPF_DW;
11042 insn->off = off & ~(size_default - 1);
11043 insn->code = BPF_LDX | BPF_MEM | size_code;
11047 cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
11049 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
11050 (ctx_field_size && !target_size)) {
11051 verbose(env, "bpf verifier is misconfigured\n");
11055 if (is_narrower_load && size < target_size) {
11056 u8 shift = bpf_ctx_narrow_access_offset(
11057 off, size, size_default) * 8;
11058 if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) {
11059 verbose(env, "bpf verifier narrow ctx load misconfigured\n");
11062 if (ctx_field_size <= 4) {
11064 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
11067 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
11068 (1 << size * 8) - 1);
11071 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
11074 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
11075 (1ULL << size * 8) - 1);
11079 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
11085 /* keep walking new program and skip insns we just inserted */
11086 env->prog = new_prog;
11087 insn = new_prog->insnsi + i + delta;
11093 static int jit_subprogs(struct bpf_verifier_env *env)
11095 struct bpf_prog *prog = env->prog, **func, *tmp;
11096 int i, j, subprog_start, subprog_end = 0, len, subprog;
11097 struct bpf_map *map_ptr;
11098 struct bpf_insn *insn;
11099 void *old_bpf_func;
11100 int err, num_exentries;
11102 if (env->subprog_cnt <= 1)
11105 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
11106 if (insn->code != (BPF_JMP | BPF_CALL) ||
11107 insn->src_reg != BPF_PSEUDO_CALL)
11109 /* Upon error here we cannot fall back to interpreter but
11110 * need a hard reject of the program. Thus -EFAULT is
11111 * propagated in any case.
11113 subprog = find_subprog(env, i + insn->imm + 1);
11115 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
11116 i + insn->imm + 1);
11119 /* temporarily remember subprog id inside insn instead of
11120 * aux_data, since next loop will split up all insns into funcs
11122 insn->off = subprog;
11123 /* remember original imm in case JIT fails and fallback
11124 * to interpreter will be needed
11126 env->insn_aux_data[i].call_imm = insn->imm;
11127 /* point imm to __bpf_call_base+1 from JITs point of view */
11131 err = bpf_prog_alloc_jited_linfo(prog);
11133 goto out_undo_insn;
11136 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
11138 goto out_undo_insn;
11140 for (i = 0; i < env->subprog_cnt; i++) {
11141 subprog_start = subprog_end;
11142 subprog_end = env->subprog_info[i + 1].start;
11144 len = subprog_end - subprog_start;
11145 /* BPF_PROG_RUN doesn't call subprogs directly,
11146 * hence main prog stats include the runtime of subprogs.
11147 * subprogs don't have IDs and not reachable via prog_get_next_id
11148 * func[i]->aux->stats will never be accessed and stays NULL
11150 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
11153 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
11154 len * sizeof(struct bpf_insn));
11155 func[i]->type = prog->type;
11156 func[i]->len = len;
11157 if (bpf_prog_calc_tag(func[i]))
11159 func[i]->is_func = 1;
11160 func[i]->aux->func_idx = i;
11161 /* Below members will be freed only at prog->aux */
11162 func[i]->aux->btf = prog->aux->btf;
11163 func[i]->aux->func_info = prog->aux->func_info;
11164 func[i]->aux->poke_tab = prog->aux->poke_tab;
11165 func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
11167 for (j = 0; j < prog->aux->size_poke_tab; j++) {
11168 struct bpf_jit_poke_descriptor *poke;
11170 poke = &prog->aux->poke_tab[j];
11171 if (poke->insn_idx < subprog_end &&
11172 poke->insn_idx >= subprog_start)
11173 poke->aux = func[i]->aux;
11176 /* Use bpf_prog_F_tag to indicate functions in stack traces.
11177 * Long term would need debug info to populate names
11179 func[i]->aux->name[0] = 'F';
11180 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
11181 func[i]->jit_requested = 1;
11182 func[i]->aux->linfo = prog->aux->linfo;
11183 func[i]->aux->nr_linfo = prog->aux->nr_linfo;
11184 func[i]->aux->jited_linfo = prog->aux->jited_linfo;
11185 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
11187 insn = func[i]->insnsi;
11188 for (j = 0; j < func[i]->len; j++, insn++) {
11189 if (BPF_CLASS(insn->code) == BPF_LDX &&
11190 BPF_MODE(insn->code) == BPF_PROBE_MEM)
11193 func[i]->aux->num_exentries = num_exentries;
11194 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
11195 func[i] = bpf_int_jit_compile(func[i]);
11196 if (!func[i]->jited) {
11203 /* at this point all bpf functions were successfully JITed
11204 * now populate all bpf_calls with correct addresses and
11205 * run last pass of JIT
11207 for (i = 0; i < env->subprog_cnt; i++) {
11208 insn = func[i]->insnsi;
11209 for (j = 0; j < func[i]->len; j++, insn++) {
11210 if (insn->code != (BPF_JMP | BPF_CALL) ||
11211 insn->src_reg != BPF_PSEUDO_CALL)
11213 subprog = insn->off;
11214 insn->imm = BPF_CAST_CALL(func[subprog]->bpf_func) -
11218 /* we use the aux data to keep a list of the start addresses
11219 * of the JITed images for each function in the program
11221 * for some architectures, such as powerpc64, the imm field
11222 * might not be large enough to hold the offset of the start
11223 * address of the callee's JITed image from __bpf_call_base
11225 * in such cases, we can lookup the start address of a callee
11226 * by using its subprog id, available from the off field of
11227 * the call instruction, as an index for this list
11229 func[i]->aux->func = func;
11230 func[i]->aux->func_cnt = env->subprog_cnt;
11232 for (i = 0; i < env->subprog_cnt; i++) {
11233 old_bpf_func = func[i]->bpf_func;
11234 tmp = bpf_int_jit_compile(func[i]);
11235 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
11236 verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
11243 /* finally lock prog and jit images for all functions and
11244 * populate kallsysm
11246 for (i = 0; i < env->subprog_cnt; i++) {
11247 bpf_prog_lock_ro(func[i]);
11248 bpf_prog_kallsyms_add(func[i]);
11251 /* Last step: make now unused interpreter insns from main
11252 * prog consistent for later dump requests, so they can
11253 * later look the same as if they were interpreted only.
11255 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
11256 if (insn->code != (BPF_JMP | BPF_CALL) ||
11257 insn->src_reg != BPF_PSEUDO_CALL)
11259 insn->off = env->insn_aux_data[i].call_imm;
11260 subprog = find_subprog(env, i + insn->off + 1);
11261 insn->imm = subprog;
11265 prog->bpf_func = func[0]->bpf_func;
11266 prog->aux->func = func;
11267 prog->aux->func_cnt = env->subprog_cnt;
11268 bpf_prog_free_unused_jited_linfo(prog);
11271 /* We failed JIT'ing, so at this point we need to unregister poke
11272 * descriptors from subprogs, so that kernel is not attempting to
11273 * patch it anymore as we're freeing the subprog JIT memory.
11275 for (i = 0; i < prog->aux->size_poke_tab; i++) {
11276 map_ptr = prog->aux->poke_tab[i].tail_call.map;
11277 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
11279 /* At this point we're guaranteed that poke descriptors are not
11280 * live anymore. We can just unlink its descriptor table as it's
11281 * released with the main prog.
11283 for (i = 0; i < env->subprog_cnt; i++) {
11286 func[i]->aux->poke_tab = NULL;
11287 bpf_jit_free(func[i]);
11291 /* cleanup main prog to be interpreted */
11292 prog->jit_requested = 0;
11293 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
11294 if (insn->code != (BPF_JMP | BPF_CALL) ||
11295 insn->src_reg != BPF_PSEUDO_CALL)
11298 insn->imm = env->insn_aux_data[i].call_imm;
11300 bpf_prog_free_jited_linfo(prog);
11304 static int fixup_call_args(struct bpf_verifier_env *env)
11306 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
11307 struct bpf_prog *prog = env->prog;
11308 struct bpf_insn *insn = prog->insnsi;
11313 if (env->prog->jit_requested &&
11314 !bpf_prog_is_dev_bound(env->prog->aux)) {
11315 err = jit_subprogs(env);
11318 if (err == -EFAULT)
11321 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
11322 if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
11323 /* When JIT fails the progs with bpf2bpf calls and tail_calls
11324 * have to be rejected, since interpreter doesn't support them yet.
11326 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
11329 for (i = 0; i < prog->len; i++, insn++) {
11330 if (insn->code != (BPF_JMP | BPF_CALL) ||
11331 insn->src_reg != BPF_PSEUDO_CALL)
11333 depth = get_callee_stack_depth(env, insn, i);
11336 bpf_patch_call_args(insn, depth);
11343 /* fixup insn->imm field of bpf_call instructions
11344 * and inline eligible helpers as explicit sequence of BPF instructions
11346 * this function is called after eBPF program passed verification
11348 static int fixup_bpf_calls(struct bpf_verifier_env *env)
11350 struct bpf_prog *prog = env->prog;
11351 bool expect_blinding = bpf_jit_blinding_enabled(prog);
11352 struct bpf_insn *insn = prog->insnsi;
11353 const struct bpf_func_proto *fn;
11354 const int insn_cnt = prog->len;
11355 const struct bpf_map_ops *ops;
11356 struct bpf_insn_aux_data *aux;
11357 struct bpf_insn insn_buf[16];
11358 struct bpf_prog *new_prog;
11359 struct bpf_map *map_ptr;
11360 int i, ret, cnt, delta = 0;
11362 for (i = 0; i < insn_cnt; i++, insn++) {
11363 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
11364 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
11365 insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
11366 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
11367 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
11368 bool isdiv = BPF_OP(insn->code) == BPF_DIV;
11369 struct bpf_insn *patchlet;
11370 struct bpf_insn chk_and_div[] = {
11371 /* [R,W]x div 0 -> 0 */
11372 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
11373 BPF_JNE | BPF_K, insn->src_reg,
11375 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
11376 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
11379 struct bpf_insn chk_and_mod[] = {
11380 /* [R,W]x mod 0 -> [R,W]x */
11381 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
11382 BPF_JEQ | BPF_K, insn->src_reg,
11383 0, 1 + (is64 ? 0 : 1), 0),
11385 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
11386 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
11389 patchlet = isdiv ? chk_and_div : chk_and_mod;
11390 cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
11391 ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
11393 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
11398 env->prog = prog = new_prog;
11399 insn = new_prog->insnsi + i + delta;
11403 if (BPF_CLASS(insn->code) == BPF_LD &&
11404 (BPF_MODE(insn->code) == BPF_ABS ||
11405 BPF_MODE(insn->code) == BPF_IND)) {
11406 cnt = env->ops->gen_ld_abs(insn, insn_buf);
11407 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
11408 verbose(env, "bpf verifier is misconfigured\n");
11412 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
11417 env->prog = prog = new_prog;
11418 insn = new_prog->insnsi + i + delta;
11422 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
11423 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
11424 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
11425 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
11426 struct bpf_insn insn_buf[16];
11427 struct bpf_insn *patch = &insn_buf[0];
11428 bool issrc, isneg, isimm;
11431 aux = &env->insn_aux_data[i + delta];
11432 if (!aux->alu_state ||
11433 aux->alu_state == BPF_ALU_NON_POINTER)
11436 isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
11437 issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
11438 BPF_ALU_SANITIZE_SRC;
11439 isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
11441 off_reg = issrc ? insn->src_reg : insn->dst_reg;
11443 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
11446 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
11447 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
11448 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
11449 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
11450 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
11451 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
11452 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
11455 *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
11456 insn->src_reg = BPF_REG_AX;
11458 insn->code = insn->code == code_add ?
11459 code_sub : code_add;
11461 if (issrc && isneg && !isimm)
11462 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
11463 cnt = patch - insn_buf;
11465 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
11470 env->prog = prog = new_prog;
11471 insn = new_prog->insnsi + i + delta;
11475 if (insn->code != (BPF_JMP | BPF_CALL))
11477 if (insn->src_reg == BPF_PSEUDO_CALL)
11480 if (insn->imm == BPF_FUNC_get_route_realm)
11481 prog->dst_needed = 1;
11482 if (insn->imm == BPF_FUNC_get_prandom_u32)
11483 bpf_user_rnd_init_once();
11484 if (insn->imm == BPF_FUNC_override_return)
11485 prog->kprobe_override = 1;
11486 if (insn->imm == BPF_FUNC_tail_call) {
11487 /* If we tail call into other programs, we
11488 * cannot make any assumptions since they can
11489 * be replaced dynamically during runtime in
11490 * the program array.
11492 prog->cb_access = 1;
11493 if (!allow_tail_call_in_subprogs(env))
11494 prog->aux->stack_depth = MAX_BPF_STACK;
11495 prog->aux->max_pkt_offset = MAX_PACKET_OFF;
11497 /* mark bpf_tail_call as different opcode to avoid
11498 * conditional branch in the interpeter for every normal
11499 * call and to prevent accidental JITing by JIT compiler
11500 * that doesn't support bpf_tail_call yet
11503 insn->code = BPF_JMP | BPF_TAIL_CALL;
11505 aux = &env->insn_aux_data[i + delta];
11506 if (env->bpf_capable && !expect_blinding &&
11507 prog->jit_requested &&
11508 !bpf_map_key_poisoned(aux) &&
11509 !bpf_map_ptr_poisoned(aux) &&
11510 !bpf_map_ptr_unpriv(aux)) {
11511 struct bpf_jit_poke_descriptor desc = {
11512 .reason = BPF_POKE_REASON_TAIL_CALL,
11513 .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
11514 .tail_call.key = bpf_map_key_immediate(aux),
11515 .insn_idx = i + delta,
11518 ret = bpf_jit_add_poke_descriptor(prog, &desc);
11520 verbose(env, "adding tail call poke descriptor failed\n");
11524 insn->imm = ret + 1;
11528 if (!bpf_map_ptr_unpriv(aux))
11531 /* instead of changing every JIT dealing with tail_call
11532 * emit two extra insns:
11533 * if (index >= max_entries) goto out;
11534 * index &= array->index_mask;
11535 * to avoid out-of-bounds cpu speculation
11537 if (bpf_map_ptr_poisoned(aux)) {
11538 verbose(env, "tail_call abusing map_ptr\n");
11542 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
11543 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
11544 map_ptr->max_entries, 2);
11545 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
11546 container_of(map_ptr,
11549 insn_buf[2] = *insn;
11551 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
11556 env->prog = prog = new_prog;
11557 insn = new_prog->insnsi + i + delta;
11561 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
11562 * and other inlining handlers are currently limited to 64 bit
11565 if (prog->jit_requested && BITS_PER_LONG == 64 &&
11566 (insn->imm == BPF_FUNC_map_lookup_elem ||
11567 insn->imm == BPF_FUNC_map_update_elem ||
11568 insn->imm == BPF_FUNC_map_delete_elem ||
11569 insn->imm == BPF_FUNC_map_push_elem ||
11570 insn->imm == BPF_FUNC_map_pop_elem ||
11571 insn->imm == BPF_FUNC_map_peek_elem)) {
11572 aux = &env->insn_aux_data[i + delta];
11573 if (bpf_map_ptr_poisoned(aux))
11574 goto patch_call_imm;
11576 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
11577 ops = map_ptr->ops;
11578 if (insn->imm == BPF_FUNC_map_lookup_elem &&
11579 ops->map_gen_lookup) {
11580 cnt = ops->map_gen_lookup(map_ptr, insn_buf);
11581 if (cnt == -EOPNOTSUPP)
11582 goto patch_map_ops_generic;
11583 if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
11584 verbose(env, "bpf verifier is misconfigured\n");
11588 new_prog = bpf_patch_insn_data(env, i + delta,
11594 env->prog = prog = new_prog;
11595 insn = new_prog->insnsi + i + delta;
11599 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
11600 (void *(*)(struct bpf_map *map, void *key))NULL));
11601 BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
11602 (int (*)(struct bpf_map *map, void *key))NULL));
11603 BUILD_BUG_ON(!__same_type(ops->map_update_elem,
11604 (int (*)(struct bpf_map *map, void *key, void *value,
11606 BUILD_BUG_ON(!__same_type(ops->map_push_elem,
11607 (int (*)(struct bpf_map *map, void *value,
11609 BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
11610 (int (*)(struct bpf_map *map, void *value))NULL));
11611 BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
11612 (int (*)(struct bpf_map *map, void *value))NULL));
11613 patch_map_ops_generic:
11614 switch (insn->imm) {
11615 case BPF_FUNC_map_lookup_elem:
11616 insn->imm = BPF_CAST_CALL(ops->map_lookup_elem) -
11619 case BPF_FUNC_map_update_elem:
11620 insn->imm = BPF_CAST_CALL(ops->map_update_elem) -
11623 case BPF_FUNC_map_delete_elem:
11624 insn->imm = BPF_CAST_CALL(ops->map_delete_elem) -
11627 case BPF_FUNC_map_push_elem:
11628 insn->imm = BPF_CAST_CALL(ops->map_push_elem) -
11631 case BPF_FUNC_map_pop_elem:
11632 insn->imm = BPF_CAST_CALL(ops->map_pop_elem) -
11635 case BPF_FUNC_map_peek_elem:
11636 insn->imm = BPF_CAST_CALL(ops->map_peek_elem) -
11641 goto patch_call_imm;
11644 if (prog->jit_requested && BITS_PER_LONG == 64 &&
11645 insn->imm == BPF_FUNC_jiffies64) {
11646 struct bpf_insn ld_jiffies_addr[2] = {
11647 BPF_LD_IMM64(BPF_REG_0,
11648 (unsigned long)&jiffies),
11651 insn_buf[0] = ld_jiffies_addr[0];
11652 insn_buf[1] = ld_jiffies_addr[1];
11653 insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
11657 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
11663 env->prog = prog = new_prog;
11664 insn = new_prog->insnsi + i + delta;
11669 fn = env->ops->get_func_proto(insn->imm, env->prog);
11670 /* all functions that have prototype and verifier allowed
11671 * programs to call them, must be real in-kernel functions
11675 "kernel subsystem misconfigured func %s#%d\n",
11676 func_id_name(insn->imm), insn->imm);
11679 insn->imm = fn->func - __bpf_call_base;
11682 /* Since poke tab is now finalized, publish aux to tracker. */
11683 for (i = 0; i < prog->aux->size_poke_tab; i++) {
11684 map_ptr = prog->aux->poke_tab[i].tail_call.map;
11685 if (!map_ptr->ops->map_poke_track ||
11686 !map_ptr->ops->map_poke_untrack ||
11687 !map_ptr->ops->map_poke_run) {
11688 verbose(env, "bpf verifier is misconfigured\n");
11692 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
11694 verbose(env, "tracking tail call prog failed\n");
11702 static void free_states(struct bpf_verifier_env *env)
11704 struct bpf_verifier_state_list *sl, *sln;
11707 sl = env->free_list;
11710 free_verifier_state(&sl->state, false);
11714 env->free_list = NULL;
11716 if (!env->explored_states)
11719 for (i = 0; i < state_htab_size(env); i++) {
11720 sl = env->explored_states[i];
11724 free_verifier_state(&sl->state, false);
11728 env->explored_states[i] = NULL;
11732 static int do_check_common(struct bpf_verifier_env *env, int subprog)
11734 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
11735 struct bpf_verifier_state *state;
11736 struct bpf_reg_state *regs;
11739 env->prev_linfo = NULL;
11742 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
11745 state->curframe = 0;
11746 state->speculative = false;
11747 state->branches = 1;
11748 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
11749 if (!state->frame[0]) {
11753 env->cur_state = state;
11754 init_func_state(env, state->frame[0],
11755 BPF_MAIN_FUNC /* callsite */,
11759 regs = state->frame[state->curframe]->regs;
11760 if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
11761 ret = btf_prepare_func_args(env, subprog, regs);
11764 for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
11765 if (regs[i].type == PTR_TO_CTX)
11766 mark_reg_known_zero(env, regs, i);
11767 else if (regs[i].type == SCALAR_VALUE)
11768 mark_reg_unknown(env, regs, i);
11771 /* 1st arg to a function */
11772 regs[BPF_REG_1].type = PTR_TO_CTX;
11773 mark_reg_known_zero(env, regs, BPF_REG_1);
11774 ret = btf_check_func_arg_match(env, subprog, regs);
11775 if (ret == -EFAULT)
11776 /* unlikely verifier bug. abort.
11777 * ret == 0 and ret < 0 are sadly acceptable for
11778 * main() function due to backward compatibility.
11779 * Like socket filter program may be written as:
11780 * int bpf_prog(struct pt_regs *ctx)
11781 * and never dereference that ctx in the program.
11782 * 'struct pt_regs' is a type mismatch for socket
11783 * filter that should be using 'struct __sk_buff'.
11788 ret = do_check(env);
11790 /* check for NULL is necessary, since cur_state can be freed inside
11791 * do_check() under memory pressure.
11793 if (env->cur_state) {
11794 free_verifier_state(env->cur_state, true);
11795 env->cur_state = NULL;
11797 while (!pop_stack(env, NULL, NULL, false));
11798 if (!ret && pop_log)
11799 bpf_vlog_reset(&env->log, 0);
11804 /* Verify all global functions in a BPF program one by one based on their BTF.
11805 * All global functions must pass verification. Otherwise the whole program is rejected.
11816 * foo() will be verified first for R1=any_scalar_value. During verification it
11817 * will be assumed that bar() already verified successfully and call to bar()
11818 * from foo() will be checked for type match only. Later bar() will be verified
11819 * independently to check that it's safe for R1=any_scalar_value.
11821 static int do_check_subprogs(struct bpf_verifier_env *env)
11823 struct bpf_prog_aux *aux = env->prog->aux;
11826 if (!aux->func_info)
11829 for (i = 1; i < env->subprog_cnt; i++) {
11830 if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
11832 env->insn_idx = env->subprog_info[i].start;
11833 WARN_ON_ONCE(env->insn_idx == 0);
11834 ret = do_check_common(env, i);
11837 } else if (env->log.level & BPF_LOG_LEVEL) {
11839 "Func#%d is safe for any args that match its prototype\n",
11846 static int do_check_main(struct bpf_verifier_env *env)
11851 ret = do_check_common(env, 0);
11853 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
11858 static void print_verification_stats(struct bpf_verifier_env *env)
11862 if (env->log.level & BPF_LOG_STATS) {
11863 verbose(env, "verification time %lld usec\n",
11864 div_u64(env->verification_time, 1000));
11865 verbose(env, "stack depth ");
11866 for (i = 0; i < env->subprog_cnt; i++) {
11867 u32 depth = env->subprog_info[i].stack_depth;
11869 verbose(env, "%d", depth);
11870 if (i + 1 < env->subprog_cnt)
11873 verbose(env, "\n");
11875 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
11876 "total_states %d peak_states %d mark_read %d\n",
11877 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
11878 env->max_states_per_insn, env->total_states,
11879 env->peak_states, env->longest_mark_read_walk);
11882 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
11884 const struct btf_type *t, *func_proto;
11885 const struct bpf_struct_ops *st_ops;
11886 const struct btf_member *member;
11887 struct bpf_prog *prog = env->prog;
11888 u32 btf_id, member_idx;
11891 if (!prog->gpl_compatible) {
11892 verbose(env, "struct ops programs must have a GPL compatible license\n");
11896 btf_id = prog->aux->attach_btf_id;
11897 st_ops = bpf_struct_ops_find(btf_id);
11899 verbose(env, "attach_btf_id %u is not a supported struct\n",
11905 member_idx = prog->expected_attach_type;
11906 if (member_idx >= btf_type_vlen(t)) {
11907 verbose(env, "attach to invalid member idx %u of struct %s\n",
11908 member_idx, st_ops->name);
11912 member = &btf_type_member(t)[member_idx];
11913 mname = btf_name_by_offset(btf_vmlinux, member->name_off);
11914 func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
11917 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
11918 mname, member_idx, st_ops->name);
11922 if (st_ops->check_member) {
11923 int err = st_ops->check_member(t, member);
11926 verbose(env, "attach to unsupported member %s of struct %s\n",
11927 mname, st_ops->name);
11932 prog->aux->attach_func_proto = func_proto;
11933 prog->aux->attach_func_name = mname;
11934 env->ops = st_ops->verifier_ops;
11938 #define SECURITY_PREFIX "security_"
11940 static int check_attach_modify_return(unsigned long addr, const char *func_name)
11942 if (within_error_injection_list(addr) ||
11943 !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
11949 /* non exhaustive list of sleepable bpf_lsm_*() functions */
11950 BTF_SET_START(btf_sleepable_lsm_hooks)
11951 #ifdef CONFIG_BPF_LSM
11952 BTF_ID(func, bpf_lsm_bprm_committed_creds)
11956 BTF_SET_END(btf_sleepable_lsm_hooks)
11958 static int check_sleepable_lsm_hook(u32 btf_id)
11960 return btf_id_set_contains(&btf_sleepable_lsm_hooks, btf_id);
11963 /* list of non-sleepable functions that are otherwise on
11964 * ALLOW_ERROR_INJECTION list
11966 BTF_SET_START(btf_non_sleepable_error_inject)
11967 /* Three functions below can be called from sleepable and non-sleepable context.
11968 * Assume non-sleepable from bpf safety point of view.
11970 BTF_ID(func, __add_to_page_cache_locked)
11971 BTF_ID(func, should_fail_alloc_page)
11972 BTF_ID(func, should_failslab)
11973 BTF_SET_END(btf_non_sleepable_error_inject)
11975 static int check_non_sleepable_error_inject(u32 btf_id)
11977 return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
11980 int bpf_check_attach_target(struct bpf_verifier_log *log,
11981 const struct bpf_prog *prog,
11982 const struct bpf_prog *tgt_prog,
11984 struct bpf_attach_target_info *tgt_info)
11986 bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
11987 const char prefix[] = "btf_trace_";
11988 int ret = 0, subprog = -1, i;
11989 const struct btf_type *t;
11990 bool conservative = true;
11996 bpf_log(log, "Tracing programs must provide btf_id\n");
11999 btf = tgt_prog ? tgt_prog->aux->btf : btf_vmlinux;
12002 "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
12005 t = btf_type_by_id(btf, btf_id);
12007 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
12010 tname = btf_name_by_offset(btf, t->name_off);
12012 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
12016 struct bpf_prog_aux *aux = tgt_prog->aux;
12018 for (i = 0; i < aux->func_info_cnt; i++)
12019 if (aux->func_info[i].type_id == btf_id) {
12023 if (subprog == -1) {
12024 bpf_log(log, "Subprog %s doesn't exist\n", tname);
12027 conservative = aux->func_info_aux[subprog].unreliable;
12028 if (prog_extension) {
12029 if (conservative) {
12031 "Cannot replace static functions\n");
12034 if (!prog->jit_requested) {
12036 "Extension programs should be JITed\n");
12040 if (!tgt_prog->jited) {
12041 bpf_log(log, "Can attach to only JITed progs\n");
12044 if (tgt_prog->type == prog->type) {
12045 /* Cannot fentry/fexit another fentry/fexit program.
12046 * Cannot attach program extension to another extension.
12047 * It's ok to attach fentry/fexit to extension program.
12049 bpf_log(log, "Cannot recursively attach\n");
12052 if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
12054 (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
12055 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
12056 /* Program extensions can extend all program types
12057 * except fentry/fexit. The reason is the following.
12058 * The fentry/fexit programs are used for performance
12059 * analysis, stats and can be attached to any program
12060 * type except themselves. When extension program is
12061 * replacing XDP function it is necessary to allow
12062 * performance analysis of all functions. Both original
12063 * XDP program and its program extension. Hence
12064 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
12065 * allowed. If extending of fentry/fexit was allowed it
12066 * would be possible to create long call chain
12067 * fentry->extension->fentry->extension beyond
12068 * reasonable stack size. Hence extending fentry is not
12071 bpf_log(log, "Cannot extend fentry/fexit\n");
12075 if (prog_extension) {
12076 bpf_log(log, "Cannot replace kernel functions\n");
12081 switch (prog->expected_attach_type) {
12082 case BPF_TRACE_RAW_TP:
12085 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
12088 if (!btf_type_is_typedef(t)) {
12089 bpf_log(log, "attach_btf_id %u is not a typedef\n",
12093 if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
12094 bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
12098 tname += sizeof(prefix) - 1;
12099 t = btf_type_by_id(btf, t->type);
12100 if (!btf_type_is_ptr(t))
12101 /* should never happen in valid vmlinux build */
12103 t = btf_type_by_id(btf, t->type);
12104 if (!btf_type_is_func_proto(t))
12105 /* should never happen in valid vmlinux build */
12109 case BPF_TRACE_ITER:
12110 if (!btf_type_is_func(t)) {
12111 bpf_log(log, "attach_btf_id %u is not a function\n",
12115 t = btf_type_by_id(btf, t->type);
12116 if (!btf_type_is_func_proto(t))
12118 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
12123 if (!prog_extension)
12126 case BPF_MODIFY_RETURN:
12128 case BPF_TRACE_FENTRY:
12129 case BPF_TRACE_FEXIT:
12130 if (!btf_type_is_func(t)) {
12131 bpf_log(log, "attach_btf_id %u is not a function\n",
12135 if (prog_extension &&
12136 btf_check_type_match(log, prog, btf, t))
12138 t = btf_type_by_id(btf, t->type);
12139 if (!btf_type_is_func_proto(t))
12142 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
12143 (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
12144 prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
12147 if (tgt_prog && conservative)
12150 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
12156 addr = (long) tgt_prog->bpf_func;
12158 addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
12160 addr = kallsyms_lookup_name(tname);
12163 "The address of function %s cannot be found\n",
12169 if (prog->aux->sleepable) {
12171 switch (prog->type) {
12172 case BPF_PROG_TYPE_TRACING:
12173 /* fentry/fexit/fmod_ret progs can be sleepable only if they are
12174 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
12176 if (!check_non_sleepable_error_inject(btf_id) &&
12177 within_error_injection_list(addr))
12180 case BPF_PROG_TYPE_LSM:
12181 /* LSM progs check that they are attached to bpf_lsm_*() funcs.
12182 * Only some of them are sleepable.
12184 if (check_sleepable_lsm_hook(btf_id))
12191 bpf_log(log, "%s is not sleepable\n", tname);
12194 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
12196 bpf_log(log, "can't modify return codes of BPF programs\n");
12199 ret = check_attach_modify_return(addr, tname);
12201 bpf_log(log, "%s() is not modifiable\n", tname);
12208 tgt_info->tgt_addr = addr;
12209 tgt_info->tgt_name = tname;
12210 tgt_info->tgt_type = t;
12214 static int check_attach_btf_id(struct bpf_verifier_env *env)
12216 struct bpf_prog *prog = env->prog;
12217 struct bpf_prog *tgt_prog = prog->aux->dst_prog;
12218 struct bpf_attach_target_info tgt_info = {};
12219 u32 btf_id = prog->aux->attach_btf_id;
12220 struct bpf_trampoline *tr;
12224 if (prog->aux->sleepable && prog->type != BPF_PROG_TYPE_TRACING &&
12225 prog->type != BPF_PROG_TYPE_LSM) {
12226 verbose(env, "Only fentry/fexit/fmod_ret and lsm programs can be sleepable\n");
12230 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
12231 return check_struct_ops_btf_id(env);
12233 if (prog->type != BPF_PROG_TYPE_TRACING &&
12234 prog->type != BPF_PROG_TYPE_LSM &&
12235 prog->type != BPF_PROG_TYPE_EXT)
12238 ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
12242 if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
12243 /* to make freplace equivalent to their targets, they need to
12244 * inherit env->ops and expected_attach_type for the rest of the
12247 env->ops = bpf_verifier_ops[tgt_prog->type];
12248 prog->expected_attach_type = tgt_prog->expected_attach_type;
12251 /* store info about the attachment target that will be used later */
12252 prog->aux->attach_func_proto = tgt_info.tgt_type;
12253 prog->aux->attach_func_name = tgt_info.tgt_name;
12256 prog->aux->saved_dst_prog_type = tgt_prog->type;
12257 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
12260 if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
12261 prog->aux->attach_btf_trace = true;
12263 } else if (prog->expected_attach_type == BPF_TRACE_ITER) {
12264 if (!bpf_iter_prog_supported(prog))
12269 if (prog->type == BPF_PROG_TYPE_LSM) {
12270 ret = bpf_lsm_verify_prog(&env->log, prog);
12275 key = bpf_trampoline_compute_key(tgt_prog, btf_id);
12276 tr = bpf_trampoline_get(key, &tgt_info);
12280 prog->aux->dst_trampoline = tr;
12284 struct btf *bpf_get_btf_vmlinux(void)
12286 if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
12287 mutex_lock(&bpf_verifier_lock);
12289 btf_vmlinux = btf_parse_vmlinux();
12290 mutex_unlock(&bpf_verifier_lock);
12292 return btf_vmlinux;
12295 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr,
12296 union bpf_attr __user *uattr)
12298 u64 start_time = ktime_get_ns();
12299 struct bpf_verifier_env *env;
12300 struct bpf_verifier_log *log;
12301 int i, len, ret = -EINVAL;
12304 /* no program is valid */
12305 if (ARRAY_SIZE(bpf_verifier_ops) == 0)
12308 /* 'struct bpf_verifier_env' can be global, but since it's not small,
12309 * allocate/free it every time bpf_check() is called
12311 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
12316 len = (*prog)->len;
12317 env->insn_aux_data =
12318 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
12320 if (!env->insn_aux_data)
12322 for (i = 0; i < len; i++)
12323 env->insn_aux_data[i].orig_idx = i;
12325 env->ops = bpf_verifier_ops[env->prog->type];
12326 is_priv = bpf_capable();
12328 bpf_get_btf_vmlinux();
12330 /* grab the mutex to protect few globals used by verifier */
12332 mutex_lock(&bpf_verifier_lock);
12334 if (attr->log_level || attr->log_buf || attr->log_size) {
12335 /* user requested verbose verifier output
12336 * and supplied buffer to store the verification trace
12338 log->level = attr->log_level;
12339 log->ubuf = (char __user *) (unsigned long) attr->log_buf;
12340 log->len_total = attr->log_size;
12343 /* log attributes have to be sane */
12344 if (log->len_total < 128 || log->len_total > UINT_MAX >> 2 ||
12345 !log->level || !log->ubuf || log->level & ~BPF_LOG_MASK)
12349 if (IS_ERR(btf_vmlinux)) {
12350 /* Either gcc or pahole or kernel are broken. */
12351 verbose(env, "in-kernel BTF is malformed\n");
12352 ret = PTR_ERR(btf_vmlinux);
12353 goto skip_full_check;
12356 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
12357 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
12358 env->strict_alignment = true;
12359 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
12360 env->strict_alignment = false;
12362 env->allow_ptr_leaks = bpf_allow_ptr_leaks();
12363 env->allow_uninit_stack = bpf_allow_uninit_stack();
12364 env->allow_ptr_to_map_access = bpf_allow_ptr_to_map_access();
12365 env->bypass_spec_v1 = bpf_bypass_spec_v1();
12366 env->bypass_spec_v4 = bpf_bypass_spec_v4();
12367 env->bpf_capable = bpf_capable();
12370 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
12372 env->explored_states = kvcalloc(state_htab_size(env),
12373 sizeof(struct bpf_verifier_state_list *),
12376 if (!env->explored_states)
12377 goto skip_full_check;
12379 ret = check_subprogs(env);
12381 goto skip_full_check;
12383 ret = check_btf_info(env, attr, uattr);
12385 goto skip_full_check;
12387 ret = check_attach_btf_id(env);
12389 goto skip_full_check;
12391 ret = resolve_pseudo_ldimm64(env);
12393 goto skip_full_check;
12395 if (bpf_prog_is_dev_bound(env->prog->aux)) {
12396 ret = bpf_prog_offload_verifier_prep(env->prog);
12398 goto skip_full_check;
12401 ret = check_cfg(env);
12403 goto skip_full_check;
12405 ret = do_check_subprogs(env);
12406 ret = ret ?: do_check_main(env);
12408 if (ret == 0 && bpf_prog_is_dev_bound(env->prog->aux))
12409 ret = bpf_prog_offload_finalize(env);
12412 kvfree(env->explored_states);
12415 ret = check_max_stack_depth(env);
12417 /* instruction rewrites happen after this point */
12420 opt_hard_wire_dead_code_branches(env);
12422 ret = opt_remove_dead_code(env);
12424 ret = opt_remove_nops(env);
12427 sanitize_dead_code(env);
12431 /* program is valid, convert *(u32*)(ctx + off) accesses */
12432 ret = convert_ctx_accesses(env);
12435 ret = fixup_bpf_calls(env);
12437 /* do 32-bit optimization after insn patching has done so those patched
12438 * insns could be handled correctly.
12440 if (ret == 0 && !bpf_prog_is_dev_bound(env->prog->aux)) {
12441 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
12442 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
12447 ret = fixup_call_args(env);
12449 env->verification_time = ktime_get_ns() - start_time;
12450 print_verification_stats(env);
12452 if (log->level && bpf_verifier_log_full(log))
12454 if (log->level && !log->ubuf) {
12456 goto err_release_maps;
12459 if (ret == 0 && env->used_map_cnt) {
12460 /* if program passed verifier, update used_maps in bpf_prog_info */
12461 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
12462 sizeof(env->used_maps[0]),
12465 if (!env->prog->aux->used_maps) {
12467 goto err_release_maps;
12470 memcpy(env->prog->aux->used_maps, env->used_maps,
12471 sizeof(env->used_maps[0]) * env->used_map_cnt);
12472 env->prog->aux->used_map_cnt = env->used_map_cnt;
12474 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
12475 * bpf_ld_imm64 instructions
12477 convert_pseudo_ld_imm64(env);
12481 adjust_btf_func(env);
12484 if (!env->prog->aux->used_maps)
12485 /* if we didn't copy map pointers into bpf_prog_info, release
12486 * them now. Otherwise free_used_maps() will release them.
12490 /* extension progs temporarily inherit the attach_type of their targets
12491 for verification purposes, so set it back to zero before returning
12493 if (env->prog->type == BPF_PROG_TYPE_EXT)
12494 env->prog->expected_attach_type = 0;
12499 mutex_unlock(&bpf_verifier_lock);
12500 vfree(env->insn_aux_data);