1 /* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com
2 * Copyright (c) 2016 Facebook
3 * Copyright (c) 2018 Covalent IO, Inc. http://covalent.io
5 * This program is free software; you can redistribute it and/or
6 * modify it under the terms of version 2 of the GNU General Public
7 * License as published by the Free Software Foundation.
9 * This program is distributed in the hope that it will be useful, but
10 * WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * General Public License for more details.
14 #include <uapi/linux/btf.h>
15 #include <linux/kernel.h>
16 #include <linux/types.h>
17 #include <linux/slab.h>
18 #include <linux/bpf.h>
19 #include <linux/btf.h>
20 #include <linux/bpf_verifier.h>
21 #include <linux/filter.h>
22 #include <net/netlink.h>
23 #include <linux/file.h>
24 #include <linux/vmalloc.h>
25 #include <linux/stringify.h>
26 #include <linux/bsearch.h>
27 #include <linux/sort.h>
28 #include <linux/perf_event.h>
29 #include <linux/ctype.h>
33 static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
34 #define BPF_PROG_TYPE(_id, _name) \
35 [_id] = & _name ## _verifier_ops,
36 #define BPF_MAP_TYPE(_id, _ops)
37 #include <linux/bpf_types.h>
42 /* bpf_check() is a static code analyzer that walks eBPF program
43 * instruction by instruction and updates register/stack state.
44 * All paths of conditional branches are analyzed until 'bpf_exit' insn.
46 * The first pass is depth-first-search to check that the program is a DAG.
47 * It rejects the following programs:
48 * - larger than BPF_MAXINSNS insns
49 * - if loop is present (detected via back-edge)
50 * - unreachable insns exist (shouldn't be a forest. program = one function)
51 * - out of bounds or malformed jumps
52 * The second pass is all possible path descent from the 1st insn.
53 * Since it's analyzing all pathes through the program, the length of the
54 * analysis is limited to 64k insn, which may be hit even if total number of
55 * insn is less then 4K, but there are too many branches that change stack/regs.
56 * Number of 'branches to be analyzed' is limited to 1k
58 * On entry to each instruction, each register has a type, and the instruction
59 * changes the types of the registers depending on instruction semantics.
60 * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
63 * All registers are 64-bit.
64 * R0 - return register
65 * R1-R5 argument passing registers
66 * R6-R9 callee saved registers
67 * R10 - frame pointer read-only
69 * At the start of BPF program the register R1 contains a pointer to bpf_context
70 * and has type PTR_TO_CTX.
72 * Verifier tracks arithmetic operations on pointers in case:
73 * BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
74 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
75 * 1st insn copies R10 (which has FRAME_PTR) type into R1
76 * and 2nd arithmetic instruction is pattern matched to recognize
77 * that it wants to construct a pointer to some element within stack.
78 * So after 2nd insn, the register R1 has type PTR_TO_STACK
79 * (and -20 constant is saved for further stack bounds checking).
80 * Meaning that this reg is a pointer to stack plus known immediate constant.
82 * Most of the time the registers have SCALAR_VALUE type, which
83 * means the register has some value, but it's not a valid pointer.
84 * (like pointer plus pointer becomes SCALAR_VALUE type)
86 * When verifier sees load or store instructions the type of base register
87 * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are
88 * four pointer types recognized by check_mem_access() function.
90 * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
91 * and the range of [ptr, ptr + map's value_size) is accessible.
93 * registers used to pass values to function calls are checked against
94 * function argument constraints.
96 * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
97 * It means that the register type passed to this function must be
98 * PTR_TO_STACK and it will be used inside the function as
99 * 'pointer to map element key'
101 * For example the argument constraints for bpf_map_lookup_elem():
102 * .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
103 * .arg1_type = ARG_CONST_MAP_PTR,
104 * .arg2_type = ARG_PTR_TO_MAP_KEY,
106 * ret_type says that this function returns 'pointer to map elem value or null'
107 * function expects 1st argument to be a const pointer to 'struct bpf_map' and
108 * 2nd argument should be a pointer to stack, which will be used inside
109 * the helper function as a pointer to map element key.
111 * On the kernel side the helper function looks like:
112 * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
114 * struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
115 * void *key = (void *) (unsigned long) r2;
118 * here kernel can access 'key' and 'map' pointers safely, knowing that
119 * [key, key + map->key_size) bytes are valid and were initialized on
120 * the stack of eBPF program.
123 * Corresponding eBPF program may look like:
124 * BPF_MOV64_REG(BPF_REG_2, BPF_REG_10), // after this insn R2 type is FRAME_PTR
125 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
126 * BPF_LD_MAP_FD(BPF_REG_1, map_fd), // after this insn R1 type is CONST_PTR_TO_MAP
127 * BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
128 * here verifier looks at prototype of map_lookup_elem() and sees:
129 * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
130 * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
132 * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
133 * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
134 * and were initialized prior to this call.
135 * If it's ok, then verifier allows this BPF_CALL insn and looks at
136 * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
137 * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
138 * returns ether pointer to map value or NULL.
140 * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
141 * insn, the register holding that pointer in the true branch changes state to
142 * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
143 * branch. See check_cond_jmp_op().
145 * After the call R0 is set to return type of the function and registers R1-R5
146 * are set to NOT_INIT to indicate that they are no longer readable.
148 * The following reference types represent a potential reference to a kernel
149 * resource which, after first being allocated, must be checked and freed by
151 * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET
153 * When the verifier sees a helper call return a reference type, it allocates a
154 * pointer id for the reference and stores it in the current function state.
155 * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into
156 * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type
157 * passes through a NULL-check conditional. For the branch wherein the state is
158 * changed to CONST_IMM, the verifier releases the reference.
160 * For each helper function that allocates a reference, such as
161 * bpf_sk_lookup_tcp(), there is a corresponding release function, such as
162 * bpf_sk_release(). When a reference type passes into the release function,
163 * the verifier also releases the reference. If any unchecked or unreleased
164 * reference remains at the end of the program, the verifier rejects it.
167 /* verifier_state + insn_idx are pushed to stack when branch is encountered */
168 struct bpf_verifier_stack_elem {
169 /* verifer state is 'st'
170 * before processing instruction 'insn_idx'
171 * and after processing instruction 'prev_insn_idx'
173 struct bpf_verifier_state st;
176 struct bpf_verifier_stack_elem *next;
179 #define BPF_COMPLEXITY_LIMIT_JMP_SEQ 8192
180 #define BPF_COMPLEXITY_LIMIT_STATES 64
182 #define BPF_MAP_PTR_UNPRIV 1UL
183 #define BPF_MAP_PTR_POISON ((void *)((0xeB9FUL << 1) + \
184 POISON_POINTER_DELTA))
185 #define BPF_MAP_PTR(X) ((struct bpf_map *)((X) & ~BPF_MAP_PTR_UNPRIV))
187 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux)
189 return BPF_MAP_PTR(aux->map_state) == BPF_MAP_PTR_POISON;
192 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux)
194 return aux->map_state & BPF_MAP_PTR_UNPRIV;
197 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
198 const struct bpf_map *map, bool unpriv)
200 BUILD_BUG_ON((unsigned long)BPF_MAP_PTR_POISON & BPF_MAP_PTR_UNPRIV);
201 unpriv |= bpf_map_ptr_unpriv(aux);
202 aux->map_state = (unsigned long)map |
203 (unpriv ? BPF_MAP_PTR_UNPRIV : 0UL);
206 struct bpf_call_arg_meta {
207 struct bpf_map *map_ptr;
212 s64 msize_smax_value;
213 u64 msize_umax_value;
218 static DEFINE_MUTEX(bpf_verifier_lock);
220 static const struct bpf_line_info *
221 find_linfo(const struct bpf_verifier_env *env, u32 insn_off)
223 const struct bpf_line_info *linfo;
224 const struct bpf_prog *prog;
228 nr_linfo = prog->aux->nr_linfo;
230 if (!nr_linfo || insn_off >= prog->len)
233 linfo = prog->aux->linfo;
234 for (i = 1; i < nr_linfo; i++)
235 if (insn_off < linfo[i].insn_off)
238 return &linfo[i - 1];
241 void bpf_verifier_vlog(struct bpf_verifier_log *log, const char *fmt,
246 n = vscnprintf(log->kbuf, BPF_VERIFIER_TMP_LOG_SIZE, fmt, args);
248 WARN_ONCE(n >= BPF_VERIFIER_TMP_LOG_SIZE - 1,
249 "verifier log line truncated - local buffer too short\n");
251 n = min(log->len_total - log->len_used - 1, n);
254 if (!copy_to_user(log->ubuf + log->len_used, log->kbuf, n + 1))
260 /* log_level controls verbosity level of eBPF verifier.
261 * bpf_verifier_log_write() is used to dump the verification trace to the log,
262 * so the user can figure out what's wrong with the program
264 __printf(2, 3) void bpf_verifier_log_write(struct bpf_verifier_env *env,
265 const char *fmt, ...)
269 if (!bpf_verifier_log_needed(&env->log))
273 bpf_verifier_vlog(&env->log, fmt, args);
276 EXPORT_SYMBOL_GPL(bpf_verifier_log_write);
278 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
280 struct bpf_verifier_env *env = private_data;
283 if (!bpf_verifier_log_needed(&env->log))
287 bpf_verifier_vlog(&env->log, fmt, args);
291 static const char *ltrim(const char *s)
299 __printf(3, 4) static void verbose_linfo(struct bpf_verifier_env *env,
301 const char *prefix_fmt, ...)
303 const struct bpf_line_info *linfo;
305 if (!bpf_verifier_log_needed(&env->log))
308 linfo = find_linfo(env, insn_off);
309 if (!linfo || linfo == env->prev_linfo)
315 va_start(args, prefix_fmt);
316 bpf_verifier_vlog(&env->log, prefix_fmt, args);
321 ltrim(btf_name_by_offset(env->prog->aux->btf,
324 env->prev_linfo = linfo;
327 static bool type_is_pkt_pointer(enum bpf_reg_type type)
329 return type == PTR_TO_PACKET ||
330 type == PTR_TO_PACKET_META;
333 static bool type_is_sk_pointer(enum bpf_reg_type type)
335 return type == PTR_TO_SOCKET ||
336 type == PTR_TO_SOCK_COMMON ||
337 type == PTR_TO_TCP_SOCK ||
338 type == PTR_TO_XDP_SOCK;
341 static bool reg_type_may_be_null(enum bpf_reg_type type)
343 return type == PTR_TO_MAP_VALUE_OR_NULL ||
344 type == PTR_TO_SOCKET_OR_NULL ||
345 type == PTR_TO_SOCK_COMMON_OR_NULL ||
346 type == PTR_TO_TCP_SOCK_OR_NULL;
349 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
351 return reg->type == PTR_TO_MAP_VALUE &&
352 map_value_has_spin_lock(reg->map_ptr);
355 static bool reg_type_may_be_refcounted_or_null(enum bpf_reg_type type)
357 return type == PTR_TO_SOCKET ||
358 type == PTR_TO_SOCKET_OR_NULL ||
359 type == PTR_TO_TCP_SOCK ||
360 type == PTR_TO_TCP_SOCK_OR_NULL;
363 static bool arg_type_may_be_refcounted(enum bpf_arg_type type)
365 return type == ARG_PTR_TO_SOCK_COMMON;
368 /* Determine whether the function releases some resources allocated by another
369 * function call. The first reference type argument will be assumed to be
370 * released by release_reference().
372 static bool is_release_function(enum bpf_func_id func_id)
374 return func_id == BPF_FUNC_sk_release;
377 static bool is_acquire_function(enum bpf_func_id func_id)
379 return func_id == BPF_FUNC_sk_lookup_tcp ||
380 func_id == BPF_FUNC_sk_lookup_udp ||
381 func_id == BPF_FUNC_skc_lookup_tcp;
384 static bool is_ptr_cast_function(enum bpf_func_id func_id)
386 return func_id == BPF_FUNC_tcp_sock ||
387 func_id == BPF_FUNC_sk_fullsock;
390 /* string representation of 'enum bpf_reg_type' */
391 static const char * const reg_type_str[] = {
393 [SCALAR_VALUE] = "inv",
394 [PTR_TO_CTX] = "ctx",
395 [CONST_PTR_TO_MAP] = "map_ptr",
396 [PTR_TO_MAP_VALUE] = "map_value",
397 [PTR_TO_MAP_VALUE_OR_NULL] = "map_value_or_null",
398 [PTR_TO_STACK] = "fp",
399 [PTR_TO_PACKET] = "pkt",
400 [PTR_TO_PACKET_META] = "pkt_meta",
401 [PTR_TO_PACKET_END] = "pkt_end",
402 [PTR_TO_FLOW_KEYS] = "flow_keys",
403 [PTR_TO_SOCKET] = "sock",
404 [PTR_TO_SOCKET_OR_NULL] = "sock_or_null",
405 [PTR_TO_SOCK_COMMON] = "sock_common",
406 [PTR_TO_SOCK_COMMON_OR_NULL] = "sock_common_or_null",
407 [PTR_TO_TCP_SOCK] = "tcp_sock",
408 [PTR_TO_TCP_SOCK_OR_NULL] = "tcp_sock_or_null",
409 [PTR_TO_TP_BUFFER] = "tp_buffer",
410 [PTR_TO_XDP_SOCK] = "xdp_sock",
413 static char slot_type_char[] = {
414 [STACK_INVALID] = '?',
420 static void print_liveness(struct bpf_verifier_env *env,
421 enum bpf_reg_liveness live)
423 if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE))
425 if (live & REG_LIVE_READ)
427 if (live & REG_LIVE_WRITTEN)
429 if (live & REG_LIVE_DONE)
433 static struct bpf_func_state *func(struct bpf_verifier_env *env,
434 const struct bpf_reg_state *reg)
436 struct bpf_verifier_state *cur = env->cur_state;
438 return cur->frame[reg->frameno];
441 static void print_verifier_state(struct bpf_verifier_env *env,
442 const struct bpf_func_state *state)
444 const struct bpf_reg_state *reg;
449 verbose(env, " frame%d:", state->frameno);
450 for (i = 0; i < MAX_BPF_REG; i++) {
451 reg = &state->regs[i];
455 verbose(env, " R%d", i);
456 print_liveness(env, reg->live);
457 verbose(env, "=%s", reg_type_str[t]);
458 if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
459 tnum_is_const(reg->var_off)) {
460 /* reg->off should be 0 for SCALAR_VALUE */
461 verbose(env, "%lld", reg->var_off.value + reg->off);
462 if (t == PTR_TO_STACK)
463 verbose(env, ",call_%d", func(env, reg)->callsite);
465 verbose(env, "(id=%d", reg->id);
466 if (reg_type_may_be_refcounted_or_null(t))
467 verbose(env, ",ref_obj_id=%d", reg->ref_obj_id);
468 if (t != SCALAR_VALUE)
469 verbose(env, ",off=%d", reg->off);
470 if (type_is_pkt_pointer(t))
471 verbose(env, ",r=%d", reg->range);
472 else if (t == CONST_PTR_TO_MAP ||
473 t == PTR_TO_MAP_VALUE ||
474 t == PTR_TO_MAP_VALUE_OR_NULL)
475 verbose(env, ",ks=%d,vs=%d",
476 reg->map_ptr->key_size,
477 reg->map_ptr->value_size);
478 if (tnum_is_const(reg->var_off)) {
479 /* Typically an immediate SCALAR_VALUE, but
480 * could be a pointer whose offset is too big
483 verbose(env, ",imm=%llx", reg->var_off.value);
485 if (reg->smin_value != reg->umin_value &&
486 reg->smin_value != S64_MIN)
487 verbose(env, ",smin_value=%lld",
488 (long long)reg->smin_value);
489 if (reg->smax_value != reg->umax_value &&
490 reg->smax_value != S64_MAX)
491 verbose(env, ",smax_value=%lld",
492 (long long)reg->smax_value);
493 if (reg->umin_value != 0)
494 verbose(env, ",umin_value=%llu",
495 (unsigned long long)reg->umin_value);
496 if (reg->umax_value != U64_MAX)
497 verbose(env, ",umax_value=%llu",
498 (unsigned long long)reg->umax_value);
499 if (!tnum_is_unknown(reg->var_off)) {
502 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
503 verbose(env, ",var_off=%s", tn_buf);
509 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
510 char types_buf[BPF_REG_SIZE + 1];
514 for (j = 0; j < BPF_REG_SIZE; j++) {
515 if (state->stack[i].slot_type[j] != STACK_INVALID)
517 types_buf[j] = slot_type_char[
518 state->stack[i].slot_type[j]];
520 types_buf[BPF_REG_SIZE] = 0;
523 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
524 print_liveness(env, state->stack[i].spilled_ptr.live);
525 if (state->stack[i].slot_type[0] == STACK_SPILL)
527 reg_type_str[state->stack[i].spilled_ptr.type]);
529 verbose(env, "=%s", types_buf);
531 if (state->acquired_refs && state->refs[0].id) {
532 verbose(env, " refs=%d", state->refs[0].id);
533 for (i = 1; i < state->acquired_refs; i++)
534 if (state->refs[i].id)
535 verbose(env, ",%d", state->refs[i].id);
540 #define COPY_STATE_FN(NAME, COUNT, FIELD, SIZE) \
541 static int copy_##NAME##_state(struct bpf_func_state *dst, \
542 const struct bpf_func_state *src) \
546 if (WARN_ON_ONCE(dst->COUNT < src->COUNT)) { \
547 /* internal bug, make state invalid to reject the program */ \
548 memset(dst, 0, sizeof(*dst)); \
551 memcpy(dst->FIELD, src->FIELD, \
552 sizeof(*src->FIELD) * (src->COUNT / SIZE)); \
555 /* copy_reference_state() */
556 COPY_STATE_FN(reference, acquired_refs, refs, 1)
557 /* copy_stack_state() */
558 COPY_STATE_FN(stack, allocated_stack, stack, BPF_REG_SIZE)
561 #define REALLOC_STATE_FN(NAME, COUNT, FIELD, SIZE) \
562 static int realloc_##NAME##_state(struct bpf_func_state *state, int size, \
565 u32 old_size = state->COUNT; \
566 struct bpf_##NAME##_state *new_##FIELD; \
567 int slot = size / SIZE; \
569 if (size <= old_size || !size) { \
572 state->COUNT = slot * SIZE; \
573 if (!size && old_size) { \
574 kfree(state->FIELD); \
575 state->FIELD = NULL; \
579 new_##FIELD = kmalloc_array(slot, sizeof(struct bpf_##NAME##_state), \
585 memcpy(new_##FIELD, state->FIELD, \
586 sizeof(*new_##FIELD) * (old_size / SIZE)); \
587 memset(new_##FIELD + old_size / SIZE, 0, \
588 sizeof(*new_##FIELD) * (size - old_size) / SIZE); \
590 state->COUNT = slot * SIZE; \
591 kfree(state->FIELD); \
592 state->FIELD = new_##FIELD; \
595 /* realloc_reference_state() */
596 REALLOC_STATE_FN(reference, acquired_refs, refs, 1)
597 /* realloc_stack_state() */
598 REALLOC_STATE_FN(stack, allocated_stack, stack, BPF_REG_SIZE)
599 #undef REALLOC_STATE_FN
601 /* do_check() starts with zero-sized stack in struct bpf_verifier_state to
602 * make it consume minimal amount of memory. check_stack_write() access from
603 * the program calls into realloc_func_state() to grow the stack size.
604 * Note there is a non-zero 'parent' pointer inside bpf_verifier_state
605 * which realloc_stack_state() copies over. It points to previous
606 * bpf_verifier_state which is never reallocated.
608 static int realloc_func_state(struct bpf_func_state *state, int stack_size,
609 int refs_size, bool copy_old)
611 int err = realloc_reference_state(state, refs_size, copy_old);
614 return realloc_stack_state(state, stack_size, copy_old);
617 /* Acquire a pointer id from the env and update the state->refs to include
618 * this new pointer reference.
619 * On success, returns a valid pointer id to associate with the register
620 * On failure, returns a negative errno.
622 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
624 struct bpf_func_state *state = cur_func(env);
625 int new_ofs = state->acquired_refs;
628 err = realloc_reference_state(state, state->acquired_refs + 1, true);
632 state->refs[new_ofs].id = id;
633 state->refs[new_ofs].insn_idx = insn_idx;
638 /* release function corresponding to acquire_reference_state(). Idempotent. */
639 static int release_reference_state(struct bpf_func_state *state, int ptr_id)
643 last_idx = state->acquired_refs - 1;
644 for (i = 0; i < state->acquired_refs; i++) {
645 if (state->refs[i].id == ptr_id) {
646 if (last_idx && i != last_idx)
647 memcpy(&state->refs[i], &state->refs[last_idx],
648 sizeof(*state->refs));
649 memset(&state->refs[last_idx], 0, sizeof(*state->refs));
650 state->acquired_refs--;
657 static int transfer_reference_state(struct bpf_func_state *dst,
658 struct bpf_func_state *src)
660 int err = realloc_reference_state(dst, src->acquired_refs, false);
663 err = copy_reference_state(dst, src);
669 static void free_func_state(struct bpf_func_state *state)
678 static void free_verifier_state(struct bpf_verifier_state *state,
683 for (i = 0; i <= state->curframe; i++) {
684 free_func_state(state->frame[i]);
685 state->frame[i] = NULL;
691 /* copy verifier state from src to dst growing dst stack space
692 * when necessary to accommodate larger src stack
694 static int copy_func_state(struct bpf_func_state *dst,
695 const struct bpf_func_state *src)
699 err = realloc_func_state(dst, src->allocated_stack, src->acquired_refs,
703 memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
704 err = copy_reference_state(dst, src);
707 return copy_stack_state(dst, src);
710 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
711 const struct bpf_verifier_state *src)
713 struct bpf_func_state *dst;
716 /* if dst has more stack frames then src frame, free them */
717 for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
718 free_func_state(dst_state->frame[i]);
719 dst_state->frame[i] = NULL;
721 dst_state->speculative = src->speculative;
722 dst_state->curframe = src->curframe;
723 dst_state->active_spin_lock = src->active_spin_lock;
724 for (i = 0; i <= src->curframe; i++) {
725 dst = dst_state->frame[i];
727 dst = kzalloc(sizeof(*dst), GFP_KERNEL);
730 dst_state->frame[i] = dst;
732 err = copy_func_state(dst, src->frame[i]);
739 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
742 struct bpf_verifier_state *cur = env->cur_state;
743 struct bpf_verifier_stack_elem *elem, *head = env->head;
746 if (env->head == NULL)
750 err = copy_verifier_state(cur, &head->st);
755 *insn_idx = head->insn_idx;
757 *prev_insn_idx = head->prev_insn_idx;
759 free_verifier_state(&head->st, false);
766 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
767 int insn_idx, int prev_insn_idx,
770 struct bpf_verifier_state *cur = env->cur_state;
771 struct bpf_verifier_stack_elem *elem;
774 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
778 elem->insn_idx = insn_idx;
779 elem->prev_insn_idx = prev_insn_idx;
780 elem->next = env->head;
783 err = copy_verifier_state(&elem->st, cur);
786 elem->st.speculative |= speculative;
787 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
788 verbose(env, "The sequence of %d jumps is too complex.\n",
794 free_verifier_state(env->cur_state, true);
795 env->cur_state = NULL;
796 /* pop all elements and return */
797 while (!pop_stack(env, NULL, NULL));
801 #define CALLER_SAVED_REGS 6
802 static const int caller_saved[CALLER_SAVED_REGS] = {
803 BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
806 static void __mark_reg_not_init(struct bpf_reg_state *reg);
808 /* Mark the unknown part of a register (variable offset or scalar value) as
809 * known to have the value @imm.
811 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
813 /* Clear id, off, and union(map_ptr, range) */
814 memset(((u8 *)reg) + sizeof(reg->type), 0,
815 offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
816 reg->var_off = tnum_const(imm);
817 reg->smin_value = (s64)imm;
818 reg->smax_value = (s64)imm;
819 reg->umin_value = imm;
820 reg->umax_value = imm;
823 /* Mark the 'variable offset' part of a register as zero. This should be
824 * used only on registers holding a pointer type.
826 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
828 __mark_reg_known(reg, 0);
831 static void __mark_reg_const_zero(struct bpf_reg_state *reg)
833 __mark_reg_known(reg, 0);
834 reg->type = SCALAR_VALUE;
837 static void mark_reg_known_zero(struct bpf_verifier_env *env,
838 struct bpf_reg_state *regs, u32 regno)
840 if (WARN_ON(regno >= MAX_BPF_REG)) {
841 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
842 /* Something bad happened, let's kill all regs */
843 for (regno = 0; regno < MAX_BPF_REG; regno++)
844 __mark_reg_not_init(regs + regno);
847 __mark_reg_known_zero(regs + regno);
850 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
852 return type_is_pkt_pointer(reg->type);
855 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
857 return reg_is_pkt_pointer(reg) ||
858 reg->type == PTR_TO_PACKET_END;
861 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
862 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
863 enum bpf_reg_type which)
865 /* The register can already have a range from prior markings.
866 * This is fine as long as it hasn't been advanced from its
869 return reg->type == which &&
872 tnum_equals_const(reg->var_off, 0);
875 /* Attempts to improve min/max values based on var_off information */
876 static void __update_reg_bounds(struct bpf_reg_state *reg)
878 /* min signed is max(sign bit) | min(other bits) */
879 reg->smin_value = max_t(s64, reg->smin_value,
880 reg->var_off.value | (reg->var_off.mask & S64_MIN));
881 /* max signed is min(sign bit) | max(other bits) */
882 reg->smax_value = min_t(s64, reg->smax_value,
883 reg->var_off.value | (reg->var_off.mask & S64_MAX));
884 reg->umin_value = max(reg->umin_value, reg->var_off.value);
885 reg->umax_value = min(reg->umax_value,
886 reg->var_off.value | reg->var_off.mask);
889 /* Uses signed min/max values to inform unsigned, and vice-versa */
890 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
892 /* Learn sign from signed bounds.
893 * If we cannot cross the sign boundary, then signed and unsigned bounds
894 * are the same, so combine. This works even in the negative case, e.g.
895 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
897 if (reg->smin_value >= 0 || reg->smax_value < 0) {
898 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
900 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
904 /* Learn sign from unsigned bounds. Signed bounds cross the sign
905 * boundary, so we must be careful.
907 if ((s64)reg->umax_value >= 0) {
908 /* Positive. We can't learn anything from the smin, but smax
909 * is positive, hence safe.
911 reg->smin_value = reg->umin_value;
912 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
914 } else if ((s64)reg->umin_value < 0) {
915 /* Negative. We can't learn anything from the smax, but smin
916 * is negative, hence safe.
918 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
920 reg->smax_value = reg->umax_value;
924 /* Attempts to improve var_off based on unsigned min/max information */
925 static void __reg_bound_offset(struct bpf_reg_state *reg)
927 reg->var_off = tnum_intersect(reg->var_off,
928 tnum_range(reg->umin_value,
932 /* Reset the min/max bounds of a register */
933 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
935 reg->smin_value = S64_MIN;
936 reg->smax_value = S64_MAX;
938 reg->umax_value = U64_MAX;
941 /* Mark a register as having a completely unknown (scalar) value. */
942 static void __mark_reg_unknown(struct bpf_reg_state *reg)
945 * Clear type, id, off, and union(map_ptr, range) and
946 * padding between 'type' and union
948 memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
949 reg->type = SCALAR_VALUE;
950 reg->var_off = tnum_unknown;
952 __mark_reg_unbounded(reg);
955 static void mark_reg_unknown(struct bpf_verifier_env *env,
956 struct bpf_reg_state *regs, u32 regno)
958 if (WARN_ON(regno >= MAX_BPF_REG)) {
959 verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
960 /* Something bad happened, let's kill all regs except FP */
961 for (regno = 0; regno < BPF_REG_FP; regno++)
962 __mark_reg_not_init(regs + regno);
965 __mark_reg_unknown(regs + regno);
968 static void __mark_reg_not_init(struct bpf_reg_state *reg)
970 __mark_reg_unknown(reg);
971 reg->type = NOT_INIT;
974 static void mark_reg_not_init(struct bpf_verifier_env *env,
975 struct bpf_reg_state *regs, u32 regno)
977 if (WARN_ON(regno >= MAX_BPF_REG)) {
978 verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
979 /* Something bad happened, let's kill all regs except FP */
980 for (regno = 0; regno < BPF_REG_FP; regno++)
981 __mark_reg_not_init(regs + regno);
984 __mark_reg_not_init(regs + regno);
987 #define DEF_NOT_SUBREG (0)
988 static void init_reg_state(struct bpf_verifier_env *env,
989 struct bpf_func_state *state)
991 struct bpf_reg_state *regs = state->regs;
994 for (i = 0; i < MAX_BPF_REG; i++) {
995 mark_reg_not_init(env, regs, i);
996 regs[i].live = REG_LIVE_NONE;
997 regs[i].parent = NULL;
998 regs[i].subreg_def = DEF_NOT_SUBREG;
1002 regs[BPF_REG_FP].type = PTR_TO_STACK;
1003 mark_reg_known_zero(env, regs, BPF_REG_FP);
1004 regs[BPF_REG_FP].frameno = state->frameno;
1006 /* 1st arg to a function */
1007 regs[BPF_REG_1].type = PTR_TO_CTX;
1008 mark_reg_known_zero(env, regs, BPF_REG_1);
1011 #define BPF_MAIN_FUNC (-1)
1012 static void init_func_state(struct bpf_verifier_env *env,
1013 struct bpf_func_state *state,
1014 int callsite, int frameno, int subprogno)
1016 state->callsite = callsite;
1017 state->frameno = frameno;
1018 state->subprogno = subprogno;
1019 init_reg_state(env, state);
1023 SRC_OP, /* register is used as source operand */
1024 DST_OP, /* register is used as destination operand */
1025 DST_OP_NO_MARK /* same as above, check only, don't mark */
1028 static int cmp_subprogs(const void *a, const void *b)
1030 return ((struct bpf_subprog_info *)a)->start -
1031 ((struct bpf_subprog_info *)b)->start;
1034 static int find_subprog(struct bpf_verifier_env *env, int off)
1036 struct bpf_subprog_info *p;
1038 p = bsearch(&off, env->subprog_info, env->subprog_cnt,
1039 sizeof(env->subprog_info[0]), cmp_subprogs);
1042 return p - env->subprog_info;
1046 static int add_subprog(struct bpf_verifier_env *env, int off)
1048 int insn_cnt = env->prog->len;
1051 if (off >= insn_cnt || off < 0) {
1052 verbose(env, "call to invalid destination\n");
1055 ret = find_subprog(env, off);
1058 if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
1059 verbose(env, "too many subprograms\n");
1062 env->subprog_info[env->subprog_cnt++].start = off;
1063 sort(env->subprog_info, env->subprog_cnt,
1064 sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
1068 static int check_subprogs(struct bpf_verifier_env *env)
1070 int i, ret, subprog_start, subprog_end, off, cur_subprog = 0;
1071 struct bpf_subprog_info *subprog = env->subprog_info;
1072 struct bpf_insn *insn = env->prog->insnsi;
1073 int insn_cnt = env->prog->len;
1075 /* Add entry function. */
1076 ret = add_subprog(env, 0);
1080 /* determine subprog starts. The end is one before the next starts */
1081 for (i = 0; i < insn_cnt; i++) {
1082 if (insn[i].code != (BPF_JMP | BPF_CALL))
1084 if (insn[i].src_reg != BPF_PSEUDO_CALL)
1086 if (!env->allow_ptr_leaks) {
1087 verbose(env, "function calls to other bpf functions are allowed for root only\n");
1090 ret = add_subprog(env, i + insn[i].imm + 1);
1095 /* Add a fake 'exit' subprog which could simplify subprog iteration
1096 * logic. 'subprog_cnt' should not be increased.
1098 subprog[env->subprog_cnt].start = insn_cnt;
1100 if (env->log.level & BPF_LOG_LEVEL2)
1101 for (i = 0; i < env->subprog_cnt; i++)
1102 verbose(env, "func#%d @%d\n", i, subprog[i].start);
1104 /* now check that all jumps are within the same subprog */
1105 subprog_start = subprog[cur_subprog].start;
1106 subprog_end = subprog[cur_subprog + 1].start;
1107 for (i = 0; i < insn_cnt; i++) {
1108 u8 code = insn[i].code;
1110 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
1112 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
1114 off = i + insn[i].off + 1;
1115 if (off < subprog_start || off >= subprog_end) {
1116 verbose(env, "jump out of range from insn %d to %d\n", i, off);
1120 if (i == subprog_end - 1) {
1121 /* to avoid fall-through from one subprog into another
1122 * the last insn of the subprog should be either exit
1123 * or unconditional jump back
1125 if (code != (BPF_JMP | BPF_EXIT) &&
1126 code != (BPF_JMP | BPF_JA)) {
1127 verbose(env, "last insn is not an exit or jmp\n");
1130 subprog_start = subprog_end;
1132 if (cur_subprog < env->subprog_cnt)
1133 subprog_end = subprog[cur_subprog + 1].start;
1139 /* Parentage chain of this register (or stack slot) should take care of all
1140 * issues like callee-saved registers, stack slot allocation time, etc.
1142 static int mark_reg_read(struct bpf_verifier_env *env,
1143 const struct bpf_reg_state *state,
1144 struct bpf_reg_state *parent, u8 flag)
1146 bool writes = parent == state->parent; /* Observe write marks */
1150 /* if read wasn't screened by an earlier write ... */
1151 if (writes && state->live & REG_LIVE_WRITTEN)
1153 if (parent->live & REG_LIVE_DONE) {
1154 verbose(env, "verifier BUG type %s var_off %lld off %d\n",
1155 reg_type_str[parent->type],
1156 parent->var_off.value, parent->off);
1159 /* The first condition is more likely to be true than the
1160 * second, checked it first.
1162 if ((parent->live & REG_LIVE_READ) == flag ||
1163 parent->live & REG_LIVE_READ64)
1164 /* The parentage chain never changes and
1165 * this parent was already marked as LIVE_READ.
1166 * There is no need to keep walking the chain again and
1167 * keep re-marking all parents as LIVE_READ.
1168 * This case happens when the same register is read
1169 * multiple times without writes into it in-between.
1170 * Also, if parent has the stronger REG_LIVE_READ64 set,
1171 * then no need to set the weak REG_LIVE_READ32.
1174 /* ... then we depend on parent's value */
1175 parent->live |= flag;
1176 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
1177 if (flag == REG_LIVE_READ64)
1178 parent->live &= ~REG_LIVE_READ32;
1180 parent = state->parent;
1185 if (env->longest_mark_read_walk < cnt)
1186 env->longest_mark_read_walk = cnt;
1190 /* This function is supposed to be used by the following 32-bit optimization
1191 * code only. It returns TRUE if the source or destination register operates
1192 * on 64-bit, otherwise return FALSE.
1194 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
1195 u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
1200 class = BPF_CLASS(code);
1202 if (class == BPF_JMP) {
1203 /* BPF_EXIT for "main" will reach here. Return TRUE
1208 if (op == BPF_CALL) {
1209 /* BPF to BPF call will reach here because of marking
1210 * caller saved clobber with DST_OP_NO_MARK for which we
1211 * don't care the register def because they are anyway
1212 * marked as NOT_INIT already.
1214 if (insn->src_reg == BPF_PSEUDO_CALL)
1216 /* Helper call will reach here because of arg type
1217 * check, conservatively return TRUE.
1226 if (class == BPF_ALU64 || class == BPF_JMP ||
1227 /* BPF_END always use BPF_ALU class. */
1228 (class == BPF_ALU && op == BPF_END && insn->imm == 64))
1231 if (class == BPF_ALU || class == BPF_JMP32)
1234 if (class == BPF_LDX) {
1236 return BPF_SIZE(code) == BPF_DW;
1237 /* LDX source must be ptr. */
1241 if (class == BPF_STX) {
1242 if (reg->type != SCALAR_VALUE)
1244 return BPF_SIZE(code) == BPF_DW;
1247 if (class == BPF_LD) {
1248 u8 mode = BPF_MODE(code);
1251 if (mode == BPF_IMM)
1254 /* Both LD_IND and LD_ABS return 32-bit data. */
1258 /* Implicit ctx ptr. */
1259 if (regno == BPF_REG_6)
1262 /* Explicit source could be any width. */
1266 if (class == BPF_ST)
1267 /* The only source register for BPF_ST is a ptr. */
1270 /* Conservatively return true at default. */
1274 /* Return TRUE if INSN doesn't have explicit value define. */
1275 static bool insn_no_def(struct bpf_insn *insn)
1277 u8 class = BPF_CLASS(insn->code);
1279 return (class == BPF_JMP || class == BPF_JMP32 ||
1280 class == BPF_STX || class == BPF_ST);
1283 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
1284 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
1286 if (insn_no_def(insn))
1289 return !is_reg64(env, insn, insn->dst_reg, NULL, DST_OP);
1292 static void mark_insn_zext(struct bpf_verifier_env *env,
1293 struct bpf_reg_state *reg)
1295 s32 def_idx = reg->subreg_def;
1297 if (def_idx == DEF_NOT_SUBREG)
1300 env->insn_aux_data[def_idx - 1].zext_dst = true;
1301 /* The dst will be zero extended, so won't be sub-register anymore. */
1302 reg->subreg_def = DEF_NOT_SUBREG;
1305 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
1306 enum reg_arg_type t)
1308 struct bpf_verifier_state *vstate = env->cur_state;
1309 struct bpf_func_state *state = vstate->frame[vstate->curframe];
1310 struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
1311 struct bpf_reg_state *reg, *regs = state->regs;
1314 if (regno >= MAX_BPF_REG) {
1315 verbose(env, "R%d is invalid\n", regno);
1320 rw64 = is_reg64(env, insn, regno, reg, t);
1322 /* check whether register used as source operand can be read */
1323 if (reg->type == NOT_INIT) {
1324 verbose(env, "R%d !read_ok\n", regno);
1327 /* We don't need to worry about FP liveness because it's read-only */
1328 if (regno == BPF_REG_FP)
1332 mark_insn_zext(env, reg);
1334 return mark_reg_read(env, reg, reg->parent,
1335 rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
1337 /* check whether register used as dest operand can be written to */
1338 if (regno == BPF_REG_FP) {
1339 verbose(env, "frame pointer is read only\n");
1342 reg->live |= REG_LIVE_WRITTEN;
1343 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
1345 mark_reg_unknown(env, regs, regno);
1350 static bool is_spillable_regtype(enum bpf_reg_type type)
1353 case PTR_TO_MAP_VALUE:
1354 case PTR_TO_MAP_VALUE_OR_NULL:
1358 case PTR_TO_PACKET_META:
1359 case PTR_TO_PACKET_END:
1360 case PTR_TO_FLOW_KEYS:
1361 case CONST_PTR_TO_MAP:
1363 case PTR_TO_SOCKET_OR_NULL:
1364 case PTR_TO_SOCK_COMMON:
1365 case PTR_TO_SOCK_COMMON_OR_NULL:
1366 case PTR_TO_TCP_SOCK:
1367 case PTR_TO_TCP_SOCK_OR_NULL:
1368 case PTR_TO_XDP_SOCK:
1375 /* Does this register contain a constant zero? */
1376 static bool register_is_null(struct bpf_reg_state *reg)
1378 return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
1381 static bool register_is_const(struct bpf_reg_state *reg)
1383 return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
1386 static void save_register_state(struct bpf_func_state *state,
1387 int spi, struct bpf_reg_state *reg)
1391 state->stack[spi].spilled_ptr = *reg;
1392 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
1394 for (i = 0; i < BPF_REG_SIZE; i++)
1395 state->stack[spi].slot_type[i] = STACK_SPILL;
1398 /* check_stack_read/write functions track spill/fill of registers,
1399 * stack boundary and alignment are checked in check_mem_access()
1401 static int check_stack_write(struct bpf_verifier_env *env,
1402 struct bpf_func_state *state, /* func where register points to */
1403 int off, int size, int value_regno, int insn_idx)
1405 struct bpf_func_state *cur; /* state of the current function */
1406 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
1407 struct bpf_reg_state *reg = NULL;
1409 err = realloc_func_state(state, round_up(slot + 1, BPF_REG_SIZE),
1410 state->acquired_refs, true);
1413 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
1414 * so it's aligned access and [off, off + size) are within stack limits
1416 if (!env->allow_ptr_leaks &&
1417 state->stack[spi].slot_type[0] == STACK_SPILL &&
1418 size != BPF_REG_SIZE) {
1419 verbose(env, "attempt to corrupt spilled pointer on stack\n");
1423 cur = env->cur_state->frame[env->cur_state->curframe];
1424 if (value_regno >= 0)
1425 reg = &cur->regs[value_regno];
1427 if (reg && size == BPF_REG_SIZE && register_is_const(reg) &&
1428 !register_is_null(reg) && env->allow_ptr_leaks) {
1429 save_register_state(state, spi, reg);
1430 } else if (reg && is_spillable_regtype(reg->type)) {
1431 /* register containing pointer is being spilled into stack */
1432 if (size != BPF_REG_SIZE) {
1433 verbose_linfo(env, insn_idx, "; ");
1434 verbose(env, "invalid size of register spill\n");
1438 if (state != cur && reg->type == PTR_TO_STACK) {
1439 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
1443 if (!env->allow_ptr_leaks) {
1444 bool sanitize = false;
1446 if (state->stack[spi].slot_type[0] == STACK_SPILL &&
1447 register_is_const(&state->stack[spi].spilled_ptr))
1449 for (i = 0; i < BPF_REG_SIZE; i++)
1450 if (state->stack[spi].slot_type[i] == STACK_MISC) {
1455 int *poff = &env->insn_aux_data[insn_idx].sanitize_stack_off;
1456 int soff = (-spi - 1) * BPF_REG_SIZE;
1458 /* detected reuse of integer stack slot with a pointer
1459 * which means either llvm is reusing stack slot or
1460 * an attacker is trying to exploit CVE-2018-3639
1461 * (speculative store bypass)
1462 * Have to sanitize that slot with preemptive
1465 if (*poff && *poff != soff) {
1466 /* disallow programs where single insn stores
1467 * into two different stack slots, since verifier
1468 * cannot sanitize them
1471 "insn %d cannot access two stack slots fp%d and fp%d",
1472 insn_idx, *poff, soff);
1478 save_register_state(state, spi, reg);
1480 u8 type = STACK_MISC;
1482 /* regular write of data into stack destroys any spilled ptr */
1483 state->stack[spi].spilled_ptr.type = NOT_INIT;
1484 /* Mark slots as STACK_MISC if they belonged to spilled ptr. */
1485 if (state->stack[spi].slot_type[0] == STACK_SPILL)
1486 for (i = 0; i < BPF_REG_SIZE; i++)
1487 state->stack[spi].slot_type[i] = STACK_MISC;
1489 /* only mark the slot as written if all 8 bytes were written
1490 * otherwise read propagation may incorrectly stop too soon
1491 * when stack slots are partially written.
1492 * This heuristic means that read propagation will be
1493 * conservative, since it will add reg_live_read marks
1494 * to stack slots all the way to first state when programs
1495 * writes+reads less than 8 bytes
1497 if (size == BPF_REG_SIZE)
1498 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
1500 /* when we zero initialize stack slots mark them as such */
1501 if (reg && register_is_null(reg))
1504 /* Mark slots affected by this stack write. */
1505 for (i = 0; i < size; i++)
1506 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
1512 static int check_stack_read(struct bpf_verifier_env *env,
1513 struct bpf_func_state *reg_state /* func where register points to */,
1514 int off, int size, int value_regno)
1516 struct bpf_verifier_state *vstate = env->cur_state;
1517 struct bpf_func_state *state = vstate->frame[vstate->curframe];
1518 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
1519 struct bpf_reg_state *reg;
1522 if (reg_state->allocated_stack <= slot) {
1523 verbose(env, "invalid read from stack off %d+0 size %d\n",
1527 stype = reg_state->stack[spi].slot_type;
1528 reg = ®_state->stack[spi].spilled_ptr;
1530 if (stype[0] == STACK_SPILL) {
1531 if (size != BPF_REG_SIZE) {
1532 if (reg->type != SCALAR_VALUE) {
1533 verbose_linfo(env, env->insn_idx, "; ");
1534 verbose(env, "invalid size of register fill\n");
1537 if (value_regno >= 0) {
1538 mark_reg_unknown(env, state->regs, value_regno);
1539 state->regs[value_regno].live |= REG_LIVE_WRITTEN;
1541 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
1544 for (i = 1; i < BPF_REG_SIZE; i++) {
1545 if (stype[(slot - i) % BPF_REG_SIZE] != STACK_SPILL) {
1546 verbose(env, "corrupted spill memory\n");
1551 if (value_regno >= 0) {
1552 /* restore register state from stack */
1553 state->regs[value_regno] = *reg;
1554 /* mark reg as written since spilled pointer state likely
1555 * has its liveness marks cleared by is_state_visited()
1556 * which resets stack/reg liveness for state transitions
1558 state->regs[value_regno].live |= REG_LIVE_WRITTEN;
1560 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
1564 for (i = 0; i < size; i++) {
1565 if (stype[(slot - i) % BPF_REG_SIZE] == STACK_MISC)
1567 if (stype[(slot - i) % BPF_REG_SIZE] == STACK_ZERO) {
1571 verbose(env, "invalid read from stack off %d+%d size %d\n",
1575 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
1576 if (value_regno >= 0) {
1577 if (zeros == size) {
1578 /* any size read into register is zero extended,
1579 * so the whole register == const_zero
1581 __mark_reg_const_zero(&state->regs[value_regno]);
1583 /* have read misc data from the stack */
1584 mark_reg_unknown(env, state->regs, value_regno);
1586 state->regs[value_regno].live |= REG_LIVE_WRITTEN;
1592 static int check_stack_access(struct bpf_verifier_env *env,
1593 const struct bpf_reg_state *reg,
1596 /* Stack accesses must be at a fixed offset, so that we
1597 * can determine what type of data were returned. See
1598 * check_stack_read().
1600 if (!tnum_is_const(reg->var_off)) {
1603 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
1604 verbose(env, "variable stack access var_off=%s off=%d size=%d\n",
1609 if (off >= 0 || off < -MAX_BPF_STACK) {
1610 verbose(env, "invalid stack off=%d size=%d\n", off, size);
1617 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
1618 int off, int size, enum bpf_access_type type)
1620 struct bpf_reg_state *regs = cur_regs(env);
1621 struct bpf_map *map = regs[regno].map_ptr;
1622 u32 cap = bpf_map_flags_to_cap(map);
1624 if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
1625 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
1626 map->value_size, off, size);
1630 if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
1631 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
1632 map->value_size, off, size);
1639 /* check read/write into map element returned by bpf_map_lookup_elem() */
1640 static int __check_map_access(struct bpf_verifier_env *env, u32 regno, int off,
1641 int size, bool zero_size_allowed)
1643 struct bpf_reg_state *regs = cur_regs(env);
1644 struct bpf_map *map = regs[regno].map_ptr;
1646 if (off < 0 || size < 0 || (size == 0 && !zero_size_allowed) ||
1647 off + size > map->value_size) {
1648 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
1649 map->value_size, off, size);
1655 /* check read/write into a map element with possible variable offset */
1656 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
1657 int off, int size, bool zero_size_allowed)
1659 struct bpf_verifier_state *vstate = env->cur_state;
1660 struct bpf_func_state *state = vstate->frame[vstate->curframe];
1661 struct bpf_reg_state *reg = &state->regs[regno];
1664 /* We may have adjusted the register to this map value, so we
1665 * need to try adding each of min_value and max_value to off
1666 * to make sure our theoretical access will be safe.
1668 if (env->log.level & BPF_LOG_LEVEL)
1669 print_verifier_state(env, state);
1671 /* The minimum value is only important with signed
1672 * comparisons where we can't assume the floor of a
1673 * value is 0. If we are using signed variables for our
1674 * index'es we need to make sure that whatever we use
1675 * will have a set floor within our range.
1677 if (reg->smin_value < 0 &&
1678 (reg->smin_value == S64_MIN ||
1679 (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
1680 reg->smin_value + off < 0)) {
1681 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
1685 err = __check_map_access(env, regno, reg->smin_value + off, size,
1688 verbose(env, "R%d min value is outside of the array range\n",
1693 /* If we haven't set a max value then we need to bail since we can't be
1694 * sure we won't do bad things.
1695 * If reg->umax_value + off could overflow, treat that as unbounded too.
1697 if (reg->umax_value >= BPF_MAX_VAR_OFF) {
1698 verbose(env, "R%d unbounded memory access, make sure to bounds check any array access into a map\n",
1702 err = __check_map_access(env, regno, reg->umax_value + off, size,
1705 verbose(env, "R%d max value is outside of the array range\n",
1708 if (map_value_has_spin_lock(reg->map_ptr)) {
1709 u32 lock = reg->map_ptr->spin_lock_off;
1711 /* if any part of struct bpf_spin_lock can be touched by
1712 * load/store reject this program.
1713 * To check that [x1, x2) overlaps with [y1, y2)
1714 * it is sufficient to check x1 < y2 && y1 < x2.
1716 if (reg->smin_value + off < lock + sizeof(struct bpf_spin_lock) &&
1717 lock < reg->umax_value + off + size) {
1718 verbose(env, "bpf_spin_lock cannot be accessed directly by load/store\n");
1725 #define MAX_PACKET_OFF 0xffff
1727 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
1728 const struct bpf_call_arg_meta *meta,
1729 enum bpf_access_type t)
1731 switch (env->prog->type) {
1732 /* Program types only with direct read access go here! */
1733 case BPF_PROG_TYPE_LWT_IN:
1734 case BPF_PROG_TYPE_LWT_OUT:
1735 case BPF_PROG_TYPE_LWT_SEG6LOCAL:
1736 case BPF_PROG_TYPE_SK_REUSEPORT:
1737 case BPF_PROG_TYPE_FLOW_DISSECTOR:
1738 case BPF_PROG_TYPE_CGROUP_SKB:
1743 /* Program types with direct read + write access go here! */
1744 case BPF_PROG_TYPE_SCHED_CLS:
1745 case BPF_PROG_TYPE_SCHED_ACT:
1746 case BPF_PROG_TYPE_XDP:
1747 case BPF_PROG_TYPE_LWT_XMIT:
1748 case BPF_PROG_TYPE_SK_SKB:
1749 case BPF_PROG_TYPE_SK_MSG:
1751 return meta->pkt_access;
1753 env->seen_direct_write = true;
1760 static int __check_packet_access(struct bpf_verifier_env *env, u32 regno,
1761 int off, int size, bool zero_size_allowed)
1763 struct bpf_reg_state *regs = cur_regs(env);
1764 struct bpf_reg_state *reg = ®s[regno];
1766 if (off < 0 || size < 0 || (size == 0 && !zero_size_allowed) ||
1767 (u64)off + size > reg->range) {
1768 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
1769 off, size, regno, reg->id, reg->off, reg->range);
1775 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
1776 int size, bool zero_size_allowed)
1778 struct bpf_reg_state *regs = cur_regs(env);
1779 struct bpf_reg_state *reg = ®s[regno];
1782 /* We may have added a variable offset to the packet pointer; but any
1783 * reg->range we have comes after that. We are only checking the fixed
1787 /* We don't allow negative numbers, because we aren't tracking enough
1788 * detail to prove they're safe.
1790 if (reg->smin_value < 0) {
1791 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
1795 err = __check_packet_access(env, regno, off, size, zero_size_allowed);
1797 verbose(env, "R%d offset is outside of the packet\n", regno);
1801 /* __check_packet_access has made sure "off + size - 1" is within u16.
1802 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
1803 * otherwise find_good_pkt_pointers would have refused to set range info
1804 * that __check_packet_access would have rejected this pkt access.
1805 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
1807 env->prog->aux->max_pkt_offset =
1808 max_t(u32, env->prog->aux->max_pkt_offset,
1809 off + reg->umax_value + size - 1);
1814 /* check access to 'struct bpf_context' fields. Supports fixed offsets only */
1815 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
1816 enum bpf_access_type t, enum bpf_reg_type *reg_type)
1818 struct bpf_insn_access_aux info = {
1819 .reg_type = *reg_type,
1822 if (env->ops->is_valid_access &&
1823 env->ops->is_valid_access(off, size, t, env->prog, &info)) {
1824 /* A non zero info.ctx_field_size indicates that this field is a
1825 * candidate for later verifier transformation to load the whole
1826 * field and then apply a mask when accessed with a narrower
1827 * access than actual ctx access size. A zero info.ctx_field_size
1828 * will only allow for whole field access and rejects any other
1829 * type of narrower access.
1831 *reg_type = info.reg_type;
1833 env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
1834 /* remember the offset of last byte accessed in ctx */
1835 if (env->prog->aux->max_ctx_offset < off + size)
1836 env->prog->aux->max_ctx_offset = off + size;
1840 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
1844 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
1847 if (size < 0 || off < 0 ||
1848 (u64)off + size > sizeof(struct bpf_flow_keys)) {
1849 verbose(env, "invalid access to flow keys off=%d size=%d\n",
1856 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
1857 u32 regno, int off, int size,
1858 enum bpf_access_type t)
1860 struct bpf_reg_state *regs = cur_regs(env);
1861 struct bpf_reg_state *reg = ®s[regno];
1862 struct bpf_insn_access_aux info = {};
1865 if (reg->smin_value < 0) {
1866 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
1871 switch (reg->type) {
1872 case PTR_TO_SOCK_COMMON:
1873 valid = bpf_sock_common_is_valid_access(off, size, t, &info);
1876 valid = bpf_sock_is_valid_access(off, size, t, &info);
1878 case PTR_TO_TCP_SOCK:
1879 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
1881 case PTR_TO_XDP_SOCK:
1882 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
1890 env->insn_aux_data[insn_idx].ctx_field_size =
1891 info.ctx_field_size;
1895 verbose(env, "R%d invalid %s access off=%d size=%d\n",
1896 regno, reg_type_str[reg->type], off, size);
1901 static bool __is_pointer_value(bool allow_ptr_leaks,
1902 const struct bpf_reg_state *reg)
1904 if (allow_ptr_leaks)
1907 return reg->type != SCALAR_VALUE;
1910 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
1912 return cur_regs(env) + regno;
1915 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
1917 return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
1920 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
1922 const struct bpf_reg_state *reg = reg_state(env, regno);
1924 return reg->type == PTR_TO_CTX;
1927 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
1929 const struct bpf_reg_state *reg = reg_state(env, regno);
1931 return type_is_sk_pointer(reg->type);
1934 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
1936 const struct bpf_reg_state *reg = reg_state(env, regno);
1938 return type_is_pkt_pointer(reg->type);
1941 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
1943 const struct bpf_reg_state *reg = reg_state(env, regno);
1945 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
1946 return reg->type == PTR_TO_FLOW_KEYS;
1949 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
1950 const struct bpf_reg_state *reg,
1951 int off, int size, bool strict)
1953 struct tnum reg_off;
1956 /* Byte size accesses are always allowed. */
1957 if (!strict || size == 1)
1960 /* For platforms that do not have a Kconfig enabling
1961 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
1962 * NET_IP_ALIGN is universally set to '2'. And on platforms
1963 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
1964 * to this code only in strict mode where we want to emulate
1965 * the NET_IP_ALIGN==2 checking. Therefore use an
1966 * unconditional IP align value of '2'.
1970 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
1971 if (!tnum_is_aligned(reg_off, size)) {
1974 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
1976 "misaligned packet access off %d+%s+%d+%d size %d\n",
1977 ip_align, tn_buf, reg->off, off, size);
1984 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
1985 const struct bpf_reg_state *reg,
1986 const char *pointer_desc,
1987 int off, int size, bool strict)
1989 struct tnum reg_off;
1991 /* Byte size accesses are always allowed. */
1992 if (!strict || size == 1)
1995 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
1996 if (!tnum_is_aligned(reg_off, size)) {
1999 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
2000 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
2001 pointer_desc, tn_buf, reg->off, off, size);
2008 static int check_ptr_alignment(struct bpf_verifier_env *env,
2009 const struct bpf_reg_state *reg, int off,
2010 int size, bool strict_alignment_once)
2012 bool strict = env->strict_alignment || strict_alignment_once;
2013 const char *pointer_desc = "";
2015 switch (reg->type) {
2017 case PTR_TO_PACKET_META:
2018 /* Special case, because of NET_IP_ALIGN. Given metadata sits
2019 * right in front, treat it the very same way.
2021 return check_pkt_ptr_alignment(env, reg, off, size, strict);
2022 case PTR_TO_FLOW_KEYS:
2023 pointer_desc = "flow keys ";
2025 case PTR_TO_MAP_VALUE:
2026 pointer_desc = "value ";
2029 pointer_desc = "context ";
2032 pointer_desc = "stack ";
2033 /* The stack spill tracking logic in check_stack_write()
2034 * and check_stack_read() relies on stack accesses being
2040 pointer_desc = "sock ";
2042 case PTR_TO_SOCK_COMMON:
2043 pointer_desc = "sock_common ";
2045 case PTR_TO_TCP_SOCK:
2046 pointer_desc = "tcp_sock ";
2048 case PTR_TO_XDP_SOCK:
2049 pointer_desc = "xdp_sock ";
2054 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
2058 static int update_stack_depth(struct bpf_verifier_env *env,
2059 const struct bpf_func_state *func,
2062 u16 stack = env->subprog_info[func->subprogno].stack_depth;
2067 /* update known max for given subprogram */
2068 env->subprog_info[func->subprogno].stack_depth = -off;
2072 /* starting from main bpf function walk all instructions of the function
2073 * and recursively walk all callees that given function can call.
2074 * Ignore jump and exit insns.
2075 * Since recursion is prevented by check_cfg() this algorithm
2076 * only needs a local stack of MAX_CALL_FRAMES to remember callsites
2078 static int check_max_stack_depth(struct bpf_verifier_env *env)
2080 int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
2081 struct bpf_subprog_info *subprog = env->subprog_info;
2082 struct bpf_insn *insn = env->prog->insnsi;
2083 int ret_insn[MAX_CALL_FRAMES];
2084 int ret_prog[MAX_CALL_FRAMES];
2087 /* round up to 32-bytes, since this is granularity
2088 * of interpreter stack size
2090 depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
2091 if (depth > MAX_BPF_STACK) {
2092 verbose(env, "combined stack size of %d calls is %d. Too large\n",
2097 subprog_end = subprog[idx + 1].start;
2098 for (; i < subprog_end; i++) {
2099 if (insn[i].code != (BPF_JMP | BPF_CALL))
2101 if (insn[i].src_reg != BPF_PSEUDO_CALL)
2103 /* remember insn and function to return to */
2104 ret_insn[frame] = i + 1;
2105 ret_prog[frame] = idx;
2107 /* find the callee */
2108 i = i + insn[i].imm + 1;
2109 idx = find_subprog(env, i);
2111 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
2116 if (frame >= MAX_CALL_FRAMES) {
2117 verbose(env, "the call stack of %d frames is too deep !\n",
2123 /* end of for() loop means the last insn of the 'subprog'
2124 * was reached. Doesn't matter whether it was JA or EXIT
2128 depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
2130 i = ret_insn[frame];
2131 idx = ret_prog[frame];
2135 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
2136 static int get_callee_stack_depth(struct bpf_verifier_env *env,
2137 const struct bpf_insn *insn, int idx)
2139 int start = idx + insn->imm + 1, subprog;
2141 subprog = find_subprog(env, start);
2143 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
2147 return env->subprog_info[subprog].stack_depth;
2151 static int check_ctx_reg(struct bpf_verifier_env *env,
2152 const struct bpf_reg_state *reg, int regno)
2154 /* Access to ctx or passing it to a helper is only allowed in
2155 * its original, unmodified form.
2159 verbose(env, "dereference of modified ctx ptr R%d off=%d disallowed\n",
2164 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
2167 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
2168 verbose(env, "variable ctx access var_off=%s disallowed\n", tn_buf);
2175 static int check_tp_buffer_access(struct bpf_verifier_env *env,
2176 const struct bpf_reg_state *reg,
2177 int regno, int off, int size)
2181 "R%d invalid tracepoint buffer access: off=%d, size=%d",
2185 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
2188 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
2190 "R%d invalid variable buffer offset: off=%d, var_off=%s",
2191 regno, off, tn_buf);
2194 if (off + size > env->prog->aux->max_tp_access)
2195 env->prog->aux->max_tp_access = off + size;
2201 /* truncate register to smaller size (in bytes)
2202 * must be called with size < BPF_REG_SIZE
2204 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
2208 /* clear high bits in bit representation */
2209 reg->var_off = tnum_cast(reg->var_off, size);
2211 /* fix arithmetic bounds */
2212 mask = ((u64)1 << (size * 8)) - 1;
2213 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
2214 reg->umin_value &= mask;
2215 reg->umax_value &= mask;
2217 reg->umin_value = 0;
2218 reg->umax_value = mask;
2220 reg->smin_value = reg->umin_value;
2221 reg->smax_value = reg->umax_value;
2224 /* check whether memory at (regno + off) is accessible for t = (read | write)
2225 * if t==write, value_regno is a register which value is stored into memory
2226 * if t==read, value_regno is a register which will receive the value from memory
2227 * if t==write && value_regno==-1, some unknown value is stored into memory
2228 * if t==read && value_regno==-1, don't care what we read from memory
2230 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
2231 int off, int bpf_size, enum bpf_access_type t,
2232 int value_regno, bool strict_alignment_once)
2234 struct bpf_reg_state *regs = cur_regs(env);
2235 struct bpf_reg_state *reg = regs + regno;
2236 struct bpf_func_state *state;
2239 size = bpf_size_to_bytes(bpf_size);
2243 /* alignment checks will add in reg->off themselves */
2244 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
2248 /* for access checks, reg->off is just part of off */
2251 if (reg->type == PTR_TO_MAP_VALUE) {
2252 if (t == BPF_WRITE && value_regno >= 0 &&
2253 is_pointer_value(env, value_regno)) {
2254 verbose(env, "R%d leaks addr into map\n", value_regno);
2257 err = check_map_access_type(env, regno, off, size, t);
2260 err = check_map_access(env, regno, off, size, false);
2261 if (!err && t == BPF_READ && value_regno >= 0)
2262 mark_reg_unknown(env, regs, value_regno);
2264 } else if (reg->type == PTR_TO_CTX) {
2265 enum bpf_reg_type reg_type = SCALAR_VALUE;
2267 if (t == BPF_WRITE && value_regno >= 0 &&
2268 is_pointer_value(env, value_regno)) {
2269 verbose(env, "R%d leaks addr into ctx\n", value_regno);
2273 err = check_ctx_reg(env, reg, regno);
2277 err = check_ctx_access(env, insn_idx, off, size, t, ®_type);
2278 if (!err && t == BPF_READ && value_regno >= 0) {
2279 /* ctx access returns either a scalar, or a
2280 * PTR_TO_PACKET[_META,_END]. In the latter
2281 * case, we know the offset is zero.
2283 if (reg_type == SCALAR_VALUE) {
2284 mark_reg_unknown(env, regs, value_regno);
2286 mark_reg_known_zero(env, regs,
2288 if (reg_type_may_be_null(reg_type))
2289 regs[value_regno].id = ++env->id_gen;
2290 /* A load of ctx field could have different
2291 * actual load size with the one encoded in the
2292 * insn. When the dst is PTR, it is for sure not
2295 regs[value_regno].subreg_def = DEF_NOT_SUBREG;
2297 regs[value_regno].type = reg_type;
2300 } else if (reg->type == PTR_TO_STACK) {
2301 off += reg->var_off.value;
2302 err = check_stack_access(env, reg, off, size);
2306 state = func(env, reg);
2307 err = update_stack_depth(env, state, off);
2312 err = check_stack_write(env, state, off, size,
2313 value_regno, insn_idx);
2315 err = check_stack_read(env, state, off, size,
2317 } else if (reg_is_pkt_pointer(reg)) {
2318 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
2319 verbose(env, "cannot write into packet\n");
2322 if (t == BPF_WRITE && value_regno >= 0 &&
2323 is_pointer_value(env, value_regno)) {
2324 verbose(env, "R%d leaks addr into packet\n",
2328 err = check_packet_access(env, regno, off, size, false);
2329 if (!err && t == BPF_READ && value_regno >= 0)
2330 mark_reg_unknown(env, regs, value_regno);
2331 } else if (reg->type == PTR_TO_FLOW_KEYS) {
2332 if (t == BPF_WRITE && value_regno >= 0 &&
2333 is_pointer_value(env, value_regno)) {
2334 verbose(env, "R%d leaks addr into flow keys\n",
2339 err = check_flow_keys_access(env, off, size);
2340 if (!err && t == BPF_READ && value_regno >= 0)
2341 mark_reg_unknown(env, regs, value_regno);
2342 } else if (type_is_sk_pointer(reg->type)) {
2343 if (t == BPF_WRITE) {
2344 verbose(env, "R%d cannot write into %s\n",
2345 regno, reg_type_str[reg->type]);
2348 err = check_sock_access(env, insn_idx, regno, off, size, t);
2349 if (!err && value_regno >= 0)
2350 mark_reg_unknown(env, regs, value_regno);
2351 } else if (reg->type == PTR_TO_TP_BUFFER) {
2352 err = check_tp_buffer_access(env, reg, regno, off, size);
2353 if (!err && t == BPF_READ && value_regno >= 0)
2354 mark_reg_unknown(env, regs, value_regno);
2356 verbose(env, "R%d invalid mem access '%s'\n", regno,
2357 reg_type_str[reg->type]);
2361 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
2362 regs[value_regno].type == SCALAR_VALUE) {
2363 /* b/h/w load zero-extends, mark upper bits as known 0 */
2364 coerce_reg_to_size(®s[value_regno], size);
2369 static int check_xadd(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
2373 if ((BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) ||
2375 verbose(env, "BPF_XADD uses reserved fields\n");
2379 /* check src1 operand */
2380 err = check_reg_arg(env, insn->src_reg, SRC_OP);
2384 /* check src2 operand */
2385 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
2389 if (is_pointer_value(env, insn->src_reg)) {
2390 verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
2394 if (is_ctx_reg(env, insn->dst_reg) ||
2395 is_pkt_reg(env, insn->dst_reg) ||
2396 is_flow_key_reg(env, insn->dst_reg) ||
2397 is_sk_reg(env, insn->dst_reg)) {
2398 verbose(env, "BPF_XADD stores into R%d %s is not allowed\n",
2400 reg_type_str[reg_state(env, insn->dst_reg)->type]);
2404 /* check whether atomic_add can read the memory */
2405 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
2406 BPF_SIZE(insn->code), BPF_READ, -1, true);
2410 /* check whether atomic_add can write into the same memory */
2411 return check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
2412 BPF_SIZE(insn->code), BPF_WRITE, -1, true);
2415 static int __check_stack_boundary(struct bpf_verifier_env *env, u32 regno,
2416 int off, int access_size,
2417 bool zero_size_allowed)
2419 struct bpf_reg_state *reg = reg_state(env, regno);
2421 if (off >= 0 || off < -MAX_BPF_STACK || off + access_size > 0 ||
2422 access_size < 0 || (access_size == 0 && !zero_size_allowed)) {
2423 if (tnum_is_const(reg->var_off)) {
2424 verbose(env, "invalid stack type R%d off=%d access_size=%d\n",
2425 regno, off, access_size);
2429 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
2430 verbose(env, "invalid stack type R%d var_off=%s access_size=%d\n",
2431 regno, tn_buf, access_size);
2438 /* when register 'regno' is passed into function that will read 'access_size'
2439 * bytes from that pointer, make sure that it's within stack boundary
2440 * and all elements of stack are initialized.
2441 * Unlike most pointer bounds-checking functions, this one doesn't take an
2442 * 'off' argument, so it has to add in reg->off itself.
2444 static int check_stack_boundary(struct bpf_verifier_env *env, int regno,
2445 int access_size, bool zero_size_allowed,
2446 struct bpf_call_arg_meta *meta)
2448 struct bpf_reg_state *reg = reg_state(env, regno);
2449 struct bpf_func_state *state = func(env, reg);
2450 int err, min_off, max_off, i, j, slot, spi;
2452 if (reg->type != PTR_TO_STACK) {
2453 /* Allow zero-byte read from NULL, regardless of pointer type */
2454 if (zero_size_allowed && access_size == 0 &&
2455 register_is_null(reg))
2458 verbose(env, "R%d type=%s expected=%s\n", regno,
2459 reg_type_str[reg->type],
2460 reg_type_str[PTR_TO_STACK]);
2464 if (tnum_is_const(reg->var_off)) {
2465 min_off = max_off = reg->var_off.value + reg->off;
2466 err = __check_stack_boundary(env, regno, min_off, access_size,
2471 /* Variable offset is prohibited for unprivileged mode for
2472 * simplicity since it requires corresponding support in
2473 * Spectre masking for stack ALU.
2474 * See also retrieve_ptr_limit().
2476 if (!env->allow_ptr_leaks) {
2479 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
2480 verbose(env, "R%d indirect variable offset stack access prohibited for !root, var_off=%s\n",
2484 /* Only initialized buffer on stack is allowed to be accessed
2485 * with variable offset. With uninitialized buffer it's hard to
2486 * guarantee that whole memory is marked as initialized on
2487 * helper return since specific bounds are unknown what may
2488 * cause uninitialized stack leaking.
2490 if (meta && meta->raw_mode)
2493 if (reg->smax_value >= BPF_MAX_VAR_OFF ||
2494 reg->smax_value <= -BPF_MAX_VAR_OFF) {
2495 verbose(env, "R%d unbounded indirect variable offset stack access\n",
2499 min_off = reg->smin_value + reg->off;
2500 max_off = reg->smax_value + reg->off;
2501 err = __check_stack_boundary(env, regno, min_off, access_size,
2504 verbose(env, "R%d min value is outside of stack bound\n",
2508 err = __check_stack_boundary(env, regno, max_off, access_size,
2511 verbose(env, "R%d max value is outside of stack bound\n",
2517 if (meta && meta->raw_mode) {
2518 meta->access_size = access_size;
2519 meta->regno = regno;
2523 for (i = min_off; i < max_off + access_size; i++) {
2527 spi = slot / BPF_REG_SIZE;
2528 if (state->allocated_stack <= slot)
2530 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
2531 if (*stype == STACK_MISC)
2533 if (*stype == STACK_ZERO) {
2534 /* helper can write anything into the stack */
2535 *stype = STACK_MISC;
2538 if (state->stack[spi].slot_type[0] == STACK_SPILL &&
2539 state->stack[spi].spilled_ptr.type == SCALAR_VALUE) {
2540 __mark_reg_unknown(&state->stack[spi].spilled_ptr);
2541 for (j = 0; j < BPF_REG_SIZE; j++)
2542 state->stack[spi].slot_type[j] = STACK_MISC;
2547 if (tnum_is_const(reg->var_off)) {
2548 verbose(env, "invalid indirect read from stack off %d+%d size %d\n",
2549 min_off, i - min_off, access_size);
2553 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
2554 verbose(env, "invalid indirect read from stack var_off %s+%d size %d\n",
2555 tn_buf, i - min_off, access_size);
2559 /* reading any byte out of 8-byte 'spill_slot' will cause
2560 * the whole slot to be marked as 'read'
2562 mark_reg_read(env, &state->stack[spi].spilled_ptr,
2563 state->stack[spi].spilled_ptr.parent,
2566 return update_stack_depth(env, state, min_off);
2569 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
2570 int access_size, bool zero_size_allowed,
2571 struct bpf_call_arg_meta *meta)
2573 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
2575 switch (reg->type) {
2577 case PTR_TO_PACKET_META:
2578 return check_packet_access(env, regno, reg->off, access_size,
2580 case PTR_TO_MAP_VALUE:
2581 if (check_map_access_type(env, regno, reg->off, access_size,
2582 meta && meta->raw_mode ? BPF_WRITE :
2585 return check_map_access(env, regno, reg->off, access_size,
2587 default: /* scalar_value|ptr_to_stack or invalid ptr */
2588 return check_stack_boundary(env, regno, access_size,
2589 zero_size_allowed, meta);
2593 /* Implementation details:
2594 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL
2595 * Two bpf_map_lookups (even with the same key) will have different reg->id.
2596 * For traditional PTR_TO_MAP_VALUE the verifier clears reg->id after
2597 * value_or_null->value transition, since the verifier only cares about
2598 * the range of access to valid map value pointer and doesn't care about actual
2599 * address of the map element.
2600 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
2601 * reg->id > 0 after value_or_null->value transition. By doing so
2602 * two bpf_map_lookups will be considered two different pointers that
2603 * point to different bpf_spin_locks.
2604 * The verifier allows taking only one bpf_spin_lock at a time to avoid
2606 * Since only one bpf_spin_lock is allowed the checks are simpler than
2607 * reg_is_refcounted() logic. The verifier needs to remember only
2608 * one spin_lock instead of array of acquired_refs.
2609 * cur_state->active_spin_lock remembers which map value element got locked
2610 * and clears it after bpf_spin_unlock.
2612 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
2615 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
2616 struct bpf_verifier_state *cur = env->cur_state;
2617 bool is_const = tnum_is_const(reg->var_off);
2618 struct bpf_map *map = reg->map_ptr;
2619 u64 val = reg->var_off.value;
2621 if (reg->type != PTR_TO_MAP_VALUE) {
2622 verbose(env, "R%d is not a pointer to map_value\n", regno);
2627 "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
2633 "map '%s' has to have BTF in order to use bpf_spin_lock\n",
2637 if (!map_value_has_spin_lock(map)) {
2638 if (map->spin_lock_off == -E2BIG)
2640 "map '%s' has more than one 'struct bpf_spin_lock'\n",
2642 else if (map->spin_lock_off == -ENOENT)
2644 "map '%s' doesn't have 'struct bpf_spin_lock'\n",
2648 "map '%s' is not a struct type or bpf_spin_lock is mangled\n",
2652 if (map->spin_lock_off != val + reg->off) {
2653 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock'\n",
2658 if (cur->active_spin_lock) {
2660 "Locking two bpf_spin_locks are not allowed\n");
2663 cur->active_spin_lock = reg->id;
2665 if (!cur->active_spin_lock) {
2666 verbose(env, "bpf_spin_unlock without taking a lock\n");
2669 if (cur->active_spin_lock != reg->id) {
2670 verbose(env, "bpf_spin_unlock of different lock\n");
2673 cur->active_spin_lock = 0;
2678 static bool arg_type_is_mem_ptr(enum bpf_arg_type type)
2680 return type == ARG_PTR_TO_MEM ||
2681 type == ARG_PTR_TO_MEM_OR_NULL ||
2682 type == ARG_PTR_TO_UNINIT_MEM;
2685 static bool arg_type_is_mem_size(enum bpf_arg_type type)
2687 return type == ARG_CONST_SIZE ||
2688 type == ARG_CONST_SIZE_OR_ZERO;
2691 static bool arg_type_is_int_ptr(enum bpf_arg_type type)
2693 return type == ARG_PTR_TO_INT ||
2694 type == ARG_PTR_TO_LONG;
2697 static int int_ptr_type_to_size(enum bpf_arg_type type)
2699 if (type == ARG_PTR_TO_INT)
2701 else if (type == ARG_PTR_TO_LONG)
2707 static int check_func_arg(struct bpf_verifier_env *env, u32 regno,
2708 enum bpf_arg_type arg_type,
2709 struct bpf_call_arg_meta *meta)
2711 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
2712 enum bpf_reg_type expected_type, type = reg->type;
2715 if (arg_type == ARG_DONTCARE)
2718 err = check_reg_arg(env, regno, SRC_OP);
2722 if (arg_type == ARG_ANYTHING) {
2723 if (is_pointer_value(env, regno)) {
2724 verbose(env, "R%d leaks addr into helper function\n",
2731 if (type_is_pkt_pointer(type) &&
2732 !may_access_direct_pkt_data(env, meta, BPF_READ)) {
2733 verbose(env, "helper access to the packet is not allowed\n");
2737 if (arg_type == ARG_PTR_TO_MAP_KEY ||
2738 arg_type == ARG_PTR_TO_MAP_VALUE ||
2739 arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE ||
2740 arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL) {
2741 expected_type = PTR_TO_STACK;
2742 if (register_is_null(reg) &&
2743 arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL)
2744 /* final test in check_stack_boundary() */;
2745 else if (!type_is_pkt_pointer(type) &&
2746 type != PTR_TO_MAP_VALUE &&
2747 type != expected_type)
2749 } else if (arg_type == ARG_CONST_SIZE ||
2750 arg_type == ARG_CONST_SIZE_OR_ZERO) {
2751 expected_type = SCALAR_VALUE;
2752 if (type != expected_type)
2754 } else if (arg_type == ARG_CONST_MAP_PTR) {
2755 expected_type = CONST_PTR_TO_MAP;
2756 if (type != expected_type)
2758 } else if (arg_type == ARG_PTR_TO_CTX) {
2759 expected_type = PTR_TO_CTX;
2760 if (type != expected_type)
2762 err = check_ctx_reg(env, reg, regno);
2765 } else if (arg_type == ARG_PTR_TO_SOCK_COMMON) {
2766 expected_type = PTR_TO_SOCK_COMMON;
2767 /* Any sk pointer can be ARG_PTR_TO_SOCK_COMMON */
2768 if (!type_is_sk_pointer(type))
2770 if (reg->ref_obj_id) {
2771 if (meta->ref_obj_id) {
2772 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
2773 regno, reg->ref_obj_id,
2777 meta->ref_obj_id = reg->ref_obj_id;
2779 } else if (arg_type == ARG_PTR_TO_SOCKET) {
2780 expected_type = PTR_TO_SOCKET;
2781 if (type != expected_type)
2783 } else if (arg_type == ARG_PTR_TO_SPIN_LOCK) {
2784 if (meta->func_id == BPF_FUNC_spin_lock) {
2785 if (process_spin_lock(env, regno, true))
2787 } else if (meta->func_id == BPF_FUNC_spin_unlock) {
2788 if (process_spin_lock(env, regno, false))
2791 verbose(env, "verifier internal error\n");
2794 } else if (arg_type_is_mem_ptr(arg_type)) {
2795 expected_type = PTR_TO_STACK;
2796 /* One exception here. In case function allows for NULL to be
2797 * passed in as argument, it's a SCALAR_VALUE type. Final test
2798 * happens during stack boundary checking.
2800 if (register_is_null(reg) &&
2801 arg_type == ARG_PTR_TO_MEM_OR_NULL)
2802 /* final test in check_stack_boundary() */;
2803 else if (!type_is_pkt_pointer(type) &&
2804 type != PTR_TO_MAP_VALUE &&
2805 type != expected_type)
2807 meta->raw_mode = arg_type == ARG_PTR_TO_UNINIT_MEM;
2808 } else if (arg_type_is_int_ptr(arg_type)) {
2809 expected_type = PTR_TO_STACK;
2810 if (!type_is_pkt_pointer(type) &&
2811 type != PTR_TO_MAP_VALUE &&
2812 type != expected_type)
2815 verbose(env, "unsupported arg_type %d\n", arg_type);
2819 if (arg_type == ARG_CONST_MAP_PTR) {
2820 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
2821 meta->map_ptr = reg->map_ptr;
2822 } else if (arg_type == ARG_PTR_TO_MAP_KEY) {
2823 /* bpf_map_xxx(..., map_ptr, ..., key) call:
2824 * check that [key, key + map->key_size) are within
2825 * stack limits and initialized
2827 if (!meta->map_ptr) {
2828 /* in function declaration map_ptr must come before
2829 * map_key, so that it's verified and known before
2830 * we have to check map_key here. Otherwise it means
2831 * that kernel subsystem misconfigured verifier
2833 verbose(env, "invalid map_ptr to access map->key\n");
2836 err = check_helper_mem_access(env, regno,
2837 meta->map_ptr->key_size, false,
2839 } else if (arg_type == ARG_PTR_TO_MAP_VALUE ||
2840 (arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL &&
2841 !register_is_null(reg)) ||
2842 arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE) {
2843 /* bpf_map_xxx(..., map_ptr, ..., value) call:
2844 * check [value, value + map->value_size) validity
2846 if (!meta->map_ptr) {
2847 /* kernel subsystem misconfigured verifier */
2848 verbose(env, "invalid map_ptr to access map->value\n");
2851 meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE);
2852 err = check_helper_mem_access(env, regno,
2853 meta->map_ptr->value_size, false,
2855 } else if (arg_type_is_mem_size(arg_type)) {
2856 bool zero_size_allowed = (arg_type == ARG_CONST_SIZE_OR_ZERO);
2858 /* remember the mem_size which may be used later
2859 * to refine return values.
2861 meta->msize_smax_value = reg->smax_value;
2862 meta->msize_umax_value = reg->umax_value;
2864 /* The register is SCALAR_VALUE; the access check
2865 * happens using its boundaries.
2867 if (!tnum_is_const(reg->var_off))
2868 /* For unprivileged variable accesses, disable raw
2869 * mode so that the program is required to
2870 * initialize all the memory that the helper could
2871 * just partially fill up.
2875 if (reg->smin_value < 0) {
2876 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
2881 if (reg->umin_value == 0) {
2882 err = check_helper_mem_access(env, regno - 1, 0,
2889 if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
2890 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
2894 err = check_helper_mem_access(env, regno - 1,
2896 zero_size_allowed, meta);
2897 } else if (arg_type_is_int_ptr(arg_type)) {
2898 int size = int_ptr_type_to_size(arg_type);
2900 err = check_helper_mem_access(env, regno, size, false, meta);
2903 err = check_ptr_alignment(env, reg, 0, size, true);
2908 verbose(env, "R%d type=%s expected=%s\n", regno,
2909 reg_type_str[type], reg_type_str[expected_type]);
2913 static int check_map_func_compatibility(struct bpf_verifier_env *env,
2914 struct bpf_map *map, int func_id)
2919 /* We need a two way check, first is from map perspective ... */
2920 switch (map->map_type) {
2921 case BPF_MAP_TYPE_PROG_ARRAY:
2922 if (func_id != BPF_FUNC_tail_call)
2925 case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
2926 if (func_id != BPF_FUNC_perf_event_read &&
2927 func_id != BPF_FUNC_perf_event_output &&
2928 func_id != BPF_FUNC_perf_event_read_value)
2931 case BPF_MAP_TYPE_STACK_TRACE:
2932 if (func_id != BPF_FUNC_get_stackid)
2935 case BPF_MAP_TYPE_CGROUP_ARRAY:
2936 if (func_id != BPF_FUNC_skb_under_cgroup &&
2937 func_id != BPF_FUNC_current_task_under_cgroup)
2940 case BPF_MAP_TYPE_CGROUP_STORAGE:
2941 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
2942 if (func_id != BPF_FUNC_get_local_storage)
2945 /* devmap returns a pointer to a live net_device ifindex that we cannot
2946 * allow to be modified from bpf side. So do not allow lookup elements
2949 case BPF_MAP_TYPE_DEVMAP:
2950 if (func_id != BPF_FUNC_redirect_map)
2953 /* Restrict bpf side of cpumap and xskmap, open when use-cases
2956 case BPF_MAP_TYPE_CPUMAP:
2957 if (func_id != BPF_FUNC_redirect_map)
2960 case BPF_MAP_TYPE_XSKMAP:
2961 if (func_id != BPF_FUNC_redirect_map &&
2962 func_id != BPF_FUNC_map_lookup_elem)
2965 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
2966 case BPF_MAP_TYPE_HASH_OF_MAPS:
2967 if (func_id != BPF_FUNC_map_lookup_elem)
2970 case BPF_MAP_TYPE_SOCKMAP:
2971 if (func_id != BPF_FUNC_sk_redirect_map &&
2972 func_id != BPF_FUNC_sock_map_update &&
2973 func_id != BPF_FUNC_map_delete_elem &&
2974 func_id != BPF_FUNC_msg_redirect_map)
2977 case BPF_MAP_TYPE_SOCKHASH:
2978 if (func_id != BPF_FUNC_sk_redirect_hash &&
2979 func_id != BPF_FUNC_sock_hash_update &&
2980 func_id != BPF_FUNC_map_delete_elem &&
2981 func_id != BPF_FUNC_msg_redirect_hash)
2984 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
2985 if (func_id != BPF_FUNC_sk_select_reuseport)
2988 case BPF_MAP_TYPE_QUEUE:
2989 case BPF_MAP_TYPE_STACK:
2990 if (func_id != BPF_FUNC_map_peek_elem &&
2991 func_id != BPF_FUNC_map_pop_elem &&
2992 func_id != BPF_FUNC_map_push_elem)
2995 case BPF_MAP_TYPE_SK_STORAGE:
2996 if (func_id != BPF_FUNC_sk_storage_get &&
2997 func_id != BPF_FUNC_sk_storage_delete)
3004 /* ... and second from the function itself. */
3006 case BPF_FUNC_tail_call:
3007 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
3009 if (env->subprog_cnt > 1) {
3010 verbose(env, "tail_calls are not allowed in programs with bpf-to-bpf calls\n");
3014 case BPF_FUNC_perf_event_read:
3015 case BPF_FUNC_perf_event_output:
3016 case BPF_FUNC_perf_event_read_value:
3017 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
3020 case BPF_FUNC_get_stackid:
3021 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
3024 case BPF_FUNC_current_task_under_cgroup:
3025 case BPF_FUNC_skb_under_cgroup:
3026 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
3029 case BPF_FUNC_redirect_map:
3030 if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
3031 map->map_type != BPF_MAP_TYPE_CPUMAP &&
3032 map->map_type != BPF_MAP_TYPE_XSKMAP)
3035 case BPF_FUNC_sk_redirect_map:
3036 case BPF_FUNC_msg_redirect_map:
3037 case BPF_FUNC_sock_map_update:
3038 if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
3041 case BPF_FUNC_sk_redirect_hash:
3042 case BPF_FUNC_msg_redirect_hash:
3043 case BPF_FUNC_sock_hash_update:
3044 if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
3047 case BPF_FUNC_get_local_storage:
3048 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
3049 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
3052 case BPF_FUNC_sk_select_reuseport:
3053 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY)
3056 case BPF_FUNC_map_peek_elem:
3057 case BPF_FUNC_map_pop_elem:
3058 case BPF_FUNC_map_push_elem:
3059 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
3060 map->map_type != BPF_MAP_TYPE_STACK)
3063 case BPF_FUNC_sk_storage_get:
3064 case BPF_FUNC_sk_storage_delete:
3065 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
3074 verbose(env, "cannot pass map_type %d into func %s#%d\n",
3075 map->map_type, func_id_name(func_id), func_id);
3079 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
3083 if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
3085 if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
3087 if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
3089 if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
3091 if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
3094 /* We only support one arg being in raw mode at the moment,
3095 * which is sufficient for the helper functions we have
3101 static bool check_args_pair_invalid(enum bpf_arg_type arg_curr,
3102 enum bpf_arg_type arg_next)
3104 return (arg_type_is_mem_ptr(arg_curr) &&
3105 !arg_type_is_mem_size(arg_next)) ||
3106 (!arg_type_is_mem_ptr(arg_curr) &&
3107 arg_type_is_mem_size(arg_next));
3110 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
3112 /* bpf_xxx(..., buf, len) call will access 'len'
3113 * bytes from memory 'buf'. Both arg types need
3114 * to be paired, so make sure there's no buggy
3115 * helper function specification.
3117 if (arg_type_is_mem_size(fn->arg1_type) ||
3118 arg_type_is_mem_ptr(fn->arg5_type) ||
3119 check_args_pair_invalid(fn->arg1_type, fn->arg2_type) ||
3120 check_args_pair_invalid(fn->arg2_type, fn->arg3_type) ||
3121 check_args_pair_invalid(fn->arg3_type, fn->arg4_type) ||
3122 check_args_pair_invalid(fn->arg4_type, fn->arg5_type))
3128 static bool check_refcount_ok(const struct bpf_func_proto *fn, int func_id)
3132 if (arg_type_may_be_refcounted(fn->arg1_type))
3134 if (arg_type_may_be_refcounted(fn->arg2_type))
3136 if (arg_type_may_be_refcounted(fn->arg3_type))
3138 if (arg_type_may_be_refcounted(fn->arg4_type))
3140 if (arg_type_may_be_refcounted(fn->arg5_type))
3143 /* A reference acquiring function cannot acquire
3144 * another refcounted ptr.
3146 if (is_acquire_function(func_id) && count)
3149 /* We only support one arg being unreferenced at the moment,
3150 * which is sufficient for the helper functions we have right now.
3155 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
3157 return check_raw_mode_ok(fn) &&
3158 check_arg_pair_ok(fn) &&
3159 check_refcount_ok(fn, func_id) ? 0 : -EINVAL;
3162 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
3163 * are now invalid, so turn them into unknown SCALAR_VALUE.
3165 static void __clear_all_pkt_pointers(struct bpf_verifier_env *env,
3166 struct bpf_func_state *state)
3168 struct bpf_reg_state *regs = state->regs, *reg;
3171 for (i = 0; i < MAX_BPF_REG; i++)
3172 if (reg_is_pkt_pointer_any(®s[i]))
3173 mark_reg_unknown(env, regs, i);
3175 bpf_for_each_spilled_reg(i, state, reg) {
3178 if (reg_is_pkt_pointer_any(reg))
3179 __mark_reg_unknown(reg);
3183 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
3185 struct bpf_verifier_state *vstate = env->cur_state;
3188 for (i = 0; i <= vstate->curframe; i++)
3189 __clear_all_pkt_pointers(env, vstate->frame[i]);
3192 static void release_reg_references(struct bpf_verifier_env *env,
3193 struct bpf_func_state *state,
3196 struct bpf_reg_state *regs = state->regs, *reg;
3199 for (i = 0; i < MAX_BPF_REG; i++)
3200 if (regs[i].ref_obj_id == ref_obj_id)
3201 mark_reg_unknown(env, regs, i);
3203 bpf_for_each_spilled_reg(i, state, reg) {
3206 if (reg->ref_obj_id == ref_obj_id)
3207 __mark_reg_unknown(reg);
3211 /* The pointer with the specified id has released its reference to kernel
3212 * resources. Identify all copies of the same pointer and clear the reference.
3214 static int release_reference(struct bpf_verifier_env *env,
3217 struct bpf_verifier_state *vstate = env->cur_state;
3221 err = release_reference_state(cur_func(env), ref_obj_id);
3225 for (i = 0; i <= vstate->curframe; i++)
3226 release_reg_references(env, vstate->frame[i], ref_obj_id);
3231 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
3234 struct bpf_verifier_state *state = env->cur_state;
3235 struct bpf_func_state *caller, *callee;
3236 int i, err, subprog, target_insn;
3238 if (state->curframe + 1 >= MAX_CALL_FRAMES) {
3239 verbose(env, "the call stack of %d frames is too deep\n",
3240 state->curframe + 2);
3244 target_insn = *insn_idx + insn->imm;
3245 subprog = find_subprog(env, target_insn + 1);
3247 verbose(env, "verifier bug. No program starts at insn %d\n",
3252 caller = state->frame[state->curframe];
3253 if (state->frame[state->curframe + 1]) {
3254 verbose(env, "verifier bug. Frame %d already allocated\n",
3255 state->curframe + 1);
3259 callee = kzalloc(sizeof(*callee), GFP_KERNEL);
3262 state->frame[state->curframe + 1] = callee;
3264 /* callee cannot access r0, r6 - r9 for reading and has to write
3265 * into its own stack before reading from it.
3266 * callee can read/write into caller's stack
3268 init_func_state(env, callee,
3269 /* remember the callsite, it will be used by bpf_exit */
3270 *insn_idx /* callsite */,
3271 state->curframe + 1 /* frameno within this callchain */,
3272 subprog /* subprog number within this prog */);
3274 /* Transfer references to the callee */
3275 err = transfer_reference_state(callee, caller);
3279 /* copy r1 - r5 args that callee can access. The copy includes parent
3280 * pointers, which connects us up to the liveness chain
3282 for (i = BPF_REG_1; i <= BPF_REG_5; i++)
3283 callee->regs[i] = caller->regs[i];
3285 /* after the call registers r0 - r5 were scratched */
3286 for (i = 0; i < CALLER_SAVED_REGS; i++) {
3287 mark_reg_not_init(env, caller->regs, caller_saved[i]);
3288 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
3291 /* only increment it after check_reg_arg() finished */
3294 /* and go analyze first insn of the callee */
3295 *insn_idx = target_insn;
3297 if (env->log.level & BPF_LOG_LEVEL) {
3298 verbose(env, "caller:\n");
3299 print_verifier_state(env, caller);
3300 verbose(env, "callee:\n");
3301 print_verifier_state(env, callee);
3306 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
3308 struct bpf_verifier_state *state = env->cur_state;
3309 struct bpf_func_state *caller, *callee;
3310 struct bpf_reg_state *r0;
3313 callee = state->frame[state->curframe];
3314 r0 = &callee->regs[BPF_REG_0];
3315 if (r0->type == PTR_TO_STACK) {
3316 /* technically it's ok to return caller's stack pointer
3317 * (or caller's caller's pointer) back to the caller,
3318 * since these pointers are valid. Only current stack
3319 * pointer will be invalid as soon as function exits,
3320 * but let's be conservative
3322 verbose(env, "cannot return stack pointer to the caller\n");
3327 caller = state->frame[state->curframe];
3328 /* return to the caller whatever r0 had in the callee */
3329 caller->regs[BPF_REG_0] = *r0;
3331 /* Transfer references to the caller */
3332 err = transfer_reference_state(caller, callee);
3336 *insn_idx = callee->callsite + 1;
3337 if (env->log.level & BPF_LOG_LEVEL) {
3338 verbose(env, "returning from callee:\n");
3339 print_verifier_state(env, callee);
3340 verbose(env, "to caller at %d:\n", *insn_idx);
3341 print_verifier_state(env, caller);
3343 /* clear everything in the callee */
3344 free_func_state(callee);
3345 state->frame[state->curframe + 1] = NULL;
3349 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
3351 struct bpf_call_arg_meta *meta)
3353 struct bpf_reg_state *ret_reg = ®s[BPF_REG_0];
3355 if (ret_type != RET_INTEGER ||
3356 (func_id != BPF_FUNC_get_stack &&
3357 func_id != BPF_FUNC_probe_read_str))
3360 ret_reg->smax_value = meta->msize_smax_value;
3361 ret_reg->umax_value = meta->msize_umax_value;
3362 __reg_deduce_bounds(ret_reg);
3363 __reg_bound_offset(ret_reg);
3367 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
3368 int func_id, int insn_idx)
3370 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
3371 struct bpf_map *map = meta->map_ptr;
3373 if (func_id != BPF_FUNC_tail_call &&
3374 func_id != BPF_FUNC_map_lookup_elem &&
3375 func_id != BPF_FUNC_map_update_elem &&
3376 func_id != BPF_FUNC_map_delete_elem &&
3377 func_id != BPF_FUNC_map_push_elem &&
3378 func_id != BPF_FUNC_map_pop_elem &&
3379 func_id != BPF_FUNC_map_peek_elem)
3383 verbose(env, "kernel subsystem misconfigured verifier\n");
3387 /* In case of read-only, some additional restrictions
3388 * need to be applied in order to prevent altering the
3389 * state of the map from program side.
3391 if ((map->map_flags & BPF_F_RDONLY_PROG) &&
3392 (func_id == BPF_FUNC_map_delete_elem ||
3393 func_id == BPF_FUNC_map_update_elem ||
3394 func_id == BPF_FUNC_map_push_elem ||
3395 func_id == BPF_FUNC_map_pop_elem)) {
3396 verbose(env, "write into map forbidden\n");
3400 if (!BPF_MAP_PTR(aux->map_state))
3401 bpf_map_ptr_store(aux, meta->map_ptr,
3402 meta->map_ptr->unpriv_array);
3403 else if (BPF_MAP_PTR(aux->map_state) != meta->map_ptr)
3404 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
3405 meta->map_ptr->unpriv_array);
3409 static int check_reference_leak(struct bpf_verifier_env *env)
3411 struct bpf_func_state *state = cur_func(env);
3414 for (i = 0; i < state->acquired_refs; i++) {
3415 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
3416 state->refs[i].id, state->refs[i].insn_idx);
3418 return state->acquired_refs ? -EINVAL : 0;
3421 static int check_helper_call(struct bpf_verifier_env *env, int func_id, int insn_idx)
3423 const struct bpf_func_proto *fn = NULL;
3424 struct bpf_reg_state *regs;
3425 struct bpf_call_arg_meta meta;
3429 /* find function prototype */
3430 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
3431 verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
3436 if (env->ops->get_func_proto)
3437 fn = env->ops->get_func_proto(func_id, env->prog);
3439 verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
3444 /* eBPF programs must be GPL compatible to use GPL-ed functions */
3445 if (!env->prog->gpl_compatible && fn->gpl_only) {
3446 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
3450 /* With LD_ABS/IND some JITs save/restore skb from r1. */
3451 changes_data = bpf_helper_changes_pkt_data(fn->func);
3452 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
3453 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
3454 func_id_name(func_id), func_id);
3458 memset(&meta, 0, sizeof(meta));
3459 meta.pkt_access = fn->pkt_access;
3461 err = check_func_proto(fn, func_id);
3463 verbose(env, "kernel subsystem misconfigured func %s#%d\n",
3464 func_id_name(func_id), func_id);
3468 meta.func_id = func_id;
3470 err = check_func_arg(env, BPF_REG_1, fn->arg1_type, &meta);
3473 err = check_func_arg(env, BPF_REG_2, fn->arg2_type, &meta);
3476 err = check_func_arg(env, BPF_REG_3, fn->arg3_type, &meta);
3479 err = check_func_arg(env, BPF_REG_4, fn->arg4_type, &meta);
3482 err = check_func_arg(env, BPF_REG_5, fn->arg5_type, &meta);
3486 err = record_func_map(env, &meta, func_id, insn_idx);
3490 /* Mark slots with STACK_MISC in case of raw mode, stack offset
3491 * is inferred from register state.
3493 for (i = 0; i < meta.access_size; i++) {
3494 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
3495 BPF_WRITE, -1, false);
3500 if (func_id == BPF_FUNC_tail_call) {
3501 err = check_reference_leak(env);
3503 verbose(env, "tail_call would lead to reference leak\n");
3506 } else if (is_release_function(func_id)) {
3507 err = release_reference(env, meta.ref_obj_id);
3509 verbose(env, "func %s#%d reference has not been acquired before\n",
3510 func_id_name(func_id), func_id);
3515 regs = cur_regs(env);
3517 /* check that flags argument in get_local_storage(map, flags) is 0,
3518 * this is required because get_local_storage() can't return an error.
3520 if (func_id == BPF_FUNC_get_local_storage &&
3521 !register_is_null(®s[BPF_REG_2])) {
3522 verbose(env, "get_local_storage() doesn't support non-zero flags\n");
3526 /* reset caller saved regs */
3527 for (i = 0; i < CALLER_SAVED_REGS; i++) {
3528 mark_reg_not_init(env, regs, caller_saved[i]);
3529 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
3532 /* helper call returns 64-bit value. */
3533 regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
3535 /* update return register (already marked as written above) */
3536 if (fn->ret_type == RET_INTEGER) {
3537 /* sets type to SCALAR_VALUE */
3538 mark_reg_unknown(env, regs, BPF_REG_0);
3539 } else if (fn->ret_type == RET_VOID) {
3540 regs[BPF_REG_0].type = NOT_INIT;
3541 } else if (fn->ret_type == RET_PTR_TO_MAP_VALUE_OR_NULL ||
3542 fn->ret_type == RET_PTR_TO_MAP_VALUE) {
3543 /* There is no offset yet applied, variable or fixed */
3544 mark_reg_known_zero(env, regs, BPF_REG_0);
3545 /* remember map_ptr, so that check_map_access()
3546 * can check 'value_size' boundary of memory access
3547 * to map element returned from bpf_map_lookup_elem()
3549 if (meta.map_ptr == NULL) {
3551 "kernel subsystem misconfigured verifier\n");
3554 regs[BPF_REG_0].map_ptr = meta.map_ptr;
3555 if (fn->ret_type == RET_PTR_TO_MAP_VALUE) {
3556 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE;
3557 if (map_value_has_spin_lock(meta.map_ptr))
3558 regs[BPF_REG_0].id = ++env->id_gen;
3560 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE_OR_NULL;
3561 regs[BPF_REG_0].id = ++env->id_gen;
3563 } else if (fn->ret_type == RET_PTR_TO_SOCKET_OR_NULL) {
3564 mark_reg_known_zero(env, regs, BPF_REG_0);
3565 regs[BPF_REG_0].type = PTR_TO_SOCKET_OR_NULL;
3566 regs[BPF_REG_0].id = ++env->id_gen;
3567 } else if (fn->ret_type == RET_PTR_TO_SOCK_COMMON_OR_NULL) {
3568 mark_reg_known_zero(env, regs, BPF_REG_0);
3569 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON_OR_NULL;
3570 regs[BPF_REG_0].id = ++env->id_gen;
3571 } else if (fn->ret_type == RET_PTR_TO_TCP_SOCK_OR_NULL) {
3572 mark_reg_known_zero(env, regs, BPF_REG_0);
3573 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK_OR_NULL;
3574 regs[BPF_REG_0].id = ++env->id_gen;
3576 verbose(env, "unknown return type %d of func %s#%d\n",
3577 fn->ret_type, func_id_name(func_id), func_id);
3581 if (is_ptr_cast_function(func_id)) {
3582 /* For release_reference() */
3583 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
3584 } else if (is_acquire_function(func_id)) {
3585 int id = acquire_reference_state(env, insn_idx);
3589 /* For mark_ptr_or_null_reg() */
3590 regs[BPF_REG_0].id = id;
3591 /* For release_reference() */
3592 regs[BPF_REG_0].ref_obj_id = id;
3595 do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
3597 err = check_map_func_compatibility(env, meta.map_ptr, func_id);
3601 if (func_id == BPF_FUNC_get_stack && !env->prog->has_callchain_buf) {
3602 const char *err_str;
3604 #ifdef CONFIG_PERF_EVENTS
3605 err = get_callchain_buffers(sysctl_perf_event_max_stack);
3606 err_str = "cannot get callchain buffer for func %s#%d\n";
3609 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
3612 verbose(env, err_str, func_id_name(func_id), func_id);
3616 env->prog->has_callchain_buf = true;
3620 clear_all_pkt_pointers(env);
3624 static bool signed_add_overflows(s64 a, s64 b)
3626 /* Do the add in u64, where overflow is well-defined */
3627 s64 res = (s64)((u64)a + (u64)b);
3634 static bool signed_sub_overflows(s64 a, s64 b)
3636 /* Do the sub in u64, where overflow is well-defined */
3637 s64 res = (s64)((u64)a - (u64)b);
3644 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
3645 const struct bpf_reg_state *reg,
3646 enum bpf_reg_type type)
3648 bool known = tnum_is_const(reg->var_off);
3649 s64 val = reg->var_off.value;
3650 s64 smin = reg->smin_value;
3652 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
3653 verbose(env, "math between %s pointer and %lld is not allowed\n",
3654 reg_type_str[type], val);
3658 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
3659 verbose(env, "%s pointer offset %d is not allowed\n",
3660 reg_type_str[type], reg->off);
3664 if (smin == S64_MIN) {
3665 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
3666 reg_type_str[type]);
3670 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
3671 verbose(env, "value %lld makes %s pointer be out of bounds\n",
3672 smin, reg_type_str[type]);
3679 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
3681 return &env->insn_aux_data[env->insn_idx];
3684 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
3685 u32 *ptr_limit, u8 opcode, bool off_is_neg)
3687 bool mask_to_left = (opcode == BPF_ADD && off_is_neg) ||
3688 (opcode == BPF_SUB && !off_is_neg);
3691 switch (ptr_reg->type) {
3693 /* Indirect variable offset stack access is prohibited in
3694 * unprivileged mode so it's not handled here.
3696 off = ptr_reg->off + ptr_reg->var_off.value;
3698 *ptr_limit = MAX_BPF_STACK + off;
3702 case PTR_TO_MAP_VALUE:
3704 *ptr_limit = ptr_reg->umax_value + ptr_reg->off;
3706 off = ptr_reg->smin_value + ptr_reg->off;
3707 *ptr_limit = ptr_reg->map_ptr->value_size - off;
3715 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
3716 const struct bpf_insn *insn)
3718 return env->allow_ptr_leaks || BPF_SRC(insn->code) == BPF_K;
3721 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
3722 u32 alu_state, u32 alu_limit)
3724 /* If we arrived here from different branches with different
3725 * state or limits to sanitize, then this won't work.
3727 if (aux->alu_state &&
3728 (aux->alu_state != alu_state ||
3729 aux->alu_limit != alu_limit))
3732 /* Corresponding fixup done in fixup_bpf_calls(). */
3733 aux->alu_state = alu_state;
3734 aux->alu_limit = alu_limit;
3738 static int sanitize_val_alu(struct bpf_verifier_env *env,
3739 struct bpf_insn *insn)
3741 struct bpf_insn_aux_data *aux = cur_aux(env);
3743 if (can_skip_alu_sanitation(env, insn))
3746 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
3749 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
3750 struct bpf_insn *insn,
3751 const struct bpf_reg_state *ptr_reg,
3752 struct bpf_reg_state *dst_reg,
3755 struct bpf_verifier_state *vstate = env->cur_state;
3756 struct bpf_insn_aux_data *aux = cur_aux(env);
3757 bool ptr_is_dst_reg = ptr_reg == dst_reg;
3758 u8 opcode = BPF_OP(insn->code);
3759 u32 alu_state, alu_limit;
3760 struct bpf_reg_state tmp;
3763 if (can_skip_alu_sanitation(env, insn))
3766 /* We already marked aux for masking from non-speculative
3767 * paths, thus we got here in the first place. We only care
3768 * to explore bad access from here.
3770 if (vstate->speculative)
3773 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
3774 alu_state |= ptr_is_dst_reg ?
3775 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
3777 if (retrieve_ptr_limit(ptr_reg, &alu_limit, opcode, off_is_neg))
3779 if (update_alu_sanitation_state(aux, alu_state, alu_limit))
3782 /* Simulate and find potential out-of-bounds access under
3783 * speculative execution from truncation as a result of
3784 * masking when off was not within expected range. If off
3785 * sits in dst, then we temporarily need to move ptr there
3786 * to simulate dst (== 0) +/-= ptr. Needed, for example,
3787 * for cases where we use K-based arithmetic in one direction
3788 * and truncated reg-based in the other in order to explore
3791 if (!ptr_is_dst_reg) {
3793 *dst_reg = *ptr_reg;
3795 ret = push_stack(env, env->insn_idx + 1, env->insn_idx, true);
3796 if (!ptr_is_dst_reg && ret)
3798 return !ret ? -EFAULT : 0;
3801 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
3802 * Caller should also handle BPF_MOV case separately.
3803 * If we return -EACCES, caller may want to try again treating pointer as a
3804 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks.
3806 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
3807 struct bpf_insn *insn,
3808 const struct bpf_reg_state *ptr_reg,
3809 const struct bpf_reg_state *off_reg)
3811 struct bpf_verifier_state *vstate = env->cur_state;
3812 struct bpf_func_state *state = vstate->frame[vstate->curframe];
3813 struct bpf_reg_state *regs = state->regs, *dst_reg;
3814 bool known = tnum_is_const(off_reg->var_off);
3815 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
3816 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
3817 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
3818 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
3819 u32 dst = insn->dst_reg, src = insn->src_reg;
3820 u8 opcode = BPF_OP(insn->code);
3823 dst_reg = ®s[dst];
3825 if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
3826 smin_val > smax_val || umin_val > umax_val) {
3827 /* Taint dst register if offset had invalid bounds derived from
3828 * e.g. dead branches.
3830 __mark_reg_unknown(dst_reg);
3834 if (BPF_CLASS(insn->code) != BPF_ALU64) {
3835 /* 32-bit ALU ops on pointers produce (meaningless) scalars */
3837 "R%d 32-bit pointer arithmetic prohibited\n",
3842 switch (ptr_reg->type) {
3843 case PTR_TO_MAP_VALUE_OR_NULL:
3844 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
3845 dst, reg_type_str[ptr_reg->type]);
3847 case CONST_PTR_TO_MAP:
3848 case PTR_TO_PACKET_END:
3850 case PTR_TO_SOCKET_OR_NULL:
3851 case PTR_TO_SOCK_COMMON:
3852 case PTR_TO_SOCK_COMMON_OR_NULL:
3853 case PTR_TO_TCP_SOCK:
3854 case PTR_TO_TCP_SOCK_OR_NULL:
3855 case PTR_TO_XDP_SOCK:
3856 verbose(env, "R%d pointer arithmetic on %s prohibited\n",
3857 dst, reg_type_str[ptr_reg->type]);
3859 case PTR_TO_MAP_VALUE:
3860 if (!env->allow_ptr_leaks && !known && (smin_val < 0) != (smax_val < 0)) {
3861 verbose(env, "R%d has unknown scalar with mixed signed bounds, pointer arithmetic with it prohibited for !root\n",
3862 off_reg == dst_reg ? dst : src);
3870 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
3871 * The id may be overwritten later if we create a new variable offset.
3873 dst_reg->type = ptr_reg->type;
3874 dst_reg->id = ptr_reg->id;
3876 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
3877 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
3882 ret = sanitize_ptr_alu(env, insn, ptr_reg, dst_reg, smin_val < 0);
3884 verbose(env, "R%d tried to add from different maps or paths\n", dst);
3887 /* We can take a fixed offset as long as it doesn't overflow
3888 * the s32 'off' field
3890 if (known && (ptr_reg->off + smin_val ==
3891 (s64)(s32)(ptr_reg->off + smin_val))) {
3892 /* pointer += K. Accumulate it into fixed offset */
3893 dst_reg->smin_value = smin_ptr;
3894 dst_reg->smax_value = smax_ptr;
3895 dst_reg->umin_value = umin_ptr;
3896 dst_reg->umax_value = umax_ptr;
3897 dst_reg->var_off = ptr_reg->var_off;
3898 dst_reg->off = ptr_reg->off + smin_val;
3899 dst_reg->raw = ptr_reg->raw;
3902 /* A new variable offset is created. Note that off_reg->off
3903 * == 0, since it's a scalar.
3904 * dst_reg gets the pointer type and since some positive
3905 * integer value was added to the pointer, give it a new 'id'
3906 * if it's a PTR_TO_PACKET.
3907 * this creates a new 'base' pointer, off_reg (variable) gets
3908 * added into the variable offset, and we copy the fixed offset
3911 if (signed_add_overflows(smin_ptr, smin_val) ||
3912 signed_add_overflows(smax_ptr, smax_val)) {
3913 dst_reg->smin_value = S64_MIN;
3914 dst_reg->smax_value = S64_MAX;
3916 dst_reg->smin_value = smin_ptr + smin_val;
3917 dst_reg->smax_value = smax_ptr + smax_val;
3919 if (umin_ptr + umin_val < umin_ptr ||
3920 umax_ptr + umax_val < umax_ptr) {
3921 dst_reg->umin_value = 0;
3922 dst_reg->umax_value = U64_MAX;
3924 dst_reg->umin_value = umin_ptr + umin_val;
3925 dst_reg->umax_value = umax_ptr + umax_val;
3927 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
3928 dst_reg->off = ptr_reg->off;
3929 dst_reg->raw = ptr_reg->raw;
3930 if (reg_is_pkt_pointer(ptr_reg)) {
3931 dst_reg->id = ++env->id_gen;
3932 /* something was added to pkt_ptr, set range to zero */
3937 ret = sanitize_ptr_alu(env, insn, ptr_reg, dst_reg, smin_val < 0);
3939 verbose(env, "R%d tried to sub from different maps or paths\n", dst);
3942 if (dst_reg == off_reg) {
3943 /* scalar -= pointer. Creates an unknown scalar */
3944 verbose(env, "R%d tried to subtract pointer from scalar\n",
3948 /* We don't allow subtraction from FP, because (according to
3949 * test_verifier.c test "invalid fp arithmetic", JITs might not
3950 * be able to deal with it.
3952 if (ptr_reg->type == PTR_TO_STACK) {
3953 verbose(env, "R%d subtraction from stack pointer prohibited\n",
3957 if (known && (ptr_reg->off - smin_val ==
3958 (s64)(s32)(ptr_reg->off - smin_val))) {
3959 /* pointer -= K. Subtract it from fixed offset */
3960 dst_reg->smin_value = smin_ptr;
3961 dst_reg->smax_value = smax_ptr;
3962 dst_reg->umin_value = umin_ptr;
3963 dst_reg->umax_value = umax_ptr;
3964 dst_reg->var_off = ptr_reg->var_off;
3965 dst_reg->id = ptr_reg->id;
3966 dst_reg->off = ptr_reg->off - smin_val;
3967 dst_reg->raw = ptr_reg->raw;
3970 /* A new variable offset is created. If the subtrahend is known
3971 * nonnegative, then any reg->range we had before is still good.
3973 if (signed_sub_overflows(smin_ptr, smax_val) ||
3974 signed_sub_overflows(smax_ptr, smin_val)) {
3975 /* Overflow possible, we know nothing */
3976 dst_reg->smin_value = S64_MIN;
3977 dst_reg->smax_value = S64_MAX;
3979 dst_reg->smin_value = smin_ptr - smax_val;
3980 dst_reg->smax_value = smax_ptr - smin_val;
3982 if (umin_ptr < umax_val) {
3983 /* Overflow possible, we know nothing */
3984 dst_reg->umin_value = 0;
3985 dst_reg->umax_value = U64_MAX;
3987 /* Cannot overflow (as long as bounds are consistent) */
3988 dst_reg->umin_value = umin_ptr - umax_val;
3989 dst_reg->umax_value = umax_ptr - umin_val;
3991 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
3992 dst_reg->off = ptr_reg->off;
3993 dst_reg->raw = ptr_reg->raw;
3994 if (reg_is_pkt_pointer(ptr_reg)) {
3995 dst_reg->id = ++env->id_gen;
3996 /* something was added to pkt_ptr, set range to zero */
4004 /* bitwise ops on pointers are troublesome, prohibit. */
4005 verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
4006 dst, bpf_alu_string[opcode >> 4]);
4009 /* other operators (e.g. MUL,LSH) produce non-pointer results */
4010 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
4011 dst, bpf_alu_string[opcode >> 4]);
4015 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
4018 __update_reg_bounds(dst_reg);
4019 __reg_deduce_bounds(dst_reg);
4020 __reg_bound_offset(dst_reg);
4022 /* For unprivileged we require that resulting offset must be in bounds
4023 * in order to be able to sanitize access later on.
4025 if (!env->allow_ptr_leaks) {
4026 if (dst_reg->type == PTR_TO_MAP_VALUE &&
4027 check_map_access(env, dst, dst_reg->off, 1, false)) {
4028 verbose(env, "R%d pointer arithmetic of map value goes out of range, "
4029 "prohibited for !root\n", dst);
4031 } else if (dst_reg->type == PTR_TO_STACK &&
4032 check_stack_access(env, dst_reg, dst_reg->off +
4033 dst_reg->var_off.value, 1)) {
4034 verbose(env, "R%d stack pointer arithmetic goes out of range, "
4035 "prohibited for !root\n", dst);
4043 /* WARNING: This function does calculations on 64-bit values, but the actual
4044 * execution may occur on 32-bit values. Therefore, things like bitshifts
4045 * need extra checks in the 32-bit case.
4047 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
4048 struct bpf_insn *insn,
4049 struct bpf_reg_state *dst_reg,
4050 struct bpf_reg_state src_reg)
4052 struct bpf_reg_state *regs = cur_regs(env);
4053 u8 opcode = BPF_OP(insn->code);
4054 bool src_known, dst_known;
4055 s64 smin_val, smax_val;
4056 u64 umin_val, umax_val;
4057 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
4058 u32 dst = insn->dst_reg;
4061 if (insn_bitness == 32) {
4062 /* Relevant for 32-bit RSH: Information can propagate towards
4063 * LSB, so it isn't sufficient to only truncate the output to
4066 coerce_reg_to_size(dst_reg, 4);
4067 coerce_reg_to_size(&src_reg, 4);
4070 smin_val = src_reg.smin_value;
4071 smax_val = src_reg.smax_value;
4072 umin_val = src_reg.umin_value;
4073 umax_val = src_reg.umax_value;
4074 src_known = tnum_is_const(src_reg.var_off);
4075 dst_known = tnum_is_const(dst_reg->var_off);
4077 if ((src_known && (smin_val != smax_val || umin_val != umax_val)) ||
4078 smin_val > smax_val || umin_val > umax_val) {
4079 /* Taint dst register if offset had invalid bounds derived from
4080 * e.g. dead branches.
4082 __mark_reg_unknown(dst_reg);
4087 opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
4088 __mark_reg_unknown(dst_reg);
4094 ret = sanitize_val_alu(env, insn);
4096 verbose(env, "R%d tried to add from different pointers or scalars\n", dst);
4099 if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
4100 signed_add_overflows(dst_reg->smax_value, smax_val)) {
4101 dst_reg->smin_value = S64_MIN;
4102 dst_reg->smax_value = S64_MAX;
4104 dst_reg->smin_value += smin_val;
4105 dst_reg->smax_value += smax_val;
4107 if (dst_reg->umin_value + umin_val < umin_val ||
4108 dst_reg->umax_value + umax_val < umax_val) {
4109 dst_reg->umin_value = 0;
4110 dst_reg->umax_value = U64_MAX;
4112 dst_reg->umin_value += umin_val;
4113 dst_reg->umax_value += umax_val;
4115 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
4118 ret = sanitize_val_alu(env, insn);
4120 verbose(env, "R%d tried to sub from different pointers or scalars\n", dst);
4123 if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
4124 signed_sub_overflows(dst_reg->smax_value, smin_val)) {
4125 /* Overflow possible, we know nothing */
4126 dst_reg->smin_value = S64_MIN;
4127 dst_reg->smax_value = S64_MAX;
4129 dst_reg->smin_value -= smax_val;
4130 dst_reg->smax_value -= smin_val;
4132 if (dst_reg->umin_value < umax_val) {
4133 /* Overflow possible, we know nothing */
4134 dst_reg->umin_value = 0;
4135 dst_reg->umax_value = U64_MAX;
4137 /* Cannot overflow (as long as bounds are consistent) */
4138 dst_reg->umin_value -= umax_val;
4139 dst_reg->umax_value -= umin_val;
4141 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
4144 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
4145 if (smin_val < 0 || dst_reg->smin_value < 0) {
4146 /* Ain't nobody got time to multiply that sign */
4147 __mark_reg_unbounded(dst_reg);
4148 __update_reg_bounds(dst_reg);
4151 /* Both values are positive, so we can work with unsigned and
4152 * copy the result to signed (unless it exceeds S64_MAX).
4154 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
4155 /* Potential overflow, we know nothing */
4156 __mark_reg_unbounded(dst_reg);
4157 /* (except what we can learn from the var_off) */
4158 __update_reg_bounds(dst_reg);
4161 dst_reg->umin_value *= umin_val;
4162 dst_reg->umax_value *= umax_val;
4163 if (dst_reg->umax_value > S64_MAX) {
4164 /* Overflow possible, we know nothing */
4165 dst_reg->smin_value = S64_MIN;
4166 dst_reg->smax_value = S64_MAX;
4168 dst_reg->smin_value = dst_reg->umin_value;
4169 dst_reg->smax_value = dst_reg->umax_value;
4173 if (src_known && dst_known) {
4174 __mark_reg_known(dst_reg, dst_reg->var_off.value &
4175 src_reg.var_off.value);
4178 /* We get our minimum from the var_off, since that's inherently
4179 * bitwise. Our maximum is the minimum of the operands' maxima.
4181 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
4182 dst_reg->umin_value = dst_reg->var_off.value;
4183 dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
4184 if (dst_reg->smin_value < 0 || smin_val < 0) {
4185 /* Lose signed bounds when ANDing negative numbers,
4186 * ain't nobody got time for that.
4188 dst_reg->smin_value = S64_MIN;
4189 dst_reg->smax_value = S64_MAX;
4191 /* ANDing two positives gives a positive, so safe to
4192 * cast result into s64.
4194 dst_reg->smin_value = dst_reg->umin_value;
4195 dst_reg->smax_value = dst_reg->umax_value;
4197 /* We may learn something more from the var_off */
4198 __update_reg_bounds(dst_reg);
4201 if (src_known && dst_known) {
4202 __mark_reg_known(dst_reg, dst_reg->var_off.value |
4203 src_reg.var_off.value);
4206 /* We get our maximum from the var_off, and our minimum is the
4207 * maximum of the operands' minima
4209 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
4210 dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
4211 dst_reg->umax_value = dst_reg->var_off.value |
4212 dst_reg->var_off.mask;
4213 if (dst_reg->smin_value < 0 || smin_val < 0) {
4214 /* Lose signed bounds when ORing negative numbers,
4215 * ain't nobody got time for that.
4217 dst_reg->smin_value = S64_MIN;
4218 dst_reg->smax_value = S64_MAX;
4220 /* ORing two positives gives a positive, so safe to
4221 * cast result into s64.
4223 dst_reg->smin_value = dst_reg->umin_value;
4224 dst_reg->smax_value = dst_reg->umax_value;
4226 /* We may learn something more from the var_off */
4227 __update_reg_bounds(dst_reg);
4230 if (umax_val >= insn_bitness) {
4231 /* Shifts greater than 31 or 63 are undefined.
4232 * This includes shifts by a negative number.
4234 mark_reg_unknown(env, regs, insn->dst_reg);
4237 /* We lose all sign bit information (except what we can pick
4240 dst_reg->smin_value = S64_MIN;
4241 dst_reg->smax_value = S64_MAX;
4242 /* If we might shift our top bit out, then we know nothing */
4243 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
4244 dst_reg->umin_value = 0;
4245 dst_reg->umax_value = U64_MAX;
4247 dst_reg->umin_value <<= umin_val;
4248 dst_reg->umax_value <<= umax_val;
4250 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
4251 /* We may learn something more from the var_off */
4252 __update_reg_bounds(dst_reg);
4255 if (umax_val >= insn_bitness) {
4256 /* Shifts greater than 31 or 63 are undefined.
4257 * This includes shifts by a negative number.
4259 mark_reg_unknown(env, regs, insn->dst_reg);
4262 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
4263 * be negative, then either:
4264 * 1) src_reg might be zero, so the sign bit of the result is
4265 * unknown, so we lose our signed bounds
4266 * 2) it's known negative, thus the unsigned bounds capture the
4268 * 3) the signed bounds cross zero, so they tell us nothing
4270 * If the value in dst_reg is known nonnegative, then again the
4271 * unsigned bounts capture the signed bounds.
4272 * Thus, in all cases it suffices to blow away our signed bounds
4273 * and rely on inferring new ones from the unsigned bounds and
4274 * var_off of the result.
4276 dst_reg->smin_value = S64_MIN;
4277 dst_reg->smax_value = S64_MAX;
4278 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
4279 dst_reg->umin_value >>= umax_val;
4280 dst_reg->umax_value >>= umin_val;
4281 /* We may learn something more from the var_off */
4282 __update_reg_bounds(dst_reg);
4285 if (umax_val >= insn_bitness) {
4286 /* Shifts greater than 31 or 63 are undefined.
4287 * This includes shifts by a negative number.
4289 mark_reg_unknown(env, regs, insn->dst_reg);
4293 /* Upon reaching here, src_known is true and
4294 * umax_val is equal to umin_val.
4296 dst_reg->smin_value >>= umin_val;
4297 dst_reg->smax_value >>= umin_val;
4298 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val);
4300 /* blow away the dst_reg umin_value/umax_value and rely on
4301 * dst_reg var_off to refine the result.
4303 dst_reg->umin_value = 0;
4304 dst_reg->umax_value = U64_MAX;
4305 __update_reg_bounds(dst_reg);
4308 mark_reg_unknown(env, regs, insn->dst_reg);
4312 if (BPF_CLASS(insn->code) != BPF_ALU64) {
4313 /* 32-bit ALU ops are (32,32)->32 */
4314 coerce_reg_to_size(dst_reg, 4);
4317 __reg_deduce_bounds(dst_reg);
4318 __reg_bound_offset(dst_reg);
4322 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
4325 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
4326 struct bpf_insn *insn)
4328 struct bpf_verifier_state *vstate = env->cur_state;
4329 struct bpf_func_state *state = vstate->frame[vstate->curframe];
4330 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
4331 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
4332 u8 opcode = BPF_OP(insn->code);
4334 dst_reg = ®s[insn->dst_reg];
4336 if (dst_reg->type != SCALAR_VALUE)
4338 if (BPF_SRC(insn->code) == BPF_X) {
4339 src_reg = ®s[insn->src_reg];
4340 if (src_reg->type != SCALAR_VALUE) {
4341 if (dst_reg->type != SCALAR_VALUE) {
4342 /* Combining two pointers by any ALU op yields
4343 * an arbitrary scalar. Disallow all math except
4344 * pointer subtraction
4346 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
4347 mark_reg_unknown(env, regs, insn->dst_reg);
4350 verbose(env, "R%d pointer %s pointer prohibited\n",
4352 bpf_alu_string[opcode >> 4]);
4355 /* scalar += pointer
4356 * This is legal, but we have to reverse our
4357 * src/dest handling in computing the range
4359 return adjust_ptr_min_max_vals(env, insn,
4362 } else if (ptr_reg) {
4363 /* pointer += scalar */
4364 return adjust_ptr_min_max_vals(env, insn,
4368 /* Pretend the src is a reg with a known value, since we only
4369 * need to be able to read from this state.
4371 off_reg.type = SCALAR_VALUE;
4372 __mark_reg_known(&off_reg, insn->imm);
4374 if (ptr_reg) /* pointer += K */
4375 return adjust_ptr_min_max_vals(env, insn,
4379 /* Got here implies adding two SCALAR_VALUEs */
4380 if (WARN_ON_ONCE(ptr_reg)) {
4381 print_verifier_state(env, state);
4382 verbose(env, "verifier internal error: unexpected ptr_reg\n");
4385 if (WARN_ON(!src_reg)) {
4386 print_verifier_state(env, state);
4387 verbose(env, "verifier internal error: no src_reg\n");
4390 return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
4393 /* check validity of 32-bit and 64-bit arithmetic operations */
4394 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
4396 struct bpf_reg_state *regs = cur_regs(env);
4397 u8 opcode = BPF_OP(insn->code);
4400 if (opcode == BPF_END || opcode == BPF_NEG) {
4401 if (opcode == BPF_NEG) {
4402 if (BPF_SRC(insn->code) != 0 ||
4403 insn->src_reg != BPF_REG_0 ||
4404 insn->off != 0 || insn->imm != 0) {
4405 verbose(env, "BPF_NEG uses reserved fields\n");
4409 if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
4410 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
4411 BPF_CLASS(insn->code) == BPF_ALU64) {
4412 verbose(env, "BPF_END uses reserved fields\n");
4417 /* check src operand */
4418 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
4422 if (is_pointer_value(env, insn->dst_reg)) {
4423 verbose(env, "R%d pointer arithmetic prohibited\n",
4428 /* check dest operand */
4429 err = check_reg_arg(env, insn->dst_reg, DST_OP);
4433 } else if (opcode == BPF_MOV) {
4435 if (BPF_SRC(insn->code) == BPF_X) {
4436 if (insn->imm != 0 || insn->off != 0) {
4437 verbose(env, "BPF_MOV uses reserved fields\n");
4441 /* check src operand */
4442 err = check_reg_arg(env, insn->src_reg, SRC_OP);
4446 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
4447 verbose(env, "BPF_MOV uses reserved fields\n");
4452 /* check dest operand, mark as required later */
4453 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
4457 if (BPF_SRC(insn->code) == BPF_X) {
4458 struct bpf_reg_state *src_reg = regs + insn->src_reg;
4459 struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
4461 if (BPF_CLASS(insn->code) == BPF_ALU64) {
4463 * copy register state to dest reg
4465 *dst_reg = *src_reg;
4466 dst_reg->live |= REG_LIVE_WRITTEN;
4467 dst_reg->subreg_def = DEF_NOT_SUBREG;
4470 if (is_pointer_value(env, insn->src_reg)) {
4472 "R%d partial copy of pointer\n",
4475 } else if (src_reg->type == SCALAR_VALUE) {
4476 *dst_reg = *src_reg;
4477 dst_reg->live |= REG_LIVE_WRITTEN;
4478 dst_reg->subreg_def = env->insn_idx + 1;
4480 mark_reg_unknown(env, regs,
4483 coerce_reg_to_size(dst_reg, 4);
4487 * remember the value we stored into this reg
4489 /* clear any state __mark_reg_known doesn't set */
4490 mark_reg_unknown(env, regs, insn->dst_reg);
4491 regs[insn->dst_reg].type = SCALAR_VALUE;
4492 if (BPF_CLASS(insn->code) == BPF_ALU64) {
4493 __mark_reg_known(regs + insn->dst_reg,
4496 __mark_reg_known(regs + insn->dst_reg,
4501 } else if (opcode > BPF_END) {
4502 verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
4505 } else { /* all other ALU ops: and, sub, xor, add, ... */
4507 if (BPF_SRC(insn->code) == BPF_X) {
4508 if (insn->imm != 0 || insn->off != 0) {
4509 verbose(env, "BPF_ALU uses reserved fields\n");
4512 /* check src1 operand */
4513 err = check_reg_arg(env, insn->src_reg, SRC_OP);
4517 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
4518 verbose(env, "BPF_ALU uses reserved fields\n");
4523 /* check src2 operand */
4524 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
4528 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
4529 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
4530 verbose(env, "div by zero\n");
4534 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
4535 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
4536 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
4538 if (insn->imm < 0 || insn->imm >= size) {
4539 verbose(env, "invalid shift %d\n", insn->imm);
4544 /* check dest operand */
4545 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
4549 return adjust_reg_min_max_vals(env, insn);
4555 static void __find_good_pkt_pointers(struct bpf_func_state *state,
4556 struct bpf_reg_state *dst_reg,
4557 enum bpf_reg_type type, u16 new_range)
4559 struct bpf_reg_state *reg;
4562 for (i = 0; i < MAX_BPF_REG; i++) {
4563 reg = &state->regs[i];
4564 if (reg->type == type && reg->id == dst_reg->id)
4565 /* keep the maximum range already checked */
4566 reg->range = max(reg->range, new_range);
4569 bpf_for_each_spilled_reg(i, state, reg) {
4572 if (reg->type == type && reg->id == dst_reg->id)
4573 reg->range = max(reg->range, new_range);
4577 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
4578 struct bpf_reg_state *dst_reg,
4579 enum bpf_reg_type type,
4580 bool range_right_open)
4585 if (dst_reg->off < 0 ||
4586 (dst_reg->off == 0 && range_right_open))
4587 /* This doesn't give us any range */
4590 if (dst_reg->umax_value > MAX_PACKET_OFF ||
4591 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
4592 /* Risk of overflow. For instance, ptr + (1<<63) may be less
4593 * than pkt_end, but that's because it's also less than pkt.
4597 new_range = dst_reg->off;
4598 if (range_right_open)
4601 /* Examples for register markings:
4603 * pkt_data in dst register:
4607 * if (r2 > pkt_end) goto <handle exception>
4612 * if (r2 < pkt_end) goto <access okay>
4613 * <handle exception>
4616 * r2 == dst_reg, pkt_end == src_reg
4617 * r2=pkt(id=n,off=8,r=0)
4618 * r3=pkt(id=n,off=0,r=0)
4620 * pkt_data in src register:
4624 * if (pkt_end >= r2) goto <access okay>
4625 * <handle exception>
4629 * if (pkt_end <= r2) goto <handle exception>
4633 * pkt_end == dst_reg, r2 == src_reg
4634 * r2=pkt(id=n,off=8,r=0)
4635 * r3=pkt(id=n,off=0,r=0)
4637 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
4638 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
4639 * and [r3, r3 + 8-1) respectively is safe to access depending on
4643 /* If our ids match, then we must have the same max_value. And we
4644 * don't care about the other reg's fixed offset, since if it's too big
4645 * the range won't allow anything.
4646 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
4648 for (i = 0; i <= vstate->curframe; i++)
4649 __find_good_pkt_pointers(vstate->frame[i], dst_reg, type,
4653 /* compute branch direction of the expression "if (reg opcode val) goto target;"
4655 * 1 - branch will be taken and "goto target" will be executed
4656 * 0 - branch will not be taken and fall-through to next insn
4657 * -1 - unknown. Example: "if (reg < 5)" is unknown when register value range [0,10]
4659 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
4662 struct bpf_reg_state reg_lo;
4665 if (__is_pointer_value(false, reg))
4671 /* For JMP32, only low 32 bits are compared, coerce_reg_to_size
4672 * could truncate high bits and update umin/umax according to
4673 * information of low bits.
4675 coerce_reg_to_size(reg, 4);
4676 /* smin/smax need special handling. For example, after coerce,
4677 * if smin_value is 0x00000000ffffffffLL, the value is -1 when
4678 * used as operand to JMP32. It is a negative number from s32's
4679 * point of view, while it is a positive number when seen as
4680 * s64. The smin/smax are kept as s64, therefore, when used with
4681 * JMP32, they need to be transformed into s32, then sign
4682 * extended back to s64.
4684 * Also, smin/smax were copied from umin/umax. If umin/umax has
4685 * different sign bit, then min/max relationship doesn't
4686 * maintain after casting into s32, for this case, set smin/smax
4689 if ((reg->umax_value ^ reg->umin_value) &
4691 reg->smin_value = S32_MIN;
4692 reg->smax_value = S32_MAX;
4694 reg->smin_value = (s64)(s32)reg->smin_value;
4695 reg->smax_value = (s64)(s32)reg->smax_value;
4698 sval = (s64)(s32)val;
4705 if (tnum_is_const(reg->var_off))
4706 return !!tnum_equals_const(reg->var_off, val);
4709 if (tnum_is_const(reg->var_off))
4710 return !tnum_equals_const(reg->var_off, val);
4713 if ((~reg->var_off.mask & reg->var_off.value) & val)
4715 if (!((reg->var_off.mask | reg->var_off.value) & val))
4719 if (reg->umin_value > val)
4721 else if (reg->umax_value <= val)
4725 if (reg->smin_value > sval)
4727 else if (reg->smax_value < sval)
4731 if (reg->umax_value < val)
4733 else if (reg->umin_value >= val)
4737 if (reg->smax_value < sval)
4739 else if (reg->smin_value >= sval)
4743 if (reg->umin_value >= val)
4745 else if (reg->umax_value < val)
4749 if (reg->smin_value >= sval)
4751 else if (reg->smax_value < sval)
4755 if (reg->umax_value <= val)
4757 else if (reg->umin_value > val)
4761 if (reg->smax_value <= sval)
4763 else if (reg->smin_value > sval)
4771 /* Generate min value of the high 32-bit from TNUM info. */
4772 static u64 gen_hi_min(struct tnum var)
4774 return var.value & ~0xffffffffULL;
4777 /* Generate max value of the high 32-bit from TNUM info. */
4778 static u64 gen_hi_max(struct tnum var)
4780 return (var.value | var.mask) & ~0xffffffffULL;
4783 /* Return true if VAL is compared with a s64 sign extended from s32, and they
4784 * are with the same signedness.
4786 static bool cmp_val_with_extended_s64(s64 sval, struct bpf_reg_state *reg)
4788 return ((s32)sval >= 0 &&
4789 reg->smin_value >= 0 && reg->smax_value <= S32_MAX) ||
4791 reg->smax_value <= 0 && reg->smin_value >= S32_MIN);
4794 /* Adjusts the register min/max values in the case that the dst_reg is the
4795 * variable register that we are working on, and src_reg is a constant or we're
4796 * simply doing a BPF_K check.
4797 * In JEQ/JNE cases we also adjust the var_off values.
4799 static void reg_set_min_max(struct bpf_reg_state *true_reg,
4800 struct bpf_reg_state *false_reg, u64 val,
4801 u8 opcode, bool is_jmp32)
4805 /* If the dst_reg is a pointer, we can't learn anything about its
4806 * variable offset from the compare (unless src_reg were a pointer into
4807 * the same object, but we don't bother with that.
4808 * Since false_reg and true_reg have the same type by construction, we
4809 * only need to check one of them for pointerness.
4811 if (__is_pointer_value(false, false_reg))
4814 val = is_jmp32 ? (u32)val : val;
4815 sval = is_jmp32 ? (s64)(s32)val : (s64)val;
4821 struct bpf_reg_state *reg =
4822 opcode == BPF_JEQ ? true_reg : false_reg;
4824 /* For BPF_JEQ, if this is false we know nothing Jon Snow, but
4825 * if it is true we know the value for sure. Likewise for
4829 u64 old_v = reg->var_off.value;
4830 u64 hi_mask = ~0xffffffffULL;
4832 reg->var_off.value = (old_v & hi_mask) | val;
4833 reg->var_off.mask &= hi_mask;
4835 __mark_reg_known(reg, val);
4840 false_reg->var_off = tnum_and(false_reg->var_off,
4842 if (is_power_of_2(val))
4843 true_reg->var_off = tnum_or(true_reg->var_off,
4849 u64 false_umax = opcode == BPF_JGT ? val : val - 1;
4850 u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
4853 false_umax += gen_hi_max(false_reg->var_off);
4854 true_umin += gen_hi_min(true_reg->var_off);
4856 false_reg->umax_value = min(false_reg->umax_value, false_umax);
4857 true_reg->umin_value = max(true_reg->umin_value, true_umin);
4863 s64 false_smax = opcode == BPF_JSGT ? sval : sval - 1;
4864 s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
4866 /* If the full s64 was not sign-extended from s32 then don't
4867 * deduct further info.
4869 if (is_jmp32 && !cmp_val_with_extended_s64(sval, false_reg))
4871 false_reg->smax_value = min(false_reg->smax_value, false_smax);
4872 true_reg->smin_value = max(true_reg->smin_value, true_smin);
4878 u64 false_umin = opcode == BPF_JLT ? val : val + 1;
4879 u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
4882 false_umin += gen_hi_min(false_reg->var_off);
4883 true_umax += gen_hi_max(true_reg->var_off);
4885 false_reg->umin_value = max(false_reg->umin_value, false_umin);
4886 true_reg->umax_value = min(true_reg->umax_value, true_umax);
4892 s64 false_smin = opcode == BPF_JSLT ? sval : sval + 1;
4893 s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
4895 if (is_jmp32 && !cmp_val_with_extended_s64(sval, false_reg))
4897 false_reg->smin_value = max(false_reg->smin_value, false_smin);
4898 true_reg->smax_value = min(true_reg->smax_value, true_smax);
4905 __reg_deduce_bounds(false_reg);
4906 __reg_deduce_bounds(true_reg);
4907 /* We might have learned some bits from the bounds. */
4908 __reg_bound_offset(false_reg);
4909 __reg_bound_offset(true_reg);
4910 /* Intersecting with the old var_off might have improved our bounds
4911 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
4912 * then new var_off is (0; 0x7f...fc) which improves our umax.
4914 __update_reg_bounds(false_reg);
4915 __update_reg_bounds(true_reg);
4918 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
4921 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
4922 struct bpf_reg_state *false_reg, u64 val,
4923 u8 opcode, bool is_jmp32)
4927 if (__is_pointer_value(false, false_reg))
4930 val = is_jmp32 ? (u32)val : val;
4931 sval = is_jmp32 ? (s64)(s32)val : (s64)val;
4937 struct bpf_reg_state *reg =
4938 opcode == BPF_JEQ ? true_reg : false_reg;
4941 u64 old_v = reg->var_off.value;
4942 u64 hi_mask = ~0xffffffffULL;
4944 reg->var_off.value = (old_v & hi_mask) | val;
4945 reg->var_off.mask &= hi_mask;
4947 __mark_reg_known(reg, val);
4952 false_reg->var_off = tnum_and(false_reg->var_off,
4954 if (is_power_of_2(val))
4955 true_reg->var_off = tnum_or(true_reg->var_off,
4961 u64 false_umin = opcode == BPF_JGT ? val : val + 1;
4962 u64 true_umax = opcode == BPF_JGT ? val - 1 : val;
4965 false_umin += gen_hi_min(false_reg->var_off);
4966 true_umax += gen_hi_max(true_reg->var_off);
4968 false_reg->umin_value = max(false_reg->umin_value, false_umin);
4969 true_reg->umax_value = min(true_reg->umax_value, true_umax);
4975 s64 false_smin = opcode == BPF_JSGT ? sval : sval + 1;
4976 s64 true_smax = opcode == BPF_JSGT ? sval - 1 : sval;
4978 if (is_jmp32 && !cmp_val_with_extended_s64(sval, false_reg))
4980 false_reg->smin_value = max(false_reg->smin_value, false_smin);
4981 true_reg->smax_value = min(true_reg->smax_value, true_smax);
4987 u64 false_umax = opcode == BPF_JLT ? val : val - 1;
4988 u64 true_umin = opcode == BPF_JLT ? val + 1 : val;
4991 false_umax += gen_hi_max(false_reg->var_off);
4992 true_umin += gen_hi_min(true_reg->var_off);
4994 false_reg->umax_value = min(false_reg->umax_value, false_umax);
4995 true_reg->umin_value = max(true_reg->umin_value, true_umin);
5001 s64 false_smax = opcode == BPF_JSLT ? sval : sval - 1;
5002 s64 true_smin = opcode == BPF_JSLT ? sval + 1 : sval;
5004 if (is_jmp32 && !cmp_val_with_extended_s64(sval, false_reg))
5006 false_reg->smax_value = min(false_reg->smax_value, false_smax);
5007 true_reg->smin_value = max(true_reg->smin_value, true_smin);
5014 __reg_deduce_bounds(false_reg);
5015 __reg_deduce_bounds(true_reg);
5016 /* We might have learned some bits from the bounds. */
5017 __reg_bound_offset(false_reg);
5018 __reg_bound_offset(true_reg);
5019 /* Intersecting with the old var_off might have improved our bounds
5020 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
5021 * then new var_off is (0; 0x7f...fc) which improves our umax.
5023 __update_reg_bounds(false_reg);
5024 __update_reg_bounds(true_reg);
5027 /* Regs are known to be equal, so intersect their min/max/var_off */
5028 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
5029 struct bpf_reg_state *dst_reg)
5031 src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
5032 dst_reg->umin_value);
5033 src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
5034 dst_reg->umax_value);
5035 src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
5036 dst_reg->smin_value);
5037 src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
5038 dst_reg->smax_value);
5039 src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
5041 /* We might have learned new bounds from the var_off. */
5042 __update_reg_bounds(src_reg);
5043 __update_reg_bounds(dst_reg);
5044 /* We might have learned something about the sign bit. */
5045 __reg_deduce_bounds(src_reg);
5046 __reg_deduce_bounds(dst_reg);
5047 /* We might have learned some bits from the bounds. */
5048 __reg_bound_offset(src_reg);
5049 __reg_bound_offset(dst_reg);
5050 /* Intersecting with the old var_off might have improved our bounds
5051 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
5052 * then new var_off is (0; 0x7f...fc) which improves our umax.
5054 __update_reg_bounds(src_reg);
5055 __update_reg_bounds(dst_reg);
5058 static void reg_combine_min_max(struct bpf_reg_state *true_src,
5059 struct bpf_reg_state *true_dst,
5060 struct bpf_reg_state *false_src,
5061 struct bpf_reg_state *false_dst,
5066 __reg_combine_min_max(true_src, true_dst);
5069 __reg_combine_min_max(false_src, false_dst);
5074 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
5075 struct bpf_reg_state *reg, u32 id,
5078 if (reg_type_may_be_null(reg->type) && reg->id == id) {
5079 /* Old offset (both fixed and variable parts) should
5080 * have been known-zero, because we don't allow pointer
5081 * arithmetic on pointers that might be NULL.
5083 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value ||
5084 !tnum_equals_const(reg->var_off, 0) ||
5086 __mark_reg_known_zero(reg);
5090 reg->type = SCALAR_VALUE;
5091 } else if (reg->type == PTR_TO_MAP_VALUE_OR_NULL) {
5092 if (reg->map_ptr->inner_map_meta) {
5093 reg->type = CONST_PTR_TO_MAP;
5094 reg->map_ptr = reg->map_ptr->inner_map_meta;
5095 } else if (reg->map_ptr->map_type ==
5096 BPF_MAP_TYPE_XSKMAP) {
5097 reg->type = PTR_TO_XDP_SOCK;
5099 reg->type = PTR_TO_MAP_VALUE;
5101 } else if (reg->type == PTR_TO_SOCKET_OR_NULL) {
5102 reg->type = PTR_TO_SOCKET;
5103 } else if (reg->type == PTR_TO_SOCK_COMMON_OR_NULL) {
5104 reg->type = PTR_TO_SOCK_COMMON;
5105 } else if (reg->type == PTR_TO_TCP_SOCK_OR_NULL) {
5106 reg->type = PTR_TO_TCP_SOCK;
5109 /* We don't need id and ref_obj_id from this point
5110 * onwards anymore, thus we should better reset it,
5111 * so that state pruning has chances to take effect.
5114 reg->ref_obj_id = 0;
5115 } else if (!reg_may_point_to_spin_lock(reg)) {
5116 /* For not-NULL ptr, reg->ref_obj_id will be reset
5117 * in release_reg_references().
5119 * reg->id is still used by spin_lock ptr. Other
5120 * than spin_lock ptr type, reg->id can be reset.
5127 static void __mark_ptr_or_null_regs(struct bpf_func_state *state, u32 id,
5130 struct bpf_reg_state *reg;
5133 for (i = 0; i < MAX_BPF_REG; i++)
5134 mark_ptr_or_null_reg(state, &state->regs[i], id, is_null);
5136 bpf_for_each_spilled_reg(i, state, reg) {
5139 mark_ptr_or_null_reg(state, reg, id, is_null);
5143 /* The logic is similar to find_good_pkt_pointers(), both could eventually
5144 * be folded together at some point.
5146 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
5149 struct bpf_func_state *state = vstate->frame[vstate->curframe];
5150 struct bpf_reg_state *regs = state->regs;
5151 u32 ref_obj_id = regs[regno].ref_obj_id;
5152 u32 id = regs[regno].id;
5155 if (ref_obj_id && ref_obj_id == id && is_null)
5156 /* regs[regno] is in the " == NULL" branch.
5157 * No one could have freed the reference state before
5158 * doing the NULL check.
5160 WARN_ON_ONCE(release_reference_state(state, id));
5162 for (i = 0; i <= vstate->curframe; i++)
5163 __mark_ptr_or_null_regs(vstate->frame[i], id, is_null);
5166 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
5167 struct bpf_reg_state *dst_reg,
5168 struct bpf_reg_state *src_reg,
5169 struct bpf_verifier_state *this_branch,
5170 struct bpf_verifier_state *other_branch)
5172 if (BPF_SRC(insn->code) != BPF_X)
5175 /* Pointers are always 64-bit. */
5176 if (BPF_CLASS(insn->code) == BPF_JMP32)
5179 switch (BPF_OP(insn->code)) {
5181 if ((dst_reg->type == PTR_TO_PACKET &&
5182 src_reg->type == PTR_TO_PACKET_END) ||
5183 (dst_reg->type == PTR_TO_PACKET_META &&
5184 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
5185 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
5186 find_good_pkt_pointers(this_branch, dst_reg,
5187 dst_reg->type, false);
5188 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
5189 src_reg->type == PTR_TO_PACKET) ||
5190 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
5191 src_reg->type == PTR_TO_PACKET_META)) {
5192 /* pkt_end > pkt_data', pkt_data > pkt_meta' */
5193 find_good_pkt_pointers(other_branch, src_reg,
5194 src_reg->type, true);
5200 if ((dst_reg->type == PTR_TO_PACKET &&
5201 src_reg->type == PTR_TO_PACKET_END) ||
5202 (dst_reg->type == PTR_TO_PACKET_META &&
5203 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
5204 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
5205 find_good_pkt_pointers(other_branch, dst_reg,
5206 dst_reg->type, true);
5207 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
5208 src_reg->type == PTR_TO_PACKET) ||
5209 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
5210 src_reg->type == PTR_TO_PACKET_META)) {
5211 /* pkt_end < pkt_data', pkt_data > pkt_meta' */
5212 find_good_pkt_pointers(this_branch, src_reg,
5213 src_reg->type, false);
5219 if ((dst_reg->type == PTR_TO_PACKET &&
5220 src_reg->type == PTR_TO_PACKET_END) ||
5221 (dst_reg->type == PTR_TO_PACKET_META &&
5222 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
5223 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
5224 find_good_pkt_pointers(this_branch, dst_reg,
5225 dst_reg->type, true);
5226 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
5227 src_reg->type == PTR_TO_PACKET) ||
5228 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
5229 src_reg->type == PTR_TO_PACKET_META)) {
5230 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
5231 find_good_pkt_pointers(other_branch, src_reg,
5232 src_reg->type, false);
5238 if ((dst_reg->type == PTR_TO_PACKET &&
5239 src_reg->type == PTR_TO_PACKET_END) ||
5240 (dst_reg->type == PTR_TO_PACKET_META &&
5241 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
5242 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
5243 find_good_pkt_pointers(other_branch, dst_reg,
5244 dst_reg->type, false);
5245 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
5246 src_reg->type == PTR_TO_PACKET) ||
5247 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
5248 src_reg->type == PTR_TO_PACKET_META)) {
5249 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
5250 find_good_pkt_pointers(this_branch, src_reg,
5251 src_reg->type, true);
5263 static int check_cond_jmp_op(struct bpf_verifier_env *env,
5264 struct bpf_insn *insn, int *insn_idx)
5266 struct bpf_verifier_state *this_branch = env->cur_state;
5267 struct bpf_verifier_state *other_branch;
5268 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
5269 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
5270 u8 opcode = BPF_OP(insn->code);
5275 /* Only conditional jumps are expected to reach here. */
5276 if (opcode == BPF_JA || opcode > BPF_JSLE) {
5277 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
5281 if (BPF_SRC(insn->code) == BPF_X) {
5282 if (insn->imm != 0) {
5283 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
5287 /* check src1 operand */
5288 err = check_reg_arg(env, insn->src_reg, SRC_OP);
5292 if (is_pointer_value(env, insn->src_reg)) {
5293 verbose(env, "R%d pointer comparison prohibited\n",
5297 src_reg = ®s[insn->src_reg];
5299 if (insn->src_reg != BPF_REG_0) {
5300 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
5305 /* check src2 operand */
5306 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
5310 dst_reg = ®s[insn->dst_reg];
5311 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
5313 if (BPF_SRC(insn->code) == BPF_K)
5314 pred = is_branch_taken(dst_reg, insn->imm,
5316 else if (src_reg->type == SCALAR_VALUE &&
5317 tnum_is_const(src_reg->var_off))
5318 pred = is_branch_taken(dst_reg, src_reg->var_off.value,
5321 /* only follow the goto, ignore fall-through */
5322 *insn_idx += insn->off;
5324 } else if (pred == 0) {
5325 /* only follow fall-through branch, since
5326 * that's where the program will go
5331 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
5335 other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
5337 /* detect if we are comparing against a constant value so we can adjust
5338 * our min/max values for our dst register.
5339 * this is only legit if both are scalars (or pointers to the same
5340 * object, I suppose, but we don't support that right now), because
5341 * otherwise the different base pointers mean the offsets aren't
5344 if (BPF_SRC(insn->code) == BPF_X) {
5345 struct bpf_reg_state *src_reg = ®s[insn->src_reg];
5346 struct bpf_reg_state lo_reg0 = *dst_reg;
5347 struct bpf_reg_state lo_reg1 = *src_reg;
5348 struct bpf_reg_state *src_lo, *dst_lo;
5352 coerce_reg_to_size(dst_lo, 4);
5353 coerce_reg_to_size(src_lo, 4);
5355 if (dst_reg->type == SCALAR_VALUE &&
5356 src_reg->type == SCALAR_VALUE) {
5357 if (tnum_is_const(src_reg->var_off) ||
5358 (is_jmp32 && tnum_is_const(src_lo->var_off)))
5359 reg_set_min_max(&other_branch_regs[insn->dst_reg],
5362 ? src_lo->var_off.value
5363 : src_reg->var_off.value,
5365 else if (tnum_is_const(dst_reg->var_off) ||
5366 (is_jmp32 && tnum_is_const(dst_lo->var_off)))
5367 reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
5370 ? dst_lo->var_off.value
5371 : dst_reg->var_off.value,
5373 else if (!is_jmp32 &&
5374 (opcode == BPF_JEQ || opcode == BPF_JNE))
5375 /* Comparing for equality, we can combine knowledge */
5376 reg_combine_min_max(&other_branch_regs[insn->src_reg],
5377 &other_branch_regs[insn->dst_reg],
5378 src_reg, dst_reg, opcode);
5380 } else if (dst_reg->type == SCALAR_VALUE) {
5381 reg_set_min_max(&other_branch_regs[insn->dst_reg],
5382 dst_reg, insn->imm, opcode, is_jmp32);
5385 /* detect if R == 0 where R is returned from bpf_map_lookup_elem().
5386 * NOTE: these optimizations below are related with pointer comparison
5387 * which will never be JMP32.
5389 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
5390 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
5391 reg_type_may_be_null(dst_reg->type)) {
5392 /* Mark all identical registers in each branch as either
5393 * safe or unknown depending R == 0 or R != 0 conditional.
5395 mark_ptr_or_null_regs(this_branch, insn->dst_reg,
5397 mark_ptr_or_null_regs(other_branch, insn->dst_reg,
5399 } else if (!try_match_pkt_pointers(insn, dst_reg, ®s[insn->src_reg],
5400 this_branch, other_branch) &&
5401 is_pointer_value(env, insn->dst_reg)) {
5402 verbose(env, "R%d pointer comparison prohibited\n",
5406 if (env->log.level & BPF_LOG_LEVEL)
5407 print_verifier_state(env, this_branch->frame[this_branch->curframe]);
5411 /* verify BPF_LD_IMM64 instruction */
5412 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
5414 struct bpf_insn_aux_data *aux = cur_aux(env);
5415 struct bpf_reg_state *regs = cur_regs(env);
5416 struct bpf_map *map;
5419 if (BPF_SIZE(insn->code) != BPF_DW) {
5420 verbose(env, "invalid BPF_LD_IMM insn\n");
5423 if (insn->off != 0) {
5424 verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
5428 err = check_reg_arg(env, insn->dst_reg, DST_OP);
5432 if (insn->src_reg == 0) {
5433 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
5435 regs[insn->dst_reg].type = SCALAR_VALUE;
5436 __mark_reg_known(®s[insn->dst_reg], imm);
5440 map = env->used_maps[aux->map_index];
5441 mark_reg_known_zero(env, regs, insn->dst_reg);
5442 regs[insn->dst_reg].map_ptr = map;
5444 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE) {
5445 regs[insn->dst_reg].type = PTR_TO_MAP_VALUE;
5446 regs[insn->dst_reg].off = aux->map_off;
5447 if (map_value_has_spin_lock(map))
5448 regs[insn->dst_reg].id = ++env->id_gen;
5449 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD) {
5450 regs[insn->dst_reg].type = CONST_PTR_TO_MAP;
5452 verbose(env, "bpf verifier is misconfigured\n");
5459 static bool may_access_skb(enum bpf_prog_type type)
5462 case BPF_PROG_TYPE_SOCKET_FILTER:
5463 case BPF_PROG_TYPE_SCHED_CLS:
5464 case BPF_PROG_TYPE_SCHED_ACT:
5471 /* verify safety of LD_ABS|LD_IND instructions:
5472 * - they can only appear in the programs where ctx == skb
5473 * - since they are wrappers of function calls, they scratch R1-R5 registers,
5474 * preserve R6-R9, and store return value into R0
5477 * ctx == skb == R6 == CTX
5480 * SRC == any register
5481 * IMM == 32-bit immediate
5484 * R0 - 8/16/32-bit skb data converted to cpu endianness
5486 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
5488 struct bpf_reg_state *regs = cur_regs(env);
5489 u8 mode = BPF_MODE(insn->code);
5492 if (!may_access_skb(env->prog->type)) {
5493 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
5497 if (!env->ops->gen_ld_abs) {
5498 verbose(env, "bpf verifier is misconfigured\n");
5502 if (env->subprog_cnt > 1) {
5503 /* when program has LD_ABS insn JITs and interpreter assume
5504 * that r1 == ctx == skb which is not the case for callees
5505 * that can have arbitrary arguments. It's problematic
5506 * for main prog as well since JITs would need to analyze
5507 * all functions in order to make proper register save/restore
5508 * decisions in the main prog. Hence disallow LD_ABS with calls
5510 verbose(env, "BPF_LD_[ABS|IND] instructions cannot be mixed with bpf-to-bpf calls\n");
5514 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
5515 BPF_SIZE(insn->code) == BPF_DW ||
5516 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
5517 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
5521 /* check whether implicit source operand (register R6) is readable */
5522 err = check_reg_arg(env, BPF_REG_6, SRC_OP);
5526 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
5527 * gen_ld_abs() may terminate the program at runtime, leading to
5530 err = check_reference_leak(env);
5532 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
5536 if (env->cur_state->active_spin_lock) {
5537 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
5541 if (regs[BPF_REG_6].type != PTR_TO_CTX) {
5543 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
5547 if (mode == BPF_IND) {
5548 /* check explicit source operand */
5549 err = check_reg_arg(env, insn->src_reg, SRC_OP);
5554 /* reset caller saved regs to unreadable */
5555 for (i = 0; i < CALLER_SAVED_REGS; i++) {
5556 mark_reg_not_init(env, regs, caller_saved[i]);
5557 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
5560 /* mark destination R0 register as readable, since it contains
5561 * the value fetched from the packet.
5562 * Already marked as written above.
5564 mark_reg_unknown(env, regs, BPF_REG_0);
5565 /* ld_abs load up to 32-bit skb data. */
5566 regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
5570 static int check_return_code(struct bpf_verifier_env *env)
5572 struct tnum enforce_attach_type_range = tnum_unknown;
5573 struct bpf_reg_state *reg;
5574 struct tnum range = tnum_range(0, 1);
5576 switch (env->prog->type) {
5577 case BPF_PROG_TYPE_CGROUP_SKB:
5578 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
5579 range = tnum_range(0, 3);
5580 enforce_attach_type_range = tnum_range(2, 3);
5582 case BPF_PROG_TYPE_CGROUP_SOCK:
5583 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
5584 case BPF_PROG_TYPE_SOCK_OPS:
5585 case BPF_PROG_TYPE_CGROUP_DEVICE:
5586 case BPF_PROG_TYPE_CGROUP_SYSCTL:
5592 reg = cur_regs(env) + BPF_REG_0;
5593 if (reg->type != SCALAR_VALUE) {
5594 verbose(env, "At program exit the register R0 is not a known value (%s)\n",
5595 reg_type_str[reg->type]);
5599 if (!tnum_in(range, reg->var_off)) {
5602 verbose(env, "At program exit the register R0 ");
5603 if (!tnum_is_unknown(reg->var_off)) {
5604 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5605 verbose(env, "has value %s", tn_buf);
5607 verbose(env, "has unknown scalar value");
5609 tnum_strn(tn_buf, sizeof(tn_buf), range);
5610 verbose(env, " should have been %s\n", tn_buf);
5614 if (!tnum_is_unknown(enforce_attach_type_range) &&
5615 tnum_in(enforce_attach_type_range, reg->var_off))
5616 env->prog->enforce_expected_attach_type = 1;
5620 /* non-recursive DFS pseudo code
5621 * 1 procedure DFS-iterative(G,v):
5622 * 2 label v as discovered
5623 * 3 let S be a stack
5625 * 5 while S is not empty
5627 * 7 if t is what we're looking for:
5629 * 9 for all edges e in G.adjacentEdges(t) do
5630 * 10 if edge e is already labelled
5631 * 11 continue with the next edge
5632 * 12 w <- G.adjacentVertex(t,e)
5633 * 13 if vertex w is not discovered and not explored
5634 * 14 label e as tree-edge
5635 * 15 label w as discovered
5638 * 18 else if vertex w is discovered
5639 * 19 label e as back-edge
5641 * 21 // vertex w is explored
5642 * 22 label e as forward- or cross-edge
5643 * 23 label t as explored
5648 * 0x11 - discovered and fall-through edge labelled
5649 * 0x12 - discovered and fall-through and branch edges labelled
5660 static u32 state_htab_size(struct bpf_verifier_env *env)
5662 return env->prog->len;
5665 static struct bpf_verifier_state_list **explored_state(
5666 struct bpf_verifier_env *env,
5669 struct bpf_verifier_state *cur = env->cur_state;
5670 struct bpf_func_state *state = cur->frame[cur->curframe];
5672 return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
5675 static void init_explored_state(struct bpf_verifier_env *env, int idx)
5677 env->insn_aux_data[idx].prune_point = true;
5680 /* t, w, e - match pseudo-code above:
5681 * t - index of current instruction
5682 * w - next instruction
5685 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env)
5687 int *insn_stack = env->cfg.insn_stack;
5688 int *insn_state = env->cfg.insn_state;
5690 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
5693 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
5696 if (w < 0 || w >= env->prog->len) {
5697 verbose_linfo(env, t, "%d: ", t);
5698 verbose(env, "jump out of range from insn %d to %d\n", t, w);
5703 /* mark branch target for state pruning */
5704 init_explored_state(env, w);
5706 if (insn_state[w] == 0) {
5708 insn_state[t] = DISCOVERED | e;
5709 insn_state[w] = DISCOVERED;
5710 if (env->cfg.cur_stack >= env->prog->len)
5712 insn_stack[env->cfg.cur_stack++] = w;
5714 } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
5715 verbose_linfo(env, t, "%d: ", t);
5716 verbose_linfo(env, w, "%d: ", w);
5717 verbose(env, "back-edge from insn %d to %d\n", t, w);
5719 } else if (insn_state[w] == EXPLORED) {
5720 /* forward- or cross-edge */
5721 insn_state[t] = DISCOVERED | e;
5723 verbose(env, "insn state internal bug\n");
5729 /* non-recursive depth-first-search to detect loops in BPF program
5730 * loop == back-edge in directed graph
5732 static int check_cfg(struct bpf_verifier_env *env)
5734 struct bpf_insn *insns = env->prog->insnsi;
5735 int insn_cnt = env->prog->len;
5736 int *insn_stack, *insn_state;
5740 insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
5744 insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
5750 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
5751 insn_stack[0] = 0; /* 0 is the first instruction */
5752 env->cfg.cur_stack = 1;
5755 if (env->cfg.cur_stack == 0)
5757 t = insn_stack[env->cfg.cur_stack - 1];
5759 if (BPF_CLASS(insns[t].code) == BPF_JMP ||
5760 BPF_CLASS(insns[t].code) == BPF_JMP32) {
5761 u8 opcode = BPF_OP(insns[t].code);
5763 if (opcode == BPF_EXIT) {
5765 } else if (opcode == BPF_CALL) {
5766 ret = push_insn(t, t + 1, FALLTHROUGH, env);
5771 if (t + 1 < insn_cnt)
5772 init_explored_state(env, t + 1);
5773 if (insns[t].src_reg == BPF_PSEUDO_CALL) {
5774 init_explored_state(env, t);
5775 ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env);
5781 } else if (opcode == BPF_JA) {
5782 if (BPF_SRC(insns[t].code) != BPF_K) {
5786 /* unconditional jump with single edge */
5787 ret = push_insn(t, t + insns[t].off + 1,
5793 /* tell verifier to check for equivalent states
5794 * after every call and jump
5796 if (t + 1 < insn_cnt)
5797 init_explored_state(env, t + 1);
5799 /* conditional jump with two edges */
5800 init_explored_state(env, t);
5801 ret = push_insn(t, t + 1, FALLTHROUGH, env);
5807 ret = push_insn(t, t + insns[t].off + 1, BRANCH, env);
5814 /* all other non-branch instructions with single
5817 ret = push_insn(t, t + 1, FALLTHROUGH, env);
5825 insn_state[t] = EXPLORED;
5826 if (env->cfg.cur_stack-- <= 0) {
5827 verbose(env, "pop stack internal bug\n");
5834 for (i = 0; i < insn_cnt; i++) {
5835 if (insn_state[i] != EXPLORED) {
5836 verbose(env, "unreachable insn %d\n", i);
5841 ret = 0; /* cfg looks good */
5846 env->cfg.insn_state = env->cfg.insn_stack = NULL;
5850 /* The minimum supported BTF func info size */
5851 #define MIN_BPF_FUNCINFO_SIZE 8
5852 #define MAX_FUNCINFO_REC_SIZE 252
5854 static int check_btf_func(struct bpf_verifier_env *env,
5855 const union bpf_attr *attr,
5856 union bpf_attr __user *uattr)
5858 u32 i, nfuncs, urec_size, min_size;
5859 u32 krec_size = sizeof(struct bpf_func_info);
5860 struct bpf_func_info *krecord;
5861 const struct btf_type *type;
5862 struct bpf_prog *prog;
5863 const struct btf *btf;
5864 void __user *urecord;
5865 u32 prev_offset = 0;
5868 nfuncs = attr->func_info_cnt;
5872 if (nfuncs != env->subprog_cnt) {
5873 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
5877 urec_size = attr->func_info_rec_size;
5878 if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
5879 urec_size > MAX_FUNCINFO_REC_SIZE ||
5880 urec_size % sizeof(u32)) {
5881 verbose(env, "invalid func info rec size %u\n", urec_size);
5886 btf = prog->aux->btf;
5888 urecord = u64_to_user_ptr(attr->func_info);
5889 min_size = min_t(u32, krec_size, urec_size);
5891 krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
5895 for (i = 0; i < nfuncs; i++) {
5896 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
5898 if (ret == -E2BIG) {
5899 verbose(env, "nonzero tailing record in func info");
5900 /* set the size kernel expects so loader can zero
5901 * out the rest of the record.
5903 if (put_user(min_size, &uattr->func_info_rec_size))
5909 if (copy_from_user(&krecord[i], urecord, min_size)) {
5914 /* check insn_off */
5916 if (krecord[i].insn_off) {
5918 "nonzero insn_off %u for the first func info record",
5919 krecord[i].insn_off);
5923 } else if (krecord[i].insn_off <= prev_offset) {
5925 "same or smaller insn offset (%u) than previous func info record (%u)",
5926 krecord[i].insn_off, prev_offset);
5931 if (env->subprog_info[i].start != krecord[i].insn_off) {
5932 verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
5938 type = btf_type_by_id(btf, krecord[i].type_id);
5939 if (!type || BTF_INFO_KIND(type->info) != BTF_KIND_FUNC) {
5940 verbose(env, "invalid type id %d in func info",
5941 krecord[i].type_id);
5946 prev_offset = krecord[i].insn_off;
5947 urecord += urec_size;
5950 prog->aux->func_info = krecord;
5951 prog->aux->func_info_cnt = nfuncs;
5959 static void adjust_btf_func(struct bpf_verifier_env *env)
5963 if (!env->prog->aux->func_info)
5966 for (i = 0; i < env->subprog_cnt; i++)
5967 env->prog->aux->func_info[i].insn_off = env->subprog_info[i].start;
5970 #define MIN_BPF_LINEINFO_SIZE (offsetof(struct bpf_line_info, line_col) + \
5971 sizeof(((struct bpf_line_info *)(0))->line_col))
5972 #define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE
5974 static int check_btf_line(struct bpf_verifier_env *env,
5975 const union bpf_attr *attr,
5976 union bpf_attr __user *uattr)
5978 u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
5979 struct bpf_subprog_info *sub;
5980 struct bpf_line_info *linfo;
5981 struct bpf_prog *prog;
5982 const struct btf *btf;
5983 void __user *ulinfo;
5986 nr_linfo = attr->line_info_cnt;
5990 rec_size = attr->line_info_rec_size;
5991 if (rec_size < MIN_BPF_LINEINFO_SIZE ||
5992 rec_size > MAX_LINEINFO_REC_SIZE ||
5993 rec_size & (sizeof(u32) - 1))
5996 /* Need to zero it in case the userspace may
5997 * pass in a smaller bpf_line_info object.
5999 linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
6000 GFP_KERNEL | __GFP_NOWARN);
6005 btf = prog->aux->btf;
6008 sub = env->subprog_info;
6009 ulinfo = u64_to_user_ptr(attr->line_info);
6010 expected_size = sizeof(struct bpf_line_info);
6011 ncopy = min_t(u32, expected_size, rec_size);
6012 for (i = 0; i < nr_linfo; i++) {
6013 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
6015 if (err == -E2BIG) {
6016 verbose(env, "nonzero tailing record in line_info");
6017 if (put_user(expected_size,
6018 &uattr->line_info_rec_size))
6024 if (copy_from_user(&linfo[i], ulinfo, ncopy)) {
6030 * Check insn_off to ensure
6031 * 1) strictly increasing AND
6032 * 2) bounded by prog->len
6034 * The linfo[0].insn_off == 0 check logically falls into
6035 * the later "missing bpf_line_info for func..." case
6036 * because the first linfo[0].insn_off must be the
6037 * first sub also and the first sub must have
6038 * subprog_info[0].start == 0.
6040 if ((i && linfo[i].insn_off <= prev_offset) ||
6041 linfo[i].insn_off >= prog->len) {
6042 verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
6043 i, linfo[i].insn_off, prev_offset,
6049 if (!prog->insnsi[linfo[i].insn_off].code) {
6051 "Invalid insn code at line_info[%u].insn_off\n",
6057 if (!btf_name_by_offset(btf, linfo[i].line_off) ||
6058 !btf_name_by_offset(btf, linfo[i].file_name_off)) {
6059 verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
6064 if (s != env->subprog_cnt) {
6065 if (linfo[i].insn_off == sub[s].start) {
6066 sub[s].linfo_idx = i;
6068 } else if (sub[s].start < linfo[i].insn_off) {
6069 verbose(env, "missing bpf_line_info for func#%u\n", s);
6075 prev_offset = linfo[i].insn_off;
6079 if (s != env->subprog_cnt) {
6080 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
6081 env->subprog_cnt - s, s);
6086 prog->aux->linfo = linfo;
6087 prog->aux->nr_linfo = nr_linfo;
6096 static int check_btf_info(struct bpf_verifier_env *env,
6097 const union bpf_attr *attr,
6098 union bpf_attr __user *uattr)
6103 if (!attr->func_info_cnt && !attr->line_info_cnt)
6106 btf = btf_get_by_fd(attr->prog_btf_fd);
6108 return PTR_ERR(btf);
6109 env->prog->aux->btf = btf;
6111 err = check_btf_func(env, attr, uattr);
6115 err = check_btf_line(env, attr, uattr);
6122 /* check %cur's range satisfies %old's */
6123 static bool range_within(struct bpf_reg_state *old,
6124 struct bpf_reg_state *cur)
6126 return old->umin_value <= cur->umin_value &&
6127 old->umax_value >= cur->umax_value &&
6128 old->smin_value <= cur->smin_value &&
6129 old->smax_value >= cur->smax_value;
6132 /* Maximum number of register states that can exist at once */
6133 #define ID_MAP_SIZE (MAX_BPF_REG + MAX_BPF_STACK / BPF_REG_SIZE)
6139 /* If in the old state two registers had the same id, then they need to have
6140 * the same id in the new state as well. But that id could be different from
6141 * the old state, so we need to track the mapping from old to new ids.
6142 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
6143 * regs with old id 5 must also have new id 9 for the new state to be safe. But
6144 * regs with a different old id could still have new id 9, we don't care about
6146 * So we look through our idmap to see if this old id has been seen before. If
6147 * so, we require the new id to match; otherwise, we add the id pair to the map.
6149 static bool check_ids(u32 old_id, u32 cur_id, struct idpair *idmap)
6153 for (i = 0; i < ID_MAP_SIZE; i++) {
6154 if (!idmap[i].old) {
6155 /* Reached an empty slot; haven't seen this id before */
6156 idmap[i].old = old_id;
6157 idmap[i].cur = cur_id;
6160 if (idmap[i].old == old_id)
6161 return idmap[i].cur == cur_id;
6163 /* We ran out of idmap slots, which should be impossible */
6168 static void clean_func_state(struct bpf_verifier_env *env,
6169 struct bpf_func_state *st)
6171 enum bpf_reg_liveness live;
6174 for (i = 0; i < BPF_REG_FP; i++) {
6175 live = st->regs[i].live;
6176 /* liveness must not touch this register anymore */
6177 st->regs[i].live |= REG_LIVE_DONE;
6178 if (!(live & REG_LIVE_READ))
6179 /* since the register is unused, clear its state
6180 * to make further comparison simpler
6182 __mark_reg_not_init(&st->regs[i]);
6185 for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
6186 live = st->stack[i].spilled_ptr.live;
6187 /* liveness must not touch this stack slot anymore */
6188 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
6189 if (!(live & REG_LIVE_READ)) {
6190 __mark_reg_not_init(&st->stack[i].spilled_ptr);
6191 for (j = 0; j < BPF_REG_SIZE; j++)
6192 st->stack[i].slot_type[j] = STACK_INVALID;
6197 static void clean_verifier_state(struct bpf_verifier_env *env,
6198 struct bpf_verifier_state *st)
6202 if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
6203 /* all regs in this state in all frames were already marked */
6206 for (i = 0; i <= st->curframe; i++)
6207 clean_func_state(env, st->frame[i]);
6210 /* the parentage chains form a tree.
6211 * the verifier states are added to state lists at given insn and
6212 * pushed into state stack for future exploration.
6213 * when the verifier reaches bpf_exit insn some of the verifer states
6214 * stored in the state lists have their final liveness state already,
6215 * but a lot of states will get revised from liveness point of view when
6216 * the verifier explores other branches.
6219 * 2: if r1 == 100 goto pc+1
6222 * when the verifier reaches exit insn the register r0 in the state list of
6223 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
6224 * of insn 2 and goes exploring further. At the insn 4 it will walk the
6225 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
6227 * Since the verifier pushes the branch states as it sees them while exploring
6228 * the program the condition of walking the branch instruction for the second
6229 * time means that all states below this branch were already explored and
6230 * their final liveness markes are already propagated.
6231 * Hence when the verifier completes the search of state list in is_state_visited()
6232 * we can call this clean_live_states() function to mark all liveness states
6233 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
6235 * This function also clears the registers and stack for states that !READ
6236 * to simplify state merging.
6238 * Important note here that walking the same branch instruction in the callee
6239 * doesn't meant that the states are DONE. The verifier has to compare
6242 static void clean_live_states(struct bpf_verifier_env *env, int insn,
6243 struct bpf_verifier_state *cur)
6245 struct bpf_verifier_state_list *sl;
6248 sl = *explored_state(env, insn);
6250 if (sl->state.insn_idx != insn ||
6251 sl->state.curframe != cur->curframe)
6253 for (i = 0; i <= cur->curframe; i++)
6254 if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
6256 clean_verifier_state(env, &sl->state);
6262 /* Returns true if (rold safe implies rcur safe) */
6263 static bool regsafe(struct bpf_reg_state *rold, struct bpf_reg_state *rcur,
6264 struct idpair *idmap)
6268 if (!(rold->live & REG_LIVE_READ))
6269 /* explored state didn't use this */
6272 equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, parent)) == 0;
6274 if (rold->type == PTR_TO_STACK)
6275 /* two stack pointers are equal only if they're pointing to
6276 * the same stack frame, since fp-8 in foo != fp-8 in bar
6278 return equal && rold->frameno == rcur->frameno;
6283 if (rold->type == NOT_INIT)
6284 /* explored state can't have used this */
6286 if (rcur->type == NOT_INIT)
6288 switch (rold->type) {
6290 if (rcur->type == SCALAR_VALUE) {
6291 /* new val must satisfy old val knowledge */
6292 return range_within(rold, rcur) &&
6293 tnum_in(rold->var_off, rcur->var_off);
6295 /* We're trying to use a pointer in place of a scalar.
6296 * Even if the scalar was unbounded, this could lead to
6297 * pointer leaks because scalars are allowed to leak
6298 * while pointers are not. We could make this safe in
6299 * special cases if root is calling us, but it's
6300 * probably not worth the hassle.
6304 case PTR_TO_MAP_VALUE:
6305 /* If the new min/max/var_off satisfy the old ones and
6306 * everything else matches, we are OK.
6307 * 'id' is not compared, since it's only used for maps with
6308 * bpf_spin_lock inside map element and in such cases if
6309 * the rest of the prog is valid for one map element then
6310 * it's valid for all map elements regardless of the key
6311 * used in bpf_map_lookup()
6313 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
6314 range_within(rold, rcur) &&
6315 tnum_in(rold->var_off, rcur->var_off);
6316 case PTR_TO_MAP_VALUE_OR_NULL:
6317 /* a PTR_TO_MAP_VALUE could be safe to use as a
6318 * PTR_TO_MAP_VALUE_OR_NULL into the same map.
6319 * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
6320 * checked, doing so could have affected others with the same
6321 * id, and we can't check for that because we lost the id when
6322 * we converted to a PTR_TO_MAP_VALUE.
6324 if (rcur->type != PTR_TO_MAP_VALUE_OR_NULL)
6326 if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
6328 /* Check our ids match any regs they're supposed to */
6329 return check_ids(rold->id, rcur->id, idmap);
6330 case PTR_TO_PACKET_META:
6332 if (rcur->type != rold->type)
6334 /* We must have at least as much range as the old ptr
6335 * did, so that any accesses which were safe before are
6336 * still safe. This is true even if old range < old off,
6337 * since someone could have accessed through (ptr - k), or
6338 * even done ptr -= k in a register, to get a safe access.
6340 if (rold->range > rcur->range)
6342 /* If the offsets don't match, we can't trust our alignment;
6343 * nor can we be sure that we won't fall out of range.
6345 if (rold->off != rcur->off)
6347 /* id relations must be preserved */
6348 if (rold->id && !check_ids(rold->id, rcur->id, idmap))
6350 /* new val must satisfy old val knowledge */
6351 return range_within(rold, rcur) &&
6352 tnum_in(rold->var_off, rcur->var_off);
6354 case CONST_PTR_TO_MAP:
6355 case PTR_TO_PACKET_END:
6356 case PTR_TO_FLOW_KEYS:
6358 case PTR_TO_SOCKET_OR_NULL:
6359 case PTR_TO_SOCK_COMMON:
6360 case PTR_TO_SOCK_COMMON_OR_NULL:
6361 case PTR_TO_TCP_SOCK:
6362 case PTR_TO_TCP_SOCK_OR_NULL:
6363 case PTR_TO_XDP_SOCK:
6364 /* Only valid matches are exact, which memcmp() above
6365 * would have accepted
6368 /* Don't know what's going on, just say it's not safe */
6372 /* Shouldn't get here; if we do, say it's not safe */
6377 static bool stacksafe(struct bpf_func_state *old,
6378 struct bpf_func_state *cur,
6379 struct idpair *idmap)
6383 /* walk slots of the explored stack and ignore any additional
6384 * slots in the current stack, since explored(safe) state
6387 for (i = 0; i < old->allocated_stack; i++) {
6388 spi = i / BPF_REG_SIZE;
6390 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
6391 i += BPF_REG_SIZE - 1;
6392 /* explored state didn't use this */
6396 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
6399 /* explored stack has more populated slots than current stack
6400 * and these slots were used
6402 if (i >= cur->allocated_stack)
6405 /* if old state was safe with misc data in the stack
6406 * it will be safe with zero-initialized stack.
6407 * The opposite is not true
6409 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
6410 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
6412 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
6413 cur->stack[spi].slot_type[i % BPF_REG_SIZE])
6414 /* Ex: old explored (safe) state has STACK_SPILL in
6415 * this stack slot, but current has has STACK_MISC ->
6416 * this verifier states are not equivalent,
6417 * return false to continue verification of this path
6420 if (i % BPF_REG_SIZE)
6422 if (old->stack[spi].slot_type[0] != STACK_SPILL)
6424 if (!regsafe(&old->stack[spi].spilled_ptr,
6425 &cur->stack[spi].spilled_ptr,
6427 /* when explored and current stack slot are both storing
6428 * spilled registers, check that stored pointers types
6429 * are the same as well.
6430 * Ex: explored safe path could have stored
6431 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
6432 * but current path has stored:
6433 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
6434 * such verifier states are not equivalent.
6435 * return false to continue verification of this path
6442 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur)
6444 if (old->acquired_refs != cur->acquired_refs)
6446 return !memcmp(old->refs, cur->refs,
6447 sizeof(*old->refs) * old->acquired_refs);
6450 /* compare two verifier states
6452 * all states stored in state_list are known to be valid, since
6453 * verifier reached 'bpf_exit' instruction through them
6455 * this function is called when verifier exploring different branches of
6456 * execution popped from the state stack. If it sees an old state that has
6457 * more strict register state and more strict stack state then this execution
6458 * branch doesn't need to be explored further, since verifier already
6459 * concluded that more strict state leads to valid finish.
6461 * Therefore two states are equivalent if register state is more conservative
6462 * and explored stack state is more conservative than the current one.
6465 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
6466 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
6468 * In other words if current stack state (one being explored) has more
6469 * valid slots than old one that already passed validation, it means
6470 * the verifier can stop exploring and conclude that current state is valid too
6472 * Similarly with registers. If explored state has register type as invalid
6473 * whereas register type in current state is meaningful, it means that
6474 * the current state will reach 'bpf_exit' instruction safely
6476 static bool func_states_equal(struct bpf_func_state *old,
6477 struct bpf_func_state *cur)
6479 struct idpair *idmap;
6483 idmap = kcalloc(ID_MAP_SIZE, sizeof(struct idpair), GFP_KERNEL);
6484 /* If we failed to allocate the idmap, just say it's not safe */
6488 for (i = 0; i < MAX_BPF_REG; i++) {
6489 if (!regsafe(&old->regs[i], &cur->regs[i], idmap))
6493 if (!stacksafe(old, cur, idmap))
6496 if (!refsafe(old, cur))
6504 static bool states_equal(struct bpf_verifier_env *env,
6505 struct bpf_verifier_state *old,
6506 struct bpf_verifier_state *cur)
6510 if (old->curframe != cur->curframe)
6513 /* Verification state from speculative execution simulation
6514 * must never prune a non-speculative execution one.
6516 if (old->speculative && !cur->speculative)
6519 if (old->active_spin_lock != cur->active_spin_lock)
6522 /* for states to be equal callsites have to be the same
6523 * and all frame states need to be equivalent
6525 for (i = 0; i <= old->curframe; i++) {
6526 if (old->frame[i]->callsite != cur->frame[i]->callsite)
6528 if (!func_states_equal(old->frame[i], cur->frame[i]))
6534 /* Return 0 if no propagation happened. Return negative error code if error
6535 * happened. Otherwise, return the propagated bit.
6537 static int propagate_liveness_reg(struct bpf_verifier_env *env,
6538 struct bpf_reg_state *reg,
6539 struct bpf_reg_state *parent_reg)
6541 u8 parent_flag = parent_reg->live & REG_LIVE_READ;
6542 u8 flag = reg->live & REG_LIVE_READ;
6545 /* When comes here, read flags of PARENT_REG or REG could be any of
6546 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
6547 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
6549 if (parent_flag == REG_LIVE_READ64 ||
6550 /* Or if there is no read flag from REG. */
6552 /* Or if the read flag from REG is the same as PARENT_REG. */
6553 parent_flag == flag)
6556 err = mark_reg_read(env, reg, parent_reg, flag);
6563 /* A write screens off any subsequent reads; but write marks come from the
6564 * straight-line code between a state and its parent. When we arrive at an
6565 * equivalent state (jump target or such) we didn't arrive by the straight-line
6566 * code, so read marks in the state must propagate to the parent regardless
6567 * of the state's write marks. That's what 'parent == state->parent' comparison
6568 * in mark_reg_read() is for.
6570 static int propagate_liveness(struct bpf_verifier_env *env,
6571 const struct bpf_verifier_state *vstate,
6572 struct bpf_verifier_state *vparent)
6574 struct bpf_reg_state *state_reg, *parent_reg;
6575 struct bpf_func_state *state, *parent;
6576 int i, frame, err = 0;
6578 if (vparent->curframe != vstate->curframe) {
6579 WARN(1, "propagate_live: parent frame %d current frame %d\n",
6580 vparent->curframe, vstate->curframe);
6583 /* Propagate read liveness of registers... */
6584 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
6585 for (frame = 0; frame <= vstate->curframe; frame++) {
6586 parent = vparent->frame[frame];
6587 state = vstate->frame[frame];
6588 parent_reg = parent->regs;
6589 state_reg = state->regs;
6590 /* We don't need to worry about FP liveness, it's read-only */
6591 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
6592 err = propagate_liveness_reg(env, &state_reg[i],
6596 if (err == REG_LIVE_READ64)
6597 mark_insn_zext(env, &parent_reg[i]);
6600 /* Propagate stack slots. */
6601 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
6602 i < parent->allocated_stack / BPF_REG_SIZE; i++) {
6603 parent_reg = &parent->stack[i].spilled_ptr;
6604 state_reg = &state->stack[i].spilled_ptr;
6605 err = propagate_liveness_reg(env, state_reg,
6614 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
6616 struct bpf_verifier_state_list *new_sl;
6617 struct bpf_verifier_state_list *sl, **pprev;
6618 struct bpf_verifier_state *cur = env->cur_state, *new;
6619 int i, j, err, states_cnt = 0;
6621 if (!env->insn_aux_data[insn_idx].prune_point)
6622 /* this 'insn_idx' instruction wasn't marked, so we will not
6623 * be doing state search here
6627 pprev = explored_state(env, insn_idx);
6630 clean_live_states(env, insn_idx, cur);
6634 if (sl->state.insn_idx != insn_idx)
6636 if (states_equal(env, &sl->state, cur)) {
6638 /* reached equivalent register/stack state,
6640 * Registers read by the continuation are read by us.
6641 * If we have any write marks in env->cur_state, they
6642 * will prevent corresponding reads in the continuation
6643 * from reaching our parent (an explored_state). Our
6644 * own state will get the read marks recorded, but
6645 * they'll be immediately forgotten as we're pruning
6646 * this state and will pop a new one.
6648 err = propagate_liveness(env, &sl->state, cur);
6654 /* heuristic to determine whether this state is beneficial
6655 * to keep checking from state equivalence point of view.
6656 * Higher numbers increase max_states_per_insn and verification time,
6657 * but do not meaningfully decrease insn_processed.
6659 if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
6660 /* the state is unlikely to be useful. Remove it to
6661 * speed up verification
6664 if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
6665 free_verifier_state(&sl->state, false);
6669 /* cannot free this state, since parentage chain may
6670 * walk it later. Add it for free_list instead to
6671 * be freed at the end of verification
6673 sl->next = env->free_list;
6674 env->free_list = sl;
6684 if (env->max_states_per_insn < states_cnt)
6685 env->max_states_per_insn = states_cnt;
6687 if (!env->allow_ptr_leaks && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
6690 /* there were no equivalent states, remember current one.
6691 * technically the current state is not proven to be safe yet,
6692 * but it will either reach outer most bpf_exit (which means it's safe)
6693 * or it will be rejected. Since there are no loops, we won't be
6694 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
6695 * again on the way to bpf_exit
6697 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
6700 env->total_states++;
6703 /* add new state to the head of linked list */
6704 new = &new_sl->state;
6705 err = copy_verifier_state(new, cur);
6707 free_verifier_state(new, false);
6711 new->insn_idx = insn_idx;
6712 new_sl->next = *explored_state(env, insn_idx);
6713 *explored_state(env, insn_idx) = new_sl;
6714 /* connect new state to parentage chain. Current frame needs all
6715 * registers connected. Only r6 - r9 of the callers are alive (pushed
6716 * to the stack implicitly by JITs) so in callers' frames connect just
6717 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
6718 * the state of the call instruction (with WRITTEN set), and r0 comes
6719 * from callee with its full parentage chain, anyway.
6721 for (j = 0; j <= cur->curframe; j++)
6722 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
6723 cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
6724 /* clear write marks in current state: the writes we did are not writes
6725 * our child did, so they don't screen off its reads from us.
6726 * (There are no read marks in current state, because reads always mark
6727 * their parent and current state never has children yet. Only
6728 * explored_states can get read marks.)
6730 for (i = 0; i < BPF_REG_FP; i++)
6731 cur->frame[cur->curframe]->regs[i].live = REG_LIVE_NONE;
6733 /* all stack frames are accessible from callee, clear them all */
6734 for (j = 0; j <= cur->curframe; j++) {
6735 struct bpf_func_state *frame = cur->frame[j];
6736 struct bpf_func_state *newframe = new->frame[j];
6738 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
6739 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
6740 frame->stack[i].spilled_ptr.parent =
6741 &newframe->stack[i].spilled_ptr;
6747 /* Return true if it's OK to have the same insn return a different type. */
6748 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
6753 case PTR_TO_SOCKET_OR_NULL:
6754 case PTR_TO_SOCK_COMMON:
6755 case PTR_TO_SOCK_COMMON_OR_NULL:
6756 case PTR_TO_TCP_SOCK:
6757 case PTR_TO_TCP_SOCK_OR_NULL:
6758 case PTR_TO_XDP_SOCK:
6765 /* If an instruction was previously used with particular pointer types, then we
6766 * need to be careful to avoid cases such as the below, where it may be ok
6767 * for one branch accessing the pointer, but not ok for the other branch:
6772 * R1 = some_other_valid_ptr;
6775 * R2 = *(u32 *)(R1 + 0);
6777 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
6779 return src != prev && (!reg_type_mismatch_ok(src) ||
6780 !reg_type_mismatch_ok(prev));
6783 static int do_check(struct bpf_verifier_env *env)
6785 struct bpf_verifier_state *state;
6786 struct bpf_insn *insns = env->prog->insnsi;
6787 struct bpf_reg_state *regs;
6788 int insn_cnt = env->prog->len;
6789 bool do_print_state = false;
6791 env->prev_linfo = NULL;
6793 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
6796 state->curframe = 0;
6797 state->speculative = false;
6798 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
6799 if (!state->frame[0]) {
6803 env->cur_state = state;
6804 init_func_state(env, state->frame[0],
6805 BPF_MAIN_FUNC /* callsite */,
6807 0 /* subprogno, zero == main subprog */);
6810 struct bpf_insn *insn;
6814 if (env->insn_idx >= insn_cnt) {
6815 verbose(env, "invalid insn idx %d insn_cnt %d\n",
6816 env->insn_idx, insn_cnt);
6820 insn = &insns[env->insn_idx];
6821 class = BPF_CLASS(insn->code);
6823 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
6825 "BPF program is too large. Processed %d insn\n",
6826 env->insn_processed);
6830 err = is_state_visited(env, env->insn_idx);
6834 /* found equivalent state, can prune the search */
6835 if (env->log.level & BPF_LOG_LEVEL) {
6837 verbose(env, "\nfrom %d to %d%s: safe\n",
6838 env->prev_insn_idx, env->insn_idx,
6839 env->cur_state->speculative ?
6840 " (speculative execution)" : "");
6842 verbose(env, "%d: safe\n", env->insn_idx);
6844 goto process_bpf_exit;
6847 if (signal_pending(current))
6853 if (env->log.level & BPF_LOG_LEVEL2 ||
6854 (env->log.level & BPF_LOG_LEVEL && do_print_state)) {
6855 if (env->log.level & BPF_LOG_LEVEL2)
6856 verbose(env, "%d:", env->insn_idx);
6858 verbose(env, "\nfrom %d to %d%s:",
6859 env->prev_insn_idx, env->insn_idx,
6860 env->cur_state->speculative ?
6861 " (speculative execution)" : "");
6862 print_verifier_state(env, state->frame[state->curframe]);
6863 do_print_state = false;
6866 if (env->log.level & BPF_LOG_LEVEL) {
6867 const struct bpf_insn_cbs cbs = {
6868 .cb_print = verbose,
6869 .private_data = env,
6872 verbose_linfo(env, env->insn_idx, "; ");
6873 verbose(env, "%d: ", env->insn_idx);
6874 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
6877 if (bpf_prog_is_dev_bound(env->prog->aux)) {
6878 err = bpf_prog_offload_verify_insn(env, env->insn_idx,
6879 env->prev_insn_idx);
6884 regs = cur_regs(env);
6885 env->insn_aux_data[env->insn_idx].seen = true;
6887 if (class == BPF_ALU || class == BPF_ALU64) {
6888 err = check_alu_op(env, insn);
6892 } else if (class == BPF_LDX) {
6893 enum bpf_reg_type *prev_src_type, src_reg_type;
6895 /* check for reserved fields is already done */
6897 /* check src operand */
6898 err = check_reg_arg(env, insn->src_reg, SRC_OP);
6902 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
6906 src_reg_type = regs[insn->src_reg].type;
6908 /* check that memory (src_reg + off) is readable,
6909 * the state of dst_reg will be updated by this func
6911 err = check_mem_access(env, env->insn_idx, insn->src_reg,
6912 insn->off, BPF_SIZE(insn->code),
6913 BPF_READ, insn->dst_reg, false);
6917 prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type;
6919 if (*prev_src_type == NOT_INIT) {
6921 * dst_reg = *(u32 *)(src_reg + off)
6922 * save type to validate intersecting paths
6924 *prev_src_type = src_reg_type;
6926 } else if (reg_type_mismatch(src_reg_type, *prev_src_type)) {
6927 /* ABuser program is trying to use the same insn
6928 * dst_reg = *(u32*) (src_reg + off)
6929 * with different pointer types:
6930 * src_reg == ctx in one branch and
6931 * src_reg == stack|map in some other branch.
6934 verbose(env, "same insn cannot be used with different pointers\n");
6938 } else if (class == BPF_STX) {
6939 enum bpf_reg_type *prev_dst_type, dst_reg_type;
6941 if (BPF_MODE(insn->code) == BPF_XADD) {
6942 err = check_xadd(env, env->insn_idx, insn);
6949 /* check src1 operand */
6950 err = check_reg_arg(env, insn->src_reg, SRC_OP);
6953 /* check src2 operand */
6954 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
6958 dst_reg_type = regs[insn->dst_reg].type;
6960 /* check that memory (dst_reg + off) is writeable */
6961 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
6962 insn->off, BPF_SIZE(insn->code),
6963 BPF_WRITE, insn->src_reg, false);
6967 prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type;
6969 if (*prev_dst_type == NOT_INIT) {
6970 *prev_dst_type = dst_reg_type;
6971 } else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) {
6972 verbose(env, "same insn cannot be used with different pointers\n");
6976 } else if (class == BPF_ST) {
6977 if (BPF_MODE(insn->code) != BPF_MEM ||
6978 insn->src_reg != BPF_REG_0) {
6979 verbose(env, "BPF_ST uses reserved fields\n");
6982 /* check src operand */
6983 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
6987 if (is_ctx_reg(env, insn->dst_reg)) {
6988 verbose(env, "BPF_ST stores into R%d %s is not allowed\n",
6990 reg_type_str[reg_state(env, insn->dst_reg)->type]);
6994 /* check that memory (dst_reg + off) is writeable */
6995 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
6996 insn->off, BPF_SIZE(insn->code),
6997 BPF_WRITE, -1, false);
7001 } else if (class == BPF_JMP || class == BPF_JMP32) {
7002 u8 opcode = BPF_OP(insn->code);
7004 if (opcode == BPF_CALL) {
7005 if (BPF_SRC(insn->code) != BPF_K ||
7007 (insn->src_reg != BPF_REG_0 &&
7008 insn->src_reg != BPF_PSEUDO_CALL) ||
7009 insn->dst_reg != BPF_REG_0 ||
7010 class == BPF_JMP32) {
7011 verbose(env, "BPF_CALL uses reserved fields\n");
7015 if (env->cur_state->active_spin_lock &&
7016 (insn->src_reg == BPF_PSEUDO_CALL ||
7017 insn->imm != BPF_FUNC_spin_unlock)) {
7018 verbose(env, "function calls are not allowed while holding a lock\n");
7021 if (insn->src_reg == BPF_PSEUDO_CALL)
7022 err = check_func_call(env, insn, &env->insn_idx);
7024 err = check_helper_call(env, insn->imm, env->insn_idx);
7028 } else if (opcode == BPF_JA) {
7029 if (BPF_SRC(insn->code) != BPF_K ||
7031 insn->src_reg != BPF_REG_0 ||
7032 insn->dst_reg != BPF_REG_0 ||
7033 class == BPF_JMP32) {
7034 verbose(env, "BPF_JA uses reserved fields\n");
7038 env->insn_idx += insn->off + 1;
7041 } else if (opcode == BPF_EXIT) {
7042 if (BPF_SRC(insn->code) != BPF_K ||
7044 insn->src_reg != BPF_REG_0 ||
7045 insn->dst_reg != BPF_REG_0 ||
7046 class == BPF_JMP32) {
7047 verbose(env, "BPF_EXIT uses reserved fields\n");
7051 if (env->cur_state->active_spin_lock) {
7052 verbose(env, "bpf_spin_unlock is missing\n");
7056 if (state->curframe) {
7057 /* exit from nested function */
7058 env->prev_insn_idx = env->insn_idx;
7059 err = prepare_func_exit(env, &env->insn_idx);
7062 do_print_state = true;
7066 err = check_reference_leak(env);
7070 /* eBPF calling convetion is such that R0 is used
7071 * to return the value from eBPF program.
7072 * Make sure that it's readable at this time
7073 * of bpf_exit, which means that program wrote
7074 * something into it earlier
7076 err = check_reg_arg(env, BPF_REG_0, SRC_OP);
7080 if (is_pointer_value(env, BPF_REG_0)) {
7081 verbose(env, "R0 leaks addr as return value\n");
7085 err = check_return_code(env);
7089 err = pop_stack(env, &env->prev_insn_idx,
7096 do_print_state = true;
7100 err = check_cond_jmp_op(env, insn, &env->insn_idx);
7104 } else if (class == BPF_LD) {
7105 u8 mode = BPF_MODE(insn->code);
7107 if (mode == BPF_ABS || mode == BPF_IND) {
7108 err = check_ld_abs(env, insn);
7112 } else if (mode == BPF_IMM) {
7113 err = check_ld_imm(env, insn);
7118 env->insn_aux_data[env->insn_idx].seen = true;
7120 verbose(env, "invalid BPF_LD mode\n");
7124 verbose(env, "unknown insn class %d\n", class);
7131 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
7135 static int check_map_prealloc(struct bpf_map *map)
7137 return (map->map_type != BPF_MAP_TYPE_HASH &&
7138 map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
7139 map->map_type != BPF_MAP_TYPE_HASH_OF_MAPS) ||
7140 !(map->map_flags & BPF_F_NO_PREALLOC);
7143 static bool is_tracing_prog_type(enum bpf_prog_type type)
7146 case BPF_PROG_TYPE_KPROBE:
7147 case BPF_PROG_TYPE_TRACEPOINT:
7148 case BPF_PROG_TYPE_PERF_EVENT:
7149 case BPF_PROG_TYPE_RAW_TRACEPOINT:
7156 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
7157 struct bpf_map *map,
7158 struct bpf_prog *prog)
7161 /* Make sure that BPF_PROG_TYPE_PERF_EVENT programs only use
7162 * preallocated hash maps, since doing memory allocation
7163 * in overflow_handler can crash depending on where nmi got
7166 if (prog->type == BPF_PROG_TYPE_PERF_EVENT) {
7167 if (!check_map_prealloc(map)) {
7168 verbose(env, "perf_event programs can only use preallocated hash map\n");
7171 if (map->inner_map_meta &&
7172 !check_map_prealloc(map->inner_map_meta)) {
7173 verbose(env, "perf_event programs can only use preallocated inner hash map\n");
7178 if ((is_tracing_prog_type(prog->type) ||
7179 prog->type == BPF_PROG_TYPE_SOCKET_FILTER) &&
7180 map_value_has_spin_lock(map)) {
7181 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
7185 if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) &&
7186 !bpf_offload_prog_map_match(prog, map)) {
7187 verbose(env, "offload device mismatch between prog and map\n");
7194 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
7196 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
7197 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
7200 /* look for pseudo eBPF instructions that access map FDs and
7201 * replace them with actual map pointers
7203 static int replace_map_fd_with_map_ptr(struct bpf_verifier_env *env)
7205 struct bpf_insn *insn = env->prog->insnsi;
7206 int insn_cnt = env->prog->len;
7209 err = bpf_prog_calc_tag(env->prog);
7213 for (i = 0; i < insn_cnt; i++, insn++) {
7214 if (BPF_CLASS(insn->code) == BPF_LDX &&
7215 (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
7216 verbose(env, "BPF_LDX uses reserved fields\n");
7220 if (BPF_CLASS(insn->code) == BPF_STX &&
7221 ((BPF_MODE(insn->code) != BPF_MEM &&
7222 BPF_MODE(insn->code) != BPF_XADD) || insn->imm != 0)) {
7223 verbose(env, "BPF_STX uses reserved fields\n");
7227 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
7228 struct bpf_insn_aux_data *aux;
7229 struct bpf_map *map;
7233 if (i == insn_cnt - 1 || insn[1].code != 0 ||
7234 insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
7236 verbose(env, "invalid bpf_ld_imm64 insn\n");
7240 if (insn[0].src_reg == 0)
7241 /* valid generic load 64-bit imm */
7244 /* In final convert_pseudo_ld_imm64() step, this is
7245 * converted into regular 64-bit imm load insn.
7247 if ((insn[0].src_reg != BPF_PSEUDO_MAP_FD &&
7248 insn[0].src_reg != BPF_PSEUDO_MAP_VALUE) ||
7249 (insn[0].src_reg == BPF_PSEUDO_MAP_FD &&
7250 insn[1].imm != 0)) {
7252 "unrecognized bpf_ld_imm64 insn\n");
7256 f = fdget(insn[0].imm);
7257 map = __bpf_map_get(f);
7259 verbose(env, "fd %d is not pointing to valid bpf_map\n",
7261 return PTR_ERR(map);
7264 err = check_map_prog_compatibility(env, map, env->prog);
7270 aux = &env->insn_aux_data[i];
7271 if (insn->src_reg == BPF_PSEUDO_MAP_FD) {
7272 addr = (unsigned long)map;
7274 u32 off = insn[1].imm;
7276 if (off >= BPF_MAX_VAR_OFF) {
7277 verbose(env, "direct value offset of %u is not allowed\n", off);
7282 if (!map->ops->map_direct_value_addr) {
7283 verbose(env, "no direct value access support for this map type\n");
7288 err = map->ops->map_direct_value_addr(map, &addr, off);
7290 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
7291 map->value_size, off);
7300 insn[0].imm = (u32)addr;
7301 insn[1].imm = addr >> 32;
7303 /* check whether we recorded this map already */
7304 for (j = 0; j < env->used_map_cnt; j++) {
7305 if (env->used_maps[j] == map) {
7312 if (env->used_map_cnt >= MAX_USED_MAPS) {
7317 /* hold the map. If the program is rejected by verifier,
7318 * the map will be released by release_maps() or it
7319 * will be used by the valid program until it's unloaded
7320 * and all maps are released in free_used_maps()
7322 map = bpf_map_inc(map, false);
7325 return PTR_ERR(map);
7328 aux->map_index = env->used_map_cnt;
7329 env->used_maps[env->used_map_cnt++] = map;
7331 if (bpf_map_is_cgroup_storage(map) &&
7332 bpf_cgroup_storage_assign(env->prog, map)) {
7333 verbose(env, "only one cgroup storage of each type is allowed\n");
7345 /* Basic sanity check before we invest more work here. */
7346 if (!bpf_opcode_in_insntable(insn->code)) {
7347 verbose(env, "unknown opcode %02x\n", insn->code);
7352 /* now all pseudo BPF_LD_IMM64 instructions load valid
7353 * 'struct bpf_map *' into a register instead of user map_fd.
7354 * These pointers will be used later by verifier to validate map access.
7359 /* drop refcnt of maps used by the rejected program */
7360 static void release_maps(struct bpf_verifier_env *env)
7362 enum bpf_cgroup_storage_type stype;
7365 for_each_cgroup_storage_type(stype) {
7366 if (!env->prog->aux->cgroup_storage[stype])
7368 bpf_cgroup_storage_release(env->prog,
7369 env->prog->aux->cgroup_storage[stype]);
7372 for (i = 0; i < env->used_map_cnt; i++)
7373 bpf_map_put(env->used_maps[i]);
7376 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
7377 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
7379 struct bpf_insn *insn = env->prog->insnsi;
7380 int insn_cnt = env->prog->len;
7383 for (i = 0; i < insn_cnt; i++, insn++)
7384 if (insn->code == (BPF_LD | BPF_IMM | BPF_DW))
7388 /* single env->prog->insni[off] instruction was replaced with the range
7389 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying
7390 * [0, off) and [off, end) to new locations, so the patched range stays zero
7392 static int adjust_insn_aux_data(struct bpf_verifier_env *env,
7393 struct bpf_prog *new_prog, u32 off, u32 cnt)
7395 struct bpf_insn_aux_data *new_data, *old_data = env->insn_aux_data;
7396 struct bpf_insn *insn = new_prog->insnsi;
7400 /* aux info at OFF always needs adjustment, no matter fast path
7401 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
7402 * original insn at old prog.
7404 old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
7408 prog_len = new_prog->len;
7409 new_data = vzalloc(array_size(prog_len,
7410 sizeof(struct bpf_insn_aux_data)));
7413 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
7414 memcpy(new_data + off + cnt - 1, old_data + off,
7415 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
7416 for (i = off; i < off + cnt - 1; i++) {
7417 new_data[i].seen = true;
7418 new_data[i].zext_dst = insn_has_def32(env, insn + i);
7420 env->insn_aux_data = new_data;
7425 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
7431 /* NOTE: fake 'exit' subprog should be updated as well. */
7432 for (i = 0; i <= env->subprog_cnt; i++) {
7433 if (env->subprog_info[i].start <= off)
7435 env->subprog_info[i].start += len - 1;
7439 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
7440 const struct bpf_insn *patch, u32 len)
7442 struct bpf_prog *new_prog;
7444 new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
7445 if (IS_ERR(new_prog)) {
7446 if (PTR_ERR(new_prog) == -ERANGE)
7448 "insn %d cannot be patched due to 16-bit range\n",
7449 env->insn_aux_data[off].orig_idx);
7452 if (adjust_insn_aux_data(env, new_prog, off, len))
7454 adjust_subprog_starts(env, off, len);
7458 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
7463 /* find first prog starting at or after off (first to remove) */
7464 for (i = 0; i < env->subprog_cnt; i++)
7465 if (env->subprog_info[i].start >= off)
7467 /* find first prog starting at or after off + cnt (first to stay) */
7468 for (j = i; j < env->subprog_cnt; j++)
7469 if (env->subprog_info[j].start >= off + cnt)
7471 /* if j doesn't start exactly at off + cnt, we are just removing
7472 * the front of previous prog
7474 if (env->subprog_info[j].start != off + cnt)
7478 struct bpf_prog_aux *aux = env->prog->aux;
7481 /* move fake 'exit' subprog as well */
7482 move = env->subprog_cnt + 1 - j;
7484 memmove(env->subprog_info + i,
7485 env->subprog_info + j,
7486 sizeof(*env->subprog_info) * move);
7487 env->subprog_cnt -= j - i;
7489 /* remove func_info */
7490 if (aux->func_info) {
7491 move = aux->func_info_cnt - j;
7493 memmove(aux->func_info + i,
7495 sizeof(*aux->func_info) * move);
7496 aux->func_info_cnt -= j - i;
7497 /* func_info->insn_off is set after all code rewrites,
7498 * in adjust_btf_func() - no need to adjust
7502 /* convert i from "first prog to remove" to "first to adjust" */
7503 if (env->subprog_info[i].start == off)
7507 /* update fake 'exit' subprog as well */
7508 for (; i <= env->subprog_cnt; i++)
7509 env->subprog_info[i].start -= cnt;
7514 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
7517 struct bpf_prog *prog = env->prog;
7518 u32 i, l_off, l_cnt, nr_linfo;
7519 struct bpf_line_info *linfo;
7521 nr_linfo = prog->aux->nr_linfo;
7525 linfo = prog->aux->linfo;
7527 /* find first line info to remove, count lines to be removed */
7528 for (i = 0; i < nr_linfo; i++)
7529 if (linfo[i].insn_off >= off)
7534 for (; i < nr_linfo; i++)
7535 if (linfo[i].insn_off < off + cnt)
7540 /* First live insn doesn't match first live linfo, it needs to "inherit"
7541 * last removed linfo. prog is already modified, so prog->len == off
7542 * means no live instructions after (tail of the program was removed).
7544 if (prog->len != off && l_cnt &&
7545 (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
7547 linfo[--i].insn_off = off + cnt;
7550 /* remove the line info which refer to the removed instructions */
7552 memmove(linfo + l_off, linfo + i,
7553 sizeof(*linfo) * (nr_linfo - i));
7555 prog->aux->nr_linfo -= l_cnt;
7556 nr_linfo = prog->aux->nr_linfo;
7559 /* pull all linfo[i].insn_off >= off + cnt in by cnt */
7560 for (i = l_off; i < nr_linfo; i++)
7561 linfo[i].insn_off -= cnt;
7563 /* fix up all subprogs (incl. 'exit') which start >= off */
7564 for (i = 0; i <= env->subprog_cnt; i++)
7565 if (env->subprog_info[i].linfo_idx > l_off) {
7566 /* program may have started in the removed region but
7567 * may not be fully removed
7569 if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
7570 env->subprog_info[i].linfo_idx -= l_cnt;
7572 env->subprog_info[i].linfo_idx = l_off;
7578 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
7580 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
7581 unsigned int orig_prog_len = env->prog->len;
7584 if (bpf_prog_is_dev_bound(env->prog->aux))
7585 bpf_prog_offload_remove_insns(env, off, cnt);
7587 err = bpf_remove_insns(env->prog, off, cnt);
7591 err = adjust_subprog_starts_after_remove(env, off, cnt);
7595 err = bpf_adj_linfo_after_remove(env, off, cnt);
7599 memmove(aux_data + off, aux_data + off + cnt,
7600 sizeof(*aux_data) * (orig_prog_len - off - cnt));
7605 /* The verifier does more data flow analysis than llvm and will not
7606 * explore branches that are dead at run time. Malicious programs can
7607 * have dead code too. Therefore replace all dead at-run-time code
7610 * Just nops are not optimal, e.g. if they would sit at the end of the
7611 * program and through another bug we would manage to jump there, then
7612 * we'd execute beyond program memory otherwise. Returning exception
7613 * code also wouldn't work since we can have subprogs where the dead
7614 * code could be located.
7616 static void sanitize_dead_code(struct bpf_verifier_env *env)
7618 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
7619 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
7620 struct bpf_insn *insn = env->prog->insnsi;
7621 const int insn_cnt = env->prog->len;
7624 for (i = 0; i < insn_cnt; i++) {
7625 if (aux_data[i].seen)
7627 memcpy(insn + i, &trap, sizeof(trap));
7631 static bool insn_is_cond_jump(u8 code)
7635 if (BPF_CLASS(code) == BPF_JMP32)
7638 if (BPF_CLASS(code) != BPF_JMP)
7642 return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
7645 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
7647 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
7648 struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
7649 struct bpf_insn *insn = env->prog->insnsi;
7650 const int insn_cnt = env->prog->len;
7653 for (i = 0; i < insn_cnt; i++, insn++) {
7654 if (!insn_is_cond_jump(insn->code))
7657 if (!aux_data[i + 1].seen)
7659 else if (!aux_data[i + 1 + insn->off].seen)
7664 if (bpf_prog_is_dev_bound(env->prog->aux))
7665 bpf_prog_offload_replace_insn(env, i, &ja);
7667 memcpy(insn, &ja, sizeof(ja));
7671 static int opt_remove_dead_code(struct bpf_verifier_env *env)
7673 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
7674 int insn_cnt = env->prog->len;
7677 for (i = 0; i < insn_cnt; i++) {
7681 while (i + j < insn_cnt && !aux_data[i + j].seen)
7686 err = verifier_remove_insns(env, i, j);
7689 insn_cnt = env->prog->len;
7695 static int opt_remove_nops(struct bpf_verifier_env *env)
7697 const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
7698 struct bpf_insn *insn = env->prog->insnsi;
7699 int insn_cnt = env->prog->len;
7702 for (i = 0; i < insn_cnt; i++) {
7703 if (memcmp(&insn[i], &ja, sizeof(ja)))
7706 err = verifier_remove_insns(env, i, 1);
7716 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
7717 const union bpf_attr *attr)
7719 struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
7720 struct bpf_insn_aux_data *aux = env->insn_aux_data;
7721 int i, patch_len, delta = 0, len = env->prog->len;
7722 struct bpf_insn *insns = env->prog->insnsi;
7723 struct bpf_prog *new_prog;
7726 rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
7727 zext_patch[1] = BPF_ZEXT_REG(0);
7728 rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
7729 rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
7730 rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
7731 for (i = 0; i < len; i++) {
7732 int adj_idx = i + delta;
7733 struct bpf_insn insn;
7735 insn = insns[adj_idx];
7736 if (!aux[adj_idx].zext_dst) {
7744 class = BPF_CLASS(code);
7745 if (insn_no_def(&insn))
7748 /* NOTE: arg "reg" (the fourth one) is only used for
7749 * BPF_STX which has been ruled out in above
7750 * check, it is safe to pass NULL here.
7752 if (is_reg64(env, &insn, insn.dst_reg, NULL, DST_OP)) {
7753 if (class == BPF_LD &&
7754 BPF_MODE(code) == BPF_IMM)
7759 /* ctx load could be transformed into wider load. */
7760 if (class == BPF_LDX &&
7761 aux[adj_idx].ptr_type == PTR_TO_CTX)
7764 imm_rnd = get_random_int();
7765 rnd_hi32_patch[0] = insn;
7766 rnd_hi32_patch[1].imm = imm_rnd;
7767 rnd_hi32_patch[3].dst_reg = insn.dst_reg;
7768 patch = rnd_hi32_patch;
7770 goto apply_patch_buffer;
7773 if (!bpf_jit_needs_zext())
7776 zext_patch[0] = insn;
7777 zext_patch[1].dst_reg = insn.dst_reg;
7778 zext_patch[1].src_reg = insn.dst_reg;
7782 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
7785 env->prog = new_prog;
7786 insns = new_prog->insnsi;
7787 aux = env->insn_aux_data;
7788 delta += patch_len - 1;
7794 /* convert load instructions that access fields of a context type into a
7795 * sequence of instructions that access fields of the underlying structure:
7796 * struct __sk_buff -> struct sk_buff
7797 * struct bpf_sock_ops -> struct sock
7799 static int convert_ctx_accesses(struct bpf_verifier_env *env)
7801 const struct bpf_verifier_ops *ops = env->ops;
7802 int i, cnt, size, ctx_field_size, delta = 0;
7803 const int insn_cnt = env->prog->len;
7804 struct bpf_insn insn_buf[16], *insn;
7805 u32 target_size, size_default, off;
7806 struct bpf_prog *new_prog;
7807 enum bpf_access_type type;
7808 bool is_narrower_load;
7810 if (ops->gen_prologue || env->seen_direct_write) {
7811 if (!ops->gen_prologue) {
7812 verbose(env, "bpf verifier is misconfigured\n");
7815 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
7817 if (cnt >= ARRAY_SIZE(insn_buf)) {
7818 verbose(env, "bpf verifier is misconfigured\n");
7821 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
7825 env->prog = new_prog;
7830 if (bpf_prog_is_dev_bound(env->prog->aux))
7833 insn = env->prog->insnsi + delta;
7835 for (i = 0; i < insn_cnt; i++, insn++) {
7836 bpf_convert_ctx_access_t convert_ctx_access;
7838 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
7839 insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
7840 insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
7841 insn->code == (BPF_LDX | BPF_MEM | BPF_DW))
7843 else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
7844 insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
7845 insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
7846 insn->code == (BPF_STX | BPF_MEM | BPF_DW))
7851 if (type == BPF_WRITE &&
7852 env->insn_aux_data[i + delta].sanitize_stack_off) {
7853 struct bpf_insn patch[] = {
7854 /* Sanitize suspicious stack slot with zero.
7855 * There are no memory dependencies for this store,
7856 * since it's only using frame pointer and immediate
7859 BPF_ST_MEM(BPF_DW, BPF_REG_FP,
7860 env->insn_aux_data[i + delta].sanitize_stack_off,
7862 /* the original STX instruction will immediately
7863 * overwrite the same stack slot with appropriate value
7868 cnt = ARRAY_SIZE(patch);
7869 new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
7874 env->prog = new_prog;
7875 insn = new_prog->insnsi + i + delta;
7879 switch (env->insn_aux_data[i + delta].ptr_type) {
7881 if (!ops->convert_ctx_access)
7883 convert_ctx_access = ops->convert_ctx_access;
7886 case PTR_TO_SOCK_COMMON:
7887 convert_ctx_access = bpf_sock_convert_ctx_access;
7889 case PTR_TO_TCP_SOCK:
7890 convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
7892 case PTR_TO_XDP_SOCK:
7893 convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
7899 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
7900 size = BPF_LDST_BYTES(insn);
7902 /* If the read access is a narrower load of the field,
7903 * convert to a 4/8-byte load, to minimum program type specific
7904 * convert_ctx_access changes. If conversion is successful,
7905 * we will apply proper mask to the result.
7907 is_narrower_load = size < ctx_field_size;
7908 size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
7910 if (is_narrower_load) {
7913 if (type == BPF_WRITE) {
7914 verbose(env, "bpf verifier narrow ctx access misconfigured\n");
7919 if (ctx_field_size == 4)
7921 else if (ctx_field_size == 8)
7924 insn->off = off & ~(size_default - 1);
7925 insn->code = BPF_LDX | BPF_MEM | size_code;
7929 cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
7931 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
7932 (ctx_field_size && !target_size)) {
7933 verbose(env, "bpf verifier is misconfigured\n");
7937 if (is_narrower_load && size < target_size) {
7938 u8 shift = (off & (size_default - 1)) * 8;
7940 if (ctx_field_size <= 4) {
7942 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
7945 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
7946 (1 << size * 8) - 1);
7949 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
7952 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
7953 (1ULL << size * 8) - 1);
7957 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
7963 /* keep walking new program and skip insns we just inserted */
7964 env->prog = new_prog;
7965 insn = new_prog->insnsi + i + delta;
7971 static int jit_subprogs(struct bpf_verifier_env *env)
7973 struct bpf_prog *prog = env->prog, **func, *tmp;
7974 int i, j, subprog_start, subprog_end = 0, len, subprog;
7975 struct bpf_insn *insn;
7979 if (env->subprog_cnt <= 1)
7982 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
7983 if (insn->code != (BPF_JMP | BPF_CALL) ||
7984 insn->src_reg != BPF_PSEUDO_CALL)
7986 /* Upon error here we cannot fall back to interpreter but
7987 * need a hard reject of the program. Thus -EFAULT is
7988 * propagated in any case.
7990 subprog = find_subprog(env, i + insn->imm + 1);
7992 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
7996 /* temporarily remember subprog id inside insn instead of
7997 * aux_data, since next loop will split up all insns into funcs
7999 insn->off = subprog;
8000 /* remember original imm in case JIT fails and fallback
8001 * to interpreter will be needed
8003 env->insn_aux_data[i].call_imm = insn->imm;
8004 /* point imm to __bpf_call_base+1 from JITs point of view */
8008 err = bpf_prog_alloc_jited_linfo(prog);
8013 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
8017 for (i = 0; i < env->subprog_cnt; i++) {
8018 subprog_start = subprog_end;
8019 subprog_end = env->subprog_info[i + 1].start;
8021 len = subprog_end - subprog_start;
8022 /* BPF_PROG_RUN doesn't call subprogs directly,
8023 * hence main prog stats include the runtime of subprogs.
8024 * subprogs don't have IDs and not reachable via prog_get_next_id
8025 * func[i]->aux->stats will never be accessed and stays NULL
8027 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
8030 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
8031 len * sizeof(struct bpf_insn));
8032 func[i]->type = prog->type;
8034 if (bpf_prog_calc_tag(func[i]))
8036 func[i]->is_func = 1;
8037 func[i]->aux->func_idx = i;
8038 /* the btf and func_info will be freed only at prog->aux */
8039 func[i]->aux->btf = prog->aux->btf;
8040 func[i]->aux->func_info = prog->aux->func_info;
8042 /* Use bpf_prog_F_tag to indicate functions in stack traces.
8043 * Long term would need debug info to populate names
8045 func[i]->aux->name[0] = 'F';
8046 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
8047 func[i]->jit_requested = 1;
8048 func[i]->aux->linfo = prog->aux->linfo;
8049 func[i]->aux->nr_linfo = prog->aux->nr_linfo;
8050 func[i]->aux->jited_linfo = prog->aux->jited_linfo;
8051 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
8052 func[i] = bpf_int_jit_compile(func[i]);
8053 if (!func[i]->jited) {
8059 /* at this point all bpf functions were successfully JITed
8060 * now populate all bpf_calls with correct addresses and
8061 * run last pass of JIT
8063 for (i = 0; i < env->subprog_cnt; i++) {
8064 insn = func[i]->insnsi;
8065 for (j = 0; j < func[i]->len; j++, insn++) {
8066 if (insn->code != (BPF_JMP | BPF_CALL) ||
8067 insn->src_reg != BPF_PSEUDO_CALL)
8069 subprog = insn->off;
8070 insn->imm = BPF_CAST_CALL(func[subprog]->bpf_func) -
8074 /* we use the aux data to keep a list of the start addresses
8075 * of the JITed images for each function in the program
8077 * for some architectures, such as powerpc64, the imm field
8078 * might not be large enough to hold the offset of the start
8079 * address of the callee's JITed image from __bpf_call_base
8081 * in such cases, we can lookup the start address of a callee
8082 * by using its subprog id, available from the off field of
8083 * the call instruction, as an index for this list
8085 func[i]->aux->func = func;
8086 func[i]->aux->func_cnt = env->subprog_cnt;
8088 for (i = 0; i < env->subprog_cnt; i++) {
8089 old_bpf_func = func[i]->bpf_func;
8090 tmp = bpf_int_jit_compile(func[i]);
8091 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
8092 verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
8099 /* finally lock prog and jit images for all functions and
8102 for (i = 0; i < env->subprog_cnt; i++) {
8103 bpf_prog_lock_ro(func[i]);
8104 bpf_prog_kallsyms_add(func[i]);
8107 /* Last step: make now unused interpreter insns from main
8108 * prog consistent for later dump requests, so they can
8109 * later look the same as if they were interpreted only.
8111 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
8112 if (insn->code != (BPF_JMP | BPF_CALL) ||
8113 insn->src_reg != BPF_PSEUDO_CALL)
8115 insn->off = env->insn_aux_data[i].call_imm;
8116 subprog = find_subprog(env, i + insn->off + 1);
8117 insn->imm = subprog;
8121 prog->bpf_func = func[0]->bpf_func;
8122 prog->aux->func = func;
8123 prog->aux->func_cnt = env->subprog_cnt;
8124 bpf_prog_free_unused_jited_linfo(prog);
8127 for (i = 0; i < env->subprog_cnt; i++)
8129 bpf_jit_free(func[i]);
8132 /* cleanup main prog to be interpreted */
8133 prog->jit_requested = 0;
8134 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
8135 if (insn->code != (BPF_JMP | BPF_CALL) ||
8136 insn->src_reg != BPF_PSEUDO_CALL)
8139 insn->imm = env->insn_aux_data[i].call_imm;
8141 bpf_prog_free_jited_linfo(prog);
8145 static int fixup_call_args(struct bpf_verifier_env *env)
8147 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
8148 struct bpf_prog *prog = env->prog;
8149 struct bpf_insn *insn = prog->insnsi;
8154 if (env->prog->jit_requested &&
8155 !bpf_prog_is_dev_bound(env->prog->aux)) {
8156 err = jit_subprogs(env);
8162 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
8163 for (i = 0; i < prog->len; i++, insn++) {
8164 if (insn->code != (BPF_JMP | BPF_CALL) ||
8165 insn->src_reg != BPF_PSEUDO_CALL)
8167 depth = get_callee_stack_depth(env, insn, i);
8170 bpf_patch_call_args(insn, depth);
8177 /* fixup insn->imm field of bpf_call instructions
8178 * and inline eligible helpers as explicit sequence of BPF instructions
8180 * this function is called after eBPF program passed verification
8182 static int fixup_bpf_calls(struct bpf_verifier_env *env)
8184 struct bpf_prog *prog = env->prog;
8185 struct bpf_insn *insn = prog->insnsi;
8186 const struct bpf_func_proto *fn;
8187 const int insn_cnt = prog->len;
8188 const struct bpf_map_ops *ops;
8189 struct bpf_insn_aux_data *aux;
8190 struct bpf_insn insn_buf[16];
8191 struct bpf_prog *new_prog;
8192 struct bpf_map *map_ptr;
8193 int i, cnt, delta = 0;
8195 for (i = 0; i < insn_cnt; i++, insn++) {
8196 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
8197 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
8198 insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
8199 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
8200 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
8201 struct bpf_insn mask_and_div[] = {
8202 BPF_MOV32_REG(insn->src_reg, insn->src_reg),
8204 BPF_JMP_IMM(BPF_JNE, insn->src_reg, 0, 2),
8205 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
8206 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
8209 struct bpf_insn mask_and_mod[] = {
8210 BPF_MOV32_REG(insn->src_reg, insn->src_reg),
8211 /* Rx mod 0 -> Rx */
8212 BPF_JMP_IMM(BPF_JEQ, insn->src_reg, 0, 1),
8215 struct bpf_insn *patchlet;
8217 if (insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
8218 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
8219 patchlet = mask_and_div + (is64 ? 1 : 0);
8220 cnt = ARRAY_SIZE(mask_and_div) - (is64 ? 1 : 0);
8222 patchlet = mask_and_mod + (is64 ? 1 : 0);
8223 cnt = ARRAY_SIZE(mask_and_mod) - (is64 ? 1 : 0);
8226 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
8231 env->prog = prog = new_prog;
8232 insn = new_prog->insnsi + i + delta;
8236 if (BPF_CLASS(insn->code) == BPF_LD &&
8237 (BPF_MODE(insn->code) == BPF_ABS ||
8238 BPF_MODE(insn->code) == BPF_IND)) {
8239 cnt = env->ops->gen_ld_abs(insn, insn_buf);
8240 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
8241 verbose(env, "bpf verifier is misconfigured\n");
8245 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
8250 env->prog = prog = new_prog;
8251 insn = new_prog->insnsi + i + delta;
8255 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
8256 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
8257 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
8258 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
8259 struct bpf_insn insn_buf[16];
8260 struct bpf_insn *patch = &insn_buf[0];
8264 aux = &env->insn_aux_data[i + delta];
8265 if (!aux->alu_state ||
8266 aux->alu_state == BPF_ALU_NON_POINTER)
8269 isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
8270 issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
8271 BPF_ALU_SANITIZE_SRC;
8273 off_reg = issrc ? insn->src_reg : insn->dst_reg;
8275 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
8276 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit - 1);
8277 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
8278 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
8279 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
8280 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
8282 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX,
8284 insn->src_reg = BPF_REG_AX;
8286 *patch++ = BPF_ALU64_REG(BPF_AND, off_reg,
8290 insn->code = insn->code == code_add ?
8291 code_sub : code_add;
8294 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
8295 cnt = patch - insn_buf;
8297 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
8302 env->prog = prog = new_prog;
8303 insn = new_prog->insnsi + i + delta;
8307 if (insn->code != (BPF_JMP | BPF_CALL))
8309 if (insn->src_reg == BPF_PSEUDO_CALL)
8312 if (insn->imm == BPF_FUNC_get_route_realm)
8313 prog->dst_needed = 1;
8314 if (insn->imm == BPF_FUNC_get_prandom_u32)
8315 bpf_user_rnd_init_once();
8316 if (insn->imm == BPF_FUNC_override_return)
8317 prog->kprobe_override = 1;
8318 if (insn->imm == BPF_FUNC_tail_call) {
8319 /* If we tail call into other programs, we
8320 * cannot make any assumptions since they can
8321 * be replaced dynamically during runtime in
8322 * the program array.
8324 prog->cb_access = 1;
8325 env->prog->aux->stack_depth = MAX_BPF_STACK;
8326 env->prog->aux->max_pkt_offset = MAX_PACKET_OFF;
8328 /* mark bpf_tail_call as different opcode to avoid
8329 * conditional branch in the interpeter for every normal
8330 * call and to prevent accidental JITing by JIT compiler
8331 * that doesn't support bpf_tail_call yet
8334 insn->code = BPF_JMP | BPF_TAIL_CALL;
8336 aux = &env->insn_aux_data[i + delta];
8337 if (!bpf_map_ptr_unpriv(aux))
8340 /* instead of changing every JIT dealing with tail_call
8341 * emit two extra insns:
8342 * if (index >= max_entries) goto out;
8343 * index &= array->index_mask;
8344 * to avoid out-of-bounds cpu speculation
8346 if (bpf_map_ptr_poisoned(aux)) {
8347 verbose(env, "tail_call abusing map_ptr\n");
8351 map_ptr = BPF_MAP_PTR(aux->map_state);
8352 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
8353 map_ptr->max_entries, 2);
8354 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
8355 container_of(map_ptr,
8358 insn_buf[2] = *insn;
8360 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
8365 env->prog = prog = new_prog;
8366 insn = new_prog->insnsi + i + delta;
8370 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
8371 * and other inlining handlers are currently limited to 64 bit
8374 if (prog->jit_requested && BITS_PER_LONG == 64 &&
8375 (insn->imm == BPF_FUNC_map_lookup_elem ||
8376 insn->imm == BPF_FUNC_map_update_elem ||
8377 insn->imm == BPF_FUNC_map_delete_elem ||
8378 insn->imm == BPF_FUNC_map_push_elem ||
8379 insn->imm == BPF_FUNC_map_pop_elem ||
8380 insn->imm == BPF_FUNC_map_peek_elem)) {
8381 aux = &env->insn_aux_data[i + delta];
8382 if (bpf_map_ptr_poisoned(aux))
8383 goto patch_call_imm;
8385 map_ptr = BPF_MAP_PTR(aux->map_state);
8387 if (insn->imm == BPF_FUNC_map_lookup_elem &&
8388 ops->map_gen_lookup) {
8389 cnt = ops->map_gen_lookup(map_ptr, insn_buf);
8390 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
8391 verbose(env, "bpf verifier is misconfigured\n");
8395 new_prog = bpf_patch_insn_data(env, i + delta,
8401 env->prog = prog = new_prog;
8402 insn = new_prog->insnsi + i + delta;
8406 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
8407 (void *(*)(struct bpf_map *map, void *key))NULL));
8408 BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
8409 (int (*)(struct bpf_map *map, void *key))NULL));
8410 BUILD_BUG_ON(!__same_type(ops->map_update_elem,
8411 (int (*)(struct bpf_map *map, void *key, void *value,
8413 BUILD_BUG_ON(!__same_type(ops->map_push_elem,
8414 (int (*)(struct bpf_map *map, void *value,
8416 BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
8417 (int (*)(struct bpf_map *map, void *value))NULL));
8418 BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
8419 (int (*)(struct bpf_map *map, void *value))NULL));
8421 switch (insn->imm) {
8422 case BPF_FUNC_map_lookup_elem:
8423 insn->imm = BPF_CAST_CALL(ops->map_lookup_elem) -
8426 case BPF_FUNC_map_update_elem:
8427 insn->imm = BPF_CAST_CALL(ops->map_update_elem) -
8430 case BPF_FUNC_map_delete_elem:
8431 insn->imm = BPF_CAST_CALL(ops->map_delete_elem) -
8434 case BPF_FUNC_map_push_elem:
8435 insn->imm = BPF_CAST_CALL(ops->map_push_elem) -
8438 case BPF_FUNC_map_pop_elem:
8439 insn->imm = BPF_CAST_CALL(ops->map_pop_elem) -
8442 case BPF_FUNC_map_peek_elem:
8443 insn->imm = BPF_CAST_CALL(ops->map_peek_elem) -
8448 goto patch_call_imm;
8452 fn = env->ops->get_func_proto(insn->imm, env->prog);
8453 /* all functions that have prototype and verifier allowed
8454 * programs to call them, must be real in-kernel functions
8458 "kernel subsystem misconfigured func %s#%d\n",
8459 func_id_name(insn->imm), insn->imm);
8462 insn->imm = fn->func - __bpf_call_base;
8468 static void free_states(struct bpf_verifier_env *env)
8470 struct bpf_verifier_state_list *sl, *sln;
8473 sl = env->free_list;
8476 free_verifier_state(&sl->state, false);
8481 if (!env->explored_states)
8484 for (i = 0; i < state_htab_size(env); i++) {
8485 sl = env->explored_states[i];
8489 free_verifier_state(&sl->state, false);
8495 kvfree(env->explored_states);
8498 static void print_verification_stats(struct bpf_verifier_env *env)
8502 if (env->log.level & BPF_LOG_STATS) {
8503 verbose(env, "verification time %lld usec\n",
8504 div_u64(env->verification_time, 1000));
8505 verbose(env, "stack depth ");
8506 for (i = 0; i < env->subprog_cnt; i++) {
8507 u32 depth = env->subprog_info[i].stack_depth;
8509 verbose(env, "%d", depth);
8510 if (i + 1 < env->subprog_cnt)
8515 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
8516 "total_states %d peak_states %d mark_read %d\n",
8517 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
8518 env->max_states_per_insn, env->total_states,
8519 env->peak_states, env->longest_mark_read_walk);
8522 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr,
8523 union bpf_attr __user *uattr)
8525 u64 start_time = ktime_get_ns();
8526 struct bpf_verifier_env *env;
8527 struct bpf_verifier_log *log;
8528 int i, len, ret = -EINVAL;
8531 /* no program is valid */
8532 if (ARRAY_SIZE(bpf_verifier_ops) == 0)
8535 /* 'struct bpf_verifier_env' can be global, but since it's not small,
8536 * allocate/free it every time bpf_check() is called
8538 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
8544 env->insn_aux_data =
8545 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
8547 if (!env->insn_aux_data)
8549 for (i = 0; i < len; i++)
8550 env->insn_aux_data[i].orig_idx = i;
8552 env->ops = bpf_verifier_ops[env->prog->type];
8553 is_priv = capable(CAP_SYS_ADMIN);
8555 /* grab the mutex to protect few globals used by verifier */
8557 mutex_lock(&bpf_verifier_lock);
8559 if (attr->log_level || attr->log_buf || attr->log_size) {
8560 /* user requested verbose verifier output
8561 * and supplied buffer to store the verification trace
8563 log->level = attr->log_level;
8564 log->ubuf = (char __user *) (unsigned long) attr->log_buf;
8565 log->len_total = attr->log_size;
8568 /* log attributes have to be sane */
8569 if (log->len_total < 128 || log->len_total > UINT_MAX >> 2 ||
8570 !log->level || !log->ubuf || log->level & ~BPF_LOG_MASK)
8574 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
8575 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
8576 env->strict_alignment = true;
8577 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
8578 env->strict_alignment = false;
8580 env->allow_ptr_leaks = is_priv;
8582 ret = replace_map_fd_with_map_ptr(env);
8584 goto skip_full_check;
8586 if (bpf_prog_is_dev_bound(env->prog->aux)) {
8587 ret = bpf_prog_offload_verifier_prep(env->prog);
8589 goto skip_full_check;
8592 env->explored_states = kvcalloc(state_htab_size(env),
8593 sizeof(struct bpf_verifier_state_list *),
8596 if (!env->explored_states)
8597 goto skip_full_check;
8599 ret = check_subprogs(env);
8601 goto skip_full_check;
8603 ret = check_btf_info(env, attr, uattr);
8605 goto skip_full_check;
8607 ret = check_cfg(env);
8609 goto skip_full_check;
8611 ret = do_check(env);
8612 if (env->cur_state) {
8613 free_verifier_state(env->cur_state, true);
8614 env->cur_state = NULL;
8617 if (ret == 0 && bpf_prog_is_dev_bound(env->prog->aux))
8618 ret = bpf_prog_offload_finalize(env);
8621 while (!pop_stack(env, NULL, NULL));
8625 ret = check_max_stack_depth(env);
8627 /* instruction rewrites happen after this point */
8630 opt_hard_wire_dead_code_branches(env);
8632 ret = opt_remove_dead_code(env);
8634 ret = opt_remove_nops(env);
8637 sanitize_dead_code(env);
8641 /* program is valid, convert *(u32*)(ctx + off) accesses */
8642 ret = convert_ctx_accesses(env);
8645 ret = fixup_bpf_calls(env);
8647 /* do 32-bit optimization after insn patching has done so those patched
8648 * insns could be handled correctly.
8650 if (ret == 0 && !bpf_prog_is_dev_bound(env->prog->aux)) {
8651 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
8652 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
8657 ret = fixup_call_args(env);
8659 env->verification_time = ktime_get_ns() - start_time;
8660 print_verification_stats(env);
8662 if (log->level && bpf_verifier_log_full(log))
8664 if (log->level && !log->ubuf) {
8666 goto err_release_maps;
8669 if (ret == 0 && env->used_map_cnt) {
8670 /* if program passed verifier, update used_maps in bpf_prog_info */
8671 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
8672 sizeof(env->used_maps[0]),
8675 if (!env->prog->aux->used_maps) {
8677 goto err_release_maps;
8680 memcpy(env->prog->aux->used_maps, env->used_maps,
8681 sizeof(env->used_maps[0]) * env->used_map_cnt);
8682 env->prog->aux->used_map_cnt = env->used_map_cnt;
8684 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
8685 * bpf_ld_imm64 instructions
8687 convert_pseudo_ld_imm64(env);
8691 adjust_btf_func(env);
8694 if (!env->prog->aux->used_maps)
8695 /* if we didn't copy map pointers into bpf_prog_info, release
8696 * them now. Otherwise free_used_maps() will release them.
8702 mutex_unlock(&bpf_verifier_lock);
8703 vfree(env->insn_aux_data);