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_INSNS 131072
180 #define BPF_COMPLEXITY_LIMIT_STACK 1024
181 #define BPF_COMPLEXITY_LIMIT_STATES 64
183 #define BPF_MAP_PTR_UNPRIV 1UL
184 #define BPF_MAP_PTR_POISON ((void *)((0xeB9FUL << 1) + \
185 POISON_POINTER_DELTA))
186 #define BPF_MAP_PTR(X) ((struct bpf_map *)((X) & ~BPF_MAP_PTR_UNPRIV))
188 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux)
190 return BPF_MAP_PTR(aux->map_state) == BPF_MAP_PTR_POISON;
193 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux)
195 return aux->map_state & BPF_MAP_PTR_UNPRIV;
198 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
199 const struct bpf_map *map, bool unpriv)
201 BUILD_BUG_ON((unsigned long)BPF_MAP_PTR_POISON & BPF_MAP_PTR_UNPRIV);
202 unpriv |= bpf_map_ptr_unpriv(aux);
203 aux->map_state = (unsigned long)map |
204 (unpriv ? BPF_MAP_PTR_UNPRIV : 0UL);
207 struct bpf_call_arg_meta {
208 struct bpf_map *map_ptr;
213 s64 msize_smax_value;
214 u64 msize_umax_value;
219 static DEFINE_MUTEX(bpf_verifier_lock);
221 static const struct bpf_line_info *
222 find_linfo(const struct bpf_verifier_env *env, u32 insn_off)
224 const struct bpf_line_info *linfo;
225 const struct bpf_prog *prog;
229 nr_linfo = prog->aux->nr_linfo;
231 if (!nr_linfo || insn_off >= prog->len)
234 linfo = prog->aux->linfo;
235 for (i = 1; i < nr_linfo; i++)
236 if (insn_off < linfo[i].insn_off)
239 return &linfo[i - 1];
242 void bpf_verifier_vlog(struct bpf_verifier_log *log, const char *fmt,
247 n = vscnprintf(log->kbuf, BPF_VERIFIER_TMP_LOG_SIZE, fmt, args);
249 WARN_ONCE(n >= BPF_VERIFIER_TMP_LOG_SIZE - 1,
250 "verifier log line truncated - local buffer too short\n");
252 n = min(log->len_total - log->len_used - 1, n);
255 if (!copy_to_user(log->ubuf + log->len_used, log->kbuf, n + 1))
261 /* log_level controls verbosity level of eBPF verifier.
262 * bpf_verifier_log_write() is used to dump the verification trace to the log,
263 * so the user can figure out what's wrong with the program
265 __printf(2, 3) void bpf_verifier_log_write(struct bpf_verifier_env *env,
266 const char *fmt, ...)
270 if (!bpf_verifier_log_needed(&env->log))
274 bpf_verifier_vlog(&env->log, fmt, args);
277 EXPORT_SYMBOL_GPL(bpf_verifier_log_write);
279 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
281 struct bpf_verifier_env *env = private_data;
284 if (!bpf_verifier_log_needed(&env->log))
288 bpf_verifier_vlog(&env->log, fmt, args);
292 static const char *ltrim(const char *s)
300 __printf(3, 4) static void verbose_linfo(struct bpf_verifier_env *env,
302 const char *prefix_fmt, ...)
304 const struct bpf_line_info *linfo;
306 if (!bpf_verifier_log_needed(&env->log))
309 linfo = find_linfo(env, insn_off);
310 if (!linfo || linfo == env->prev_linfo)
316 va_start(args, prefix_fmt);
317 bpf_verifier_vlog(&env->log, prefix_fmt, args);
322 ltrim(btf_name_by_offset(env->prog->aux->btf,
325 env->prev_linfo = linfo;
328 static bool type_is_pkt_pointer(enum bpf_reg_type type)
330 return type == PTR_TO_PACKET ||
331 type == PTR_TO_PACKET_META;
334 static bool reg_type_may_be_null(enum bpf_reg_type type)
336 return type == PTR_TO_MAP_VALUE_OR_NULL ||
337 type == PTR_TO_SOCKET_OR_NULL;
340 static bool type_is_refcounted(enum bpf_reg_type type)
342 return type == PTR_TO_SOCKET;
345 static bool type_is_refcounted_or_null(enum bpf_reg_type type)
347 return type == PTR_TO_SOCKET || type == PTR_TO_SOCKET_OR_NULL;
350 static bool reg_is_refcounted(const struct bpf_reg_state *reg)
352 return type_is_refcounted(reg->type);
355 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
357 return reg->type == PTR_TO_MAP_VALUE &&
358 map_value_has_spin_lock(reg->map_ptr);
361 static bool reg_is_refcounted_or_null(const struct bpf_reg_state *reg)
363 return type_is_refcounted_or_null(reg->type);
366 static bool arg_type_is_refcounted(enum bpf_arg_type type)
368 return type == ARG_PTR_TO_SOCKET;
371 /* Determine whether the function releases some resources allocated by another
372 * function call. The first reference type argument will be assumed to be
373 * released by release_reference().
375 static bool is_release_function(enum bpf_func_id func_id)
377 return func_id == BPF_FUNC_sk_release;
380 /* string representation of 'enum bpf_reg_type' */
381 static const char * const reg_type_str[] = {
383 [SCALAR_VALUE] = "inv",
384 [PTR_TO_CTX] = "ctx",
385 [CONST_PTR_TO_MAP] = "map_ptr",
386 [PTR_TO_MAP_VALUE] = "map_value",
387 [PTR_TO_MAP_VALUE_OR_NULL] = "map_value_or_null",
388 [PTR_TO_STACK] = "fp",
389 [PTR_TO_PACKET] = "pkt",
390 [PTR_TO_PACKET_META] = "pkt_meta",
391 [PTR_TO_PACKET_END] = "pkt_end",
392 [PTR_TO_FLOW_KEYS] = "flow_keys",
393 [PTR_TO_SOCKET] = "sock",
394 [PTR_TO_SOCKET_OR_NULL] = "sock_or_null",
397 static char slot_type_char[] = {
398 [STACK_INVALID] = '?',
404 static void print_liveness(struct bpf_verifier_env *env,
405 enum bpf_reg_liveness live)
407 if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE))
409 if (live & REG_LIVE_READ)
411 if (live & REG_LIVE_WRITTEN)
413 if (live & REG_LIVE_DONE)
417 static struct bpf_func_state *func(struct bpf_verifier_env *env,
418 const struct bpf_reg_state *reg)
420 struct bpf_verifier_state *cur = env->cur_state;
422 return cur->frame[reg->frameno];
425 static void print_verifier_state(struct bpf_verifier_env *env,
426 const struct bpf_func_state *state)
428 const struct bpf_reg_state *reg;
433 verbose(env, " frame%d:", state->frameno);
434 for (i = 0; i < MAX_BPF_REG; i++) {
435 reg = &state->regs[i];
439 verbose(env, " R%d", i);
440 print_liveness(env, reg->live);
441 verbose(env, "=%s", reg_type_str[t]);
442 if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
443 tnum_is_const(reg->var_off)) {
444 /* reg->off should be 0 for SCALAR_VALUE */
445 verbose(env, "%lld", reg->var_off.value + reg->off);
446 if (t == PTR_TO_STACK)
447 verbose(env, ",call_%d", func(env, reg)->callsite);
449 verbose(env, "(id=%d", reg->id);
450 if (t != SCALAR_VALUE)
451 verbose(env, ",off=%d", reg->off);
452 if (type_is_pkt_pointer(t))
453 verbose(env, ",r=%d", reg->range);
454 else if (t == CONST_PTR_TO_MAP ||
455 t == PTR_TO_MAP_VALUE ||
456 t == PTR_TO_MAP_VALUE_OR_NULL)
457 verbose(env, ",ks=%d,vs=%d",
458 reg->map_ptr->key_size,
459 reg->map_ptr->value_size);
460 if (tnum_is_const(reg->var_off)) {
461 /* Typically an immediate SCALAR_VALUE, but
462 * could be a pointer whose offset is too big
465 verbose(env, ",imm=%llx", reg->var_off.value);
467 if (reg->smin_value != reg->umin_value &&
468 reg->smin_value != S64_MIN)
469 verbose(env, ",smin_value=%lld",
470 (long long)reg->smin_value);
471 if (reg->smax_value != reg->umax_value &&
472 reg->smax_value != S64_MAX)
473 verbose(env, ",smax_value=%lld",
474 (long long)reg->smax_value);
475 if (reg->umin_value != 0)
476 verbose(env, ",umin_value=%llu",
477 (unsigned long long)reg->umin_value);
478 if (reg->umax_value != U64_MAX)
479 verbose(env, ",umax_value=%llu",
480 (unsigned long long)reg->umax_value);
481 if (!tnum_is_unknown(reg->var_off)) {
484 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
485 verbose(env, ",var_off=%s", tn_buf);
491 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
492 char types_buf[BPF_REG_SIZE + 1];
496 for (j = 0; j < BPF_REG_SIZE; j++) {
497 if (state->stack[i].slot_type[j] != STACK_INVALID)
499 types_buf[j] = slot_type_char[
500 state->stack[i].slot_type[j]];
502 types_buf[BPF_REG_SIZE] = 0;
505 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
506 print_liveness(env, state->stack[i].spilled_ptr.live);
507 if (state->stack[i].slot_type[0] == STACK_SPILL)
509 reg_type_str[state->stack[i].spilled_ptr.type]);
511 verbose(env, "=%s", types_buf);
513 if (state->acquired_refs && state->refs[0].id) {
514 verbose(env, " refs=%d", state->refs[0].id);
515 for (i = 1; i < state->acquired_refs; i++)
516 if (state->refs[i].id)
517 verbose(env, ",%d", state->refs[i].id);
522 #define COPY_STATE_FN(NAME, COUNT, FIELD, SIZE) \
523 static int copy_##NAME##_state(struct bpf_func_state *dst, \
524 const struct bpf_func_state *src) \
528 if (WARN_ON_ONCE(dst->COUNT < src->COUNT)) { \
529 /* internal bug, make state invalid to reject the program */ \
530 memset(dst, 0, sizeof(*dst)); \
533 memcpy(dst->FIELD, src->FIELD, \
534 sizeof(*src->FIELD) * (src->COUNT / SIZE)); \
537 /* copy_reference_state() */
538 COPY_STATE_FN(reference, acquired_refs, refs, 1)
539 /* copy_stack_state() */
540 COPY_STATE_FN(stack, allocated_stack, stack, BPF_REG_SIZE)
543 #define REALLOC_STATE_FN(NAME, COUNT, FIELD, SIZE) \
544 static int realloc_##NAME##_state(struct bpf_func_state *state, int size, \
547 u32 old_size = state->COUNT; \
548 struct bpf_##NAME##_state *new_##FIELD; \
549 int slot = size / SIZE; \
551 if (size <= old_size || !size) { \
554 state->COUNT = slot * SIZE; \
555 if (!size && old_size) { \
556 kfree(state->FIELD); \
557 state->FIELD = NULL; \
561 new_##FIELD = kmalloc_array(slot, sizeof(struct bpf_##NAME##_state), \
567 memcpy(new_##FIELD, state->FIELD, \
568 sizeof(*new_##FIELD) * (old_size / SIZE)); \
569 memset(new_##FIELD + old_size / SIZE, 0, \
570 sizeof(*new_##FIELD) * (size - old_size) / SIZE); \
572 state->COUNT = slot * SIZE; \
573 kfree(state->FIELD); \
574 state->FIELD = new_##FIELD; \
577 /* realloc_reference_state() */
578 REALLOC_STATE_FN(reference, acquired_refs, refs, 1)
579 /* realloc_stack_state() */
580 REALLOC_STATE_FN(stack, allocated_stack, stack, BPF_REG_SIZE)
581 #undef REALLOC_STATE_FN
583 /* do_check() starts with zero-sized stack in struct bpf_verifier_state to
584 * make it consume minimal amount of memory. check_stack_write() access from
585 * the program calls into realloc_func_state() to grow the stack size.
586 * Note there is a non-zero 'parent' pointer inside bpf_verifier_state
587 * which realloc_stack_state() copies over. It points to previous
588 * bpf_verifier_state which is never reallocated.
590 static int realloc_func_state(struct bpf_func_state *state, int stack_size,
591 int refs_size, bool copy_old)
593 int err = realloc_reference_state(state, refs_size, copy_old);
596 return realloc_stack_state(state, stack_size, copy_old);
599 /* Acquire a pointer id from the env and update the state->refs to include
600 * this new pointer reference.
601 * On success, returns a valid pointer id to associate with the register
602 * On failure, returns a negative errno.
604 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
606 struct bpf_func_state *state = cur_func(env);
607 int new_ofs = state->acquired_refs;
610 err = realloc_reference_state(state, state->acquired_refs + 1, true);
614 state->refs[new_ofs].id = id;
615 state->refs[new_ofs].insn_idx = insn_idx;
620 /* release function corresponding to acquire_reference_state(). Idempotent. */
621 static int __release_reference_state(struct bpf_func_state *state, int ptr_id)
628 last_idx = state->acquired_refs - 1;
629 for (i = 0; i < state->acquired_refs; i++) {
630 if (state->refs[i].id == ptr_id) {
631 if (last_idx && i != last_idx)
632 memcpy(&state->refs[i], &state->refs[last_idx],
633 sizeof(*state->refs));
634 memset(&state->refs[last_idx], 0, sizeof(*state->refs));
635 state->acquired_refs--;
642 /* variation on the above for cases where we expect that there must be an
643 * outstanding reference for the specified ptr_id.
645 static int release_reference_state(struct bpf_verifier_env *env, int ptr_id)
647 struct bpf_func_state *state = cur_func(env);
650 err = __release_reference_state(state, ptr_id);
651 if (WARN_ON_ONCE(err != 0))
652 verbose(env, "verifier internal error: can't release reference\n");
656 static int transfer_reference_state(struct bpf_func_state *dst,
657 struct bpf_func_state *src)
659 int err = realloc_reference_state(dst, src->acquired_refs, false);
662 err = copy_reference_state(dst, src);
668 static void free_func_state(struct bpf_func_state *state)
677 static void free_verifier_state(struct bpf_verifier_state *state,
682 for (i = 0; i <= state->curframe; i++) {
683 free_func_state(state->frame[i]);
684 state->frame[i] = NULL;
690 /* copy verifier state from src to dst growing dst stack space
691 * when necessary to accommodate larger src stack
693 static int copy_func_state(struct bpf_func_state *dst,
694 const struct bpf_func_state *src)
698 err = realloc_func_state(dst, src->allocated_stack, src->acquired_refs,
702 memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
703 err = copy_reference_state(dst, src);
706 return copy_stack_state(dst, src);
709 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
710 const struct bpf_verifier_state *src)
712 struct bpf_func_state *dst;
715 /* if dst has more stack frames then src frame, free them */
716 for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
717 free_func_state(dst_state->frame[i]);
718 dst_state->frame[i] = NULL;
720 dst_state->speculative = src->speculative;
721 dst_state->curframe = src->curframe;
722 dst_state->active_spin_lock = src->active_spin_lock;
723 for (i = 0; i <= src->curframe; i++) {
724 dst = dst_state->frame[i];
726 dst = kzalloc(sizeof(*dst), GFP_KERNEL);
729 dst_state->frame[i] = dst;
731 err = copy_func_state(dst, src->frame[i]);
738 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
741 struct bpf_verifier_state *cur = env->cur_state;
742 struct bpf_verifier_stack_elem *elem, *head = env->head;
745 if (env->head == NULL)
749 err = copy_verifier_state(cur, &head->st);
754 *insn_idx = head->insn_idx;
756 *prev_insn_idx = head->prev_insn_idx;
758 free_verifier_state(&head->st, false);
765 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
766 int insn_idx, int prev_insn_idx,
769 struct bpf_verifier_state *cur = env->cur_state;
770 struct bpf_verifier_stack_elem *elem;
773 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
777 elem->insn_idx = insn_idx;
778 elem->prev_insn_idx = prev_insn_idx;
779 elem->next = env->head;
782 err = copy_verifier_state(&elem->st, cur);
785 elem->st.speculative |= speculative;
786 if (env->stack_size > BPF_COMPLEXITY_LIMIT_STACK) {
787 verbose(env, "BPF program is too complex\n");
792 free_verifier_state(env->cur_state, true);
793 env->cur_state = NULL;
794 /* pop all elements and return */
795 while (!pop_stack(env, NULL, NULL));
799 #define CALLER_SAVED_REGS 6
800 static const int caller_saved[CALLER_SAVED_REGS] = {
801 BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
804 static void __mark_reg_not_init(struct bpf_reg_state *reg);
806 /* Mark the unknown part of a register (variable offset or scalar value) as
807 * known to have the value @imm.
809 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
811 /* Clear id, off, and union(map_ptr, range) */
812 memset(((u8 *)reg) + sizeof(reg->type), 0,
813 offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
814 reg->var_off = tnum_const(imm);
815 reg->smin_value = (s64)imm;
816 reg->smax_value = (s64)imm;
817 reg->umin_value = imm;
818 reg->umax_value = imm;
821 /* Mark the 'variable offset' part of a register as zero. This should be
822 * used only on registers holding a pointer type.
824 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
826 __mark_reg_known(reg, 0);
829 static void __mark_reg_const_zero(struct bpf_reg_state *reg)
831 __mark_reg_known(reg, 0);
832 reg->type = SCALAR_VALUE;
835 static void mark_reg_known_zero(struct bpf_verifier_env *env,
836 struct bpf_reg_state *regs, u32 regno)
838 if (WARN_ON(regno >= MAX_BPF_REG)) {
839 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
840 /* Something bad happened, let's kill all regs */
841 for (regno = 0; regno < MAX_BPF_REG; regno++)
842 __mark_reg_not_init(regs + regno);
845 __mark_reg_known_zero(regs + regno);
848 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
850 return type_is_pkt_pointer(reg->type);
853 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
855 return reg_is_pkt_pointer(reg) ||
856 reg->type == PTR_TO_PACKET_END;
859 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
860 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
861 enum bpf_reg_type which)
863 /* The register can already have a range from prior markings.
864 * This is fine as long as it hasn't been advanced from its
867 return reg->type == which &&
870 tnum_equals_const(reg->var_off, 0);
873 /* Attempts to improve min/max values based on var_off information */
874 static void __update_reg_bounds(struct bpf_reg_state *reg)
876 /* min signed is max(sign bit) | min(other bits) */
877 reg->smin_value = max_t(s64, reg->smin_value,
878 reg->var_off.value | (reg->var_off.mask & S64_MIN));
879 /* max signed is min(sign bit) | max(other bits) */
880 reg->smax_value = min_t(s64, reg->smax_value,
881 reg->var_off.value | (reg->var_off.mask & S64_MAX));
882 reg->umin_value = max(reg->umin_value, reg->var_off.value);
883 reg->umax_value = min(reg->umax_value,
884 reg->var_off.value | reg->var_off.mask);
887 /* Uses signed min/max values to inform unsigned, and vice-versa */
888 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
890 /* Learn sign from signed bounds.
891 * If we cannot cross the sign boundary, then signed and unsigned bounds
892 * are the same, so combine. This works even in the negative case, e.g.
893 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
895 if (reg->smin_value >= 0 || reg->smax_value < 0) {
896 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
898 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
902 /* Learn sign from unsigned bounds. Signed bounds cross the sign
903 * boundary, so we must be careful.
905 if ((s64)reg->umax_value >= 0) {
906 /* Positive. We can't learn anything from the smin, but smax
907 * is positive, hence safe.
909 reg->smin_value = reg->umin_value;
910 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
912 } else if ((s64)reg->umin_value < 0) {
913 /* Negative. We can't learn anything from the smax, but smin
914 * is negative, hence safe.
916 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
918 reg->smax_value = reg->umax_value;
922 /* Attempts to improve var_off based on unsigned min/max information */
923 static void __reg_bound_offset(struct bpf_reg_state *reg)
925 reg->var_off = tnum_intersect(reg->var_off,
926 tnum_range(reg->umin_value,
930 /* Reset the min/max bounds of a register */
931 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
933 reg->smin_value = S64_MIN;
934 reg->smax_value = S64_MAX;
936 reg->umax_value = U64_MAX;
939 /* Mark a register as having a completely unknown (scalar) value. */
940 static void __mark_reg_unknown(struct bpf_reg_state *reg)
943 * Clear type, id, off, and union(map_ptr, range) and
944 * padding between 'type' and union
946 memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
947 reg->type = SCALAR_VALUE;
948 reg->var_off = tnum_unknown;
950 __mark_reg_unbounded(reg);
953 static void mark_reg_unknown(struct bpf_verifier_env *env,
954 struct bpf_reg_state *regs, u32 regno)
956 if (WARN_ON(regno >= MAX_BPF_REG)) {
957 verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
958 /* Something bad happened, let's kill all regs except FP */
959 for (regno = 0; regno < BPF_REG_FP; regno++)
960 __mark_reg_not_init(regs + regno);
963 __mark_reg_unknown(regs + regno);
966 static void __mark_reg_not_init(struct bpf_reg_state *reg)
968 __mark_reg_unknown(reg);
969 reg->type = NOT_INIT;
972 static void mark_reg_not_init(struct bpf_verifier_env *env,
973 struct bpf_reg_state *regs, u32 regno)
975 if (WARN_ON(regno >= MAX_BPF_REG)) {
976 verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
977 /* Something bad happened, let's kill all regs except FP */
978 for (regno = 0; regno < BPF_REG_FP; regno++)
979 __mark_reg_not_init(regs + regno);
982 __mark_reg_not_init(regs + regno);
985 static void init_reg_state(struct bpf_verifier_env *env,
986 struct bpf_func_state *state)
988 struct bpf_reg_state *regs = state->regs;
991 for (i = 0; i < MAX_BPF_REG; i++) {
992 mark_reg_not_init(env, regs, i);
993 regs[i].live = REG_LIVE_NONE;
994 regs[i].parent = NULL;
998 regs[BPF_REG_FP].type = PTR_TO_STACK;
999 mark_reg_known_zero(env, regs, BPF_REG_FP);
1000 regs[BPF_REG_FP].frameno = state->frameno;
1002 /* 1st arg to a function */
1003 regs[BPF_REG_1].type = PTR_TO_CTX;
1004 mark_reg_known_zero(env, regs, BPF_REG_1);
1007 #define BPF_MAIN_FUNC (-1)
1008 static void init_func_state(struct bpf_verifier_env *env,
1009 struct bpf_func_state *state,
1010 int callsite, int frameno, int subprogno)
1012 state->callsite = callsite;
1013 state->frameno = frameno;
1014 state->subprogno = subprogno;
1015 init_reg_state(env, state);
1019 SRC_OP, /* register is used as source operand */
1020 DST_OP, /* register is used as destination operand */
1021 DST_OP_NO_MARK /* same as above, check only, don't mark */
1024 static int cmp_subprogs(const void *a, const void *b)
1026 return ((struct bpf_subprog_info *)a)->start -
1027 ((struct bpf_subprog_info *)b)->start;
1030 static int find_subprog(struct bpf_verifier_env *env, int off)
1032 struct bpf_subprog_info *p;
1034 p = bsearch(&off, env->subprog_info, env->subprog_cnt,
1035 sizeof(env->subprog_info[0]), cmp_subprogs);
1038 return p - env->subprog_info;
1042 static int add_subprog(struct bpf_verifier_env *env, int off)
1044 int insn_cnt = env->prog->len;
1047 if (off >= insn_cnt || off < 0) {
1048 verbose(env, "call to invalid destination\n");
1051 ret = find_subprog(env, off);
1054 if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
1055 verbose(env, "too many subprograms\n");
1058 env->subprog_info[env->subprog_cnt++].start = off;
1059 sort(env->subprog_info, env->subprog_cnt,
1060 sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
1064 static int check_subprogs(struct bpf_verifier_env *env)
1066 int i, ret, subprog_start, subprog_end, off, cur_subprog = 0;
1067 struct bpf_subprog_info *subprog = env->subprog_info;
1068 struct bpf_insn *insn = env->prog->insnsi;
1069 int insn_cnt = env->prog->len;
1071 /* Add entry function. */
1072 ret = add_subprog(env, 0);
1076 /* determine subprog starts. The end is one before the next starts */
1077 for (i = 0; i < insn_cnt; i++) {
1078 if (insn[i].code != (BPF_JMP | BPF_CALL))
1080 if (insn[i].src_reg != BPF_PSEUDO_CALL)
1082 if (!env->allow_ptr_leaks) {
1083 verbose(env, "function calls to other bpf functions are allowed for root only\n");
1086 ret = add_subprog(env, i + insn[i].imm + 1);
1091 /* Add a fake 'exit' subprog which could simplify subprog iteration
1092 * logic. 'subprog_cnt' should not be increased.
1094 subprog[env->subprog_cnt].start = insn_cnt;
1096 if (env->log.level > 1)
1097 for (i = 0; i < env->subprog_cnt; i++)
1098 verbose(env, "func#%d @%d\n", i, subprog[i].start);
1100 /* now check that all jumps are within the same subprog */
1101 subprog_start = subprog[cur_subprog].start;
1102 subprog_end = subprog[cur_subprog + 1].start;
1103 for (i = 0; i < insn_cnt; i++) {
1104 u8 code = insn[i].code;
1106 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
1108 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
1110 off = i + insn[i].off + 1;
1111 if (off < subprog_start || off >= subprog_end) {
1112 verbose(env, "jump out of range from insn %d to %d\n", i, off);
1116 if (i == subprog_end - 1) {
1117 /* to avoid fall-through from one subprog into another
1118 * the last insn of the subprog should be either exit
1119 * or unconditional jump back
1121 if (code != (BPF_JMP | BPF_EXIT) &&
1122 code != (BPF_JMP | BPF_JA)) {
1123 verbose(env, "last insn is not an exit or jmp\n");
1126 subprog_start = subprog_end;
1128 if (cur_subprog < env->subprog_cnt)
1129 subprog_end = subprog[cur_subprog + 1].start;
1135 /* Parentage chain of this register (or stack slot) should take care of all
1136 * issues like callee-saved registers, stack slot allocation time, etc.
1138 static int mark_reg_read(struct bpf_verifier_env *env,
1139 const struct bpf_reg_state *state,
1140 struct bpf_reg_state *parent)
1142 bool writes = parent == state->parent; /* Observe write marks */
1145 /* if read wasn't screened by an earlier write ... */
1146 if (writes && state->live & REG_LIVE_WRITTEN)
1148 if (parent->live & REG_LIVE_DONE) {
1149 verbose(env, "verifier BUG type %s var_off %lld off %d\n",
1150 reg_type_str[parent->type],
1151 parent->var_off.value, parent->off);
1154 /* ... then we depend on parent's value */
1155 parent->live |= REG_LIVE_READ;
1157 parent = state->parent;
1163 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
1164 enum reg_arg_type t)
1166 struct bpf_verifier_state *vstate = env->cur_state;
1167 struct bpf_func_state *state = vstate->frame[vstate->curframe];
1168 struct bpf_reg_state *regs = state->regs;
1170 if (regno >= MAX_BPF_REG) {
1171 verbose(env, "R%d is invalid\n", regno);
1176 /* check whether register used as source operand can be read */
1177 if (regs[regno].type == NOT_INIT) {
1178 verbose(env, "R%d !read_ok\n", regno);
1181 /* We don't need to worry about FP liveness because it's read-only */
1182 if (regno != BPF_REG_FP)
1183 return mark_reg_read(env, ®s[regno],
1184 regs[regno].parent);
1186 /* check whether register used as dest operand can be written to */
1187 if (regno == BPF_REG_FP) {
1188 verbose(env, "frame pointer is read only\n");
1191 regs[regno].live |= REG_LIVE_WRITTEN;
1193 mark_reg_unknown(env, regs, regno);
1198 static bool is_spillable_regtype(enum bpf_reg_type type)
1201 case PTR_TO_MAP_VALUE:
1202 case PTR_TO_MAP_VALUE_OR_NULL:
1206 case PTR_TO_PACKET_META:
1207 case PTR_TO_PACKET_END:
1208 case PTR_TO_FLOW_KEYS:
1209 case CONST_PTR_TO_MAP:
1211 case PTR_TO_SOCKET_OR_NULL:
1218 /* Does this register contain a constant zero? */
1219 static bool register_is_null(struct bpf_reg_state *reg)
1221 return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
1224 /* check_stack_read/write functions track spill/fill of registers,
1225 * stack boundary and alignment are checked in check_mem_access()
1227 static int check_stack_write(struct bpf_verifier_env *env,
1228 struct bpf_func_state *state, /* func where register points to */
1229 int off, int size, int value_regno, int insn_idx)
1231 struct bpf_func_state *cur; /* state of the current function */
1232 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
1233 enum bpf_reg_type type;
1235 err = realloc_func_state(state, round_up(slot + 1, BPF_REG_SIZE),
1236 state->acquired_refs, true);
1239 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
1240 * so it's aligned access and [off, off + size) are within stack limits
1242 if (!env->allow_ptr_leaks &&
1243 state->stack[spi].slot_type[0] == STACK_SPILL &&
1244 size != BPF_REG_SIZE) {
1245 verbose(env, "attempt to corrupt spilled pointer on stack\n");
1249 cur = env->cur_state->frame[env->cur_state->curframe];
1250 if (value_regno >= 0 &&
1251 is_spillable_regtype((type = cur->regs[value_regno].type))) {
1253 /* register containing pointer is being spilled into stack */
1254 if (size != BPF_REG_SIZE) {
1255 verbose(env, "invalid size of register spill\n");
1259 if (state != cur && type == PTR_TO_STACK) {
1260 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
1264 /* save register state */
1265 state->stack[spi].spilled_ptr = cur->regs[value_regno];
1266 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
1268 for (i = 0; i < BPF_REG_SIZE; i++) {
1269 if (state->stack[spi].slot_type[i] == STACK_MISC &&
1270 !env->allow_ptr_leaks) {
1271 int *poff = &env->insn_aux_data[insn_idx].sanitize_stack_off;
1272 int soff = (-spi - 1) * BPF_REG_SIZE;
1274 /* detected reuse of integer stack slot with a pointer
1275 * which means either llvm is reusing stack slot or
1276 * an attacker is trying to exploit CVE-2018-3639
1277 * (speculative store bypass)
1278 * Have to sanitize that slot with preemptive
1281 if (*poff && *poff != soff) {
1282 /* disallow programs where single insn stores
1283 * into two different stack slots, since verifier
1284 * cannot sanitize them
1287 "insn %d cannot access two stack slots fp%d and fp%d",
1288 insn_idx, *poff, soff);
1293 state->stack[spi].slot_type[i] = STACK_SPILL;
1296 u8 type = STACK_MISC;
1298 /* regular write of data into stack destroys any spilled ptr */
1299 state->stack[spi].spilled_ptr.type = NOT_INIT;
1300 /* Mark slots as STACK_MISC if they belonged to spilled ptr. */
1301 if (state->stack[spi].slot_type[0] == STACK_SPILL)
1302 for (i = 0; i < BPF_REG_SIZE; i++)
1303 state->stack[spi].slot_type[i] = STACK_MISC;
1305 /* only mark the slot as written if all 8 bytes were written
1306 * otherwise read propagation may incorrectly stop too soon
1307 * when stack slots are partially written.
1308 * This heuristic means that read propagation will be
1309 * conservative, since it will add reg_live_read marks
1310 * to stack slots all the way to first state when programs
1311 * writes+reads less than 8 bytes
1313 if (size == BPF_REG_SIZE)
1314 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
1316 /* when we zero initialize stack slots mark them as such */
1317 if (value_regno >= 0 &&
1318 register_is_null(&cur->regs[value_regno]))
1321 /* Mark slots affected by this stack write. */
1322 for (i = 0; i < size; i++)
1323 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
1329 static int check_stack_read(struct bpf_verifier_env *env,
1330 struct bpf_func_state *reg_state /* func where register points to */,
1331 int off, int size, int value_regno)
1333 struct bpf_verifier_state *vstate = env->cur_state;
1334 struct bpf_func_state *state = vstate->frame[vstate->curframe];
1335 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
1338 if (reg_state->allocated_stack <= slot) {
1339 verbose(env, "invalid read from stack off %d+0 size %d\n",
1343 stype = reg_state->stack[spi].slot_type;
1345 if (stype[0] == STACK_SPILL) {
1346 if (size != BPF_REG_SIZE) {
1347 verbose(env, "invalid size of register spill\n");
1350 for (i = 1; i < BPF_REG_SIZE; i++) {
1351 if (stype[(slot - i) % BPF_REG_SIZE] != STACK_SPILL) {
1352 verbose(env, "corrupted spill memory\n");
1357 if (value_regno >= 0) {
1358 /* restore register state from stack */
1359 state->regs[value_regno] = reg_state->stack[spi].spilled_ptr;
1360 /* mark reg as written since spilled pointer state likely
1361 * has its liveness marks cleared by is_state_visited()
1362 * which resets stack/reg liveness for state transitions
1364 state->regs[value_regno].live |= REG_LIVE_WRITTEN;
1366 mark_reg_read(env, ®_state->stack[spi].spilled_ptr,
1367 reg_state->stack[spi].spilled_ptr.parent);
1372 for (i = 0; i < size; i++) {
1373 if (stype[(slot - i) % BPF_REG_SIZE] == STACK_MISC)
1375 if (stype[(slot - i) % BPF_REG_SIZE] == STACK_ZERO) {
1379 verbose(env, "invalid read from stack off %d+%d size %d\n",
1383 mark_reg_read(env, ®_state->stack[spi].spilled_ptr,
1384 reg_state->stack[spi].spilled_ptr.parent);
1385 if (value_regno >= 0) {
1386 if (zeros == size) {
1387 /* any size read into register is zero extended,
1388 * so the whole register == const_zero
1390 __mark_reg_const_zero(&state->regs[value_regno]);
1392 /* have read misc data from the stack */
1393 mark_reg_unknown(env, state->regs, value_regno);
1395 state->regs[value_regno].live |= REG_LIVE_WRITTEN;
1401 static int check_stack_access(struct bpf_verifier_env *env,
1402 const struct bpf_reg_state *reg,
1405 /* Stack accesses must be at a fixed offset, so that we
1406 * can determine what type of data were returned. See
1407 * check_stack_read().
1409 if (!tnum_is_const(reg->var_off)) {
1412 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
1413 verbose(env, "variable stack access var_off=%s off=%d size=%d",
1418 if (off >= 0 || off < -MAX_BPF_STACK) {
1419 verbose(env, "invalid stack off=%d size=%d\n", off, size);
1426 /* check read/write into map element returned by bpf_map_lookup_elem() */
1427 static int __check_map_access(struct bpf_verifier_env *env, u32 regno, int off,
1428 int size, bool zero_size_allowed)
1430 struct bpf_reg_state *regs = cur_regs(env);
1431 struct bpf_map *map = regs[regno].map_ptr;
1433 if (off < 0 || size < 0 || (size == 0 && !zero_size_allowed) ||
1434 off + size > map->value_size) {
1435 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
1436 map->value_size, off, size);
1442 /* check read/write into a map element with possible variable offset */
1443 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
1444 int off, int size, bool zero_size_allowed)
1446 struct bpf_verifier_state *vstate = env->cur_state;
1447 struct bpf_func_state *state = vstate->frame[vstate->curframe];
1448 struct bpf_reg_state *reg = &state->regs[regno];
1451 /* We may have adjusted the register to this map value, so we
1452 * need to try adding each of min_value and max_value to off
1453 * to make sure our theoretical access will be safe.
1456 print_verifier_state(env, state);
1458 /* The minimum value is only important with signed
1459 * comparisons where we can't assume the floor of a
1460 * value is 0. If we are using signed variables for our
1461 * index'es we need to make sure that whatever we use
1462 * will have a set floor within our range.
1464 if (reg->smin_value < 0 &&
1465 (reg->smin_value == S64_MIN ||
1466 (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
1467 reg->smin_value + off < 0)) {
1468 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
1472 err = __check_map_access(env, regno, reg->smin_value + off, size,
1475 verbose(env, "R%d min value is outside of the array range\n",
1480 /* If we haven't set a max value then we need to bail since we can't be
1481 * sure we won't do bad things.
1482 * If reg->umax_value + off could overflow, treat that as unbounded too.
1484 if (reg->umax_value >= BPF_MAX_VAR_OFF) {
1485 verbose(env, "R%d unbounded memory access, make sure to bounds check any array access into a map\n",
1489 err = __check_map_access(env, regno, reg->umax_value + off, size,
1492 verbose(env, "R%d max value is outside of the array range\n",
1495 if (map_value_has_spin_lock(reg->map_ptr)) {
1496 u32 lock = reg->map_ptr->spin_lock_off;
1498 /* if any part of struct bpf_spin_lock can be touched by
1499 * load/store reject this program.
1500 * To check that [x1, x2) overlaps with [y1, y2)
1501 * it is sufficient to check x1 < y2 && y1 < x2.
1503 if (reg->smin_value + off < lock + sizeof(struct bpf_spin_lock) &&
1504 lock < reg->umax_value + off + size) {
1505 verbose(env, "bpf_spin_lock cannot be accessed directly by load/store\n");
1512 #define MAX_PACKET_OFF 0xffff
1514 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
1515 const struct bpf_call_arg_meta *meta,
1516 enum bpf_access_type t)
1518 switch (env->prog->type) {
1519 /* Program types only with direct read access go here! */
1520 case BPF_PROG_TYPE_LWT_IN:
1521 case BPF_PROG_TYPE_LWT_OUT:
1522 case BPF_PROG_TYPE_LWT_SEG6LOCAL:
1523 case BPF_PROG_TYPE_SK_REUSEPORT:
1524 case BPF_PROG_TYPE_FLOW_DISSECTOR:
1525 case BPF_PROG_TYPE_CGROUP_SKB:
1530 /* Program types with direct read + write access go here! */
1531 case BPF_PROG_TYPE_SCHED_CLS:
1532 case BPF_PROG_TYPE_SCHED_ACT:
1533 case BPF_PROG_TYPE_XDP:
1534 case BPF_PROG_TYPE_LWT_XMIT:
1535 case BPF_PROG_TYPE_SK_SKB:
1536 case BPF_PROG_TYPE_SK_MSG:
1538 return meta->pkt_access;
1540 env->seen_direct_write = true;
1547 static int __check_packet_access(struct bpf_verifier_env *env, u32 regno,
1548 int off, int size, bool zero_size_allowed)
1550 struct bpf_reg_state *regs = cur_regs(env);
1551 struct bpf_reg_state *reg = ®s[regno];
1553 if (off < 0 || size < 0 || (size == 0 && !zero_size_allowed) ||
1554 (u64)off + size > reg->range) {
1555 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
1556 off, size, regno, reg->id, reg->off, reg->range);
1562 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
1563 int size, bool zero_size_allowed)
1565 struct bpf_reg_state *regs = cur_regs(env);
1566 struct bpf_reg_state *reg = ®s[regno];
1569 /* We may have added a variable offset to the packet pointer; but any
1570 * reg->range we have comes after that. We are only checking the fixed
1574 /* We don't allow negative numbers, because we aren't tracking enough
1575 * detail to prove they're safe.
1577 if (reg->smin_value < 0) {
1578 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
1582 err = __check_packet_access(env, regno, off, size, zero_size_allowed);
1584 verbose(env, "R%d offset is outside of the packet\n", regno);
1588 /* __check_packet_access has made sure "off + size - 1" is within u16.
1589 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
1590 * otherwise find_good_pkt_pointers would have refused to set range info
1591 * that __check_packet_access would have rejected this pkt access.
1592 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
1594 env->prog->aux->max_pkt_offset =
1595 max_t(u32, env->prog->aux->max_pkt_offset,
1596 off + reg->umax_value + size - 1);
1601 /* check access to 'struct bpf_context' fields. Supports fixed offsets only */
1602 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
1603 enum bpf_access_type t, enum bpf_reg_type *reg_type)
1605 struct bpf_insn_access_aux info = {
1606 .reg_type = *reg_type,
1609 if (env->ops->is_valid_access &&
1610 env->ops->is_valid_access(off, size, t, env->prog, &info)) {
1611 /* A non zero info.ctx_field_size indicates that this field is a
1612 * candidate for later verifier transformation to load the whole
1613 * field and then apply a mask when accessed with a narrower
1614 * access than actual ctx access size. A zero info.ctx_field_size
1615 * will only allow for whole field access and rejects any other
1616 * type of narrower access.
1618 *reg_type = info.reg_type;
1620 env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
1621 /* remember the offset of last byte accessed in ctx */
1622 if (env->prog->aux->max_ctx_offset < off + size)
1623 env->prog->aux->max_ctx_offset = off + size;
1627 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
1631 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
1634 if (size < 0 || off < 0 ||
1635 (u64)off + size > sizeof(struct bpf_flow_keys)) {
1636 verbose(env, "invalid access to flow keys off=%d size=%d\n",
1643 static int check_sock_access(struct bpf_verifier_env *env, u32 regno, int off,
1644 int size, enum bpf_access_type t)
1646 struct bpf_reg_state *regs = cur_regs(env);
1647 struct bpf_reg_state *reg = ®s[regno];
1648 struct bpf_insn_access_aux info;
1650 if (reg->smin_value < 0) {
1651 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
1656 if (!bpf_sock_is_valid_access(off, size, t, &info)) {
1657 verbose(env, "invalid bpf_sock access off=%d size=%d\n",
1665 static bool __is_pointer_value(bool allow_ptr_leaks,
1666 const struct bpf_reg_state *reg)
1668 if (allow_ptr_leaks)
1671 return reg->type != SCALAR_VALUE;
1674 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
1676 return cur_regs(env) + regno;
1679 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
1681 return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
1684 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
1686 const struct bpf_reg_state *reg = reg_state(env, regno);
1688 return reg->type == PTR_TO_CTX ||
1689 reg->type == PTR_TO_SOCKET;
1692 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
1694 const struct bpf_reg_state *reg = reg_state(env, regno);
1696 return type_is_pkt_pointer(reg->type);
1699 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
1701 const struct bpf_reg_state *reg = reg_state(env, regno);
1703 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
1704 return reg->type == PTR_TO_FLOW_KEYS;
1707 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
1708 const struct bpf_reg_state *reg,
1709 int off, int size, bool strict)
1711 struct tnum reg_off;
1714 /* Byte size accesses are always allowed. */
1715 if (!strict || size == 1)
1718 /* For platforms that do not have a Kconfig enabling
1719 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
1720 * NET_IP_ALIGN is universally set to '2'. And on platforms
1721 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
1722 * to this code only in strict mode where we want to emulate
1723 * the NET_IP_ALIGN==2 checking. Therefore use an
1724 * unconditional IP align value of '2'.
1728 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
1729 if (!tnum_is_aligned(reg_off, size)) {
1732 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
1734 "misaligned packet access off %d+%s+%d+%d size %d\n",
1735 ip_align, tn_buf, reg->off, off, size);
1742 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
1743 const struct bpf_reg_state *reg,
1744 const char *pointer_desc,
1745 int off, int size, bool strict)
1747 struct tnum reg_off;
1749 /* Byte size accesses are always allowed. */
1750 if (!strict || size == 1)
1753 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
1754 if (!tnum_is_aligned(reg_off, size)) {
1757 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
1758 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
1759 pointer_desc, tn_buf, reg->off, off, size);
1766 static int check_ptr_alignment(struct bpf_verifier_env *env,
1767 const struct bpf_reg_state *reg, int off,
1768 int size, bool strict_alignment_once)
1770 bool strict = env->strict_alignment || strict_alignment_once;
1771 const char *pointer_desc = "";
1773 switch (reg->type) {
1775 case PTR_TO_PACKET_META:
1776 /* Special case, because of NET_IP_ALIGN. Given metadata sits
1777 * right in front, treat it the very same way.
1779 return check_pkt_ptr_alignment(env, reg, off, size, strict);
1780 case PTR_TO_FLOW_KEYS:
1781 pointer_desc = "flow keys ";
1783 case PTR_TO_MAP_VALUE:
1784 pointer_desc = "value ";
1787 pointer_desc = "context ";
1790 pointer_desc = "stack ";
1791 /* The stack spill tracking logic in check_stack_write()
1792 * and check_stack_read() relies on stack accesses being
1798 pointer_desc = "sock ";
1803 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
1807 static int update_stack_depth(struct bpf_verifier_env *env,
1808 const struct bpf_func_state *func,
1811 u16 stack = env->subprog_info[func->subprogno].stack_depth;
1816 /* update known max for given subprogram */
1817 env->subprog_info[func->subprogno].stack_depth = -off;
1821 /* starting from main bpf function walk all instructions of the function
1822 * and recursively walk all callees that given function can call.
1823 * Ignore jump and exit insns.
1824 * Since recursion is prevented by check_cfg() this algorithm
1825 * only needs a local stack of MAX_CALL_FRAMES to remember callsites
1827 static int check_max_stack_depth(struct bpf_verifier_env *env)
1829 int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
1830 struct bpf_subprog_info *subprog = env->subprog_info;
1831 struct bpf_insn *insn = env->prog->insnsi;
1832 int ret_insn[MAX_CALL_FRAMES];
1833 int ret_prog[MAX_CALL_FRAMES];
1836 /* round up to 32-bytes, since this is granularity
1837 * of interpreter stack size
1839 depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
1840 if (depth > MAX_BPF_STACK) {
1841 verbose(env, "combined stack size of %d calls is %d. Too large\n",
1846 subprog_end = subprog[idx + 1].start;
1847 for (; i < subprog_end; i++) {
1848 if (insn[i].code != (BPF_JMP | BPF_CALL))
1850 if (insn[i].src_reg != BPF_PSEUDO_CALL)
1852 /* remember insn and function to return to */
1853 ret_insn[frame] = i + 1;
1854 ret_prog[frame] = idx;
1856 /* find the callee */
1857 i = i + insn[i].imm + 1;
1858 idx = find_subprog(env, i);
1860 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
1865 if (frame >= MAX_CALL_FRAMES) {
1866 WARN_ONCE(1, "verifier bug. Call stack is too deep\n");
1871 /* end of for() loop means the last insn of the 'subprog'
1872 * was reached. Doesn't matter whether it was JA or EXIT
1876 depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
1878 i = ret_insn[frame];
1879 idx = ret_prog[frame];
1883 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
1884 static int get_callee_stack_depth(struct bpf_verifier_env *env,
1885 const struct bpf_insn *insn, int idx)
1887 int start = idx + insn->imm + 1, subprog;
1889 subprog = find_subprog(env, start);
1891 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
1895 return env->subprog_info[subprog].stack_depth;
1899 static int check_ctx_reg(struct bpf_verifier_env *env,
1900 const struct bpf_reg_state *reg, int regno)
1902 /* Access to ctx or passing it to a helper is only allowed in
1903 * its original, unmodified form.
1907 verbose(env, "dereference of modified ctx ptr R%d off=%d disallowed\n",
1912 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
1915 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
1916 verbose(env, "variable ctx access var_off=%s disallowed\n", tn_buf);
1923 /* truncate register to smaller size (in bytes)
1924 * must be called with size < BPF_REG_SIZE
1926 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
1930 /* clear high bits in bit representation */
1931 reg->var_off = tnum_cast(reg->var_off, size);
1933 /* fix arithmetic bounds */
1934 mask = ((u64)1 << (size * 8)) - 1;
1935 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
1936 reg->umin_value &= mask;
1937 reg->umax_value &= mask;
1939 reg->umin_value = 0;
1940 reg->umax_value = mask;
1942 reg->smin_value = reg->umin_value;
1943 reg->smax_value = reg->umax_value;
1946 /* check whether memory at (regno + off) is accessible for t = (read | write)
1947 * if t==write, value_regno is a register which value is stored into memory
1948 * if t==read, value_regno is a register which will receive the value from memory
1949 * if t==write && value_regno==-1, some unknown value is stored into memory
1950 * if t==read && value_regno==-1, don't care what we read from memory
1952 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
1953 int off, int bpf_size, enum bpf_access_type t,
1954 int value_regno, bool strict_alignment_once)
1956 struct bpf_reg_state *regs = cur_regs(env);
1957 struct bpf_reg_state *reg = regs + regno;
1958 struct bpf_func_state *state;
1961 size = bpf_size_to_bytes(bpf_size);
1965 /* alignment checks will add in reg->off themselves */
1966 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
1970 /* for access checks, reg->off is just part of off */
1973 if (reg->type == PTR_TO_MAP_VALUE) {
1974 if (t == BPF_WRITE && value_regno >= 0 &&
1975 is_pointer_value(env, value_regno)) {
1976 verbose(env, "R%d leaks addr into map\n", value_regno);
1980 err = check_map_access(env, regno, off, size, false);
1981 if (!err && t == BPF_READ && value_regno >= 0)
1982 mark_reg_unknown(env, regs, value_regno);
1984 } else if (reg->type == PTR_TO_CTX) {
1985 enum bpf_reg_type reg_type = SCALAR_VALUE;
1987 if (t == BPF_WRITE && value_regno >= 0 &&
1988 is_pointer_value(env, value_regno)) {
1989 verbose(env, "R%d leaks addr into ctx\n", value_regno);
1993 err = check_ctx_reg(env, reg, regno);
1997 err = check_ctx_access(env, insn_idx, off, size, t, ®_type);
1998 if (!err && t == BPF_READ && value_regno >= 0) {
1999 /* ctx access returns either a scalar, or a
2000 * PTR_TO_PACKET[_META,_END]. In the latter
2001 * case, we know the offset is zero.
2003 if (reg_type == SCALAR_VALUE)
2004 mark_reg_unknown(env, regs, value_regno);
2006 mark_reg_known_zero(env, regs,
2008 regs[value_regno].type = reg_type;
2011 } else if (reg->type == PTR_TO_STACK) {
2012 off += reg->var_off.value;
2013 err = check_stack_access(env, reg, off, size);
2017 state = func(env, reg);
2018 err = update_stack_depth(env, state, off);
2023 err = check_stack_write(env, state, off, size,
2024 value_regno, insn_idx);
2026 err = check_stack_read(env, state, off, size,
2028 } else if (reg_is_pkt_pointer(reg)) {
2029 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
2030 verbose(env, "cannot write into packet\n");
2033 if (t == BPF_WRITE && value_regno >= 0 &&
2034 is_pointer_value(env, value_regno)) {
2035 verbose(env, "R%d leaks addr into packet\n",
2039 err = check_packet_access(env, regno, off, size, false);
2040 if (!err && t == BPF_READ && value_regno >= 0)
2041 mark_reg_unknown(env, regs, value_regno);
2042 } else if (reg->type == PTR_TO_FLOW_KEYS) {
2043 if (t == BPF_WRITE && value_regno >= 0 &&
2044 is_pointer_value(env, value_regno)) {
2045 verbose(env, "R%d leaks addr into flow keys\n",
2050 err = check_flow_keys_access(env, off, size);
2051 if (!err && t == BPF_READ && value_regno >= 0)
2052 mark_reg_unknown(env, regs, value_regno);
2053 } else if (reg->type == PTR_TO_SOCKET) {
2054 if (t == BPF_WRITE) {
2055 verbose(env, "cannot write into socket\n");
2058 err = check_sock_access(env, regno, off, size, t);
2059 if (!err && value_regno >= 0)
2060 mark_reg_unknown(env, regs, value_regno);
2062 verbose(env, "R%d invalid mem access '%s'\n", regno,
2063 reg_type_str[reg->type]);
2067 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
2068 regs[value_regno].type == SCALAR_VALUE) {
2069 /* b/h/w load zero-extends, mark upper bits as known 0 */
2070 coerce_reg_to_size(®s[value_regno], size);
2075 static int check_xadd(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
2079 if ((BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) ||
2081 verbose(env, "BPF_XADD uses reserved fields\n");
2085 /* check src1 operand */
2086 err = check_reg_arg(env, insn->src_reg, SRC_OP);
2090 /* check src2 operand */
2091 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
2095 if (is_pointer_value(env, insn->src_reg)) {
2096 verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
2100 if (is_ctx_reg(env, insn->dst_reg) ||
2101 is_pkt_reg(env, insn->dst_reg) ||
2102 is_flow_key_reg(env, insn->dst_reg)) {
2103 verbose(env, "BPF_XADD stores into R%d %s is not allowed\n",
2105 reg_type_str[reg_state(env, insn->dst_reg)->type]);
2109 /* check whether atomic_add can read the memory */
2110 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
2111 BPF_SIZE(insn->code), BPF_READ, -1, true);
2115 /* check whether atomic_add can write into the same memory */
2116 return check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
2117 BPF_SIZE(insn->code), BPF_WRITE, -1, true);
2120 /* when register 'regno' is passed into function that will read 'access_size'
2121 * bytes from that pointer, make sure that it's within stack boundary
2122 * and all elements of stack are initialized.
2123 * Unlike most pointer bounds-checking functions, this one doesn't take an
2124 * 'off' argument, so it has to add in reg->off itself.
2126 static int check_stack_boundary(struct bpf_verifier_env *env, int regno,
2127 int access_size, bool zero_size_allowed,
2128 struct bpf_call_arg_meta *meta)
2130 struct bpf_reg_state *reg = reg_state(env, regno);
2131 struct bpf_func_state *state = func(env, reg);
2132 int off, i, slot, spi;
2134 if (reg->type != PTR_TO_STACK) {
2135 /* Allow zero-byte read from NULL, regardless of pointer type */
2136 if (zero_size_allowed && access_size == 0 &&
2137 register_is_null(reg))
2140 verbose(env, "R%d type=%s expected=%s\n", regno,
2141 reg_type_str[reg->type],
2142 reg_type_str[PTR_TO_STACK]);
2146 /* Only allow fixed-offset stack reads */
2147 if (!tnum_is_const(reg->var_off)) {
2150 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
2151 verbose(env, "invalid variable stack read R%d var_off=%s\n",
2155 off = reg->off + reg->var_off.value;
2156 if (off >= 0 || off < -MAX_BPF_STACK || off + access_size > 0 ||
2157 access_size < 0 || (access_size == 0 && !zero_size_allowed)) {
2158 verbose(env, "invalid stack type R%d off=%d access_size=%d\n",
2159 regno, off, access_size);
2163 if (meta && meta->raw_mode) {
2164 meta->access_size = access_size;
2165 meta->regno = regno;
2169 for (i = 0; i < access_size; i++) {
2172 slot = -(off + i) - 1;
2173 spi = slot / BPF_REG_SIZE;
2174 if (state->allocated_stack <= slot)
2176 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
2177 if (*stype == STACK_MISC)
2179 if (*stype == STACK_ZERO) {
2180 /* helper can write anything into the stack */
2181 *stype = STACK_MISC;
2185 verbose(env, "invalid indirect read from stack off %d+%d size %d\n",
2186 off, i, access_size);
2189 /* reading any byte out of 8-byte 'spill_slot' will cause
2190 * the whole slot to be marked as 'read'
2192 mark_reg_read(env, &state->stack[spi].spilled_ptr,
2193 state->stack[spi].spilled_ptr.parent);
2195 return update_stack_depth(env, state, off);
2198 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
2199 int access_size, bool zero_size_allowed,
2200 struct bpf_call_arg_meta *meta)
2202 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
2204 switch (reg->type) {
2206 case PTR_TO_PACKET_META:
2207 return check_packet_access(env, regno, reg->off, access_size,
2209 case PTR_TO_MAP_VALUE:
2210 return check_map_access(env, regno, reg->off, access_size,
2212 default: /* scalar_value|ptr_to_stack or invalid ptr */
2213 return check_stack_boundary(env, regno, access_size,
2214 zero_size_allowed, meta);
2218 /* Implementation details:
2219 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL
2220 * Two bpf_map_lookups (even with the same key) will have different reg->id.
2221 * For traditional PTR_TO_MAP_VALUE the verifier clears reg->id after
2222 * value_or_null->value transition, since the verifier only cares about
2223 * the range of access to valid map value pointer and doesn't care about actual
2224 * address of the map element.
2225 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
2226 * reg->id > 0 after value_or_null->value transition. By doing so
2227 * two bpf_map_lookups will be considered two different pointers that
2228 * point to different bpf_spin_locks.
2229 * The verifier allows taking only one bpf_spin_lock at a time to avoid
2231 * Since only one bpf_spin_lock is allowed the checks are simpler than
2232 * reg_is_refcounted() logic. The verifier needs to remember only
2233 * one spin_lock instead of array of acquired_refs.
2234 * cur_state->active_spin_lock remembers which map value element got locked
2235 * and clears it after bpf_spin_unlock.
2237 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
2240 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
2241 struct bpf_verifier_state *cur = env->cur_state;
2242 bool is_const = tnum_is_const(reg->var_off);
2243 struct bpf_map *map = reg->map_ptr;
2244 u64 val = reg->var_off.value;
2246 if (reg->type != PTR_TO_MAP_VALUE) {
2247 verbose(env, "R%d is not a pointer to map_value\n", regno);
2252 "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
2258 "map '%s' has to have BTF in order to use bpf_spin_lock\n",
2262 if (!map_value_has_spin_lock(map)) {
2263 if (map->spin_lock_off == -E2BIG)
2265 "map '%s' has more than one 'struct bpf_spin_lock'\n",
2267 else if (map->spin_lock_off == -ENOENT)
2269 "map '%s' doesn't have 'struct bpf_spin_lock'\n",
2273 "map '%s' is not a struct type or bpf_spin_lock is mangled\n",
2277 if (map->spin_lock_off != val + reg->off) {
2278 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock'\n",
2283 if (cur->active_spin_lock) {
2285 "Locking two bpf_spin_locks are not allowed\n");
2288 cur->active_spin_lock = reg->id;
2290 if (!cur->active_spin_lock) {
2291 verbose(env, "bpf_spin_unlock without taking a lock\n");
2294 if (cur->active_spin_lock != reg->id) {
2295 verbose(env, "bpf_spin_unlock of different lock\n");
2298 cur->active_spin_lock = 0;
2303 static bool arg_type_is_mem_ptr(enum bpf_arg_type type)
2305 return type == ARG_PTR_TO_MEM ||
2306 type == ARG_PTR_TO_MEM_OR_NULL ||
2307 type == ARG_PTR_TO_UNINIT_MEM;
2310 static bool arg_type_is_mem_size(enum bpf_arg_type type)
2312 return type == ARG_CONST_SIZE ||
2313 type == ARG_CONST_SIZE_OR_ZERO;
2316 static int check_func_arg(struct bpf_verifier_env *env, u32 regno,
2317 enum bpf_arg_type arg_type,
2318 struct bpf_call_arg_meta *meta)
2320 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
2321 enum bpf_reg_type expected_type, type = reg->type;
2324 if (arg_type == ARG_DONTCARE)
2327 err = check_reg_arg(env, regno, SRC_OP);
2331 if (arg_type == ARG_ANYTHING) {
2332 if (is_pointer_value(env, regno)) {
2333 verbose(env, "R%d leaks addr into helper function\n",
2340 if (type_is_pkt_pointer(type) &&
2341 !may_access_direct_pkt_data(env, meta, BPF_READ)) {
2342 verbose(env, "helper access to the packet is not allowed\n");
2346 if (arg_type == ARG_PTR_TO_MAP_KEY ||
2347 arg_type == ARG_PTR_TO_MAP_VALUE ||
2348 arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE) {
2349 expected_type = PTR_TO_STACK;
2350 if (!type_is_pkt_pointer(type) && type != PTR_TO_MAP_VALUE &&
2351 type != expected_type)
2353 } else if (arg_type == ARG_CONST_SIZE ||
2354 arg_type == ARG_CONST_SIZE_OR_ZERO) {
2355 expected_type = SCALAR_VALUE;
2356 if (type != expected_type)
2358 } else if (arg_type == ARG_CONST_MAP_PTR) {
2359 expected_type = CONST_PTR_TO_MAP;
2360 if (type != expected_type)
2362 } else if (arg_type == ARG_PTR_TO_CTX) {
2363 expected_type = PTR_TO_CTX;
2364 if (type != expected_type)
2366 err = check_ctx_reg(env, reg, regno);
2369 } else if (arg_type == ARG_PTR_TO_SOCKET) {
2370 expected_type = PTR_TO_SOCKET;
2371 if (type != expected_type)
2373 if (meta->ptr_id || !reg->id) {
2374 verbose(env, "verifier internal error: mismatched references meta=%d, reg=%d\n",
2375 meta->ptr_id, reg->id);
2378 meta->ptr_id = reg->id;
2379 } else if (arg_type == ARG_PTR_TO_SPIN_LOCK) {
2380 if (meta->func_id == BPF_FUNC_spin_lock) {
2381 if (process_spin_lock(env, regno, true))
2383 } else if (meta->func_id == BPF_FUNC_spin_unlock) {
2384 if (process_spin_lock(env, regno, false))
2387 verbose(env, "verifier internal error\n");
2390 } else if (arg_type_is_mem_ptr(arg_type)) {
2391 expected_type = PTR_TO_STACK;
2392 /* One exception here. In case function allows for NULL to be
2393 * passed in as argument, it's a SCALAR_VALUE type. Final test
2394 * happens during stack boundary checking.
2396 if (register_is_null(reg) &&
2397 arg_type == ARG_PTR_TO_MEM_OR_NULL)
2398 /* final test in check_stack_boundary() */;
2399 else if (!type_is_pkt_pointer(type) &&
2400 type != PTR_TO_MAP_VALUE &&
2401 type != expected_type)
2403 meta->raw_mode = arg_type == ARG_PTR_TO_UNINIT_MEM;
2405 verbose(env, "unsupported arg_type %d\n", arg_type);
2409 if (arg_type == ARG_CONST_MAP_PTR) {
2410 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
2411 meta->map_ptr = reg->map_ptr;
2412 } else if (arg_type == ARG_PTR_TO_MAP_KEY) {
2413 /* bpf_map_xxx(..., map_ptr, ..., key) call:
2414 * check that [key, key + map->key_size) are within
2415 * stack limits and initialized
2417 if (!meta->map_ptr) {
2418 /* in function declaration map_ptr must come before
2419 * map_key, so that it's verified and known before
2420 * we have to check map_key here. Otherwise it means
2421 * that kernel subsystem misconfigured verifier
2423 verbose(env, "invalid map_ptr to access map->key\n");
2426 err = check_helper_mem_access(env, regno,
2427 meta->map_ptr->key_size, false,
2429 } else if (arg_type == ARG_PTR_TO_MAP_VALUE ||
2430 arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE) {
2431 /* bpf_map_xxx(..., map_ptr, ..., value) call:
2432 * check [value, value + map->value_size) validity
2434 if (!meta->map_ptr) {
2435 /* kernel subsystem misconfigured verifier */
2436 verbose(env, "invalid map_ptr to access map->value\n");
2439 meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE);
2440 err = check_helper_mem_access(env, regno,
2441 meta->map_ptr->value_size, false,
2443 } else if (arg_type_is_mem_size(arg_type)) {
2444 bool zero_size_allowed = (arg_type == ARG_CONST_SIZE_OR_ZERO);
2446 /* remember the mem_size which may be used later
2447 * to refine return values.
2449 meta->msize_smax_value = reg->smax_value;
2450 meta->msize_umax_value = reg->umax_value;
2452 /* The register is SCALAR_VALUE; the access check
2453 * happens using its boundaries.
2455 if (!tnum_is_const(reg->var_off))
2456 /* For unprivileged variable accesses, disable raw
2457 * mode so that the program is required to
2458 * initialize all the memory that the helper could
2459 * just partially fill up.
2463 if (reg->smin_value < 0) {
2464 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
2469 if (reg->umin_value == 0) {
2470 err = check_helper_mem_access(env, regno - 1, 0,
2477 if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
2478 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
2482 err = check_helper_mem_access(env, regno - 1,
2484 zero_size_allowed, meta);
2489 verbose(env, "R%d type=%s expected=%s\n", regno,
2490 reg_type_str[type], reg_type_str[expected_type]);
2494 static int check_map_func_compatibility(struct bpf_verifier_env *env,
2495 struct bpf_map *map, int func_id)
2500 /* We need a two way check, first is from map perspective ... */
2501 switch (map->map_type) {
2502 case BPF_MAP_TYPE_PROG_ARRAY:
2503 if (func_id != BPF_FUNC_tail_call)
2506 case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
2507 if (func_id != BPF_FUNC_perf_event_read &&
2508 func_id != BPF_FUNC_perf_event_output &&
2509 func_id != BPF_FUNC_perf_event_read_value)
2512 case BPF_MAP_TYPE_STACK_TRACE:
2513 if (func_id != BPF_FUNC_get_stackid)
2516 case BPF_MAP_TYPE_CGROUP_ARRAY:
2517 if (func_id != BPF_FUNC_skb_under_cgroup &&
2518 func_id != BPF_FUNC_current_task_under_cgroup)
2521 case BPF_MAP_TYPE_CGROUP_STORAGE:
2522 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
2523 if (func_id != BPF_FUNC_get_local_storage)
2526 /* devmap returns a pointer to a live net_device ifindex that we cannot
2527 * allow to be modified from bpf side. So do not allow lookup elements
2530 case BPF_MAP_TYPE_DEVMAP:
2531 if (func_id != BPF_FUNC_redirect_map)
2534 /* Restrict bpf side of cpumap and xskmap, open when use-cases
2537 case BPF_MAP_TYPE_CPUMAP:
2538 case BPF_MAP_TYPE_XSKMAP:
2539 if (func_id != BPF_FUNC_redirect_map)
2542 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
2543 case BPF_MAP_TYPE_HASH_OF_MAPS:
2544 if (func_id != BPF_FUNC_map_lookup_elem)
2547 case BPF_MAP_TYPE_SOCKMAP:
2548 if (func_id != BPF_FUNC_sk_redirect_map &&
2549 func_id != BPF_FUNC_sock_map_update &&
2550 func_id != BPF_FUNC_map_delete_elem &&
2551 func_id != BPF_FUNC_msg_redirect_map)
2554 case BPF_MAP_TYPE_SOCKHASH:
2555 if (func_id != BPF_FUNC_sk_redirect_hash &&
2556 func_id != BPF_FUNC_sock_hash_update &&
2557 func_id != BPF_FUNC_map_delete_elem &&
2558 func_id != BPF_FUNC_msg_redirect_hash)
2561 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
2562 if (func_id != BPF_FUNC_sk_select_reuseport)
2565 case BPF_MAP_TYPE_QUEUE:
2566 case BPF_MAP_TYPE_STACK:
2567 if (func_id != BPF_FUNC_map_peek_elem &&
2568 func_id != BPF_FUNC_map_pop_elem &&
2569 func_id != BPF_FUNC_map_push_elem)
2576 /* ... and second from the function itself. */
2578 case BPF_FUNC_tail_call:
2579 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
2581 if (env->subprog_cnt > 1) {
2582 verbose(env, "tail_calls are not allowed in programs with bpf-to-bpf calls\n");
2586 case BPF_FUNC_perf_event_read:
2587 case BPF_FUNC_perf_event_output:
2588 case BPF_FUNC_perf_event_read_value:
2589 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
2592 case BPF_FUNC_get_stackid:
2593 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
2596 case BPF_FUNC_current_task_under_cgroup:
2597 case BPF_FUNC_skb_under_cgroup:
2598 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
2601 case BPF_FUNC_redirect_map:
2602 if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
2603 map->map_type != BPF_MAP_TYPE_CPUMAP &&
2604 map->map_type != BPF_MAP_TYPE_XSKMAP)
2607 case BPF_FUNC_sk_redirect_map:
2608 case BPF_FUNC_msg_redirect_map:
2609 case BPF_FUNC_sock_map_update:
2610 if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
2613 case BPF_FUNC_sk_redirect_hash:
2614 case BPF_FUNC_msg_redirect_hash:
2615 case BPF_FUNC_sock_hash_update:
2616 if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
2619 case BPF_FUNC_get_local_storage:
2620 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
2621 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
2624 case BPF_FUNC_sk_select_reuseport:
2625 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY)
2628 case BPF_FUNC_map_peek_elem:
2629 case BPF_FUNC_map_pop_elem:
2630 case BPF_FUNC_map_push_elem:
2631 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
2632 map->map_type != BPF_MAP_TYPE_STACK)
2641 verbose(env, "cannot pass map_type %d into func %s#%d\n",
2642 map->map_type, func_id_name(func_id), func_id);
2646 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
2650 if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
2652 if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
2654 if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
2656 if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
2658 if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
2661 /* We only support one arg being in raw mode at the moment,
2662 * which is sufficient for the helper functions we have
2668 static bool check_args_pair_invalid(enum bpf_arg_type arg_curr,
2669 enum bpf_arg_type arg_next)
2671 return (arg_type_is_mem_ptr(arg_curr) &&
2672 !arg_type_is_mem_size(arg_next)) ||
2673 (!arg_type_is_mem_ptr(arg_curr) &&
2674 arg_type_is_mem_size(arg_next));
2677 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
2679 /* bpf_xxx(..., buf, len) call will access 'len'
2680 * bytes from memory 'buf'. Both arg types need
2681 * to be paired, so make sure there's no buggy
2682 * helper function specification.
2684 if (arg_type_is_mem_size(fn->arg1_type) ||
2685 arg_type_is_mem_ptr(fn->arg5_type) ||
2686 check_args_pair_invalid(fn->arg1_type, fn->arg2_type) ||
2687 check_args_pair_invalid(fn->arg2_type, fn->arg3_type) ||
2688 check_args_pair_invalid(fn->arg3_type, fn->arg4_type) ||
2689 check_args_pair_invalid(fn->arg4_type, fn->arg5_type))
2695 static bool check_refcount_ok(const struct bpf_func_proto *fn)
2699 if (arg_type_is_refcounted(fn->arg1_type))
2701 if (arg_type_is_refcounted(fn->arg2_type))
2703 if (arg_type_is_refcounted(fn->arg3_type))
2705 if (arg_type_is_refcounted(fn->arg4_type))
2707 if (arg_type_is_refcounted(fn->arg5_type))
2710 /* We only support one arg being unreferenced at the moment,
2711 * which is sufficient for the helper functions we have right now.
2716 static int check_func_proto(const struct bpf_func_proto *fn)
2718 return check_raw_mode_ok(fn) &&
2719 check_arg_pair_ok(fn) &&
2720 check_refcount_ok(fn) ? 0 : -EINVAL;
2723 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
2724 * are now invalid, so turn them into unknown SCALAR_VALUE.
2726 static void __clear_all_pkt_pointers(struct bpf_verifier_env *env,
2727 struct bpf_func_state *state)
2729 struct bpf_reg_state *regs = state->regs, *reg;
2732 for (i = 0; i < MAX_BPF_REG; i++)
2733 if (reg_is_pkt_pointer_any(®s[i]))
2734 mark_reg_unknown(env, regs, i);
2736 bpf_for_each_spilled_reg(i, state, reg) {
2739 if (reg_is_pkt_pointer_any(reg))
2740 __mark_reg_unknown(reg);
2744 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
2746 struct bpf_verifier_state *vstate = env->cur_state;
2749 for (i = 0; i <= vstate->curframe; i++)
2750 __clear_all_pkt_pointers(env, vstate->frame[i]);
2753 static void release_reg_references(struct bpf_verifier_env *env,
2754 struct bpf_func_state *state, int id)
2756 struct bpf_reg_state *regs = state->regs, *reg;
2759 for (i = 0; i < MAX_BPF_REG; i++)
2760 if (regs[i].id == id)
2761 mark_reg_unknown(env, regs, i);
2763 bpf_for_each_spilled_reg(i, state, reg) {
2766 if (reg_is_refcounted(reg) && reg->id == id)
2767 __mark_reg_unknown(reg);
2771 /* The pointer with the specified id has released its reference to kernel
2772 * resources. Identify all copies of the same pointer and clear the reference.
2774 static int release_reference(struct bpf_verifier_env *env,
2775 struct bpf_call_arg_meta *meta)
2777 struct bpf_verifier_state *vstate = env->cur_state;
2780 for (i = 0; i <= vstate->curframe; i++)
2781 release_reg_references(env, vstate->frame[i], meta->ptr_id);
2783 return release_reference_state(env, meta->ptr_id);
2786 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
2789 struct bpf_verifier_state *state = env->cur_state;
2790 struct bpf_func_state *caller, *callee;
2791 int i, err, subprog, target_insn;
2793 if (state->curframe + 1 >= MAX_CALL_FRAMES) {
2794 verbose(env, "the call stack of %d frames is too deep\n",
2795 state->curframe + 2);
2799 target_insn = *insn_idx + insn->imm;
2800 subprog = find_subprog(env, target_insn + 1);
2802 verbose(env, "verifier bug. No program starts at insn %d\n",
2807 caller = state->frame[state->curframe];
2808 if (state->frame[state->curframe + 1]) {
2809 verbose(env, "verifier bug. Frame %d already allocated\n",
2810 state->curframe + 1);
2814 callee = kzalloc(sizeof(*callee), GFP_KERNEL);
2817 state->frame[state->curframe + 1] = callee;
2819 /* callee cannot access r0, r6 - r9 for reading and has to write
2820 * into its own stack before reading from it.
2821 * callee can read/write into caller's stack
2823 init_func_state(env, callee,
2824 /* remember the callsite, it will be used by bpf_exit */
2825 *insn_idx /* callsite */,
2826 state->curframe + 1 /* frameno within this callchain */,
2827 subprog /* subprog number within this prog */);
2829 /* Transfer references to the callee */
2830 err = transfer_reference_state(callee, caller);
2834 /* copy r1 - r5 args that callee can access. The copy includes parent
2835 * pointers, which connects us up to the liveness chain
2837 for (i = BPF_REG_1; i <= BPF_REG_5; i++)
2838 callee->regs[i] = caller->regs[i];
2840 /* after the call registers r0 - r5 were scratched */
2841 for (i = 0; i < CALLER_SAVED_REGS; i++) {
2842 mark_reg_not_init(env, caller->regs, caller_saved[i]);
2843 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
2846 /* only increment it after check_reg_arg() finished */
2849 /* and go analyze first insn of the callee */
2850 *insn_idx = target_insn;
2852 if (env->log.level) {
2853 verbose(env, "caller:\n");
2854 print_verifier_state(env, caller);
2855 verbose(env, "callee:\n");
2856 print_verifier_state(env, callee);
2861 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
2863 struct bpf_verifier_state *state = env->cur_state;
2864 struct bpf_func_state *caller, *callee;
2865 struct bpf_reg_state *r0;
2868 callee = state->frame[state->curframe];
2869 r0 = &callee->regs[BPF_REG_0];
2870 if (r0->type == PTR_TO_STACK) {
2871 /* technically it's ok to return caller's stack pointer
2872 * (or caller's caller's pointer) back to the caller,
2873 * since these pointers are valid. Only current stack
2874 * pointer will be invalid as soon as function exits,
2875 * but let's be conservative
2877 verbose(env, "cannot return stack pointer to the caller\n");
2882 caller = state->frame[state->curframe];
2883 /* return to the caller whatever r0 had in the callee */
2884 caller->regs[BPF_REG_0] = *r0;
2886 /* Transfer references to the caller */
2887 err = transfer_reference_state(caller, callee);
2891 *insn_idx = callee->callsite + 1;
2892 if (env->log.level) {
2893 verbose(env, "returning from callee:\n");
2894 print_verifier_state(env, callee);
2895 verbose(env, "to caller at %d:\n", *insn_idx);
2896 print_verifier_state(env, caller);
2898 /* clear everything in the callee */
2899 free_func_state(callee);
2900 state->frame[state->curframe + 1] = NULL;
2904 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
2906 struct bpf_call_arg_meta *meta)
2908 struct bpf_reg_state *ret_reg = ®s[BPF_REG_0];
2910 if (ret_type != RET_INTEGER ||
2911 (func_id != BPF_FUNC_get_stack &&
2912 func_id != BPF_FUNC_probe_read_str))
2915 ret_reg->smax_value = meta->msize_smax_value;
2916 ret_reg->umax_value = meta->msize_umax_value;
2917 __reg_deduce_bounds(ret_reg);
2918 __reg_bound_offset(ret_reg);
2922 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
2923 int func_id, int insn_idx)
2925 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
2927 if (func_id != BPF_FUNC_tail_call &&
2928 func_id != BPF_FUNC_map_lookup_elem &&
2929 func_id != BPF_FUNC_map_update_elem &&
2930 func_id != BPF_FUNC_map_delete_elem &&
2931 func_id != BPF_FUNC_map_push_elem &&
2932 func_id != BPF_FUNC_map_pop_elem &&
2933 func_id != BPF_FUNC_map_peek_elem)
2936 if (meta->map_ptr == NULL) {
2937 verbose(env, "kernel subsystem misconfigured verifier\n");
2941 if (!BPF_MAP_PTR(aux->map_state))
2942 bpf_map_ptr_store(aux, meta->map_ptr,
2943 meta->map_ptr->unpriv_array);
2944 else if (BPF_MAP_PTR(aux->map_state) != meta->map_ptr)
2945 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
2946 meta->map_ptr->unpriv_array);
2950 static int check_reference_leak(struct bpf_verifier_env *env)
2952 struct bpf_func_state *state = cur_func(env);
2955 for (i = 0; i < state->acquired_refs; i++) {
2956 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
2957 state->refs[i].id, state->refs[i].insn_idx);
2959 return state->acquired_refs ? -EINVAL : 0;
2962 static int check_helper_call(struct bpf_verifier_env *env, int func_id, int insn_idx)
2964 const struct bpf_func_proto *fn = NULL;
2965 struct bpf_reg_state *regs;
2966 struct bpf_call_arg_meta meta;
2970 /* find function prototype */
2971 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
2972 verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
2977 if (env->ops->get_func_proto)
2978 fn = env->ops->get_func_proto(func_id, env->prog);
2980 verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
2985 /* eBPF programs must be GPL compatible to use GPL-ed functions */
2986 if (!env->prog->gpl_compatible && fn->gpl_only) {
2987 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
2991 /* With LD_ABS/IND some JITs save/restore skb from r1. */
2992 changes_data = bpf_helper_changes_pkt_data(fn->func);
2993 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
2994 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
2995 func_id_name(func_id), func_id);
2999 memset(&meta, 0, sizeof(meta));
3000 meta.pkt_access = fn->pkt_access;
3002 err = check_func_proto(fn);
3004 verbose(env, "kernel subsystem misconfigured func %s#%d\n",
3005 func_id_name(func_id), func_id);
3009 meta.func_id = func_id;
3011 err = check_func_arg(env, BPF_REG_1, fn->arg1_type, &meta);
3014 err = check_func_arg(env, BPF_REG_2, fn->arg2_type, &meta);
3017 err = check_func_arg(env, BPF_REG_3, fn->arg3_type, &meta);
3020 err = check_func_arg(env, BPF_REG_4, fn->arg4_type, &meta);
3023 err = check_func_arg(env, BPF_REG_5, fn->arg5_type, &meta);
3027 err = record_func_map(env, &meta, func_id, insn_idx);
3031 /* Mark slots with STACK_MISC in case of raw mode, stack offset
3032 * is inferred from register state.
3034 for (i = 0; i < meta.access_size; i++) {
3035 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
3036 BPF_WRITE, -1, false);
3041 if (func_id == BPF_FUNC_tail_call) {
3042 err = check_reference_leak(env);
3044 verbose(env, "tail_call would lead to reference leak\n");
3047 } else if (is_release_function(func_id)) {
3048 err = release_reference(env, &meta);
3053 regs = cur_regs(env);
3055 /* check that flags argument in get_local_storage(map, flags) is 0,
3056 * this is required because get_local_storage() can't return an error.
3058 if (func_id == BPF_FUNC_get_local_storage &&
3059 !register_is_null(®s[BPF_REG_2])) {
3060 verbose(env, "get_local_storage() doesn't support non-zero flags\n");
3064 /* reset caller saved regs */
3065 for (i = 0; i < CALLER_SAVED_REGS; i++) {
3066 mark_reg_not_init(env, regs, caller_saved[i]);
3067 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
3070 /* update return register (already marked as written above) */
3071 if (fn->ret_type == RET_INTEGER) {
3072 /* sets type to SCALAR_VALUE */
3073 mark_reg_unknown(env, regs, BPF_REG_0);
3074 } else if (fn->ret_type == RET_VOID) {
3075 regs[BPF_REG_0].type = NOT_INIT;
3076 } else if (fn->ret_type == RET_PTR_TO_MAP_VALUE_OR_NULL ||
3077 fn->ret_type == RET_PTR_TO_MAP_VALUE) {
3078 /* There is no offset yet applied, variable or fixed */
3079 mark_reg_known_zero(env, regs, BPF_REG_0);
3080 /* remember map_ptr, so that check_map_access()
3081 * can check 'value_size' boundary of memory access
3082 * to map element returned from bpf_map_lookup_elem()
3084 if (meta.map_ptr == NULL) {
3086 "kernel subsystem misconfigured verifier\n");
3089 regs[BPF_REG_0].map_ptr = meta.map_ptr;
3090 if (fn->ret_type == RET_PTR_TO_MAP_VALUE) {
3091 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE;
3092 if (map_value_has_spin_lock(meta.map_ptr))
3093 regs[BPF_REG_0].id = ++env->id_gen;
3095 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE_OR_NULL;
3096 regs[BPF_REG_0].id = ++env->id_gen;
3098 } else if (fn->ret_type == RET_PTR_TO_SOCKET_OR_NULL) {
3099 int id = acquire_reference_state(env, insn_idx);
3102 mark_reg_known_zero(env, regs, BPF_REG_0);
3103 regs[BPF_REG_0].type = PTR_TO_SOCKET_OR_NULL;
3104 regs[BPF_REG_0].id = id;
3106 verbose(env, "unknown return type %d of func %s#%d\n",
3107 fn->ret_type, func_id_name(func_id), func_id);
3111 do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
3113 err = check_map_func_compatibility(env, meta.map_ptr, func_id);
3117 if (func_id == BPF_FUNC_get_stack && !env->prog->has_callchain_buf) {
3118 const char *err_str;
3120 #ifdef CONFIG_PERF_EVENTS
3121 err = get_callchain_buffers(sysctl_perf_event_max_stack);
3122 err_str = "cannot get callchain buffer for func %s#%d\n";
3125 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
3128 verbose(env, err_str, func_id_name(func_id), func_id);
3132 env->prog->has_callchain_buf = true;
3136 clear_all_pkt_pointers(env);
3140 static bool signed_add_overflows(s64 a, s64 b)
3142 /* Do the add in u64, where overflow is well-defined */
3143 s64 res = (s64)((u64)a + (u64)b);
3150 static bool signed_sub_overflows(s64 a, s64 b)
3152 /* Do the sub in u64, where overflow is well-defined */
3153 s64 res = (s64)((u64)a - (u64)b);
3160 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
3161 const struct bpf_reg_state *reg,
3162 enum bpf_reg_type type)
3164 bool known = tnum_is_const(reg->var_off);
3165 s64 val = reg->var_off.value;
3166 s64 smin = reg->smin_value;
3168 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
3169 verbose(env, "math between %s pointer and %lld is not allowed\n",
3170 reg_type_str[type], val);
3174 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
3175 verbose(env, "%s pointer offset %d is not allowed\n",
3176 reg_type_str[type], reg->off);
3180 if (smin == S64_MIN) {
3181 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
3182 reg_type_str[type]);
3186 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
3187 verbose(env, "value %lld makes %s pointer be out of bounds\n",
3188 smin, reg_type_str[type]);
3195 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
3197 return &env->insn_aux_data[env->insn_idx];
3200 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
3201 u32 *ptr_limit, u8 opcode, bool off_is_neg)
3203 bool mask_to_left = (opcode == BPF_ADD && off_is_neg) ||
3204 (opcode == BPF_SUB && !off_is_neg);
3207 switch (ptr_reg->type) {
3209 off = ptr_reg->off + ptr_reg->var_off.value;
3211 *ptr_limit = MAX_BPF_STACK + off;
3215 case PTR_TO_MAP_VALUE:
3217 *ptr_limit = ptr_reg->umax_value + ptr_reg->off;
3219 off = ptr_reg->smin_value + ptr_reg->off;
3220 *ptr_limit = ptr_reg->map_ptr->value_size - off;
3228 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
3229 const struct bpf_insn *insn)
3231 return env->allow_ptr_leaks || BPF_SRC(insn->code) == BPF_K;
3234 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
3235 u32 alu_state, u32 alu_limit)
3237 /* If we arrived here from different branches with different
3238 * state or limits to sanitize, then this won't work.
3240 if (aux->alu_state &&
3241 (aux->alu_state != alu_state ||
3242 aux->alu_limit != alu_limit))
3245 /* Corresponding fixup done in fixup_bpf_calls(). */
3246 aux->alu_state = alu_state;
3247 aux->alu_limit = alu_limit;
3251 static int sanitize_val_alu(struct bpf_verifier_env *env,
3252 struct bpf_insn *insn)
3254 struct bpf_insn_aux_data *aux = cur_aux(env);
3256 if (can_skip_alu_sanitation(env, insn))
3259 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
3262 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
3263 struct bpf_insn *insn,
3264 const struct bpf_reg_state *ptr_reg,
3265 struct bpf_reg_state *dst_reg,
3268 struct bpf_verifier_state *vstate = env->cur_state;
3269 struct bpf_insn_aux_data *aux = cur_aux(env);
3270 bool ptr_is_dst_reg = ptr_reg == dst_reg;
3271 u8 opcode = BPF_OP(insn->code);
3272 u32 alu_state, alu_limit;
3273 struct bpf_reg_state tmp;
3276 if (can_skip_alu_sanitation(env, insn))
3279 /* We already marked aux for masking from non-speculative
3280 * paths, thus we got here in the first place. We only care
3281 * to explore bad access from here.
3283 if (vstate->speculative)
3286 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
3287 alu_state |= ptr_is_dst_reg ?
3288 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
3290 if (retrieve_ptr_limit(ptr_reg, &alu_limit, opcode, off_is_neg))
3292 if (update_alu_sanitation_state(aux, alu_state, alu_limit))
3295 /* Simulate and find potential out-of-bounds access under
3296 * speculative execution from truncation as a result of
3297 * masking when off was not within expected range. If off
3298 * sits in dst, then we temporarily need to move ptr there
3299 * to simulate dst (== 0) +/-= ptr. Needed, for example,
3300 * for cases where we use K-based arithmetic in one direction
3301 * and truncated reg-based in the other in order to explore
3304 if (!ptr_is_dst_reg) {
3306 *dst_reg = *ptr_reg;
3308 ret = push_stack(env, env->insn_idx + 1, env->insn_idx, true);
3309 if (!ptr_is_dst_reg)
3311 return !ret ? -EFAULT : 0;
3314 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
3315 * Caller should also handle BPF_MOV case separately.
3316 * If we return -EACCES, caller may want to try again treating pointer as a
3317 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks.
3319 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
3320 struct bpf_insn *insn,
3321 const struct bpf_reg_state *ptr_reg,
3322 const struct bpf_reg_state *off_reg)
3324 struct bpf_verifier_state *vstate = env->cur_state;
3325 struct bpf_func_state *state = vstate->frame[vstate->curframe];
3326 struct bpf_reg_state *regs = state->regs, *dst_reg;
3327 bool known = tnum_is_const(off_reg->var_off);
3328 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
3329 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
3330 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
3331 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
3332 u32 dst = insn->dst_reg, src = insn->src_reg;
3333 u8 opcode = BPF_OP(insn->code);
3336 dst_reg = ®s[dst];
3338 if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
3339 smin_val > smax_val || umin_val > umax_val) {
3340 /* Taint dst register if offset had invalid bounds derived from
3341 * e.g. dead branches.
3343 __mark_reg_unknown(dst_reg);
3347 if (BPF_CLASS(insn->code) != BPF_ALU64) {
3348 /* 32-bit ALU ops on pointers produce (meaningless) scalars */
3350 "R%d 32-bit pointer arithmetic prohibited\n",
3355 switch (ptr_reg->type) {
3356 case PTR_TO_MAP_VALUE_OR_NULL:
3357 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
3358 dst, reg_type_str[ptr_reg->type]);
3360 case CONST_PTR_TO_MAP:
3361 case PTR_TO_PACKET_END:
3363 case PTR_TO_SOCKET_OR_NULL:
3364 verbose(env, "R%d pointer arithmetic on %s prohibited\n",
3365 dst, reg_type_str[ptr_reg->type]);
3367 case PTR_TO_MAP_VALUE:
3368 if (!env->allow_ptr_leaks && !known && (smin_val < 0) != (smax_val < 0)) {
3369 verbose(env, "R%d has unknown scalar with mixed signed bounds, pointer arithmetic with it prohibited for !root\n",
3370 off_reg == dst_reg ? dst : src);
3378 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
3379 * The id may be overwritten later if we create a new variable offset.
3381 dst_reg->type = ptr_reg->type;
3382 dst_reg->id = ptr_reg->id;
3384 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
3385 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
3390 ret = sanitize_ptr_alu(env, insn, ptr_reg, dst_reg, smin_val < 0);
3392 verbose(env, "R%d tried to add from different maps or paths\n", dst);
3395 /* We can take a fixed offset as long as it doesn't overflow
3396 * the s32 'off' field
3398 if (known && (ptr_reg->off + smin_val ==
3399 (s64)(s32)(ptr_reg->off + smin_val))) {
3400 /* pointer += K. Accumulate it into fixed offset */
3401 dst_reg->smin_value = smin_ptr;
3402 dst_reg->smax_value = smax_ptr;
3403 dst_reg->umin_value = umin_ptr;
3404 dst_reg->umax_value = umax_ptr;
3405 dst_reg->var_off = ptr_reg->var_off;
3406 dst_reg->off = ptr_reg->off + smin_val;
3407 dst_reg->raw = ptr_reg->raw;
3410 /* A new variable offset is created. Note that off_reg->off
3411 * == 0, since it's a scalar.
3412 * dst_reg gets the pointer type and since some positive
3413 * integer value was added to the pointer, give it a new 'id'
3414 * if it's a PTR_TO_PACKET.
3415 * this creates a new 'base' pointer, off_reg (variable) gets
3416 * added into the variable offset, and we copy the fixed offset
3419 if (signed_add_overflows(smin_ptr, smin_val) ||
3420 signed_add_overflows(smax_ptr, smax_val)) {
3421 dst_reg->smin_value = S64_MIN;
3422 dst_reg->smax_value = S64_MAX;
3424 dst_reg->smin_value = smin_ptr + smin_val;
3425 dst_reg->smax_value = smax_ptr + smax_val;
3427 if (umin_ptr + umin_val < umin_ptr ||
3428 umax_ptr + umax_val < umax_ptr) {
3429 dst_reg->umin_value = 0;
3430 dst_reg->umax_value = U64_MAX;
3432 dst_reg->umin_value = umin_ptr + umin_val;
3433 dst_reg->umax_value = umax_ptr + umax_val;
3435 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
3436 dst_reg->off = ptr_reg->off;
3437 dst_reg->raw = ptr_reg->raw;
3438 if (reg_is_pkt_pointer(ptr_reg)) {
3439 dst_reg->id = ++env->id_gen;
3440 /* something was added to pkt_ptr, set range to zero */
3445 ret = sanitize_ptr_alu(env, insn, ptr_reg, dst_reg, smin_val < 0);
3447 verbose(env, "R%d tried to sub from different maps or paths\n", dst);
3450 if (dst_reg == off_reg) {
3451 /* scalar -= pointer. Creates an unknown scalar */
3452 verbose(env, "R%d tried to subtract pointer from scalar\n",
3456 /* We don't allow subtraction from FP, because (according to
3457 * test_verifier.c test "invalid fp arithmetic", JITs might not
3458 * be able to deal with it.
3460 if (ptr_reg->type == PTR_TO_STACK) {
3461 verbose(env, "R%d subtraction from stack pointer prohibited\n",
3465 if (known && (ptr_reg->off - smin_val ==
3466 (s64)(s32)(ptr_reg->off - smin_val))) {
3467 /* pointer -= K. Subtract it from fixed offset */
3468 dst_reg->smin_value = smin_ptr;
3469 dst_reg->smax_value = smax_ptr;
3470 dst_reg->umin_value = umin_ptr;
3471 dst_reg->umax_value = umax_ptr;
3472 dst_reg->var_off = ptr_reg->var_off;
3473 dst_reg->id = ptr_reg->id;
3474 dst_reg->off = ptr_reg->off - smin_val;
3475 dst_reg->raw = ptr_reg->raw;
3478 /* A new variable offset is created. If the subtrahend is known
3479 * nonnegative, then any reg->range we had before is still good.
3481 if (signed_sub_overflows(smin_ptr, smax_val) ||
3482 signed_sub_overflows(smax_ptr, smin_val)) {
3483 /* Overflow possible, we know nothing */
3484 dst_reg->smin_value = S64_MIN;
3485 dst_reg->smax_value = S64_MAX;
3487 dst_reg->smin_value = smin_ptr - smax_val;
3488 dst_reg->smax_value = smax_ptr - smin_val;
3490 if (umin_ptr < umax_val) {
3491 /* Overflow possible, we know nothing */
3492 dst_reg->umin_value = 0;
3493 dst_reg->umax_value = U64_MAX;
3495 /* Cannot overflow (as long as bounds are consistent) */
3496 dst_reg->umin_value = umin_ptr - umax_val;
3497 dst_reg->umax_value = umax_ptr - umin_val;
3499 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
3500 dst_reg->off = ptr_reg->off;
3501 dst_reg->raw = ptr_reg->raw;
3502 if (reg_is_pkt_pointer(ptr_reg)) {
3503 dst_reg->id = ++env->id_gen;
3504 /* something was added to pkt_ptr, set range to zero */
3512 /* bitwise ops on pointers are troublesome, prohibit. */
3513 verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
3514 dst, bpf_alu_string[opcode >> 4]);
3517 /* other operators (e.g. MUL,LSH) produce non-pointer results */
3518 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
3519 dst, bpf_alu_string[opcode >> 4]);
3523 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
3526 __update_reg_bounds(dst_reg);
3527 __reg_deduce_bounds(dst_reg);
3528 __reg_bound_offset(dst_reg);
3530 /* For unprivileged we require that resulting offset must be in bounds
3531 * in order to be able to sanitize access later on.
3533 if (!env->allow_ptr_leaks) {
3534 if (dst_reg->type == PTR_TO_MAP_VALUE &&
3535 check_map_access(env, dst, dst_reg->off, 1, false)) {
3536 verbose(env, "R%d pointer arithmetic of map value goes out of range, "
3537 "prohibited for !root\n", dst);
3539 } else if (dst_reg->type == PTR_TO_STACK &&
3540 check_stack_access(env, dst_reg, dst_reg->off +
3541 dst_reg->var_off.value, 1)) {
3542 verbose(env, "R%d stack pointer arithmetic goes out of range, "
3543 "prohibited for !root\n", dst);
3551 /* WARNING: This function does calculations on 64-bit values, but the actual
3552 * execution may occur on 32-bit values. Therefore, things like bitshifts
3553 * need extra checks in the 32-bit case.
3555 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
3556 struct bpf_insn *insn,
3557 struct bpf_reg_state *dst_reg,
3558 struct bpf_reg_state src_reg)
3560 struct bpf_reg_state *regs = cur_regs(env);
3561 u8 opcode = BPF_OP(insn->code);
3562 bool src_known, dst_known;
3563 s64 smin_val, smax_val;
3564 u64 umin_val, umax_val;
3565 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
3566 u32 dst = insn->dst_reg;
3569 if (insn_bitness == 32) {
3570 /* Relevant for 32-bit RSH: Information can propagate towards
3571 * LSB, so it isn't sufficient to only truncate the output to
3574 coerce_reg_to_size(dst_reg, 4);
3575 coerce_reg_to_size(&src_reg, 4);
3578 smin_val = src_reg.smin_value;
3579 smax_val = src_reg.smax_value;
3580 umin_val = src_reg.umin_value;
3581 umax_val = src_reg.umax_value;
3582 src_known = tnum_is_const(src_reg.var_off);
3583 dst_known = tnum_is_const(dst_reg->var_off);
3585 if ((src_known && (smin_val != smax_val || umin_val != umax_val)) ||
3586 smin_val > smax_val || umin_val > umax_val) {
3587 /* Taint dst register if offset had invalid bounds derived from
3588 * e.g. dead branches.
3590 __mark_reg_unknown(dst_reg);
3595 opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
3596 __mark_reg_unknown(dst_reg);
3602 ret = sanitize_val_alu(env, insn);
3604 verbose(env, "R%d tried to add from different pointers or scalars\n", dst);
3607 if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
3608 signed_add_overflows(dst_reg->smax_value, smax_val)) {
3609 dst_reg->smin_value = S64_MIN;
3610 dst_reg->smax_value = S64_MAX;
3612 dst_reg->smin_value += smin_val;
3613 dst_reg->smax_value += smax_val;
3615 if (dst_reg->umin_value + umin_val < umin_val ||
3616 dst_reg->umax_value + umax_val < umax_val) {
3617 dst_reg->umin_value = 0;
3618 dst_reg->umax_value = U64_MAX;
3620 dst_reg->umin_value += umin_val;
3621 dst_reg->umax_value += umax_val;
3623 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
3626 ret = sanitize_val_alu(env, insn);
3628 verbose(env, "R%d tried to sub from different pointers or scalars\n", dst);
3631 if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
3632 signed_sub_overflows(dst_reg->smax_value, smin_val)) {
3633 /* Overflow possible, we know nothing */
3634 dst_reg->smin_value = S64_MIN;
3635 dst_reg->smax_value = S64_MAX;
3637 dst_reg->smin_value -= smax_val;
3638 dst_reg->smax_value -= smin_val;
3640 if (dst_reg->umin_value < umax_val) {
3641 /* Overflow possible, we know nothing */
3642 dst_reg->umin_value = 0;
3643 dst_reg->umax_value = U64_MAX;
3645 /* Cannot overflow (as long as bounds are consistent) */
3646 dst_reg->umin_value -= umax_val;
3647 dst_reg->umax_value -= umin_val;
3649 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
3652 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
3653 if (smin_val < 0 || dst_reg->smin_value < 0) {
3654 /* Ain't nobody got time to multiply that sign */
3655 __mark_reg_unbounded(dst_reg);
3656 __update_reg_bounds(dst_reg);
3659 /* Both values are positive, so we can work with unsigned and
3660 * copy the result to signed (unless it exceeds S64_MAX).
3662 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
3663 /* Potential overflow, we know nothing */
3664 __mark_reg_unbounded(dst_reg);
3665 /* (except what we can learn from the var_off) */
3666 __update_reg_bounds(dst_reg);
3669 dst_reg->umin_value *= umin_val;
3670 dst_reg->umax_value *= umax_val;
3671 if (dst_reg->umax_value > S64_MAX) {
3672 /* Overflow possible, we know nothing */
3673 dst_reg->smin_value = S64_MIN;
3674 dst_reg->smax_value = S64_MAX;
3676 dst_reg->smin_value = dst_reg->umin_value;
3677 dst_reg->smax_value = dst_reg->umax_value;
3681 if (src_known && dst_known) {
3682 __mark_reg_known(dst_reg, dst_reg->var_off.value &
3683 src_reg.var_off.value);
3686 /* We get our minimum from the var_off, since that's inherently
3687 * bitwise. Our maximum is the minimum of the operands' maxima.
3689 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
3690 dst_reg->umin_value = dst_reg->var_off.value;
3691 dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
3692 if (dst_reg->smin_value < 0 || smin_val < 0) {
3693 /* Lose signed bounds when ANDing negative numbers,
3694 * ain't nobody got time for that.
3696 dst_reg->smin_value = S64_MIN;
3697 dst_reg->smax_value = S64_MAX;
3699 /* ANDing two positives gives a positive, so safe to
3700 * cast result into s64.
3702 dst_reg->smin_value = dst_reg->umin_value;
3703 dst_reg->smax_value = dst_reg->umax_value;
3705 /* We may learn something more from the var_off */
3706 __update_reg_bounds(dst_reg);
3709 if (src_known && dst_known) {
3710 __mark_reg_known(dst_reg, dst_reg->var_off.value |
3711 src_reg.var_off.value);
3714 /* We get our maximum from the var_off, and our minimum is the
3715 * maximum of the operands' minima
3717 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
3718 dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
3719 dst_reg->umax_value = dst_reg->var_off.value |
3720 dst_reg->var_off.mask;
3721 if (dst_reg->smin_value < 0 || smin_val < 0) {
3722 /* Lose signed bounds when ORing negative numbers,
3723 * ain't nobody got time for that.
3725 dst_reg->smin_value = S64_MIN;
3726 dst_reg->smax_value = S64_MAX;
3728 /* ORing two positives gives a positive, so safe to
3729 * cast result into s64.
3731 dst_reg->smin_value = dst_reg->umin_value;
3732 dst_reg->smax_value = dst_reg->umax_value;
3734 /* We may learn something more from the var_off */
3735 __update_reg_bounds(dst_reg);
3738 if (umax_val >= insn_bitness) {
3739 /* Shifts greater than 31 or 63 are undefined.
3740 * This includes shifts by a negative number.
3742 mark_reg_unknown(env, regs, insn->dst_reg);
3745 /* We lose all sign bit information (except what we can pick
3748 dst_reg->smin_value = S64_MIN;
3749 dst_reg->smax_value = S64_MAX;
3750 /* If we might shift our top bit out, then we know nothing */
3751 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
3752 dst_reg->umin_value = 0;
3753 dst_reg->umax_value = U64_MAX;
3755 dst_reg->umin_value <<= umin_val;
3756 dst_reg->umax_value <<= umax_val;
3758 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
3759 /* We may learn something more from the var_off */
3760 __update_reg_bounds(dst_reg);
3763 if (umax_val >= insn_bitness) {
3764 /* Shifts greater than 31 or 63 are undefined.
3765 * This includes shifts by a negative number.
3767 mark_reg_unknown(env, regs, insn->dst_reg);
3770 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
3771 * be negative, then either:
3772 * 1) src_reg might be zero, so the sign bit of the result is
3773 * unknown, so we lose our signed bounds
3774 * 2) it's known negative, thus the unsigned bounds capture the
3776 * 3) the signed bounds cross zero, so they tell us nothing
3778 * If the value in dst_reg is known nonnegative, then again the
3779 * unsigned bounts capture the signed bounds.
3780 * Thus, in all cases it suffices to blow away our signed bounds
3781 * and rely on inferring new ones from the unsigned bounds and
3782 * var_off of the result.
3784 dst_reg->smin_value = S64_MIN;
3785 dst_reg->smax_value = S64_MAX;
3786 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
3787 dst_reg->umin_value >>= umax_val;
3788 dst_reg->umax_value >>= umin_val;
3789 /* We may learn something more from the var_off */
3790 __update_reg_bounds(dst_reg);
3793 if (umax_val >= insn_bitness) {
3794 /* Shifts greater than 31 or 63 are undefined.
3795 * This includes shifts by a negative number.
3797 mark_reg_unknown(env, regs, insn->dst_reg);
3801 /* Upon reaching here, src_known is true and
3802 * umax_val is equal to umin_val.
3804 dst_reg->smin_value >>= umin_val;
3805 dst_reg->smax_value >>= umin_val;
3806 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val);
3808 /* blow away the dst_reg umin_value/umax_value and rely on
3809 * dst_reg var_off to refine the result.
3811 dst_reg->umin_value = 0;
3812 dst_reg->umax_value = U64_MAX;
3813 __update_reg_bounds(dst_reg);
3816 mark_reg_unknown(env, regs, insn->dst_reg);
3820 if (BPF_CLASS(insn->code) != BPF_ALU64) {
3821 /* 32-bit ALU ops are (32,32)->32 */
3822 coerce_reg_to_size(dst_reg, 4);
3825 __reg_deduce_bounds(dst_reg);
3826 __reg_bound_offset(dst_reg);
3830 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
3833 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
3834 struct bpf_insn *insn)
3836 struct bpf_verifier_state *vstate = env->cur_state;
3837 struct bpf_func_state *state = vstate->frame[vstate->curframe];
3838 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
3839 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
3840 u8 opcode = BPF_OP(insn->code);
3842 dst_reg = ®s[insn->dst_reg];
3844 if (dst_reg->type != SCALAR_VALUE)
3846 if (BPF_SRC(insn->code) == BPF_X) {
3847 src_reg = ®s[insn->src_reg];
3848 if (src_reg->type != SCALAR_VALUE) {
3849 if (dst_reg->type != SCALAR_VALUE) {
3850 /* Combining two pointers by any ALU op yields
3851 * an arbitrary scalar. Disallow all math except
3852 * pointer subtraction
3854 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
3855 mark_reg_unknown(env, regs, insn->dst_reg);
3858 verbose(env, "R%d pointer %s pointer prohibited\n",
3860 bpf_alu_string[opcode >> 4]);
3863 /* scalar += pointer
3864 * This is legal, but we have to reverse our
3865 * src/dest handling in computing the range
3867 return adjust_ptr_min_max_vals(env, insn,
3870 } else if (ptr_reg) {
3871 /* pointer += scalar */
3872 return adjust_ptr_min_max_vals(env, insn,
3876 /* Pretend the src is a reg with a known value, since we only
3877 * need to be able to read from this state.
3879 off_reg.type = SCALAR_VALUE;
3880 __mark_reg_known(&off_reg, insn->imm);
3882 if (ptr_reg) /* pointer += K */
3883 return adjust_ptr_min_max_vals(env, insn,
3887 /* Got here implies adding two SCALAR_VALUEs */
3888 if (WARN_ON_ONCE(ptr_reg)) {
3889 print_verifier_state(env, state);
3890 verbose(env, "verifier internal error: unexpected ptr_reg\n");
3893 if (WARN_ON(!src_reg)) {
3894 print_verifier_state(env, state);
3895 verbose(env, "verifier internal error: no src_reg\n");
3898 return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
3901 /* check validity of 32-bit and 64-bit arithmetic operations */
3902 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
3904 struct bpf_reg_state *regs = cur_regs(env);
3905 u8 opcode = BPF_OP(insn->code);
3908 if (opcode == BPF_END || opcode == BPF_NEG) {
3909 if (opcode == BPF_NEG) {
3910 if (BPF_SRC(insn->code) != 0 ||
3911 insn->src_reg != BPF_REG_0 ||
3912 insn->off != 0 || insn->imm != 0) {
3913 verbose(env, "BPF_NEG uses reserved fields\n");
3917 if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
3918 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
3919 BPF_CLASS(insn->code) == BPF_ALU64) {
3920 verbose(env, "BPF_END uses reserved fields\n");
3925 /* check src operand */
3926 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
3930 if (is_pointer_value(env, insn->dst_reg)) {
3931 verbose(env, "R%d pointer arithmetic prohibited\n",
3936 /* check dest operand */
3937 err = check_reg_arg(env, insn->dst_reg, DST_OP);
3941 } else if (opcode == BPF_MOV) {
3943 if (BPF_SRC(insn->code) == BPF_X) {
3944 if (insn->imm != 0 || insn->off != 0) {
3945 verbose(env, "BPF_MOV uses reserved fields\n");
3949 /* check src operand */
3950 err = check_reg_arg(env, insn->src_reg, SRC_OP);
3954 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
3955 verbose(env, "BPF_MOV uses reserved fields\n");
3960 /* check dest operand, mark as required later */
3961 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
3965 if (BPF_SRC(insn->code) == BPF_X) {
3966 struct bpf_reg_state *src_reg = regs + insn->src_reg;
3967 struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
3969 if (BPF_CLASS(insn->code) == BPF_ALU64) {
3971 * copy register state to dest reg
3973 *dst_reg = *src_reg;
3974 dst_reg->live |= REG_LIVE_WRITTEN;
3977 if (is_pointer_value(env, insn->src_reg)) {
3979 "R%d partial copy of pointer\n",
3982 } else if (src_reg->type == SCALAR_VALUE) {
3983 *dst_reg = *src_reg;
3984 dst_reg->live |= REG_LIVE_WRITTEN;
3986 mark_reg_unknown(env, regs,
3989 coerce_reg_to_size(dst_reg, 4);
3993 * remember the value we stored into this reg
3995 /* clear any state __mark_reg_known doesn't set */
3996 mark_reg_unknown(env, regs, insn->dst_reg);
3997 regs[insn->dst_reg].type = SCALAR_VALUE;
3998 if (BPF_CLASS(insn->code) == BPF_ALU64) {
3999 __mark_reg_known(regs + insn->dst_reg,
4002 __mark_reg_known(regs + insn->dst_reg,
4007 } else if (opcode > BPF_END) {
4008 verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
4011 } else { /* all other ALU ops: and, sub, xor, add, ... */
4013 if (BPF_SRC(insn->code) == BPF_X) {
4014 if (insn->imm != 0 || insn->off != 0) {
4015 verbose(env, "BPF_ALU uses reserved fields\n");
4018 /* check src1 operand */
4019 err = check_reg_arg(env, insn->src_reg, SRC_OP);
4023 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
4024 verbose(env, "BPF_ALU uses reserved fields\n");
4029 /* check src2 operand */
4030 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
4034 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
4035 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
4036 verbose(env, "div by zero\n");
4040 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
4041 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
4042 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
4044 if (insn->imm < 0 || insn->imm >= size) {
4045 verbose(env, "invalid shift %d\n", insn->imm);
4050 /* check dest operand */
4051 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
4055 return adjust_reg_min_max_vals(env, insn);
4061 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
4062 struct bpf_reg_state *dst_reg,
4063 enum bpf_reg_type type,
4064 bool range_right_open)
4066 struct bpf_func_state *state = vstate->frame[vstate->curframe];
4067 struct bpf_reg_state *regs = state->regs, *reg;
4071 if (dst_reg->off < 0 ||
4072 (dst_reg->off == 0 && range_right_open))
4073 /* This doesn't give us any range */
4076 if (dst_reg->umax_value > MAX_PACKET_OFF ||
4077 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
4078 /* Risk of overflow. For instance, ptr + (1<<63) may be less
4079 * than pkt_end, but that's because it's also less than pkt.
4083 new_range = dst_reg->off;
4084 if (range_right_open)
4087 /* Examples for register markings:
4089 * pkt_data in dst register:
4093 * if (r2 > pkt_end) goto <handle exception>
4098 * if (r2 < pkt_end) goto <access okay>
4099 * <handle exception>
4102 * r2 == dst_reg, pkt_end == src_reg
4103 * r2=pkt(id=n,off=8,r=0)
4104 * r3=pkt(id=n,off=0,r=0)
4106 * pkt_data in src register:
4110 * if (pkt_end >= r2) goto <access okay>
4111 * <handle exception>
4115 * if (pkt_end <= r2) goto <handle exception>
4119 * pkt_end == dst_reg, r2 == src_reg
4120 * r2=pkt(id=n,off=8,r=0)
4121 * r3=pkt(id=n,off=0,r=0)
4123 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
4124 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
4125 * and [r3, r3 + 8-1) respectively is safe to access depending on
4129 /* If our ids match, then we must have the same max_value. And we
4130 * don't care about the other reg's fixed offset, since if it's too big
4131 * the range won't allow anything.
4132 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
4134 for (i = 0; i < MAX_BPF_REG; i++)
4135 if (regs[i].type == type && regs[i].id == dst_reg->id)
4136 /* keep the maximum range already checked */
4137 regs[i].range = max(regs[i].range, new_range);
4139 for (j = 0; j <= vstate->curframe; j++) {
4140 state = vstate->frame[j];
4141 bpf_for_each_spilled_reg(i, state, reg) {
4144 if (reg->type == type && reg->id == dst_reg->id)
4145 reg->range = max(reg->range, new_range);
4150 /* compute branch direction of the expression "if (reg opcode val) goto target;"
4152 * 1 - branch will be taken and "goto target" will be executed
4153 * 0 - branch will not be taken and fall-through to next insn
4154 * -1 - unknown. Example: "if (reg < 5)" is unknown when register value range [0,10]
4156 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
4159 struct bpf_reg_state reg_lo;
4162 if (__is_pointer_value(false, reg))
4168 /* For JMP32, only low 32 bits are compared, coerce_reg_to_size
4169 * could truncate high bits and update umin/umax according to
4170 * information of low bits.
4172 coerce_reg_to_size(reg, 4);
4173 /* smin/smax need special handling. For example, after coerce,
4174 * if smin_value is 0x00000000ffffffffLL, the value is -1 when
4175 * used as operand to JMP32. It is a negative number from s32's
4176 * point of view, while it is a positive number when seen as
4177 * s64. The smin/smax are kept as s64, therefore, when used with
4178 * JMP32, they need to be transformed into s32, then sign
4179 * extended back to s64.
4181 * Also, smin/smax were copied from umin/umax. If umin/umax has
4182 * different sign bit, then min/max relationship doesn't
4183 * maintain after casting into s32, for this case, set smin/smax
4186 if ((reg->umax_value ^ reg->umin_value) &
4188 reg->smin_value = S32_MIN;
4189 reg->smax_value = S32_MAX;
4191 reg->smin_value = (s64)(s32)reg->smin_value;
4192 reg->smax_value = (s64)(s32)reg->smax_value;
4195 sval = (s64)(s32)val;
4202 if (tnum_is_const(reg->var_off))
4203 return !!tnum_equals_const(reg->var_off, val);
4206 if (tnum_is_const(reg->var_off))
4207 return !tnum_equals_const(reg->var_off, val);
4210 if ((~reg->var_off.mask & reg->var_off.value) & val)
4212 if (!((reg->var_off.mask | reg->var_off.value) & val))
4216 if (reg->umin_value > val)
4218 else if (reg->umax_value <= val)
4222 if (reg->smin_value > sval)
4224 else if (reg->smax_value < sval)
4228 if (reg->umax_value < val)
4230 else if (reg->umin_value >= val)
4234 if (reg->smax_value < sval)
4236 else if (reg->smin_value >= sval)
4240 if (reg->umin_value >= val)
4242 else if (reg->umax_value < val)
4246 if (reg->smin_value >= sval)
4248 else if (reg->smax_value < sval)
4252 if (reg->umax_value <= val)
4254 else if (reg->umin_value > val)
4258 if (reg->smax_value <= sval)
4260 else if (reg->smin_value > sval)
4268 /* Generate min value of the high 32-bit from TNUM info. */
4269 static u64 gen_hi_min(struct tnum var)
4271 return var.value & ~0xffffffffULL;
4274 /* Generate max value of the high 32-bit from TNUM info. */
4275 static u64 gen_hi_max(struct tnum var)
4277 return (var.value | var.mask) & ~0xffffffffULL;
4280 /* Return true if VAL is compared with a s64 sign extended from s32, and they
4281 * are with the same signedness.
4283 static bool cmp_val_with_extended_s64(s64 sval, struct bpf_reg_state *reg)
4285 return ((s32)sval >= 0 &&
4286 reg->smin_value >= 0 && reg->smax_value <= S32_MAX) ||
4288 reg->smax_value <= 0 && reg->smin_value >= S32_MIN);
4291 /* Adjusts the register min/max values in the case that the dst_reg is the
4292 * variable register that we are working on, and src_reg is a constant or we're
4293 * simply doing a BPF_K check.
4294 * In JEQ/JNE cases we also adjust the var_off values.
4296 static void reg_set_min_max(struct bpf_reg_state *true_reg,
4297 struct bpf_reg_state *false_reg, u64 val,
4298 u8 opcode, bool is_jmp32)
4302 /* If the dst_reg is a pointer, we can't learn anything about its
4303 * variable offset from the compare (unless src_reg were a pointer into
4304 * the same object, but we don't bother with that.
4305 * Since false_reg and true_reg have the same type by construction, we
4306 * only need to check one of them for pointerness.
4308 if (__is_pointer_value(false, false_reg))
4311 val = is_jmp32 ? (u32)val : val;
4312 sval = is_jmp32 ? (s64)(s32)val : (s64)val;
4318 struct bpf_reg_state *reg =
4319 opcode == BPF_JEQ ? true_reg : false_reg;
4321 /* For BPF_JEQ, if this is false we know nothing Jon Snow, but
4322 * if it is true we know the value for sure. Likewise for
4326 u64 old_v = reg->var_off.value;
4327 u64 hi_mask = ~0xffffffffULL;
4329 reg->var_off.value = (old_v & hi_mask) | val;
4330 reg->var_off.mask &= hi_mask;
4332 __mark_reg_known(reg, val);
4337 false_reg->var_off = tnum_and(false_reg->var_off,
4339 if (is_power_of_2(val))
4340 true_reg->var_off = tnum_or(true_reg->var_off,
4346 u64 false_umax = opcode == BPF_JGT ? val : val - 1;
4347 u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
4350 false_umax += gen_hi_max(false_reg->var_off);
4351 true_umin += gen_hi_min(true_reg->var_off);
4353 false_reg->umax_value = min(false_reg->umax_value, false_umax);
4354 true_reg->umin_value = max(true_reg->umin_value, true_umin);
4360 s64 false_smax = opcode == BPF_JSGT ? sval : sval - 1;
4361 s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
4363 /* If the full s64 was not sign-extended from s32 then don't
4364 * deduct further info.
4366 if (is_jmp32 && !cmp_val_with_extended_s64(sval, false_reg))
4368 false_reg->smax_value = min(false_reg->smax_value, false_smax);
4369 true_reg->smin_value = max(true_reg->smin_value, true_smin);
4375 u64 false_umin = opcode == BPF_JLT ? val : val + 1;
4376 u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
4379 false_umin += gen_hi_min(false_reg->var_off);
4380 true_umax += gen_hi_max(true_reg->var_off);
4382 false_reg->umin_value = max(false_reg->umin_value, false_umin);
4383 true_reg->umax_value = min(true_reg->umax_value, true_umax);
4389 s64 false_smin = opcode == BPF_JSLT ? sval : sval + 1;
4390 s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
4392 if (is_jmp32 && !cmp_val_with_extended_s64(sval, false_reg))
4394 false_reg->smin_value = max(false_reg->smin_value, false_smin);
4395 true_reg->smax_value = min(true_reg->smax_value, true_smax);
4402 __reg_deduce_bounds(false_reg);
4403 __reg_deduce_bounds(true_reg);
4404 /* We might have learned some bits from the bounds. */
4405 __reg_bound_offset(false_reg);
4406 __reg_bound_offset(true_reg);
4407 /* Intersecting with the old var_off might have improved our bounds
4408 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
4409 * then new var_off is (0; 0x7f...fc) which improves our umax.
4411 __update_reg_bounds(false_reg);
4412 __update_reg_bounds(true_reg);
4415 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
4418 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
4419 struct bpf_reg_state *false_reg, u64 val,
4420 u8 opcode, bool is_jmp32)
4424 if (__is_pointer_value(false, false_reg))
4427 val = is_jmp32 ? (u32)val : val;
4428 sval = is_jmp32 ? (s64)(s32)val : (s64)val;
4434 struct bpf_reg_state *reg =
4435 opcode == BPF_JEQ ? true_reg : false_reg;
4438 u64 old_v = reg->var_off.value;
4439 u64 hi_mask = ~0xffffffffULL;
4441 reg->var_off.value = (old_v & hi_mask) | val;
4442 reg->var_off.mask &= hi_mask;
4444 __mark_reg_known(reg, val);
4449 false_reg->var_off = tnum_and(false_reg->var_off,
4451 if (is_power_of_2(val))
4452 true_reg->var_off = tnum_or(true_reg->var_off,
4458 u64 false_umin = opcode == BPF_JGT ? val : val + 1;
4459 u64 true_umax = opcode == BPF_JGT ? val - 1 : val;
4462 false_umin += gen_hi_min(false_reg->var_off);
4463 true_umax += gen_hi_max(true_reg->var_off);
4465 false_reg->umin_value = max(false_reg->umin_value, false_umin);
4466 true_reg->umax_value = min(true_reg->umax_value, true_umax);
4472 s64 false_smin = opcode == BPF_JSGT ? sval : sval + 1;
4473 s64 true_smax = opcode == BPF_JSGT ? sval - 1 : sval;
4475 if (is_jmp32 && !cmp_val_with_extended_s64(sval, false_reg))
4477 false_reg->smin_value = max(false_reg->smin_value, false_smin);
4478 true_reg->smax_value = min(true_reg->smax_value, true_smax);
4484 u64 false_umax = opcode == BPF_JLT ? val : val - 1;
4485 u64 true_umin = opcode == BPF_JLT ? val + 1 : val;
4488 false_umax += gen_hi_max(false_reg->var_off);
4489 true_umin += gen_hi_min(true_reg->var_off);
4491 false_reg->umax_value = min(false_reg->umax_value, false_umax);
4492 true_reg->umin_value = max(true_reg->umin_value, true_umin);
4498 s64 false_smax = opcode == BPF_JSLT ? sval : sval - 1;
4499 s64 true_smin = opcode == BPF_JSLT ? sval + 1 : sval;
4501 if (is_jmp32 && !cmp_val_with_extended_s64(sval, false_reg))
4503 false_reg->smax_value = min(false_reg->smax_value, false_smax);
4504 true_reg->smin_value = max(true_reg->smin_value, true_smin);
4511 __reg_deduce_bounds(false_reg);
4512 __reg_deduce_bounds(true_reg);
4513 /* We might have learned some bits from the bounds. */
4514 __reg_bound_offset(false_reg);
4515 __reg_bound_offset(true_reg);
4516 /* Intersecting with the old var_off might have improved our bounds
4517 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
4518 * then new var_off is (0; 0x7f...fc) which improves our umax.
4520 __update_reg_bounds(false_reg);
4521 __update_reg_bounds(true_reg);
4524 /* Regs are known to be equal, so intersect their min/max/var_off */
4525 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
4526 struct bpf_reg_state *dst_reg)
4528 src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
4529 dst_reg->umin_value);
4530 src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
4531 dst_reg->umax_value);
4532 src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
4533 dst_reg->smin_value);
4534 src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
4535 dst_reg->smax_value);
4536 src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
4538 /* We might have learned new bounds from the var_off. */
4539 __update_reg_bounds(src_reg);
4540 __update_reg_bounds(dst_reg);
4541 /* We might have learned something about the sign bit. */
4542 __reg_deduce_bounds(src_reg);
4543 __reg_deduce_bounds(dst_reg);
4544 /* We might have learned some bits from the bounds. */
4545 __reg_bound_offset(src_reg);
4546 __reg_bound_offset(dst_reg);
4547 /* Intersecting with the old var_off might have improved our bounds
4548 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
4549 * then new var_off is (0; 0x7f...fc) which improves our umax.
4551 __update_reg_bounds(src_reg);
4552 __update_reg_bounds(dst_reg);
4555 static void reg_combine_min_max(struct bpf_reg_state *true_src,
4556 struct bpf_reg_state *true_dst,
4557 struct bpf_reg_state *false_src,
4558 struct bpf_reg_state *false_dst,
4563 __reg_combine_min_max(true_src, true_dst);
4566 __reg_combine_min_max(false_src, false_dst);
4571 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
4572 struct bpf_reg_state *reg, u32 id,
4575 if (reg_type_may_be_null(reg->type) && reg->id == id) {
4576 /* Old offset (both fixed and variable parts) should
4577 * have been known-zero, because we don't allow pointer
4578 * arithmetic on pointers that might be NULL.
4580 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value ||
4581 !tnum_equals_const(reg->var_off, 0) ||
4583 __mark_reg_known_zero(reg);
4587 reg->type = SCALAR_VALUE;
4588 } else if (reg->type == PTR_TO_MAP_VALUE_OR_NULL) {
4589 if (reg->map_ptr->inner_map_meta) {
4590 reg->type = CONST_PTR_TO_MAP;
4591 reg->map_ptr = reg->map_ptr->inner_map_meta;
4593 reg->type = PTR_TO_MAP_VALUE;
4595 } else if (reg->type == PTR_TO_SOCKET_OR_NULL) {
4596 reg->type = PTR_TO_SOCKET;
4598 if (is_null || !(reg_is_refcounted(reg) ||
4599 reg_may_point_to_spin_lock(reg))) {
4600 /* We don't need id from this point onwards anymore,
4601 * thus we should better reset it, so that state
4602 * pruning has chances to take effect.
4609 /* The logic is similar to find_good_pkt_pointers(), both could eventually
4610 * be folded together at some point.
4612 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
4615 struct bpf_func_state *state = vstate->frame[vstate->curframe];
4616 struct bpf_reg_state *reg, *regs = state->regs;
4617 u32 id = regs[regno].id;
4620 if (reg_is_refcounted_or_null(®s[regno]) && is_null)
4621 __release_reference_state(state, id);
4623 for (i = 0; i < MAX_BPF_REG; i++)
4624 mark_ptr_or_null_reg(state, ®s[i], id, is_null);
4626 for (j = 0; j <= vstate->curframe; j++) {
4627 state = vstate->frame[j];
4628 bpf_for_each_spilled_reg(i, state, reg) {
4631 mark_ptr_or_null_reg(state, reg, id, is_null);
4636 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
4637 struct bpf_reg_state *dst_reg,
4638 struct bpf_reg_state *src_reg,
4639 struct bpf_verifier_state *this_branch,
4640 struct bpf_verifier_state *other_branch)
4642 if (BPF_SRC(insn->code) != BPF_X)
4645 /* Pointers are always 64-bit. */
4646 if (BPF_CLASS(insn->code) == BPF_JMP32)
4649 switch (BPF_OP(insn->code)) {
4651 if ((dst_reg->type == PTR_TO_PACKET &&
4652 src_reg->type == PTR_TO_PACKET_END) ||
4653 (dst_reg->type == PTR_TO_PACKET_META &&
4654 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
4655 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
4656 find_good_pkt_pointers(this_branch, dst_reg,
4657 dst_reg->type, false);
4658 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
4659 src_reg->type == PTR_TO_PACKET) ||
4660 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
4661 src_reg->type == PTR_TO_PACKET_META)) {
4662 /* pkt_end > pkt_data', pkt_data > pkt_meta' */
4663 find_good_pkt_pointers(other_branch, src_reg,
4664 src_reg->type, true);
4670 if ((dst_reg->type == PTR_TO_PACKET &&
4671 src_reg->type == PTR_TO_PACKET_END) ||
4672 (dst_reg->type == PTR_TO_PACKET_META &&
4673 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
4674 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
4675 find_good_pkt_pointers(other_branch, dst_reg,
4676 dst_reg->type, true);
4677 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
4678 src_reg->type == PTR_TO_PACKET) ||
4679 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
4680 src_reg->type == PTR_TO_PACKET_META)) {
4681 /* pkt_end < pkt_data', pkt_data > pkt_meta' */
4682 find_good_pkt_pointers(this_branch, src_reg,
4683 src_reg->type, false);
4689 if ((dst_reg->type == PTR_TO_PACKET &&
4690 src_reg->type == PTR_TO_PACKET_END) ||
4691 (dst_reg->type == PTR_TO_PACKET_META &&
4692 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
4693 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
4694 find_good_pkt_pointers(this_branch, dst_reg,
4695 dst_reg->type, true);
4696 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
4697 src_reg->type == PTR_TO_PACKET) ||
4698 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
4699 src_reg->type == PTR_TO_PACKET_META)) {
4700 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
4701 find_good_pkt_pointers(other_branch, src_reg,
4702 src_reg->type, false);
4708 if ((dst_reg->type == PTR_TO_PACKET &&
4709 src_reg->type == PTR_TO_PACKET_END) ||
4710 (dst_reg->type == PTR_TO_PACKET_META &&
4711 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
4712 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
4713 find_good_pkt_pointers(other_branch, dst_reg,
4714 dst_reg->type, false);
4715 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
4716 src_reg->type == PTR_TO_PACKET) ||
4717 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
4718 src_reg->type == PTR_TO_PACKET_META)) {
4719 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
4720 find_good_pkt_pointers(this_branch, src_reg,
4721 src_reg->type, true);
4733 static int check_cond_jmp_op(struct bpf_verifier_env *env,
4734 struct bpf_insn *insn, int *insn_idx)
4736 struct bpf_verifier_state *this_branch = env->cur_state;
4737 struct bpf_verifier_state *other_branch;
4738 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
4739 struct bpf_reg_state *dst_reg, *other_branch_regs;
4740 u8 opcode = BPF_OP(insn->code);
4744 /* Only conditional jumps are expected to reach here. */
4745 if (opcode == BPF_JA || opcode > BPF_JSLE) {
4746 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
4750 if (BPF_SRC(insn->code) == BPF_X) {
4751 if (insn->imm != 0) {
4752 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
4756 /* check src1 operand */
4757 err = check_reg_arg(env, insn->src_reg, SRC_OP);
4761 if (is_pointer_value(env, insn->src_reg)) {
4762 verbose(env, "R%d pointer comparison prohibited\n",
4767 if (insn->src_reg != BPF_REG_0) {
4768 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
4773 /* check src2 operand */
4774 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
4778 dst_reg = ®s[insn->dst_reg];
4779 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
4781 if (BPF_SRC(insn->code) == BPF_K) {
4782 int pred = is_branch_taken(dst_reg, insn->imm, opcode,
4786 /* only follow the goto, ignore fall-through */
4787 *insn_idx += insn->off;
4789 } else if (pred == 0) {
4790 /* only follow fall-through branch, since
4791 * that's where the program will go
4797 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
4801 other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
4803 /* detect if we are comparing against a constant value so we can adjust
4804 * our min/max values for our dst register.
4805 * this is only legit if both are scalars (or pointers to the same
4806 * object, I suppose, but we don't support that right now), because
4807 * otherwise the different base pointers mean the offsets aren't
4810 if (BPF_SRC(insn->code) == BPF_X) {
4811 struct bpf_reg_state *src_reg = ®s[insn->src_reg];
4812 struct bpf_reg_state lo_reg0 = *dst_reg;
4813 struct bpf_reg_state lo_reg1 = *src_reg;
4814 struct bpf_reg_state *src_lo, *dst_lo;
4818 coerce_reg_to_size(dst_lo, 4);
4819 coerce_reg_to_size(src_lo, 4);
4821 if (dst_reg->type == SCALAR_VALUE &&
4822 src_reg->type == SCALAR_VALUE) {
4823 if (tnum_is_const(src_reg->var_off) ||
4824 (is_jmp32 && tnum_is_const(src_lo->var_off)))
4825 reg_set_min_max(&other_branch_regs[insn->dst_reg],
4828 ? src_lo->var_off.value
4829 : src_reg->var_off.value,
4831 else if (tnum_is_const(dst_reg->var_off) ||
4832 (is_jmp32 && tnum_is_const(dst_lo->var_off)))
4833 reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
4836 ? dst_lo->var_off.value
4837 : dst_reg->var_off.value,
4839 else if (!is_jmp32 &&
4840 (opcode == BPF_JEQ || opcode == BPF_JNE))
4841 /* Comparing for equality, we can combine knowledge */
4842 reg_combine_min_max(&other_branch_regs[insn->src_reg],
4843 &other_branch_regs[insn->dst_reg],
4844 src_reg, dst_reg, opcode);
4846 } else if (dst_reg->type == SCALAR_VALUE) {
4847 reg_set_min_max(&other_branch_regs[insn->dst_reg],
4848 dst_reg, insn->imm, opcode, is_jmp32);
4851 /* detect if R == 0 where R is returned from bpf_map_lookup_elem().
4852 * NOTE: these optimizations below are related with pointer comparison
4853 * which will never be JMP32.
4855 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
4856 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
4857 reg_type_may_be_null(dst_reg->type)) {
4858 /* Mark all identical registers in each branch as either
4859 * safe or unknown depending R == 0 or R != 0 conditional.
4861 mark_ptr_or_null_regs(this_branch, insn->dst_reg,
4863 mark_ptr_or_null_regs(other_branch, insn->dst_reg,
4865 } else if (!try_match_pkt_pointers(insn, dst_reg, ®s[insn->src_reg],
4866 this_branch, other_branch) &&
4867 is_pointer_value(env, insn->dst_reg)) {
4868 verbose(env, "R%d pointer comparison prohibited\n",
4873 print_verifier_state(env, this_branch->frame[this_branch->curframe]);
4877 /* return the map pointer stored inside BPF_LD_IMM64 instruction */
4878 static struct bpf_map *ld_imm64_to_map_ptr(struct bpf_insn *insn)
4880 u64 imm64 = ((u64) (u32) insn[0].imm) | ((u64) (u32) insn[1].imm) << 32;
4882 return (struct bpf_map *) (unsigned long) imm64;
4885 /* verify BPF_LD_IMM64 instruction */
4886 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
4888 struct bpf_reg_state *regs = cur_regs(env);
4891 if (BPF_SIZE(insn->code) != BPF_DW) {
4892 verbose(env, "invalid BPF_LD_IMM insn\n");
4895 if (insn->off != 0) {
4896 verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
4900 err = check_reg_arg(env, insn->dst_reg, DST_OP);
4904 if (insn->src_reg == 0) {
4905 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
4907 regs[insn->dst_reg].type = SCALAR_VALUE;
4908 __mark_reg_known(®s[insn->dst_reg], imm);
4912 /* replace_map_fd_with_map_ptr() should have caught bad ld_imm64 */
4913 BUG_ON(insn->src_reg != BPF_PSEUDO_MAP_FD);
4915 regs[insn->dst_reg].type = CONST_PTR_TO_MAP;
4916 regs[insn->dst_reg].map_ptr = ld_imm64_to_map_ptr(insn);
4920 static bool may_access_skb(enum bpf_prog_type type)
4923 case BPF_PROG_TYPE_SOCKET_FILTER:
4924 case BPF_PROG_TYPE_SCHED_CLS:
4925 case BPF_PROG_TYPE_SCHED_ACT:
4932 /* verify safety of LD_ABS|LD_IND instructions:
4933 * - they can only appear in the programs where ctx == skb
4934 * - since they are wrappers of function calls, they scratch R1-R5 registers,
4935 * preserve R6-R9, and store return value into R0
4938 * ctx == skb == R6 == CTX
4941 * SRC == any register
4942 * IMM == 32-bit immediate
4945 * R0 - 8/16/32-bit skb data converted to cpu endianness
4947 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
4949 struct bpf_reg_state *regs = cur_regs(env);
4950 u8 mode = BPF_MODE(insn->code);
4953 if (!may_access_skb(env->prog->type)) {
4954 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
4958 if (!env->ops->gen_ld_abs) {
4959 verbose(env, "bpf verifier is misconfigured\n");
4963 if (env->subprog_cnt > 1) {
4964 /* when program has LD_ABS insn JITs and interpreter assume
4965 * that r1 == ctx == skb which is not the case for callees
4966 * that can have arbitrary arguments. It's problematic
4967 * for main prog as well since JITs would need to analyze
4968 * all functions in order to make proper register save/restore
4969 * decisions in the main prog. Hence disallow LD_ABS with calls
4971 verbose(env, "BPF_LD_[ABS|IND] instructions cannot be mixed with bpf-to-bpf calls\n");
4975 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
4976 BPF_SIZE(insn->code) == BPF_DW ||
4977 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
4978 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
4982 /* check whether implicit source operand (register R6) is readable */
4983 err = check_reg_arg(env, BPF_REG_6, SRC_OP);
4987 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
4988 * gen_ld_abs() may terminate the program at runtime, leading to
4991 err = check_reference_leak(env);
4993 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
4997 if (env->cur_state->active_spin_lock) {
4998 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
5002 if (regs[BPF_REG_6].type != PTR_TO_CTX) {
5004 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
5008 if (mode == BPF_IND) {
5009 /* check explicit source operand */
5010 err = check_reg_arg(env, insn->src_reg, SRC_OP);
5015 /* reset caller saved regs to unreadable */
5016 for (i = 0; i < CALLER_SAVED_REGS; i++) {
5017 mark_reg_not_init(env, regs, caller_saved[i]);
5018 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
5021 /* mark destination R0 register as readable, since it contains
5022 * the value fetched from the packet.
5023 * Already marked as written above.
5025 mark_reg_unknown(env, regs, BPF_REG_0);
5029 static int check_return_code(struct bpf_verifier_env *env)
5031 struct bpf_reg_state *reg;
5032 struct tnum range = tnum_range(0, 1);
5034 switch (env->prog->type) {
5035 case BPF_PROG_TYPE_CGROUP_SKB:
5036 case BPF_PROG_TYPE_CGROUP_SOCK:
5037 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
5038 case BPF_PROG_TYPE_SOCK_OPS:
5039 case BPF_PROG_TYPE_CGROUP_DEVICE:
5045 reg = cur_regs(env) + BPF_REG_0;
5046 if (reg->type != SCALAR_VALUE) {
5047 verbose(env, "At program exit the register R0 is not a known value (%s)\n",
5048 reg_type_str[reg->type]);
5052 if (!tnum_in(range, reg->var_off)) {
5053 verbose(env, "At program exit the register R0 ");
5054 if (!tnum_is_unknown(reg->var_off)) {
5057 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5058 verbose(env, "has value %s", tn_buf);
5060 verbose(env, "has unknown scalar value");
5062 verbose(env, " should have been 0 or 1\n");
5068 /* non-recursive DFS pseudo code
5069 * 1 procedure DFS-iterative(G,v):
5070 * 2 label v as discovered
5071 * 3 let S be a stack
5073 * 5 while S is not empty
5075 * 7 if t is what we're looking for:
5077 * 9 for all edges e in G.adjacentEdges(t) do
5078 * 10 if edge e is already labelled
5079 * 11 continue with the next edge
5080 * 12 w <- G.adjacentVertex(t,e)
5081 * 13 if vertex w is not discovered and not explored
5082 * 14 label e as tree-edge
5083 * 15 label w as discovered
5086 * 18 else if vertex w is discovered
5087 * 19 label e as back-edge
5089 * 21 // vertex w is explored
5090 * 22 label e as forward- or cross-edge
5091 * 23 label t as explored
5096 * 0x11 - discovered and fall-through edge labelled
5097 * 0x12 - discovered and fall-through and branch edges labelled
5108 #define STATE_LIST_MARK ((struct bpf_verifier_state_list *) -1L)
5110 static int *insn_stack; /* stack of insns to process */
5111 static int cur_stack; /* current stack index */
5112 static int *insn_state;
5114 /* t, w, e - match pseudo-code above:
5115 * t - index of current instruction
5116 * w - next instruction
5119 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env)
5121 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
5124 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
5127 if (w < 0 || w >= env->prog->len) {
5128 verbose_linfo(env, t, "%d: ", t);
5129 verbose(env, "jump out of range from insn %d to %d\n", t, w);
5134 /* mark branch target for state pruning */
5135 env->explored_states[w] = STATE_LIST_MARK;
5137 if (insn_state[w] == 0) {
5139 insn_state[t] = DISCOVERED | e;
5140 insn_state[w] = DISCOVERED;
5141 if (cur_stack >= env->prog->len)
5143 insn_stack[cur_stack++] = w;
5145 } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
5146 verbose_linfo(env, t, "%d: ", t);
5147 verbose_linfo(env, w, "%d: ", w);
5148 verbose(env, "back-edge from insn %d to %d\n", t, w);
5150 } else if (insn_state[w] == EXPLORED) {
5151 /* forward- or cross-edge */
5152 insn_state[t] = DISCOVERED | e;
5154 verbose(env, "insn state internal bug\n");
5160 /* non-recursive depth-first-search to detect loops in BPF program
5161 * loop == back-edge in directed graph
5163 static int check_cfg(struct bpf_verifier_env *env)
5165 struct bpf_insn *insns = env->prog->insnsi;
5166 int insn_cnt = env->prog->len;
5170 insn_state = kcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
5174 insn_stack = kcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
5180 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
5181 insn_stack[0] = 0; /* 0 is the first instruction */
5187 t = insn_stack[cur_stack - 1];
5189 if (BPF_CLASS(insns[t].code) == BPF_JMP ||
5190 BPF_CLASS(insns[t].code) == BPF_JMP32) {
5191 u8 opcode = BPF_OP(insns[t].code);
5193 if (opcode == BPF_EXIT) {
5195 } else if (opcode == BPF_CALL) {
5196 ret = push_insn(t, t + 1, FALLTHROUGH, env);
5201 if (t + 1 < insn_cnt)
5202 env->explored_states[t + 1] = STATE_LIST_MARK;
5203 if (insns[t].src_reg == BPF_PSEUDO_CALL) {
5204 env->explored_states[t] = STATE_LIST_MARK;
5205 ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env);
5211 } else if (opcode == BPF_JA) {
5212 if (BPF_SRC(insns[t].code) != BPF_K) {
5216 /* unconditional jump with single edge */
5217 ret = push_insn(t, t + insns[t].off + 1,
5223 /* tell verifier to check for equivalent states
5224 * after every call and jump
5226 if (t + 1 < insn_cnt)
5227 env->explored_states[t + 1] = STATE_LIST_MARK;
5229 /* conditional jump with two edges */
5230 env->explored_states[t] = STATE_LIST_MARK;
5231 ret = push_insn(t, t + 1, FALLTHROUGH, env);
5237 ret = push_insn(t, t + insns[t].off + 1, BRANCH, env);
5244 /* all other non-branch instructions with single
5247 ret = push_insn(t, t + 1, FALLTHROUGH, env);
5255 insn_state[t] = EXPLORED;
5256 if (cur_stack-- <= 0) {
5257 verbose(env, "pop stack internal bug\n");
5264 for (i = 0; i < insn_cnt; i++) {
5265 if (insn_state[i] != EXPLORED) {
5266 verbose(env, "unreachable insn %d\n", i);
5271 ret = 0; /* cfg looks good */
5279 /* The minimum supported BTF func info size */
5280 #define MIN_BPF_FUNCINFO_SIZE 8
5281 #define MAX_FUNCINFO_REC_SIZE 252
5283 static int check_btf_func(struct bpf_verifier_env *env,
5284 const union bpf_attr *attr,
5285 union bpf_attr __user *uattr)
5287 u32 i, nfuncs, urec_size, min_size;
5288 u32 krec_size = sizeof(struct bpf_func_info);
5289 struct bpf_func_info *krecord;
5290 const struct btf_type *type;
5291 struct bpf_prog *prog;
5292 const struct btf *btf;
5293 void __user *urecord;
5294 u32 prev_offset = 0;
5297 nfuncs = attr->func_info_cnt;
5301 if (nfuncs != env->subprog_cnt) {
5302 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
5306 urec_size = attr->func_info_rec_size;
5307 if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
5308 urec_size > MAX_FUNCINFO_REC_SIZE ||
5309 urec_size % sizeof(u32)) {
5310 verbose(env, "invalid func info rec size %u\n", urec_size);
5315 btf = prog->aux->btf;
5317 urecord = u64_to_user_ptr(attr->func_info);
5318 min_size = min_t(u32, krec_size, urec_size);
5320 krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
5324 for (i = 0; i < nfuncs; i++) {
5325 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
5327 if (ret == -E2BIG) {
5328 verbose(env, "nonzero tailing record in func info");
5329 /* set the size kernel expects so loader can zero
5330 * out the rest of the record.
5332 if (put_user(min_size, &uattr->func_info_rec_size))
5338 if (copy_from_user(&krecord[i], urecord, min_size)) {
5343 /* check insn_off */
5345 if (krecord[i].insn_off) {
5347 "nonzero insn_off %u for the first func info record",
5348 krecord[i].insn_off);
5352 } else if (krecord[i].insn_off <= prev_offset) {
5354 "same or smaller insn offset (%u) than previous func info record (%u)",
5355 krecord[i].insn_off, prev_offset);
5360 if (env->subprog_info[i].start != krecord[i].insn_off) {
5361 verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
5367 type = btf_type_by_id(btf, krecord[i].type_id);
5368 if (!type || BTF_INFO_KIND(type->info) != BTF_KIND_FUNC) {
5369 verbose(env, "invalid type id %d in func info",
5370 krecord[i].type_id);
5375 prev_offset = krecord[i].insn_off;
5376 urecord += urec_size;
5379 prog->aux->func_info = krecord;
5380 prog->aux->func_info_cnt = nfuncs;
5388 static void adjust_btf_func(struct bpf_verifier_env *env)
5392 if (!env->prog->aux->func_info)
5395 for (i = 0; i < env->subprog_cnt; i++)
5396 env->prog->aux->func_info[i].insn_off = env->subprog_info[i].start;
5399 #define MIN_BPF_LINEINFO_SIZE (offsetof(struct bpf_line_info, line_col) + \
5400 sizeof(((struct bpf_line_info *)(0))->line_col))
5401 #define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE
5403 static int check_btf_line(struct bpf_verifier_env *env,
5404 const union bpf_attr *attr,
5405 union bpf_attr __user *uattr)
5407 u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
5408 struct bpf_subprog_info *sub;
5409 struct bpf_line_info *linfo;
5410 struct bpf_prog *prog;
5411 const struct btf *btf;
5412 void __user *ulinfo;
5415 nr_linfo = attr->line_info_cnt;
5419 rec_size = attr->line_info_rec_size;
5420 if (rec_size < MIN_BPF_LINEINFO_SIZE ||
5421 rec_size > MAX_LINEINFO_REC_SIZE ||
5422 rec_size & (sizeof(u32) - 1))
5425 /* Need to zero it in case the userspace may
5426 * pass in a smaller bpf_line_info object.
5428 linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
5429 GFP_KERNEL | __GFP_NOWARN);
5434 btf = prog->aux->btf;
5437 sub = env->subprog_info;
5438 ulinfo = u64_to_user_ptr(attr->line_info);
5439 expected_size = sizeof(struct bpf_line_info);
5440 ncopy = min_t(u32, expected_size, rec_size);
5441 for (i = 0; i < nr_linfo; i++) {
5442 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
5444 if (err == -E2BIG) {
5445 verbose(env, "nonzero tailing record in line_info");
5446 if (put_user(expected_size,
5447 &uattr->line_info_rec_size))
5453 if (copy_from_user(&linfo[i], ulinfo, ncopy)) {
5459 * Check insn_off to ensure
5460 * 1) strictly increasing AND
5461 * 2) bounded by prog->len
5463 * The linfo[0].insn_off == 0 check logically falls into
5464 * the later "missing bpf_line_info for func..." case
5465 * because the first linfo[0].insn_off must be the
5466 * first sub also and the first sub must have
5467 * subprog_info[0].start == 0.
5469 if ((i && linfo[i].insn_off <= prev_offset) ||
5470 linfo[i].insn_off >= prog->len) {
5471 verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
5472 i, linfo[i].insn_off, prev_offset,
5478 if (!prog->insnsi[linfo[i].insn_off].code) {
5480 "Invalid insn code at line_info[%u].insn_off\n",
5486 if (!btf_name_by_offset(btf, linfo[i].line_off) ||
5487 !btf_name_by_offset(btf, linfo[i].file_name_off)) {
5488 verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
5493 if (s != env->subprog_cnt) {
5494 if (linfo[i].insn_off == sub[s].start) {
5495 sub[s].linfo_idx = i;
5497 } else if (sub[s].start < linfo[i].insn_off) {
5498 verbose(env, "missing bpf_line_info for func#%u\n", s);
5504 prev_offset = linfo[i].insn_off;
5508 if (s != env->subprog_cnt) {
5509 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
5510 env->subprog_cnt - s, s);
5515 prog->aux->linfo = linfo;
5516 prog->aux->nr_linfo = nr_linfo;
5525 static int check_btf_info(struct bpf_verifier_env *env,
5526 const union bpf_attr *attr,
5527 union bpf_attr __user *uattr)
5532 if (!attr->func_info_cnt && !attr->line_info_cnt)
5535 btf = btf_get_by_fd(attr->prog_btf_fd);
5537 return PTR_ERR(btf);
5538 env->prog->aux->btf = btf;
5540 err = check_btf_func(env, attr, uattr);
5544 err = check_btf_line(env, attr, uattr);
5551 /* check %cur's range satisfies %old's */
5552 static bool range_within(struct bpf_reg_state *old,
5553 struct bpf_reg_state *cur)
5555 return old->umin_value <= cur->umin_value &&
5556 old->umax_value >= cur->umax_value &&
5557 old->smin_value <= cur->smin_value &&
5558 old->smax_value >= cur->smax_value;
5561 /* Maximum number of register states that can exist at once */
5562 #define ID_MAP_SIZE (MAX_BPF_REG + MAX_BPF_STACK / BPF_REG_SIZE)
5568 /* If in the old state two registers had the same id, then they need to have
5569 * the same id in the new state as well. But that id could be different from
5570 * the old state, so we need to track the mapping from old to new ids.
5571 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
5572 * regs with old id 5 must also have new id 9 for the new state to be safe. But
5573 * regs with a different old id could still have new id 9, we don't care about
5575 * So we look through our idmap to see if this old id has been seen before. If
5576 * so, we require the new id to match; otherwise, we add the id pair to the map.
5578 static bool check_ids(u32 old_id, u32 cur_id, struct idpair *idmap)
5582 for (i = 0; i < ID_MAP_SIZE; i++) {
5583 if (!idmap[i].old) {
5584 /* Reached an empty slot; haven't seen this id before */
5585 idmap[i].old = old_id;
5586 idmap[i].cur = cur_id;
5589 if (idmap[i].old == old_id)
5590 return idmap[i].cur == cur_id;
5592 /* We ran out of idmap slots, which should be impossible */
5597 static void clean_func_state(struct bpf_verifier_env *env,
5598 struct bpf_func_state *st)
5600 enum bpf_reg_liveness live;
5603 for (i = 0; i < BPF_REG_FP; i++) {
5604 live = st->regs[i].live;
5605 /* liveness must not touch this register anymore */
5606 st->regs[i].live |= REG_LIVE_DONE;
5607 if (!(live & REG_LIVE_READ))
5608 /* since the register is unused, clear its state
5609 * to make further comparison simpler
5611 __mark_reg_not_init(&st->regs[i]);
5614 for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
5615 live = st->stack[i].spilled_ptr.live;
5616 /* liveness must not touch this stack slot anymore */
5617 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
5618 if (!(live & REG_LIVE_READ)) {
5619 __mark_reg_not_init(&st->stack[i].spilled_ptr);
5620 for (j = 0; j < BPF_REG_SIZE; j++)
5621 st->stack[i].slot_type[j] = STACK_INVALID;
5626 static void clean_verifier_state(struct bpf_verifier_env *env,
5627 struct bpf_verifier_state *st)
5631 if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
5632 /* all regs in this state in all frames were already marked */
5635 for (i = 0; i <= st->curframe; i++)
5636 clean_func_state(env, st->frame[i]);
5639 /* the parentage chains form a tree.
5640 * the verifier states are added to state lists at given insn and
5641 * pushed into state stack for future exploration.
5642 * when the verifier reaches bpf_exit insn some of the verifer states
5643 * stored in the state lists have their final liveness state already,
5644 * but a lot of states will get revised from liveness point of view when
5645 * the verifier explores other branches.
5648 * 2: if r1 == 100 goto pc+1
5651 * when the verifier reaches exit insn the register r0 in the state list of
5652 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
5653 * of insn 2 and goes exploring further. At the insn 4 it will walk the
5654 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
5656 * Since the verifier pushes the branch states as it sees them while exploring
5657 * the program the condition of walking the branch instruction for the second
5658 * time means that all states below this branch were already explored and
5659 * their final liveness markes are already propagated.
5660 * Hence when the verifier completes the search of state list in is_state_visited()
5661 * we can call this clean_live_states() function to mark all liveness states
5662 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
5664 * This function also clears the registers and stack for states that !READ
5665 * to simplify state merging.
5667 * Important note here that walking the same branch instruction in the callee
5668 * doesn't meant that the states are DONE. The verifier has to compare
5671 static void clean_live_states(struct bpf_verifier_env *env, int insn,
5672 struct bpf_verifier_state *cur)
5674 struct bpf_verifier_state_list *sl;
5677 sl = env->explored_states[insn];
5681 while (sl != STATE_LIST_MARK) {
5682 if (sl->state.curframe != cur->curframe)
5684 for (i = 0; i <= cur->curframe; i++)
5685 if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
5687 clean_verifier_state(env, &sl->state);
5693 /* Returns true if (rold safe implies rcur safe) */
5694 static bool regsafe(struct bpf_reg_state *rold, struct bpf_reg_state *rcur,
5695 struct idpair *idmap)
5699 if (!(rold->live & REG_LIVE_READ))
5700 /* explored state didn't use this */
5703 equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, parent)) == 0;
5705 if (rold->type == PTR_TO_STACK)
5706 /* two stack pointers are equal only if they're pointing to
5707 * the same stack frame, since fp-8 in foo != fp-8 in bar
5709 return equal && rold->frameno == rcur->frameno;
5714 if (rold->type == NOT_INIT)
5715 /* explored state can't have used this */
5717 if (rcur->type == NOT_INIT)
5719 switch (rold->type) {
5721 if (rcur->type == SCALAR_VALUE) {
5722 /* new val must satisfy old val knowledge */
5723 return range_within(rold, rcur) &&
5724 tnum_in(rold->var_off, rcur->var_off);
5726 /* We're trying to use a pointer in place of a scalar.
5727 * Even if the scalar was unbounded, this could lead to
5728 * pointer leaks because scalars are allowed to leak
5729 * while pointers are not. We could make this safe in
5730 * special cases if root is calling us, but it's
5731 * probably not worth the hassle.
5735 case PTR_TO_MAP_VALUE:
5736 /* If the new min/max/var_off satisfy the old ones and
5737 * everything else matches, we are OK.
5738 * 'id' is not compared, since it's only used for maps with
5739 * bpf_spin_lock inside map element and in such cases if
5740 * the rest of the prog is valid for one map element then
5741 * it's valid for all map elements regardless of the key
5742 * used in bpf_map_lookup()
5744 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
5745 range_within(rold, rcur) &&
5746 tnum_in(rold->var_off, rcur->var_off);
5747 case PTR_TO_MAP_VALUE_OR_NULL:
5748 /* a PTR_TO_MAP_VALUE could be safe to use as a
5749 * PTR_TO_MAP_VALUE_OR_NULL into the same map.
5750 * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
5751 * checked, doing so could have affected others with the same
5752 * id, and we can't check for that because we lost the id when
5753 * we converted to a PTR_TO_MAP_VALUE.
5755 if (rcur->type != PTR_TO_MAP_VALUE_OR_NULL)
5757 if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
5759 /* Check our ids match any regs they're supposed to */
5760 return check_ids(rold->id, rcur->id, idmap);
5761 case PTR_TO_PACKET_META:
5763 if (rcur->type != rold->type)
5765 /* We must have at least as much range as the old ptr
5766 * did, so that any accesses which were safe before are
5767 * still safe. This is true even if old range < old off,
5768 * since someone could have accessed through (ptr - k), or
5769 * even done ptr -= k in a register, to get a safe access.
5771 if (rold->range > rcur->range)
5773 /* If the offsets don't match, we can't trust our alignment;
5774 * nor can we be sure that we won't fall out of range.
5776 if (rold->off != rcur->off)
5778 /* id relations must be preserved */
5779 if (rold->id && !check_ids(rold->id, rcur->id, idmap))
5781 /* new val must satisfy old val knowledge */
5782 return range_within(rold, rcur) &&
5783 tnum_in(rold->var_off, rcur->var_off);
5785 case CONST_PTR_TO_MAP:
5786 case PTR_TO_PACKET_END:
5787 case PTR_TO_FLOW_KEYS:
5789 case PTR_TO_SOCKET_OR_NULL:
5790 /* Only valid matches are exact, which memcmp() above
5791 * would have accepted
5794 /* Don't know what's going on, just say it's not safe */
5798 /* Shouldn't get here; if we do, say it's not safe */
5803 static bool stacksafe(struct bpf_func_state *old,
5804 struct bpf_func_state *cur,
5805 struct idpair *idmap)
5809 /* walk slots of the explored stack and ignore any additional
5810 * slots in the current stack, since explored(safe) state
5813 for (i = 0; i < old->allocated_stack; i++) {
5814 spi = i / BPF_REG_SIZE;
5816 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
5817 i += BPF_REG_SIZE - 1;
5818 /* explored state didn't use this */
5822 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
5825 /* explored stack has more populated slots than current stack
5826 * and these slots were used
5828 if (i >= cur->allocated_stack)
5831 /* if old state was safe with misc data in the stack
5832 * it will be safe with zero-initialized stack.
5833 * The opposite is not true
5835 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
5836 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
5838 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
5839 cur->stack[spi].slot_type[i % BPF_REG_SIZE])
5840 /* Ex: old explored (safe) state has STACK_SPILL in
5841 * this stack slot, but current has has STACK_MISC ->
5842 * this verifier states are not equivalent,
5843 * return false to continue verification of this path
5846 if (i % BPF_REG_SIZE)
5848 if (old->stack[spi].slot_type[0] != STACK_SPILL)
5850 if (!regsafe(&old->stack[spi].spilled_ptr,
5851 &cur->stack[spi].spilled_ptr,
5853 /* when explored and current stack slot are both storing
5854 * spilled registers, check that stored pointers types
5855 * are the same as well.
5856 * Ex: explored safe path could have stored
5857 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
5858 * but current path has stored:
5859 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
5860 * such verifier states are not equivalent.
5861 * return false to continue verification of this path
5868 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur)
5870 if (old->acquired_refs != cur->acquired_refs)
5872 return !memcmp(old->refs, cur->refs,
5873 sizeof(*old->refs) * old->acquired_refs);
5876 /* compare two verifier states
5878 * all states stored in state_list are known to be valid, since
5879 * verifier reached 'bpf_exit' instruction through them
5881 * this function is called when verifier exploring different branches of
5882 * execution popped from the state stack. If it sees an old state that has
5883 * more strict register state and more strict stack state then this execution
5884 * branch doesn't need to be explored further, since verifier already
5885 * concluded that more strict state leads to valid finish.
5887 * Therefore two states are equivalent if register state is more conservative
5888 * and explored stack state is more conservative than the current one.
5891 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
5892 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
5894 * In other words if current stack state (one being explored) has more
5895 * valid slots than old one that already passed validation, it means
5896 * the verifier can stop exploring and conclude that current state is valid too
5898 * Similarly with registers. If explored state has register type as invalid
5899 * whereas register type in current state is meaningful, it means that
5900 * the current state will reach 'bpf_exit' instruction safely
5902 static bool func_states_equal(struct bpf_func_state *old,
5903 struct bpf_func_state *cur)
5905 struct idpair *idmap;
5909 idmap = kcalloc(ID_MAP_SIZE, sizeof(struct idpair), GFP_KERNEL);
5910 /* If we failed to allocate the idmap, just say it's not safe */
5914 for (i = 0; i < MAX_BPF_REG; i++) {
5915 if (!regsafe(&old->regs[i], &cur->regs[i], idmap))
5919 if (!stacksafe(old, cur, idmap))
5922 if (!refsafe(old, cur))
5930 static bool states_equal(struct bpf_verifier_env *env,
5931 struct bpf_verifier_state *old,
5932 struct bpf_verifier_state *cur)
5936 if (old->curframe != cur->curframe)
5939 /* Verification state from speculative execution simulation
5940 * must never prune a non-speculative execution one.
5942 if (old->speculative && !cur->speculative)
5945 if (old->active_spin_lock != cur->active_spin_lock)
5948 /* for states to be equal callsites have to be the same
5949 * and all frame states need to be equivalent
5951 for (i = 0; i <= old->curframe; i++) {
5952 if (old->frame[i]->callsite != cur->frame[i]->callsite)
5954 if (!func_states_equal(old->frame[i], cur->frame[i]))
5960 /* A write screens off any subsequent reads; but write marks come from the
5961 * straight-line code between a state and its parent. When we arrive at an
5962 * equivalent state (jump target or such) we didn't arrive by the straight-line
5963 * code, so read marks in the state must propagate to the parent regardless
5964 * of the state's write marks. That's what 'parent == state->parent' comparison
5965 * in mark_reg_read() is for.
5967 static int propagate_liveness(struct bpf_verifier_env *env,
5968 const struct bpf_verifier_state *vstate,
5969 struct bpf_verifier_state *vparent)
5971 int i, frame, err = 0;
5972 struct bpf_func_state *state, *parent;
5974 if (vparent->curframe != vstate->curframe) {
5975 WARN(1, "propagate_live: parent frame %d current frame %d\n",
5976 vparent->curframe, vstate->curframe);
5979 /* Propagate read liveness of registers... */
5980 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
5981 /* We don't need to worry about FP liveness because it's read-only */
5982 for (i = 0; i < BPF_REG_FP; i++) {
5983 if (vparent->frame[vparent->curframe]->regs[i].live & REG_LIVE_READ)
5985 if (vstate->frame[vstate->curframe]->regs[i].live & REG_LIVE_READ) {
5986 err = mark_reg_read(env, &vstate->frame[vstate->curframe]->regs[i],
5987 &vparent->frame[vstate->curframe]->regs[i]);
5993 /* ... and stack slots */
5994 for (frame = 0; frame <= vstate->curframe; frame++) {
5995 state = vstate->frame[frame];
5996 parent = vparent->frame[frame];
5997 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
5998 i < parent->allocated_stack / BPF_REG_SIZE; i++) {
5999 if (parent->stack[i].spilled_ptr.live & REG_LIVE_READ)
6001 if (state->stack[i].spilled_ptr.live & REG_LIVE_READ)
6002 mark_reg_read(env, &state->stack[i].spilled_ptr,
6003 &parent->stack[i].spilled_ptr);
6009 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
6011 struct bpf_verifier_state_list *new_sl;
6012 struct bpf_verifier_state_list *sl;
6013 struct bpf_verifier_state *cur = env->cur_state, *new;
6014 int i, j, err, states_cnt = 0;
6016 sl = env->explored_states[insn_idx];
6018 /* this 'insn_idx' instruction wasn't marked, so we will not
6019 * be doing state search here
6023 clean_live_states(env, insn_idx, cur);
6025 while (sl != STATE_LIST_MARK) {
6026 if (states_equal(env, &sl->state, cur)) {
6027 /* reached equivalent register/stack state,
6029 * Registers read by the continuation are read by us.
6030 * If we have any write marks in env->cur_state, they
6031 * will prevent corresponding reads in the continuation
6032 * from reaching our parent (an explored_state). Our
6033 * own state will get the read marks recorded, but
6034 * they'll be immediately forgotten as we're pruning
6035 * this state and will pop a new one.
6037 err = propagate_liveness(env, &sl->state, cur);
6046 if (!env->allow_ptr_leaks && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
6049 /* there were no equivalent states, remember current one.
6050 * technically the current state is not proven to be safe yet,
6051 * but it will either reach outer most bpf_exit (which means it's safe)
6052 * or it will be rejected. Since there are no loops, we won't be
6053 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
6054 * again on the way to bpf_exit
6056 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
6060 /* add new state to the head of linked list */
6061 new = &new_sl->state;
6062 err = copy_verifier_state(new, cur);
6064 free_verifier_state(new, false);
6068 new_sl->next = env->explored_states[insn_idx];
6069 env->explored_states[insn_idx] = new_sl;
6070 /* connect new state to parentage chain. Current frame needs all
6071 * registers connected. Only r6 - r9 of the callers are alive (pushed
6072 * to the stack implicitly by JITs) so in callers' frames connect just
6073 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
6074 * the state of the call instruction (with WRITTEN set), and r0 comes
6075 * from callee with its full parentage chain, anyway.
6077 for (j = 0; j <= cur->curframe; j++)
6078 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
6079 cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
6080 /* clear write marks in current state: the writes we did are not writes
6081 * our child did, so they don't screen off its reads from us.
6082 * (There are no read marks in current state, because reads always mark
6083 * their parent and current state never has children yet. Only
6084 * explored_states can get read marks.)
6086 for (i = 0; i < BPF_REG_FP; i++)
6087 cur->frame[cur->curframe]->regs[i].live = REG_LIVE_NONE;
6089 /* all stack frames are accessible from callee, clear them all */
6090 for (j = 0; j <= cur->curframe; j++) {
6091 struct bpf_func_state *frame = cur->frame[j];
6092 struct bpf_func_state *newframe = new->frame[j];
6094 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
6095 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
6096 frame->stack[i].spilled_ptr.parent =
6097 &newframe->stack[i].spilled_ptr;
6103 /* Return true if it's OK to have the same insn return a different type. */
6104 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
6109 case PTR_TO_SOCKET_OR_NULL:
6116 /* If an instruction was previously used with particular pointer types, then we
6117 * need to be careful to avoid cases such as the below, where it may be ok
6118 * for one branch accessing the pointer, but not ok for the other branch:
6123 * R1 = some_other_valid_ptr;
6126 * R2 = *(u32 *)(R1 + 0);
6128 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
6130 return src != prev && (!reg_type_mismatch_ok(src) ||
6131 !reg_type_mismatch_ok(prev));
6134 static int do_check(struct bpf_verifier_env *env)
6136 struct bpf_verifier_state *state;
6137 struct bpf_insn *insns = env->prog->insnsi;
6138 struct bpf_reg_state *regs;
6139 int insn_cnt = env->prog->len, i;
6140 int insn_processed = 0;
6141 bool do_print_state = false;
6143 env->prev_linfo = NULL;
6145 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
6148 state->curframe = 0;
6149 state->speculative = false;
6150 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
6151 if (!state->frame[0]) {
6155 env->cur_state = state;
6156 init_func_state(env, state->frame[0],
6157 BPF_MAIN_FUNC /* callsite */,
6159 0 /* subprogno, zero == main subprog */);
6162 struct bpf_insn *insn;
6166 if (env->insn_idx >= insn_cnt) {
6167 verbose(env, "invalid insn idx %d insn_cnt %d\n",
6168 env->insn_idx, insn_cnt);
6172 insn = &insns[env->insn_idx];
6173 class = BPF_CLASS(insn->code);
6175 if (++insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
6177 "BPF program is too large. Processed %d insn\n",
6182 err = is_state_visited(env, env->insn_idx);
6186 /* found equivalent state, can prune the search */
6187 if (env->log.level) {
6189 verbose(env, "\nfrom %d to %d%s: safe\n",
6190 env->prev_insn_idx, env->insn_idx,
6191 env->cur_state->speculative ?
6192 " (speculative execution)" : "");
6194 verbose(env, "%d: safe\n", env->insn_idx);
6196 goto process_bpf_exit;
6199 if (signal_pending(current))
6205 if (env->log.level > 1 || (env->log.level && do_print_state)) {
6206 if (env->log.level > 1)
6207 verbose(env, "%d:", env->insn_idx);
6209 verbose(env, "\nfrom %d to %d%s:",
6210 env->prev_insn_idx, env->insn_idx,
6211 env->cur_state->speculative ?
6212 " (speculative execution)" : "");
6213 print_verifier_state(env, state->frame[state->curframe]);
6214 do_print_state = false;
6217 if (env->log.level) {
6218 const struct bpf_insn_cbs cbs = {
6219 .cb_print = verbose,
6220 .private_data = env,
6223 verbose_linfo(env, env->insn_idx, "; ");
6224 verbose(env, "%d: ", env->insn_idx);
6225 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
6228 if (bpf_prog_is_dev_bound(env->prog->aux)) {
6229 err = bpf_prog_offload_verify_insn(env, env->insn_idx,
6230 env->prev_insn_idx);
6235 regs = cur_regs(env);
6236 env->insn_aux_data[env->insn_idx].seen = true;
6238 if (class == BPF_ALU || class == BPF_ALU64) {
6239 err = check_alu_op(env, insn);
6243 } else if (class == BPF_LDX) {
6244 enum bpf_reg_type *prev_src_type, src_reg_type;
6246 /* check for reserved fields is already done */
6248 /* check src operand */
6249 err = check_reg_arg(env, insn->src_reg, SRC_OP);
6253 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
6257 src_reg_type = regs[insn->src_reg].type;
6259 /* check that memory (src_reg + off) is readable,
6260 * the state of dst_reg will be updated by this func
6262 err = check_mem_access(env, env->insn_idx, insn->src_reg,
6263 insn->off, BPF_SIZE(insn->code),
6264 BPF_READ, insn->dst_reg, false);
6268 prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type;
6270 if (*prev_src_type == NOT_INIT) {
6272 * dst_reg = *(u32 *)(src_reg + off)
6273 * save type to validate intersecting paths
6275 *prev_src_type = src_reg_type;
6277 } else if (reg_type_mismatch(src_reg_type, *prev_src_type)) {
6278 /* ABuser program is trying to use the same insn
6279 * dst_reg = *(u32*) (src_reg + off)
6280 * with different pointer types:
6281 * src_reg == ctx in one branch and
6282 * src_reg == stack|map in some other branch.
6285 verbose(env, "same insn cannot be used with different pointers\n");
6289 } else if (class == BPF_STX) {
6290 enum bpf_reg_type *prev_dst_type, dst_reg_type;
6292 if (BPF_MODE(insn->code) == BPF_XADD) {
6293 err = check_xadd(env, env->insn_idx, insn);
6300 /* check src1 operand */
6301 err = check_reg_arg(env, insn->src_reg, SRC_OP);
6304 /* check src2 operand */
6305 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
6309 dst_reg_type = regs[insn->dst_reg].type;
6311 /* check that memory (dst_reg + off) is writeable */
6312 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
6313 insn->off, BPF_SIZE(insn->code),
6314 BPF_WRITE, insn->src_reg, false);
6318 prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type;
6320 if (*prev_dst_type == NOT_INIT) {
6321 *prev_dst_type = dst_reg_type;
6322 } else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) {
6323 verbose(env, "same insn cannot be used with different pointers\n");
6327 } else if (class == BPF_ST) {
6328 if (BPF_MODE(insn->code) != BPF_MEM ||
6329 insn->src_reg != BPF_REG_0) {
6330 verbose(env, "BPF_ST uses reserved fields\n");
6333 /* check src operand */
6334 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
6338 if (is_ctx_reg(env, insn->dst_reg)) {
6339 verbose(env, "BPF_ST stores into R%d %s is not allowed\n",
6341 reg_type_str[reg_state(env, insn->dst_reg)->type]);
6345 /* check that memory (dst_reg + off) is writeable */
6346 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
6347 insn->off, BPF_SIZE(insn->code),
6348 BPF_WRITE, -1, false);
6352 } else if (class == BPF_JMP || class == BPF_JMP32) {
6353 u8 opcode = BPF_OP(insn->code);
6355 if (opcode == BPF_CALL) {
6356 if (BPF_SRC(insn->code) != BPF_K ||
6358 (insn->src_reg != BPF_REG_0 &&
6359 insn->src_reg != BPF_PSEUDO_CALL) ||
6360 insn->dst_reg != BPF_REG_0 ||
6361 class == BPF_JMP32) {
6362 verbose(env, "BPF_CALL uses reserved fields\n");
6366 if (env->cur_state->active_spin_lock &&
6367 (insn->src_reg == BPF_PSEUDO_CALL ||
6368 insn->imm != BPF_FUNC_spin_unlock)) {
6369 verbose(env, "function calls are not allowed while holding a lock\n");
6372 if (insn->src_reg == BPF_PSEUDO_CALL)
6373 err = check_func_call(env, insn, &env->insn_idx);
6375 err = check_helper_call(env, insn->imm, env->insn_idx);
6379 } else if (opcode == BPF_JA) {
6380 if (BPF_SRC(insn->code) != BPF_K ||
6382 insn->src_reg != BPF_REG_0 ||
6383 insn->dst_reg != BPF_REG_0 ||
6384 class == BPF_JMP32) {
6385 verbose(env, "BPF_JA uses reserved fields\n");
6389 env->insn_idx += insn->off + 1;
6392 } else if (opcode == BPF_EXIT) {
6393 if (BPF_SRC(insn->code) != BPF_K ||
6395 insn->src_reg != BPF_REG_0 ||
6396 insn->dst_reg != BPF_REG_0 ||
6397 class == BPF_JMP32) {
6398 verbose(env, "BPF_EXIT uses reserved fields\n");
6402 if (env->cur_state->active_spin_lock) {
6403 verbose(env, "bpf_spin_unlock is missing\n");
6407 if (state->curframe) {
6408 /* exit from nested function */
6409 env->prev_insn_idx = env->insn_idx;
6410 err = prepare_func_exit(env, &env->insn_idx);
6413 do_print_state = true;
6417 err = check_reference_leak(env);
6421 /* eBPF calling convetion is such that R0 is used
6422 * to return the value from eBPF program.
6423 * Make sure that it's readable at this time
6424 * of bpf_exit, which means that program wrote
6425 * something into it earlier
6427 err = check_reg_arg(env, BPF_REG_0, SRC_OP);
6431 if (is_pointer_value(env, BPF_REG_0)) {
6432 verbose(env, "R0 leaks addr as return value\n");
6436 err = check_return_code(env);
6440 err = pop_stack(env, &env->prev_insn_idx,
6447 do_print_state = true;
6451 err = check_cond_jmp_op(env, insn, &env->insn_idx);
6455 } else if (class == BPF_LD) {
6456 u8 mode = BPF_MODE(insn->code);
6458 if (mode == BPF_ABS || mode == BPF_IND) {
6459 err = check_ld_abs(env, insn);
6463 } else if (mode == BPF_IMM) {
6464 err = check_ld_imm(env, insn);
6469 env->insn_aux_data[env->insn_idx].seen = true;
6471 verbose(env, "invalid BPF_LD mode\n");
6475 verbose(env, "unknown insn class %d\n", class);
6482 verbose(env, "processed %d insns (limit %d), stack depth ",
6483 insn_processed, BPF_COMPLEXITY_LIMIT_INSNS);
6484 for (i = 0; i < env->subprog_cnt; i++) {
6485 u32 depth = env->subprog_info[i].stack_depth;
6487 verbose(env, "%d", depth);
6488 if (i + 1 < env->subprog_cnt)
6492 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
6496 static int check_map_prealloc(struct bpf_map *map)
6498 return (map->map_type != BPF_MAP_TYPE_HASH &&
6499 map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
6500 map->map_type != BPF_MAP_TYPE_HASH_OF_MAPS) ||
6501 !(map->map_flags & BPF_F_NO_PREALLOC);
6504 static bool is_tracing_prog_type(enum bpf_prog_type type)
6507 case BPF_PROG_TYPE_KPROBE:
6508 case BPF_PROG_TYPE_TRACEPOINT:
6509 case BPF_PROG_TYPE_PERF_EVENT:
6510 case BPF_PROG_TYPE_RAW_TRACEPOINT:
6517 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
6518 struct bpf_map *map,
6519 struct bpf_prog *prog)
6522 /* Make sure that BPF_PROG_TYPE_PERF_EVENT programs only use
6523 * preallocated hash maps, since doing memory allocation
6524 * in overflow_handler can crash depending on where nmi got
6527 if (prog->type == BPF_PROG_TYPE_PERF_EVENT) {
6528 if (!check_map_prealloc(map)) {
6529 verbose(env, "perf_event programs can only use preallocated hash map\n");
6532 if (map->inner_map_meta &&
6533 !check_map_prealloc(map->inner_map_meta)) {
6534 verbose(env, "perf_event programs can only use preallocated inner hash map\n");
6539 if ((is_tracing_prog_type(prog->type) ||
6540 prog->type == BPF_PROG_TYPE_SOCKET_FILTER) &&
6541 map_value_has_spin_lock(map)) {
6542 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
6546 if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) &&
6547 !bpf_offload_prog_map_match(prog, map)) {
6548 verbose(env, "offload device mismatch between prog and map\n");
6555 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
6557 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
6558 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
6561 /* look for pseudo eBPF instructions that access map FDs and
6562 * replace them with actual map pointers
6564 static int replace_map_fd_with_map_ptr(struct bpf_verifier_env *env)
6566 struct bpf_insn *insn = env->prog->insnsi;
6567 int insn_cnt = env->prog->len;
6570 err = bpf_prog_calc_tag(env->prog);
6574 for (i = 0; i < insn_cnt; i++, insn++) {
6575 if (BPF_CLASS(insn->code) == BPF_LDX &&
6576 (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
6577 verbose(env, "BPF_LDX uses reserved fields\n");
6581 if (BPF_CLASS(insn->code) == BPF_STX &&
6582 ((BPF_MODE(insn->code) != BPF_MEM &&
6583 BPF_MODE(insn->code) != BPF_XADD) || insn->imm != 0)) {
6584 verbose(env, "BPF_STX uses reserved fields\n");
6588 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
6589 struct bpf_map *map;
6592 if (i == insn_cnt - 1 || insn[1].code != 0 ||
6593 insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
6595 verbose(env, "invalid bpf_ld_imm64 insn\n");
6599 if (insn->src_reg == 0)
6600 /* valid generic load 64-bit imm */
6603 if (insn->src_reg != BPF_PSEUDO_MAP_FD) {
6605 "unrecognized bpf_ld_imm64 insn\n");
6609 f = fdget(insn->imm);
6610 map = __bpf_map_get(f);
6612 verbose(env, "fd %d is not pointing to valid bpf_map\n",
6614 return PTR_ERR(map);
6617 err = check_map_prog_compatibility(env, map, env->prog);
6623 /* store map pointer inside BPF_LD_IMM64 instruction */
6624 insn[0].imm = (u32) (unsigned long) map;
6625 insn[1].imm = ((u64) (unsigned long) map) >> 32;
6627 /* check whether we recorded this map already */
6628 for (j = 0; j < env->used_map_cnt; j++)
6629 if (env->used_maps[j] == map) {
6634 if (env->used_map_cnt >= MAX_USED_MAPS) {
6639 /* hold the map. If the program is rejected by verifier,
6640 * the map will be released by release_maps() or it
6641 * will be used by the valid program until it's unloaded
6642 * and all maps are released in free_used_maps()
6644 map = bpf_map_inc(map, false);
6647 return PTR_ERR(map);
6649 env->used_maps[env->used_map_cnt++] = map;
6651 if (bpf_map_is_cgroup_storage(map) &&
6652 bpf_cgroup_storage_assign(env->prog, map)) {
6653 verbose(env, "only one cgroup storage of each type is allowed\n");
6665 /* Basic sanity check before we invest more work here. */
6666 if (!bpf_opcode_in_insntable(insn->code)) {
6667 verbose(env, "unknown opcode %02x\n", insn->code);
6672 /* now all pseudo BPF_LD_IMM64 instructions load valid
6673 * 'struct bpf_map *' into a register instead of user map_fd.
6674 * These pointers will be used later by verifier to validate map access.
6679 /* drop refcnt of maps used by the rejected program */
6680 static void release_maps(struct bpf_verifier_env *env)
6682 enum bpf_cgroup_storage_type stype;
6685 for_each_cgroup_storage_type(stype) {
6686 if (!env->prog->aux->cgroup_storage[stype])
6688 bpf_cgroup_storage_release(env->prog,
6689 env->prog->aux->cgroup_storage[stype]);
6692 for (i = 0; i < env->used_map_cnt; i++)
6693 bpf_map_put(env->used_maps[i]);
6696 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
6697 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
6699 struct bpf_insn *insn = env->prog->insnsi;
6700 int insn_cnt = env->prog->len;
6703 for (i = 0; i < insn_cnt; i++, insn++)
6704 if (insn->code == (BPF_LD | BPF_IMM | BPF_DW))
6708 /* single env->prog->insni[off] instruction was replaced with the range
6709 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying
6710 * [0, off) and [off, end) to new locations, so the patched range stays zero
6712 static int adjust_insn_aux_data(struct bpf_verifier_env *env, u32 prog_len,
6715 struct bpf_insn_aux_data *new_data, *old_data = env->insn_aux_data;
6720 new_data = vzalloc(array_size(prog_len,
6721 sizeof(struct bpf_insn_aux_data)));
6724 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
6725 memcpy(new_data + off + cnt - 1, old_data + off,
6726 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
6727 for (i = off; i < off + cnt - 1; i++)
6728 new_data[i].seen = true;
6729 env->insn_aux_data = new_data;
6734 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
6740 /* NOTE: fake 'exit' subprog should be updated as well. */
6741 for (i = 0; i <= env->subprog_cnt; i++) {
6742 if (env->subprog_info[i].start <= off)
6744 env->subprog_info[i].start += len - 1;
6748 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
6749 const struct bpf_insn *patch, u32 len)
6751 struct bpf_prog *new_prog;
6753 new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
6756 if (adjust_insn_aux_data(env, new_prog->len, off, len))
6758 adjust_subprog_starts(env, off, len);
6762 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
6767 /* find first prog starting at or after off (first to remove) */
6768 for (i = 0; i < env->subprog_cnt; i++)
6769 if (env->subprog_info[i].start >= off)
6771 /* find first prog starting at or after off + cnt (first to stay) */
6772 for (j = i; j < env->subprog_cnt; j++)
6773 if (env->subprog_info[j].start >= off + cnt)
6775 /* if j doesn't start exactly at off + cnt, we are just removing
6776 * the front of previous prog
6778 if (env->subprog_info[j].start != off + cnt)
6782 struct bpf_prog_aux *aux = env->prog->aux;
6785 /* move fake 'exit' subprog as well */
6786 move = env->subprog_cnt + 1 - j;
6788 memmove(env->subprog_info + i,
6789 env->subprog_info + j,
6790 sizeof(*env->subprog_info) * move);
6791 env->subprog_cnt -= j - i;
6793 /* remove func_info */
6794 if (aux->func_info) {
6795 move = aux->func_info_cnt - j;
6797 memmove(aux->func_info + i,
6799 sizeof(*aux->func_info) * move);
6800 aux->func_info_cnt -= j - i;
6801 /* func_info->insn_off is set after all code rewrites,
6802 * in adjust_btf_func() - no need to adjust
6806 /* convert i from "first prog to remove" to "first to adjust" */
6807 if (env->subprog_info[i].start == off)
6811 /* update fake 'exit' subprog as well */
6812 for (; i <= env->subprog_cnt; i++)
6813 env->subprog_info[i].start -= cnt;
6818 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
6821 struct bpf_prog *prog = env->prog;
6822 u32 i, l_off, l_cnt, nr_linfo;
6823 struct bpf_line_info *linfo;
6825 nr_linfo = prog->aux->nr_linfo;
6829 linfo = prog->aux->linfo;
6831 /* find first line info to remove, count lines to be removed */
6832 for (i = 0; i < nr_linfo; i++)
6833 if (linfo[i].insn_off >= off)
6838 for (; i < nr_linfo; i++)
6839 if (linfo[i].insn_off < off + cnt)
6844 /* First live insn doesn't match first live linfo, it needs to "inherit"
6845 * last removed linfo. prog is already modified, so prog->len == off
6846 * means no live instructions after (tail of the program was removed).
6848 if (prog->len != off && l_cnt &&
6849 (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
6851 linfo[--i].insn_off = off + cnt;
6854 /* remove the line info which refer to the removed instructions */
6856 memmove(linfo + l_off, linfo + i,
6857 sizeof(*linfo) * (nr_linfo - i));
6859 prog->aux->nr_linfo -= l_cnt;
6860 nr_linfo = prog->aux->nr_linfo;
6863 /* pull all linfo[i].insn_off >= off + cnt in by cnt */
6864 for (i = l_off; i < nr_linfo; i++)
6865 linfo[i].insn_off -= cnt;
6867 /* fix up all subprogs (incl. 'exit') which start >= off */
6868 for (i = 0; i <= env->subprog_cnt; i++)
6869 if (env->subprog_info[i].linfo_idx > l_off) {
6870 /* program may have started in the removed region but
6871 * may not be fully removed
6873 if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
6874 env->subprog_info[i].linfo_idx -= l_cnt;
6876 env->subprog_info[i].linfo_idx = l_off;
6882 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
6884 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
6885 unsigned int orig_prog_len = env->prog->len;
6888 if (bpf_prog_is_dev_bound(env->prog->aux))
6889 bpf_prog_offload_remove_insns(env, off, cnt);
6891 err = bpf_remove_insns(env->prog, off, cnt);
6895 err = adjust_subprog_starts_after_remove(env, off, cnt);
6899 err = bpf_adj_linfo_after_remove(env, off, cnt);
6903 memmove(aux_data + off, aux_data + off + cnt,
6904 sizeof(*aux_data) * (orig_prog_len - off - cnt));
6909 /* The verifier does more data flow analysis than llvm and will not
6910 * explore branches that are dead at run time. Malicious programs can
6911 * have dead code too. Therefore replace all dead at-run-time code
6914 * Just nops are not optimal, e.g. if they would sit at the end of the
6915 * program and through another bug we would manage to jump there, then
6916 * we'd execute beyond program memory otherwise. Returning exception
6917 * code also wouldn't work since we can have subprogs where the dead
6918 * code could be located.
6920 static void sanitize_dead_code(struct bpf_verifier_env *env)
6922 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
6923 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
6924 struct bpf_insn *insn = env->prog->insnsi;
6925 const int insn_cnt = env->prog->len;
6928 for (i = 0; i < insn_cnt; i++) {
6929 if (aux_data[i].seen)
6931 memcpy(insn + i, &trap, sizeof(trap));
6935 static bool insn_is_cond_jump(u8 code)
6939 if (BPF_CLASS(code) == BPF_JMP32)
6942 if (BPF_CLASS(code) != BPF_JMP)
6946 return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
6949 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
6951 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
6952 struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
6953 struct bpf_insn *insn = env->prog->insnsi;
6954 const int insn_cnt = env->prog->len;
6957 for (i = 0; i < insn_cnt; i++, insn++) {
6958 if (!insn_is_cond_jump(insn->code))
6961 if (!aux_data[i + 1].seen)
6963 else if (!aux_data[i + 1 + insn->off].seen)
6968 if (bpf_prog_is_dev_bound(env->prog->aux))
6969 bpf_prog_offload_replace_insn(env, i, &ja);
6971 memcpy(insn, &ja, sizeof(ja));
6975 static int opt_remove_dead_code(struct bpf_verifier_env *env)
6977 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
6978 int insn_cnt = env->prog->len;
6981 for (i = 0; i < insn_cnt; i++) {
6985 while (i + j < insn_cnt && !aux_data[i + j].seen)
6990 err = verifier_remove_insns(env, i, j);
6993 insn_cnt = env->prog->len;
6999 static int opt_remove_nops(struct bpf_verifier_env *env)
7001 const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
7002 struct bpf_insn *insn = env->prog->insnsi;
7003 int insn_cnt = env->prog->len;
7006 for (i = 0; i < insn_cnt; i++) {
7007 if (memcmp(&insn[i], &ja, sizeof(ja)))
7010 err = verifier_remove_insns(env, i, 1);
7020 /* convert load instructions that access fields of a context type into a
7021 * sequence of instructions that access fields of the underlying structure:
7022 * struct __sk_buff -> struct sk_buff
7023 * struct bpf_sock_ops -> struct sock
7025 static int convert_ctx_accesses(struct bpf_verifier_env *env)
7027 const struct bpf_verifier_ops *ops = env->ops;
7028 int i, cnt, size, ctx_field_size, delta = 0;
7029 const int insn_cnt = env->prog->len;
7030 struct bpf_insn insn_buf[16], *insn;
7031 u32 target_size, size_default, off;
7032 struct bpf_prog *new_prog;
7033 enum bpf_access_type type;
7034 bool is_narrower_load;
7036 if (ops->gen_prologue || env->seen_direct_write) {
7037 if (!ops->gen_prologue) {
7038 verbose(env, "bpf verifier is misconfigured\n");
7041 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
7043 if (cnt >= ARRAY_SIZE(insn_buf)) {
7044 verbose(env, "bpf verifier is misconfigured\n");
7047 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
7051 env->prog = new_prog;
7056 if (bpf_prog_is_dev_bound(env->prog->aux))
7059 insn = env->prog->insnsi + delta;
7061 for (i = 0; i < insn_cnt; i++, insn++) {
7062 bpf_convert_ctx_access_t convert_ctx_access;
7064 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
7065 insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
7066 insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
7067 insn->code == (BPF_LDX | BPF_MEM | BPF_DW))
7069 else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
7070 insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
7071 insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
7072 insn->code == (BPF_STX | BPF_MEM | BPF_DW))
7077 if (type == BPF_WRITE &&
7078 env->insn_aux_data[i + delta].sanitize_stack_off) {
7079 struct bpf_insn patch[] = {
7080 /* Sanitize suspicious stack slot with zero.
7081 * There are no memory dependencies for this store,
7082 * since it's only using frame pointer and immediate
7085 BPF_ST_MEM(BPF_DW, BPF_REG_FP,
7086 env->insn_aux_data[i + delta].sanitize_stack_off,
7088 /* the original STX instruction will immediately
7089 * overwrite the same stack slot with appropriate value
7094 cnt = ARRAY_SIZE(patch);
7095 new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
7100 env->prog = new_prog;
7101 insn = new_prog->insnsi + i + delta;
7105 switch (env->insn_aux_data[i + delta].ptr_type) {
7107 if (!ops->convert_ctx_access)
7109 convert_ctx_access = ops->convert_ctx_access;
7112 convert_ctx_access = bpf_sock_convert_ctx_access;
7118 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
7119 size = BPF_LDST_BYTES(insn);
7121 /* If the read access is a narrower load of the field,
7122 * convert to a 4/8-byte load, to minimum program type specific
7123 * convert_ctx_access changes. If conversion is successful,
7124 * we will apply proper mask to the result.
7126 is_narrower_load = size < ctx_field_size;
7127 size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
7129 if (is_narrower_load) {
7132 if (type == BPF_WRITE) {
7133 verbose(env, "bpf verifier narrow ctx access misconfigured\n");
7138 if (ctx_field_size == 4)
7140 else if (ctx_field_size == 8)
7143 insn->off = off & ~(size_default - 1);
7144 insn->code = BPF_LDX | BPF_MEM | size_code;
7148 cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
7150 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
7151 (ctx_field_size && !target_size)) {
7152 verbose(env, "bpf verifier is misconfigured\n");
7156 if (is_narrower_load && size < target_size) {
7157 u8 shift = (off & (size_default - 1)) * 8;
7159 if (ctx_field_size <= 4) {
7161 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
7164 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
7165 (1 << size * 8) - 1);
7168 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
7171 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
7172 (1 << size * 8) - 1);
7176 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
7182 /* keep walking new program and skip insns we just inserted */
7183 env->prog = new_prog;
7184 insn = new_prog->insnsi + i + delta;
7190 static int jit_subprogs(struct bpf_verifier_env *env)
7192 struct bpf_prog *prog = env->prog, **func, *tmp;
7193 int i, j, subprog_start, subprog_end = 0, len, subprog;
7194 struct bpf_insn *insn;
7198 if (env->subprog_cnt <= 1)
7201 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
7202 if (insn->code != (BPF_JMP | BPF_CALL) ||
7203 insn->src_reg != BPF_PSEUDO_CALL)
7205 /* Upon error here we cannot fall back to interpreter but
7206 * need a hard reject of the program. Thus -EFAULT is
7207 * propagated in any case.
7209 subprog = find_subprog(env, i + insn->imm + 1);
7211 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
7215 /* temporarily remember subprog id inside insn instead of
7216 * aux_data, since next loop will split up all insns into funcs
7218 insn->off = subprog;
7219 /* remember original imm in case JIT fails and fallback
7220 * to interpreter will be needed
7222 env->insn_aux_data[i].call_imm = insn->imm;
7223 /* point imm to __bpf_call_base+1 from JITs point of view */
7227 err = bpf_prog_alloc_jited_linfo(prog);
7232 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
7236 for (i = 0; i < env->subprog_cnt; i++) {
7237 subprog_start = subprog_end;
7238 subprog_end = env->subprog_info[i + 1].start;
7240 len = subprog_end - subprog_start;
7241 func[i] = bpf_prog_alloc(bpf_prog_size(len), GFP_USER);
7244 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
7245 len * sizeof(struct bpf_insn));
7246 func[i]->type = prog->type;
7248 if (bpf_prog_calc_tag(func[i]))
7250 func[i]->is_func = 1;
7251 func[i]->aux->func_idx = i;
7252 /* the btf and func_info will be freed only at prog->aux */
7253 func[i]->aux->btf = prog->aux->btf;
7254 func[i]->aux->func_info = prog->aux->func_info;
7256 /* Use bpf_prog_F_tag to indicate functions in stack traces.
7257 * Long term would need debug info to populate names
7259 func[i]->aux->name[0] = 'F';
7260 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
7261 func[i]->jit_requested = 1;
7262 func[i]->aux->linfo = prog->aux->linfo;
7263 func[i]->aux->nr_linfo = prog->aux->nr_linfo;
7264 func[i]->aux->jited_linfo = prog->aux->jited_linfo;
7265 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
7266 func[i] = bpf_int_jit_compile(func[i]);
7267 if (!func[i]->jited) {
7273 /* at this point all bpf functions were successfully JITed
7274 * now populate all bpf_calls with correct addresses and
7275 * run last pass of JIT
7277 for (i = 0; i < env->subprog_cnt; i++) {
7278 insn = func[i]->insnsi;
7279 for (j = 0; j < func[i]->len; j++, insn++) {
7280 if (insn->code != (BPF_JMP | BPF_CALL) ||
7281 insn->src_reg != BPF_PSEUDO_CALL)
7283 subprog = insn->off;
7284 insn->imm = (u64 (*)(u64, u64, u64, u64, u64))
7285 func[subprog]->bpf_func -
7289 /* we use the aux data to keep a list of the start addresses
7290 * of the JITed images for each function in the program
7292 * for some architectures, such as powerpc64, the imm field
7293 * might not be large enough to hold the offset of the start
7294 * address of the callee's JITed image from __bpf_call_base
7296 * in such cases, we can lookup the start address of a callee
7297 * by using its subprog id, available from the off field of
7298 * the call instruction, as an index for this list
7300 func[i]->aux->func = func;
7301 func[i]->aux->func_cnt = env->subprog_cnt;
7303 for (i = 0; i < env->subprog_cnt; i++) {
7304 old_bpf_func = func[i]->bpf_func;
7305 tmp = bpf_int_jit_compile(func[i]);
7306 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
7307 verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
7314 /* finally lock prog and jit images for all functions and
7317 for (i = 0; i < env->subprog_cnt; i++) {
7318 bpf_prog_lock_ro(func[i]);
7319 bpf_prog_kallsyms_add(func[i]);
7322 /* Last step: make now unused interpreter insns from main
7323 * prog consistent for later dump requests, so they can
7324 * later look the same as if they were interpreted only.
7326 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
7327 if (insn->code != (BPF_JMP | BPF_CALL) ||
7328 insn->src_reg != BPF_PSEUDO_CALL)
7330 insn->off = env->insn_aux_data[i].call_imm;
7331 subprog = find_subprog(env, i + insn->off + 1);
7332 insn->imm = subprog;
7336 prog->bpf_func = func[0]->bpf_func;
7337 prog->aux->func = func;
7338 prog->aux->func_cnt = env->subprog_cnt;
7339 bpf_prog_free_unused_jited_linfo(prog);
7342 for (i = 0; i < env->subprog_cnt; i++)
7344 bpf_jit_free(func[i]);
7347 /* cleanup main prog to be interpreted */
7348 prog->jit_requested = 0;
7349 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
7350 if (insn->code != (BPF_JMP | BPF_CALL) ||
7351 insn->src_reg != BPF_PSEUDO_CALL)
7354 insn->imm = env->insn_aux_data[i].call_imm;
7356 bpf_prog_free_jited_linfo(prog);
7360 static int fixup_call_args(struct bpf_verifier_env *env)
7362 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
7363 struct bpf_prog *prog = env->prog;
7364 struct bpf_insn *insn = prog->insnsi;
7369 if (env->prog->jit_requested &&
7370 !bpf_prog_is_dev_bound(env->prog->aux)) {
7371 err = jit_subprogs(env);
7377 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
7378 for (i = 0; i < prog->len; i++, insn++) {
7379 if (insn->code != (BPF_JMP | BPF_CALL) ||
7380 insn->src_reg != BPF_PSEUDO_CALL)
7382 depth = get_callee_stack_depth(env, insn, i);
7385 bpf_patch_call_args(insn, depth);
7392 /* fixup insn->imm field of bpf_call instructions
7393 * and inline eligible helpers as explicit sequence of BPF instructions
7395 * this function is called after eBPF program passed verification
7397 static int fixup_bpf_calls(struct bpf_verifier_env *env)
7399 struct bpf_prog *prog = env->prog;
7400 struct bpf_insn *insn = prog->insnsi;
7401 const struct bpf_func_proto *fn;
7402 const int insn_cnt = prog->len;
7403 const struct bpf_map_ops *ops;
7404 struct bpf_insn_aux_data *aux;
7405 struct bpf_insn insn_buf[16];
7406 struct bpf_prog *new_prog;
7407 struct bpf_map *map_ptr;
7408 int i, cnt, delta = 0;
7410 for (i = 0; i < insn_cnt; i++, insn++) {
7411 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
7412 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
7413 insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
7414 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
7415 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
7416 struct bpf_insn mask_and_div[] = {
7417 BPF_MOV32_REG(insn->src_reg, insn->src_reg),
7419 BPF_JMP_IMM(BPF_JNE, insn->src_reg, 0, 2),
7420 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
7421 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
7424 struct bpf_insn mask_and_mod[] = {
7425 BPF_MOV32_REG(insn->src_reg, insn->src_reg),
7426 /* Rx mod 0 -> Rx */
7427 BPF_JMP_IMM(BPF_JEQ, insn->src_reg, 0, 1),
7430 struct bpf_insn *patchlet;
7432 if (insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
7433 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
7434 patchlet = mask_and_div + (is64 ? 1 : 0);
7435 cnt = ARRAY_SIZE(mask_and_div) - (is64 ? 1 : 0);
7437 patchlet = mask_and_mod + (is64 ? 1 : 0);
7438 cnt = ARRAY_SIZE(mask_and_mod) - (is64 ? 1 : 0);
7441 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
7446 env->prog = prog = new_prog;
7447 insn = new_prog->insnsi + i + delta;
7451 if (BPF_CLASS(insn->code) == BPF_LD &&
7452 (BPF_MODE(insn->code) == BPF_ABS ||
7453 BPF_MODE(insn->code) == BPF_IND)) {
7454 cnt = env->ops->gen_ld_abs(insn, insn_buf);
7455 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
7456 verbose(env, "bpf verifier is misconfigured\n");
7460 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
7465 env->prog = prog = new_prog;
7466 insn = new_prog->insnsi + i + delta;
7470 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
7471 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
7472 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
7473 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
7474 struct bpf_insn insn_buf[16];
7475 struct bpf_insn *patch = &insn_buf[0];
7479 aux = &env->insn_aux_data[i + delta];
7480 if (!aux->alu_state)
7483 isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
7484 issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
7485 BPF_ALU_SANITIZE_SRC;
7487 off_reg = issrc ? insn->src_reg : insn->dst_reg;
7489 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
7490 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit - 1);
7491 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
7492 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
7493 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
7494 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
7496 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX,
7498 insn->src_reg = BPF_REG_AX;
7500 *patch++ = BPF_ALU64_REG(BPF_AND, off_reg,
7504 insn->code = insn->code == code_add ?
7505 code_sub : code_add;
7508 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
7509 cnt = patch - insn_buf;
7511 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
7516 env->prog = prog = new_prog;
7517 insn = new_prog->insnsi + i + delta;
7521 if (insn->code != (BPF_JMP | BPF_CALL))
7523 if (insn->src_reg == BPF_PSEUDO_CALL)
7526 if (insn->imm == BPF_FUNC_get_route_realm)
7527 prog->dst_needed = 1;
7528 if (insn->imm == BPF_FUNC_get_prandom_u32)
7529 bpf_user_rnd_init_once();
7530 if (insn->imm == BPF_FUNC_override_return)
7531 prog->kprobe_override = 1;
7532 if (insn->imm == BPF_FUNC_tail_call) {
7533 /* If we tail call into other programs, we
7534 * cannot make any assumptions since they can
7535 * be replaced dynamically during runtime in
7536 * the program array.
7538 prog->cb_access = 1;
7539 env->prog->aux->stack_depth = MAX_BPF_STACK;
7540 env->prog->aux->max_pkt_offset = MAX_PACKET_OFF;
7542 /* mark bpf_tail_call as different opcode to avoid
7543 * conditional branch in the interpeter for every normal
7544 * call and to prevent accidental JITing by JIT compiler
7545 * that doesn't support bpf_tail_call yet
7548 insn->code = BPF_JMP | BPF_TAIL_CALL;
7550 aux = &env->insn_aux_data[i + delta];
7551 if (!bpf_map_ptr_unpriv(aux))
7554 /* instead of changing every JIT dealing with tail_call
7555 * emit two extra insns:
7556 * if (index >= max_entries) goto out;
7557 * index &= array->index_mask;
7558 * to avoid out-of-bounds cpu speculation
7560 if (bpf_map_ptr_poisoned(aux)) {
7561 verbose(env, "tail_call abusing map_ptr\n");
7565 map_ptr = BPF_MAP_PTR(aux->map_state);
7566 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
7567 map_ptr->max_entries, 2);
7568 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
7569 container_of(map_ptr,
7572 insn_buf[2] = *insn;
7574 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
7579 env->prog = prog = new_prog;
7580 insn = new_prog->insnsi + i + delta;
7584 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
7585 * and other inlining handlers are currently limited to 64 bit
7588 if (prog->jit_requested && BITS_PER_LONG == 64 &&
7589 (insn->imm == BPF_FUNC_map_lookup_elem ||
7590 insn->imm == BPF_FUNC_map_update_elem ||
7591 insn->imm == BPF_FUNC_map_delete_elem ||
7592 insn->imm == BPF_FUNC_map_push_elem ||
7593 insn->imm == BPF_FUNC_map_pop_elem ||
7594 insn->imm == BPF_FUNC_map_peek_elem)) {
7595 aux = &env->insn_aux_data[i + delta];
7596 if (bpf_map_ptr_poisoned(aux))
7597 goto patch_call_imm;
7599 map_ptr = BPF_MAP_PTR(aux->map_state);
7601 if (insn->imm == BPF_FUNC_map_lookup_elem &&
7602 ops->map_gen_lookup) {
7603 cnt = ops->map_gen_lookup(map_ptr, insn_buf);
7604 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
7605 verbose(env, "bpf verifier is misconfigured\n");
7609 new_prog = bpf_patch_insn_data(env, i + delta,
7615 env->prog = prog = new_prog;
7616 insn = new_prog->insnsi + i + delta;
7620 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
7621 (void *(*)(struct bpf_map *map, void *key))NULL));
7622 BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
7623 (int (*)(struct bpf_map *map, void *key))NULL));
7624 BUILD_BUG_ON(!__same_type(ops->map_update_elem,
7625 (int (*)(struct bpf_map *map, void *key, void *value,
7627 BUILD_BUG_ON(!__same_type(ops->map_push_elem,
7628 (int (*)(struct bpf_map *map, void *value,
7630 BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
7631 (int (*)(struct bpf_map *map, void *value))NULL));
7632 BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
7633 (int (*)(struct bpf_map *map, void *value))NULL));
7635 switch (insn->imm) {
7636 case BPF_FUNC_map_lookup_elem:
7637 insn->imm = BPF_CAST_CALL(ops->map_lookup_elem) -
7640 case BPF_FUNC_map_update_elem:
7641 insn->imm = BPF_CAST_CALL(ops->map_update_elem) -
7644 case BPF_FUNC_map_delete_elem:
7645 insn->imm = BPF_CAST_CALL(ops->map_delete_elem) -
7648 case BPF_FUNC_map_push_elem:
7649 insn->imm = BPF_CAST_CALL(ops->map_push_elem) -
7652 case BPF_FUNC_map_pop_elem:
7653 insn->imm = BPF_CAST_CALL(ops->map_pop_elem) -
7656 case BPF_FUNC_map_peek_elem:
7657 insn->imm = BPF_CAST_CALL(ops->map_peek_elem) -
7662 goto patch_call_imm;
7666 fn = env->ops->get_func_proto(insn->imm, env->prog);
7667 /* all functions that have prototype and verifier allowed
7668 * programs to call them, must be real in-kernel functions
7672 "kernel subsystem misconfigured func %s#%d\n",
7673 func_id_name(insn->imm), insn->imm);
7676 insn->imm = fn->func - __bpf_call_base;
7682 static void free_states(struct bpf_verifier_env *env)
7684 struct bpf_verifier_state_list *sl, *sln;
7687 if (!env->explored_states)
7690 for (i = 0; i < env->prog->len; i++) {
7691 sl = env->explored_states[i];
7694 while (sl != STATE_LIST_MARK) {
7696 free_verifier_state(&sl->state, false);
7702 kfree(env->explored_states);
7705 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr,
7706 union bpf_attr __user *uattr)
7708 struct bpf_verifier_env *env;
7709 struct bpf_verifier_log *log;
7710 int i, len, ret = -EINVAL;
7713 /* no program is valid */
7714 if (ARRAY_SIZE(bpf_verifier_ops) == 0)
7717 /* 'struct bpf_verifier_env' can be global, but since it's not small,
7718 * allocate/free it every time bpf_check() is called
7720 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
7726 env->insn_aux_data =
7727 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
7729 if (!env->insn_aux_data)
7731 for (i = 0; i < len; i++)
7732 env->insn_aux_data[i].orig_idx = i;
7734 env->ops = bpf_verifier_ops[env->prog->type];
7736 /* grab the mutex to protect few globals used by verifier */
7737 mutex_lock(&bpf_verifier_lock);
7739 if (attr->log_level || attr->log_buf || attr->log_size) {
7740 /* user requested verbose verifier output
7741 * and supplied buffer to store the verification trace
7743 log->level = attr->log_level;
7744 log->ubuf = (char __user *) (unsigned long) attr->log_buf;
7745 log->len_total = attr->log_size;
7748 /* log attributes have to be sane */
7749 if (log->len_total < 128 || log->len_total > UINT_MAX >> 8 ||
7750 !log->level || !log->ubuf)
7754 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
7755 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
7756 env->strict_alignment = true;
7757 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
7758 env->strict_alignment = false;
7760 is_priv = capable(CAP_SYS_ADMIN);
7761 env->allow_ptr_leaks = is_priv;
7763 ret = replace_map_fd_with_map_ptr(env);
7765 goto skip_full_check;
7767 if (bpf_prog_is_dev_bound(env->prog->aux)) {
7768 ret = bpf_prog_offload_verifier_prep(env->prog);
7770 goto skip_full_check;
7773 env->explored_states = kcalloc(env->prog->len,
7774 sizeof(struct bpf_verifier_state_list *),
7777 if (!env->explored_states)
7778 goto skip_full_check;
7780 ret = check_subprogs(env);
7782 goto skip_full_check;
7784 ret = check_btf_info(env, attr, uattr);
7786 goto skip_full_check;
7788 ret = check_cfg(env);
7790 goto skip_full_check;
7792 ret = do_check(env);
7793 if (env->cur_state) {
7794 free_verifier_state(env->cur_state, true);
7795 env->cur_state = NULL;
7798 if (ret == 0 && bpf_prog_is_dev_bound(env->prog->aux))
7799 ret = bpf_prog_offload_finalize(env);
7802 while (!pop_stack(env, NULL, NULL));
7806 ret = check_max_stack_depth(env);
7808 /* instruction rewrites happen after this point */
7811 opt_hard_wire_dead_code_branches(env);
7813 ret = opt_remove_dead_code(env);
7815 ret = opt_remove_nops(env);
7818 sanitize_dead_code(env);
7822 /* program is valid, convert *(u32*)(ctx + off) accesses */
7823 ret = convert_ctx_accesses(env);
7826 ret = fixup_bpf_calls(env);
7829 ret = fixup_call_args(env);
7831 if (log->level && bpf_verifier_log_full(log))
7833 if (log->level && !log->ubuf) {
7835 goto err_release_maps;
7838 if (ret == 0 && env->used_map_cnt) {
7839 /* if program passed verifier, update used_maps in bpf_prog_info */
7840 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
7841 sizeof(env->used_maps[0]),
7844 if (!env->prog->aux->used_maps) {
7846 goto err_release_maps;
7849 memcpy(env->prog->aux->used_maps, env->used_maps,
7850 sizeof(env->used_maps[0]) * env->used_map_cnt);
7851 env->prog->aux->used_map_cnt = env->used_map_cnt;
7853 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
7854 * bpf_ld_imm64 instructions
7856 convert_pseudo_ld_imm64(env);
7860 adjust_btf_func(env);
7863 if (!env->prog->aux->used_maps)
7864 /* if we didn't copy map pointers into bpf_prog_info, release
7865 * them now. Otherwise free_used_maps() will release them.
7870 mutex_unlock(&bpf_verifier_lock);
7871 vfree(env->insn_aux_data);