1 /* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com
2 * Copyright (c) 2016 Facebook
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of version 2 of the GNU General Public
6 * License as published by the Free Software Foundation.
8 * This program is distributed in the hope that it will be useful, but
9 * WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 * General Public License for more details.
13 #include <linux/kernel.h>
14 #include <linux/types.h>
15 #include <linux/slab.h>
16 #include <linux/bpf.h>
17 #include <linux/bpf_verifier.h>
18 #include <linux/filter.h>
19 #include <net/netlink.h>
20 #include <linux/file.h>
21 #include <linux/vmalloc.h>
22 #include <linux/stringify.h>
23 #include <linux/bsearch.h>
24 #include <linux/sort.h>
28 static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
29 #define BPF_PROG_TYPE(_id, _name) \
30 [_id] = & _name ## _verifier_ops,
31 #define BPF_MAP_TYPE(_id, _ops)
32 #include <linux/bpf_types.h>
37 /* bpf_check() is a static code analyzer that walks eBPF program
38 * instruction by instruction and updates register/stack state.
39 * All paths of conditional branches are analyzed until 'bpf_exit' insn.
41 * The first pass is depth-first-search to check that the program is a DAG.
42 * It rejects the following programs:
43 * - larger than BPF_MAXINSNS insns
44 * - if loop is present (detected via back-edge)
45 * - unreachable insns exist (shouldn't be a forest. program = one function)
46 * - out of bounds or malformed jumps
47 * The second pass is all possible path descent from the 1st insn.
48 * Since it's analyzing all pathes through the program, the length of the
49 * analysis is limited to 64k insn, which may be hit even if total number of
50 * insn is less then 4K, but there are too many branches that change stack/regs.
51 * Number of 'branches to be analyzed' is limited to 1k
53 * On entry to each instruction, each register has a type, and the instruction
54 * changes the types of the registers depending on instruction semantics.
55 * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
58 * All registers are 64-bit.
59 * R0 - return register
60 * R1-R5 argument passing registers
61 * R6-R9 callee saved registers
62 * R10 - frame pointer read-only
64 * At the start of BPF program the register R1 contains a pointer to bpf_context
65 * and has type PTR_TO_CTX.
67 * Verifier tracks arithmetic operations on pointers in case:
68 * BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
69 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
70 * 1st insn copies R10 (which has FRAME_PTR) type into R1
71 * and 2nd arithmetic instruction is pattern matched to recognize
72 * that it wants to construct a pointer to some element within stack.
73 * So after 2nd insn, the register R1 has type PTR_TO_STACK
74 * (and -20 constant is saved for further stack bounds checking).
75 * Meaning that this reg is a pointer to stack plus known immediate constant.
77 * Most of the time the registers have SCALAR_VALUE type, which
78 * means the register has some value, but it's not a valid pointer.
79 * (like pointer plus pointer becomes SCALAR_VALUE type)
81 * When verifier sees load or store instructions the type of base register
82 * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK. These are three pointer
83 * types recognized by check_mem_access() function.
85 * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
86 * and the range of [ptr, ptr + map's value_size) is accessible.
88 * registers used to pass values to function calls are checked against
89 * function argument constraints.
91 * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
92 * It means that the register type passed to this function must be
93 * PTR_TO_STACK and it will be used inside the function as
94 * 'pointer to map element key'
96 * For example the argument constraints for bpf_map_lookup_elem():
97 * .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
98 * .arg1_type = ARG_CONST_MAP_PTR,
99 * .arg2_type = ARG_PTR_TO_MAP_KEY,
101 * ret_type says that this function returns 'pointer to map elem value or null'
102 * function expects 1st argument to be a const pointer to 'struct bpf_map' and
103 * 2nd argument should be a pointer to stack, which will be used inside
104 * the helper function as a pointer to map element key.
106 * On the kernel side the helper function looks like:
107 * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
109 * struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
110 * void *key = (void *) (unsigned long) r2;
113 * here kernel can access 'key' and 'map' pointers safely, knowing that
114 * [key, key + map->key_size) bytes are valid and were initialized on
115 * the stack of eBPF program.
118 * Corresponding eBPF program may look like:
119 * BPF_MOV64_REG(BPF_REG_2, BPF_REG_10), // after this insn R2 type is FRAME_PTR
120 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
121 * BPF_LD_MAP_FD(BPF_REG_1, map_fd), // after this insn R1 type is CONST_PTR_TO_MAP
122 * BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
123 * here verifier looks at prototype of map_lookup_elem() and sees:
124 * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
125 * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
127 * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
128 * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
129 * and were initialized prior to this call.
130 * If it's ok, then verifier allows this BPF_CALL insn and looks at
131 * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
132 * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
133 * returns ether pointer to map value or NULL.
135 * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
136 * insn, the register holding that pointer in the true branch changes state to
137 * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
138 * branch. See check_cond_jmp_op().
140 * After the call R0 is set to return type of the function and registers R1-R5
141 * are set to NOT_INIT to indicate that they are no longer readable.
144 /* verifier_state + insn_idx are pushed to stack when branch is encountered */
145 struct bpf_verifier_stack_elem {
146 /* verifer state is 'st'
147 * before processing instruction 'insn_idx'
148 * and after processing instruction 'prev_insn_idx'
150 struct bpf_verifier_state st;
153 struct bpf_verifier_stack_elem *next;
156 #define BPF_COMPLEXITY_LIMIT_INSNS 131072
157 #define BPF_COMPLEXITY_LIMIT_STACK 1024
159 #define BPF_MAP_PTR_POISON ((void *)0xeB9F + POISON_POINTER_DELTA)
161 struct bpf_call_arg_meta {
162 struct bpf_map *map_ptr;
169 static DEFINE_MUTEX(bpf_verifier_lock);
171 void bpf_verifier_vlog(struct bpf_verifier_log *log, const char *fmt,
176 n = vscnprintf(log->kbuf, BPF_VERIFIER_TMP_LOG_SIZE, fmt, args);
178 WARN_ONCE(n >= BPF_VERIFIER_TMP_LOG_SIZE - 1,
179 "verifier log line truncated - local buffer too short\n");
181 n = min(log->len_total - log->len_used - 1, n);
184 if (!copy_to_user(log->ubuf + log->len_used, log->kbuf, n + 1))
190 /* log_level controls verbosity level of eBPF verifier.
191 * bpf_verifier_log_write() is used to dump the verification trace to the log,
192 * so the user can figure out what's wrong with the program
194 __printf(2, 3) void bpf_verifier_log_write(struct bpf_verifier_env *env,
195 const char *fmt, ...)
199 if (!bpf_verifier_log_needed(&env->log))
203 bpf_verifier_vlog(&env->log, fmt, args);
206 EXPORT_SYMBOL_GPL(bpf_verifier_log_write);
208 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
210 struct bpf_verifier_env *env = private_data;
213 if (!bpf_verifier_log_needed(&env->log))
217 bpf_verifier_vlog(&env->log, fmt, args);
221 static bool type_is_pkt_pointer(enum bpf_reg_type type)
223 return type == PTR_TO_PACKET ||
224 type == PTR_TO_PACKET_META;
227 /* string representation of 'enum bpf_reg_type' */
228 static const char * const reg_type_str[] = {
230 [SCALAR_VALUE] = "inv",
231 [PTR_TO_CTX] = "ctx",
232 [CONST_PTR_TO_MAP] = "map_ptr",
233 [PTR_TO_MAP_VALUE] = "map_value",
234 [PTR_TO_MAP_VALUE_OR_NULL] = "map_value_or_null",
235 [PTR_TO_STACK] = "fp",
236 [PTR_TO_PACKET] = "pkt",
237 [PTR_TO_PACKET_META] = "pkt_meta",
238 [PTR_TO_PACKET_END] = "pkt_end",
241 static void print_liveness(struct bpf_verifier_env *env,
242 enum bpf_reg_liveness live)
244 if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN))
246 if (live & REG_LIVE_READ)
248 if (live & REG_LIVE_WRITTEN)
252 static struct bpf_func_state *func(struct bpf_verifier_env *env,
253 const struct bpf_reg_state *reg)
255 struct bpf_verifier_state *cur = env->cur_state;
257 return cur->frame[reg->frameno];
260 static void print_verifier_state(struct bpf_verifier_env *env,
261 const struct bpf_func_state *state)
263 const struct bpf_reg_state *reg;
268 verbose(env, " frame%d:", state->frameno);
269 for (i = 0; i < MAX_BPF_REG; i++) {
270 reg = &state->regs[i];
274 verbose(env, " R%d", i);
275 print_liveness(env, reg->live);
276 verbose(env, "=%s", reg_type_str[t]);
277 if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
278 tnum_is_const(reg->var_off)) {
279 /* reg->off should be 0 for SCALAR_VALUE */
280 verbose(env, "%lld", reg->var_off.value + reg->off);
281 if (t == PTR_TO_STACK)
282 verbose(env, ",call_%d", func(env, reg)->callsite);
284 verbose(env, "(id=%d", reg->id);
285 if (t != SCALAR_VALUE)
286 verbose(env, ",off=%d", reg->off);
287 if (type_is_pkt_pointer(t))
288 verbose(env, ",r=%d", reg->range);
289 else if (t == CONST_PTR_TO_MAP ||
290 t == PTR_TO_MAP_VALUE ||
291 t == PTR_TO_MAP_VALUE_OR_NULL)
292 verbose(env, ",ks=%d,vs=%d",
293 reg->map_ptr->key_size,
294 reg->map_ptr->value_size);
295 if (tnum_is_const(reg->var_off)) {
296 /* Typically an immediate SCALAR_VALUE, but
297 * could be a pointer whose offset is too big
300 verbose(env, ",imm=%llx", reg->var_off.value);
302 if (reg->smin_value != reg->umin_value &&
303 reg->smin_value != S64_MIN)
304 verbose(env, ",smin_value=%lld",
305 (long long)reg->smin_value);
306 if (reg->smax_value != reg->umax_value &&
307 reg->smax_value != S64_MAX)
308 verbose(env, ",smax_value=%lld",
309 (long long)reg->smax_value);
310 if (reg->umin_value != 0)
311 verbose(env, ",umin_value=%llu",
312 (unsigned long long)reg->umin_value);
313 if (reg->umax_value != U64_MAX)
314 verbose(env, ",umax_value=%llu",
315 (unsigned long long)reg->umax_value);
316 if (!tnum_is_unknown(reg->var_off)) {
319 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
320 verbose(env, ",var_off=%s", tn_buf);
326 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
327 if (state->stack[i].slot_type[0] == STACK_SPILL) {
328 verbose(env, " fp%d",
329 (-i - 1) * BPF_REG_SIZE);
330 print_liveness(env, state->stack[i].spilled_ptr.live);
332 reg_type_str[state->stack[i].spilled_ptr.type]);
334 if (state->stack[i].slot_type[0] == STACK_ZERO)
335 verbose(env, " fp%d=0", (-i - 1) * BPF_REG_SIZE);
340 static int copy_stack_state(struct bpf_func_state *dst,
341 const struct bpf_func_state *src)
345 if (WARN_ON_ONCE(dst->allocated_stack < src->allocated_stack)) {
346 /* internal bug, make state invalid to reject the program */
347 memset(dst, 0, sizeof(*dst));
350 memcpy(dst->stack, src->stack,
351 sizeof(*src->stack) * (src->allocated_stack / BPF_REG_SIZE));
355 /* do_check() starts with zero-sized stack in struct bpf_verifier_state to
356 * make it consume minimal amount of memory. check_stack_write() access from
357 * the program calls into realloc_func_state() to grow the stack size.
358 * Note there is a non-zero 'parent' pointer inside bpf_verifier_state
359 * which this function copies over. It points to previous bpf_verifier_state
360 * which is never reallocated
362 static int realloc_func_state(struct bpf_func_state *state, int size,
365 u32 old_size = state->allocated_stack;
366 struct bpf_stack_state *new_stack;
367 int slot = size / BPF_REG_SIZE;
369 if (size <= old_size || !size) {
372 state->allocated_stack = slot * BPF_REG_SIZE;
373 if (!size && old_size) {
379 new_stack = kmalloc_array(slot, sizeof(struct bpf_stack_state),
385 memcpy(new_stack, state->stack,
386 sizeof(*new_stack) * (old_size / BPF_REG_SIZE));
387 memset(new_stack + old_size / BPF_REG_SIZE, 0,
388 sizeof(*new_stack) * (size - old_size) / BPF_REG_SIZE);
390 state->allocated_stack = slot * BPF_REG_SIZE;
392 state->stack = new_stack;
396 static void free_func_state(struct bpf_func_state *state)
404 static void free_verifier_state(struct bpf_verifier_state *state,
409 for (i = 0; i <= state->curframe; i++) {
410 free_func_state(state->frame[i]);
411 state->frame[i] = NULL;
417 /* copy verifier state from src to dst growing dst stack space
418 * when necessary to accommodate larger src stack
420 static int copy_func_state(struct bpf_func_state *dst,
421 const struct bpf_func_state *src)
425 err = realloc_func_state(dst, src->allocated_stack, false);
428 memcpy(dst, src, offsetof(struct bpf_func_state, allocated_stack));
429 return copy_stack_state(dst, src);
432 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
433 const struct bpf_verifier_state *src)
435 struct bpf_func_state *dst;
438 /* if dst has more stack frames then src frame, free them */
439 for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
440 free_func_state(dst_state->frame[i]);
441 dst_state->frame[i] = NULL;
443 dst_state->curframe = src->curframe;
444 dst_state->parent = src->parent;
445 for (i = 0; i <= src->curframe; i++) {
446 dst = dst_state->frame[i];
448 dst = kzalloc(sizeof(*dst), GFP_KERNEL);
451 dst_state->frame[i] = dst;
453 err = copy_func_state(dst, src->frame[i]);
460 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
463 struct bpf_verifier_state *cur = env->cur_state;
464 struct bpf_verifier_stack_elem *elem, *head = env->head;
467 if (env->head == NULL)
471 err = copy_verifier_state(cur, &head->st);
476 *insn_idx = head->insn_idx;
478 *prev_insn_idx = head->prev_insn_idx;
480 free_verifier_state(&head->st, false);
487 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
488 int insn_idx, int prev_insn_idx)
490 struct bpf_verifier_state *cur = env->cur_state;
491 struct bpf_verifier_stack_elem *elem;
494 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
498 elem->insn_idx = insn_idx;
499 elem->prev_insn_idx = prev_insn_idx;
500 elem->next = env->head;
503 err = copy_verifier_state(&elem->st, cur);
506 if (env->stack_size > BPF_COMPLEXITY_LIMIT_STACK) {
507 verbose(env, "BPF program is too complex\n");
512 free_verifier_state(env->cur_state, true);
513 env->cur_state = NULL;
514 /* pop all elements and return */
515 while (!pop_stack(env, NULL, NULL));
519 #define CALLER_SAVED_REGS 6
520 static const int caller_saved[CALLER_SAVED_REGS] = {
521 BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
524 static void __mark_reg_not_init(struct bpf_reg_state *reg);
526 /* Mark the unknown part of a register (variable offset or scalar value) as
527 * known to have the value @imm.
529 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
532 reg->var_off = tnum_const(imm);
533 reg->smin_value = (s64)imm;
534 reg->smax_value = (s64)imm;
535 reg->umin_value = imm;
536 reg->umax_value = imm;
539 /* Mark the 'variable offset' part of a register as zero. This should be
540 * used only on registers holding a pointer type.
542 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
544 __mark_reg_known(reg, 0);
547 static void __mark_reg_const_zero(struct bpf_reg_state *reg)
549 __mark_reg_known(reg, 0);
551 reg->type = SCALAR_VALUE;
554 static void mark_reg_known_zero(struct bpf_verifier_env *env,
555 struct bpf_reg_state *regs, u32 regno)
557 if (WARN_ON(regno >= MAX_BPF_REG)) {
558 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
559 /* Something bad happened, let's kill all regs */
560 for (regno = 0; regno < MAX_BPF_REG; regno++)
561 __mark_reg_not_init(regs + regno);
564 __mark_reg_known_zero(regs + regno);
567 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
569 return type_is_pkt_pointer(reg->type);
572 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
574 return reg_is_pkt_pointer(reg) ||
575 reg->type == PTR_TO_PACKET_END;
578 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
579 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
580 enum bpf_reg_type which)
582 /* The register can already have a range from prior markings.
583 * This is fine as long as it hasn't been advanced from its
586 return reg->type == which &&
589 tnum_equals_const(reg->var_off, 0);
592 /* Attempts to improve min/max values based on var_off information */
593 static void __update_reg_bounds(struct bpf_reg_state *reg)
595 /* min signed is max(sign bit) | min(other bits) */
596 reg->smin_value = max_t(s64, reg->smin_value,
597 reg->var_off.value | (reg->var_off.mask & S64_MIN));
598 /* max signed is min(sign bit) | max(other bits) */
599 reg->smax_value = min_t(s64, reg->smax_value,
600 reg->var_off.value | (reg->var_off.mask & S64_MAX));
601 reg->umin_value = max(reg->umin_value, reg->var_off.value);
602 reg->umax_value = min(reg->umax_value,
603 reg->var_off.value | reg->var_off.mask);
606 /* Uses signed min/max values to inform unsigned, and vice-versa */
607 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
609 /* Learn sign from signed bounds.
610 * If we cannot cross the sign boundary, then signed and unsigned bounds
611 * are the same, so combine. This works even in the negative case, e.g.
612 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
614 if (reg->smin_value >= 0 || reg->smax_value < 0) {
615 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
617 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
621 /* Learn sign from unsigned bounds. Signed bounds cross the sign
622 * boundary, so we must be careful.
624 if ((s64)reg->umax_value >= 0) {
625 /* Positive. We can't learn anything from the smin, but smax
626 * is positive, hence safe.
628 reg->smin_value = reg->umin_value;
629 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
631 } else if ((s64)reg->umin_value < 0) {
632 /* Negative. We can't learn anything from the smax, but smin
633 * is negative, hence safe.
635 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
637 reg->smax_value = reg->umax_value;
641 /* Attempts to improve var_off based on unsigned min/max information */
642 static void __reg_bound_offset(struct bpf_reg_state *reg)
644 reg->var_off = tnum_intersect(reg->var_off,
645 tnum_range(reg->umin_value,
649 /* Reset the min/max bounds of a register */
650 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
652 reg->smin_value = S64_MIN;
653 reg->smax_value = S64_MAX;
655 reg->umax_value = U64_MAX;
658 /* Mark a register as having a completely unknown (scalar) value. */
659 static void __mark_reg_unknown(struct bpf_reg_state *reg)
661 reg->type = SCALAR_VALUE;
664 reg->var_off = tnum_unknown;
666 __mark_reg_unbounded(reg);
669 static void mark_reg_unknown(struct bpf_verifier_env *env,
670 struct bpf_reg_state *regs, u32 regno)
672 if (WARN_ON(regno >= MAX_BPF_REG)) {
673 verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
674 /* Something bad happened, let's kill all regs except FP */
675 for (regno = 0; regno < BPF_REG_FP; regno++)
676 __mark_reg_not_init(regs + regno);
679 __mark_reg_unknown(regs + regno);
682 static void __mark_reg_not_init(struct bpf_reg_state *reg)
684 __mark_reg_unknown(reg);
685 reg->type = NOT_INIT;
688 static void mark_reg_not_init(struct bpf_verifier_env *env,
689 struct bpf_reg_state *regs, u32 regno)
691 if (WARN_ON(regno >= MAX_BPF_REG)) {
692 verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
693 /* Something bad happened, let's kill all regs except FP */
694 for (regno = 0; regno < BPF_REG_FP; regno++)
695 __mark_reg_not_init(regs + regno);
698 __mark_reg_not_init(regs + regno);
701 static void init_reg_state(struct bpf_verifier_env *env,
702 struct bpf_func_state *state)
704 struct bpf_reg_state *regs = state->regs;
707 for (i = 0; i < MAX_BPF_REG; i++) {
708 mark_reg_not_init(env, regs, i);
709 regs[i].live = REG_LIVE_NONE;
713 regs[BPF_REG_FP].type = PTR_TO_STACK;
714 mark_reg_known_zero(env, regs, BPF_REG_FP);
715 regs[BPF_REG_FP].frameno = state->frameno;
717 /* 1st arg to a function */
718 regs[BPF_REG_1].type = PTR_TO_CTX;
719 mark_reg_known_zero(env, regs, BPF_REG_1);
722 #define BPF_MAIN_FUNC (-1)
723 static void init_func_state(struct bpf_verifier_env *env,
724 struct bpf_func_state *state,
725 int callsite, int frameno, int subprogno)
727 state->callsite = callsite;
728 state->frameno = frameno;
729 state->subprogno = subprogno;
730 init_reg_state(env, state);
734 SRC_OP, /* register is used as source operand */
735 DST_OP, /* register is used as destination operand */
736 DST_OP_NO_MARK /* same as above, check only, don't mark */
739 static int cmp_subprogs(const void *a, const void *b)
741 return *(int *)a - *(int *)b;
744 static int find_subprog(struct bpf_verifier_env *env, int off)
748 p = bsearch(&off, env->subprog_starts, env->subprog_cnt,
749 sizeof(env->subprog_starts[0]), cmp_subprogs);
752 return p - env->subprog_starts;
756 static int add_subprog(struct bpf_verifier_env *env, int off)
758 int insn_cnt = env->prog->len;
761 if (off >= insn_cnt || off < 0) {
762 verbose(env, "call to invalid destination\n");
765 ret = find_subprog(env, off);
768 if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
769 verbose(env, "too many subprograms\n");
772 env->subprog_starts[env->subprog_cnt++] = off;
773 sort(env->subprog_starts, env->subprog_cnt,
774 sizeof(env->subprog_starts[0]), cmp_subprogs, NULL);
778 static int check_subprogs(struct bpf_verifier_env *env)
780 int i, ret, subprog_start, subprog_end, off, cur_subprog = 0;
781 struct bpf_insn *insn = env->prog->insnsi;
782 int insn_cnt = env->prog->len;
784 /* determine subprog starts. The end is one before the next starts */
785 for (i = 0; i < insn_cnt; i++) {
786 if (insn[i].code != (BPF_JMP | BPF_CALL))
788 if (insn[i].src_reg != BPF_PSEUDO_CALL)
790 if (!env->allow_ptr_leaks) {
791 verbose(env, "function calls to other bpf functions are allowed for root only\n");
794 if (bpf_prog_is_dev_bound(env->prog->aux)) {
795 verbose(env, "function calls in offloaded programs are not supported yet\n");
798 ret = add_subprog(env, i + insn[i].imm + 1);
803 if (env->log.level > 1)
804 for (i = 0; i < env->subprog_cnt; i++)
805 verbose(env, "func#%d @%d\n", i, env->subprog_starts[i]);
807 /* now check that all jumps are within the same subprog */
809 if (env->subprog_cnt == cur_subprog)
810 subprog_end = insn_cnt;
812 subprog_end = env->subprog_starts[cur_subprog++];
813 for (i = 0; i < insn_cnt; i++) {
814 u8 code = insn[i].code;
816 if (BPF_CLASS(code) != BPF_JMP)
818 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
820 off = i + insn[i].off + 1;
821 if (off < subprog_start || off >= subprog_end) {
822 verbose(env, "jump out of range from insn %d to %d\n", i, off);
826 if (i == subprog_end - 1) {
827 /* to avoid fall-through from one subprog into another
828 * the last insn of the subprog should be either exit
829 * or unconditional jump back
831 if (code != (BPF_JMP | BPF_EXIT) &&
832 code != (BPF_JMP | BPF_JA)) {
833 verbose(env, "last insn is not an exit or jmp\n");
836 subprog_start = subprog_end;
837 if (env->subprog_cnt == cur_subprog)
838 subprog_end = insn_cnt;
840 subprog_end = env->subprog_starts[cur_subprog++];
847 struct bpf_verifier_state *skip_callee(struct bpf_verifier_env *env,
848 const struct bpf_verifier_state *state,
849 struct bpf_verifier_state *parent,
852 struct bpf_verifier_state *tmp = NULL;
854 /* 'parent' could be a state of caller and
855 * 'state' could be a state of callee. In such case
856 * parent->curframe < state->curframe
857 * and it's ok for r1 - r5 registers
859 * 'parent' could be a callee's state after it bpf_exit-ed.
860 * In such case parent->curframe > state->curframe
861 * and it's ok for r0 only
863 if (parent->curframe == state->curframe ||
864 (parent->curframe < state->curframe &&
865 regno >= BPF_REG_1 && regno <= BPF_REG_5) ||
866 (parent->curframe > state->curframe &&
870 if (parent->curframe > state->curframe &&
871 regno >= BPF_REG_6) {
872 /* for callee saved regs we have to skip the whole chain
873 * of states that belong to callee and mark as LIVE_READ
874 * the registers before the call
877 while (tmp && tmp->curframe != state->curframe) {
888 verbose(env, "verifier bug regno %d tmp %p\n", regno, tmp);
889 verbose(env, "regno %d parent frame %d current frame %d\n",
890 regno, parent->curframe, state->curframe);
894 static int mark_reg_read(struct bpf_verifier_env *env,
895 const struct bpf_verifier_state *state,
896 struct bpf_verifier_state *parent,
899 bool writes = parent == state->parent; /* Observe write marks */
901 if (regno == BPF_REG_FP)
902 /* We don't need to worry about FP liveness because it's read-only */
906 /* if read wasn't screened by an earlier write ... */
907 if (writes && state->frame[state->curframe]->regs[regno].live & REG_LIVE_WRITTEN)
909 parent = skip_callee(env, state, parent, regno);
912 /* ... then we depend on parent's value */
913 parent->frame[parent->curframe]->regs[regno].live |= REG_LIVE_READ;
915 parent = state->parent;
921 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
924 struct bpf_verifier_state *vstate = env->cur_state;
925 struct bpf_func_state *state = vstate->frame[vstate->curframe];
926 struct bpf_reg_state *regs = state->regs;
928 if (regno >= MAX_BPF_REG) {
929 verbose(env, "R%d is invalid\n", regno);
934 /* check whether register used as source operand can be read */
935 if (regs[regno].type == NOT_INIT) {
936 verbose(env, "R%d !read_ok\n", regno);
939 return mark_reg_read(env, vstate, vstate->parent, regno);
941 /* check whether register used as dest operand can be written to */
942 if (regno == BPF_REG_FP) {
943 verbose(env, "frame pointer is read only\n");
946 regs[regno].live |= REG_LIVE_WRITTEN;
948 mark_reg_unknown(env, regs, regno);
953 static bool is_spillable_regtype(enum bpf_reg_type type)
956 case PTR_TO_MAP_VALUE:
957 case PTR_TO_MAP_VALUE_OR_NULL:
961 case PTR_TO_PACKET_META:
962 case PTR_TO_PACKET_END:
963 case CONST_PTR_TO_MAP:
970 /* Does this register contain a constant zero? */
971 static bool register_is_null(struct bpf_reg_state *reg)
973 return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
976 /* check_stack_read/write functions track spill/fill of registers,
977 * stack boundary and alignment are checked in check_mem_access()
979 static int check_stack_write(struct bpf_verifier_env *env,
980 struct bpf_func_state *state, /* func where register points to */
981 int off, int size, int value_regno)
983 struct bpf_func_state *cur; /* state of the current function */
984 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
985 enum bpf_reg_type type;
987 err = realloc_func_state(state, round_up(slot + 1, BPF_REG_SIZE),
991 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
992 * so it's aligned access and [off, off + size) are within stack limits
994 if (!env->allow_ptr_leaks &&
995 state->stack[spi].slot_type[0] == STACK_SPILL &&
996 size != BPF_REG_SIZE) {
997 verbose(env, "attempt to corrupt spilled pointer on stack\n");
1001 cur = env->cur_state->frame[env->cur_state->curframe];
1002 if (value_regno >= 0 &&
1003 is_spillable_regtype((type = cur->regs[value_regno].type))) {
1005 /* register containing pointer is being spilled into stack */
1006 if (size != BPF_REG_SIZE) {
1007 verbose(env, "invalid size of register spill\n");
1011 if (state != cur && type == PTR_TO_STACK) {
1012 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
1016 /* save register state */
1017 state->stack[spi].spilled_ptr = cur->regs[value_regno];
1018 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
1020 for (i = 0; i < BPF_REG_SIZE; i++)
1021 state->stack[spi].slot_type[i] = STACK_SPILL;
1023 u8 type = STACK_MISC;
1025 /* regular write of data into stack */
1026 state->stack[spi].spilled_ptr = (struct bpf_reg_state) {};
1028 /* only mark the slot as written if all 8 bytes were written
1029 * otherwise read propagation may incorrectly stop too soon
1030 * when stack slots are partially written.
1031 * This heuristic means that read propagation will be
1032 * conservative, since it will add reg_live_read marks
1033 * to stack slots all the way to first state when programs
1034 * writes+reads less than 8 bytes
1036 if (size == BPF_REG_SIZE)
1037 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
1039 /* when we zero initialize stack slots mark them as such */
1040 if (value_regno >= 0 &&
1041 register_is_null(&cur->regs[value_regno]))
1044 for (i = 0; i < size; i++)
1045 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
1051 /* registers of every function are unique and mark_reg_read() propagates
1052 * the liveness in the following cases:
1053 * - from callee into caller for R1 - R5 that were used as arguments
1054 * - from caller into callee for R0 that used as result of the call
1055 * - from caller to the same caller skipping states of the callee for R6 - R9,
1056 * since R6 - R9 are callee saved by implicit function prologue and
1057 * caller's R6 != callee's R6, so when we propagate liveness up to
1058 * parent states we need to skip callee states for R6 - R9.
1060 * stack slot marking is different, since stacks of caller and callee are
1061 * accessible in both (since caller can pass a pointer to caller's stack to
1062 * callee which can pass it to another function), hence mark_stack_slot_read()
1063 * has to propagate the stack liveness to all parent states at given frame number.
1073 * First *ptr is reading from f1's stack and mark_stack_slot_read() has
1074 * to mark liveness at the f1's frame and not f2's frame.
1075 * Second *ptr is also reading from f1's stack and mark_stack_slot_read() has
1076 * to propagate liveness to f2 states at f1's frame level and further into
1077 * f1 states at f1's frame level until write into that stack slot
1079 static void mark_stack_slot_read(struct bpf_verifier_env *env,
1080 const struct bpf_verifier_state *state,
1081 struct bpf_verifier_state *parent,
1082 int slot, int frameno)
1084 bool writes = parent == state->parent; /* Observe write marks */
1087 if (parent->frame[frameno]->allocated_stack <= slot * BPF_REG_SIZE)
1088 /* since LIVE_WRITTEN mark is only done for full 8-byte
1089 * write the read marks are conservative and parent
1090 * state may not even have the stack allocated. In such case
1091 * end the propagation, since the loop reached beginning
1095 /* if read wasn't screened by an earlier write ... */
1096 if (writes && state->frame[frameno]->stack[slot].spilled_ptr.live & REG_LIVE_WRITTEN)
1098 /* ... then we depend on parent's value */
1099 parent->frame[frameno]->stack[slot].spilled_ptr.live |= REG_LIVE_READ;
1101 parent = state->parent;
1106 static int check_stack_read(struct bpf_verifier_env *env,
1107 struct bpf_func_state *reg_state /* func where register points to */,
1108 int off, int size, int value_regno)
1110 struct bpf_verifier_state *vstate = env->cur_state;
1111 struct bpf_func_state *state = vstate->frame[vstate->curframe];
1112 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
1115 if (reg_state->allocated_stack <= slot) {
1116 verbose(env, "invalid read from stack off %d+0 size %d\n",
1120 stype = reg_state->stack[spi].slot_type;
1122 if (stype[0] == STACK_SPILL) {
1123 if (size != BPF_REG_SIZE) {
1124 verbose(env, "invalid size of register spill\n");
1127 for (i = 1; i < BPF_REG_SIZE; i++) {
1128 if (stype[(slot - i) % BPF_REG_SIZE] != STACK_SPILL) {
1129 verbose(env, "corrupted spill memory\n");
1134 if (value_regno >= 0) {
1135 /* restore register state from stack */
1136 state->regs[value_regno] = reg_state->stack[spi].spilled_ptr;
1137 /* mark reg as written since spilled pointer state likely
1138 * has its liveness marks cleared by is_state_visited()
1139 * which resets stack/reg liveness for state transitions
1141 state->regs[value_regno].live |= REG_LIVE_WRITTEN;
1143 mark_stack_slot_read(env, vstate, vstate->parent, spi,
1144 reg_state->frameno);
1149 for (i = 0; i < size; i++) {
1150 if (stype[(slot - i) % BPF_REG_SIZE] == STACK_MISC)
1152 if (stype[(slot - i) % BPF_REG_SIZE] == STACK_ZERO) {
1156 verbose(env, "invalid read from stack off %d+%d size %d\n",
1160 mark_stack_slot_read(env, vstate, vstate->parent, spi,
1161 reg_state->frameno);
1162 if (value_regno >= 0) {
1163 if (zeros == size) {
1164 /* any size read into register is zero extended,
1165 * so the whole register == const_zero
1167 __mark_reg_const_zero(&state->regs[value_regno]);
1169 /* have read misc data from the stack */
1170 mark_reg_unknown(env, state->regs, value_regno);
1172 state->regs[value_regno].live |= REG_LIVE_WRITTEN;
1178 /* check read/write into map element returned by bpf_map_lookup_elem() */
1179 static int __check_map_access(struct bpf_verifier_env *env, u32 regno, int off,
1180 int size, bool zero_size_allowed)
1182 struct bpf_reg_state *regs = cur_regs(env);
1183 struct bpf_map *map = regs[regno].map_ptr;
1185 if (off < 0 || size < 0 || (size == 0 && !zero_size_allowed) ||
1186 off + size > map->value_size) {
1187 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
1188 map->value_size, off, size);
1194 /* check read/write into a map element with possible variable offset */
1195 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
1196 int off, int size, bool zero_size_allowed)
1198 struct bpf_verifier_state *vstate = env->cur_state;
1199 struct bpf_func_state *state = vstate->frame[vstate->curframe];
1200 struct bpf_reg_state *reg = &state->regs[regno];
1203 /* We may have adjusted the register to this map value, so we
1204 * need to try adding each of min_value and max_value to off
1205 * to make sure our theoretical access will be safe.
1208 print_verifier_state(env, state);
1209 /* The minimum value is only important with signed
1210 * comparisons where we can't assume the floor of a
1211 * value is 0. If we are using signed variables for our
1212 * index'es we need to make sure that whatever we use
1213 * will have a set floor within our range.
1215 if (reg->smin_value < 0) {
1216 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
1220 err = __check_map_access(env, regno, reg->smin_value + off, size,
1223 verbose(env, "R%d min value is outside of the array range\n",
1228 /* If we haven't set a max value then we need to bail since we can't be
1229 * sure we won't do bad things.
1230 * If reg->umax_value + off could overflow, treat that as unbounded too.
1232 if (reg->umax_value >= BPF_MAX_VAR_OFF) {
1233 verbose(env, "R%d unbounded memory access, make sure to bounds check any array access into a map\n",
1237 err = __check_map_access(env, regno, reg->umax_value + off, size,
1240 verbose(env, "R%d max value is outside of the array range\n",
1245 #define MAX_PACKET_OFF 0xffff
1247 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
1248 const struct bpf_call_arg_meta *meta,
1249 enum bpf_access_type t)
1251 switch (env->prog->type) {
1252 case BPF_PROG_TYPE_LWT_IN:
1253 case BPF_PROG_TYPE_LWT_OUT:
1254 /* dst_input() and dst_output() can't write for now */
1258 case BPF_PROG_TYPE_SCHED_CLS:
1259 case BPF_PROG_TYPE_SCHED_ACT:
1260 case BPF_PROG_TYPE_XDP:
1261 case BPF_PROG_TYPE_LWT_XMIT:
1262 case BPF_PROG_TYPE_SK_SKB:
1263 case BPF_PROG_TYPE_SK_MSG:
1265 return meta->pkt_access;
1267 env->seen_direct_write = true;
1274 static int __check_packet_access(struct bpf_verifier_env *env, u32 regno,
1275 int off, int size, bool zero_size_allowed)
1277 struct bpf_reg_state *regs = cur_regs(env);
1278 struct bpf_reg_state *reg = ®s[regno];
1280 if (off < 0 || size < 0 || (size == 0 && !zero_size_allowed) ||
1281 (u64)off + size > reg->range) {
1282 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
1283 off, size, regno, reg->id, reg->off, reg->range);
1289 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
1290 int size, bool zero_size_allowed)
1292 struct bpf_reg_state *regs = cur_regs(env);
1293 struct bpf_reg_state *reg = ®s[regno];
1296 /* We may have added a variable offset to the packet pointer; but any
1297 * reg->range we have comes after that. We are only checking the fixed
1301 /* We don't allow negative numbers, because we aren't tracking enough
1302 * detail to prove they're safe.
1304 if (reg->smin_value < 0) {
1305 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
1309 err = __check_packet_access(env, regno, off, size, zero_size_allowed);
1311 verbose(env, "R%d offset is outside of the packet\n", regno);
1317 /* check access to 'struct bpf_context' fields. Supports fixed offsets only */
1318 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
1319 enum bpf_access_type t, enum bpf_reg_type *reg_type)
1321 struct bpf_insn_access_aux info = {
1322 .reg_type = *reg_type,
1325 if (env->ops->is_valid_access &&
1326 env->ops->is_valid_access(off, size, t, env->prog, &info)) {
1327 /* A non zero info.ctx_field_size indicates that this field is a
1328 * candidate for later verifier transformation to load the whole
1329 * field and then apply a mask when accessed with a narrower
1330 * access than actual ctx access size. A zero info.ctx_field_size
1331 * will only allow for whole field access and rejects any other
1332 * type of narrower access.
1334 *reg_type = info.reg_type;
1336 env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
1337 /* remember the offset of last byte accessed in ctx */
1338 if (env->prog->aux->max_ctx_offset < off + size)
1339 env->prog->aux->max_ctx_offset = off + size;
1343 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
1347 static bool __is_pointer_value(bool allow_ptr_leaks,
1348 const struct bpf_reg_state *reg)
1350 if (allow_ptr_leaks)
1353 return reg->type != SCALAR_VALUE;
1356 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
1358 return __is_pointer_value(env->allow_ptr_leaks, cur_regs(env) + regno);
1361 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
1363 const struct bpf_reg_state *reg = cur_regs(env) + regno;
1365 return reg->type == PTR_TO_CTX;
1368 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
1370 const struct bpf_reg_state *reg = cur_regs(env) + regno;
1372 return type_is_pkt_pointer(reg->type);
1375 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
1376 const struct bpf_reg_state *reg,
1377 int off, int size, bool strict)
1379 struct tnum reg_off;
1382 /* Byte size accesses are always allowed. */
1383 if (!strict || size == 1)
1386 /* For platforms that do not have a Kconfig enabling
1387 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
1388 * NET_IP_ALIGN is universally set to '2'. And on platforms
1389 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
1390 * to this code only in strict mode where we want to emulate
1391 * the NET_IP_ALIGN==2 checking. Therefore use an
1392 * unconditional IP align value of '2'.
1396 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
1397 if (!tnum_is_aligned(reg_off, size)) {
1400 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
1402 "misaligned packet access off %d+%s+%d+%d size %d\n",
1403 ip_align, tn_buf, reg->off, off, size);
1410 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
1411 const struct bpf_reg_state *reg,
1412 const char *pointer_desc,
1413 int off, int size, bool strict)
1415 struct tnum reg_off;
1417 /* Byte size accesses are always allowed. */
1418 if (!strict || size == 1)
1421 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
1422 if (!tnum_is_aligned(reg_off, size)) {
1425 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
1426 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
1427 pointer_desc, tn_buf, reg->off, off, size);
1434 static int check_ptr_alignment(struct bpf_verifier_env *env,
1435 const struct bpf_reg_state *reg, int off,
1436 int size, bool strict_alignment_once)
1438 bool strict = env->strict_alignment || strict_alignment_once;
1439 const char *pointer_desc = "";
1441 switch (reg->type) {
1443 case PTR_TO_PACKET_META:
1444 /* Special case, because of NET_IP_ALIGN. Given metadata sits
1445 * right in front, treat it the very same way.
1447 return check_pkt_ptr_alignment(env, reg, off, size, strict);
1448 case PTR_TO_MAP_VALUE:
1449 pointer_desc = "value ";
1452 pointer_desc = "context ";
1455 pointer_desc = "stack ";
1456 /* The stack spill tracking logic in check_stack_write()
1457 * and check_stack_read() relies on stack accesses being
1465 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
1469 static int update_stack_depth(struct bpf_verifier_env *env,
1470 const struct bpf_func_state *func,
1473 u16 stack = env->subprog_stack_depth[func->subprogno];
1478 /* update known max for given subprogram */
1479 env->subprog_stack_depth[func->subprogno] = -off;
1483 /* starting from main bpf function walk all instructions of the function
1484 * and recursively walk all callees that given function can call.
1485 * Ignore jump and exit insns.
1486 * Since recursion is prevented by check_cfg() this algorithm
1487 * only needs a local stack of MAX_CALL_FRAMES to remember callsites
1489 static int check_max_stack_depth(struct bpf_verifier_env *env)
1491 int depth = 0, frame = 0, subprog = 0, i = 0, subprog_end;
1492 struct bpf_insn *insn = env->prog->insnsi;
1493 int insn_cnt = env->prog->len;
1494 int ret_insn[MAX_CALL_FRAMES];
1495 int ret_prog[MAX_CALL_FRAMES];
1498 /* round up to 32-bytes, since this is granularity
1499 * of interpreter stack size
1501 depth += round_up(max_t(u32, env->subprog_stack_depth[subprog], 1), 32);
1502 if (depth > MAX_BPF_STACK) {
1503 verbose(env, "combined stack size of %d calls is %d. Too large\n",
1508 if (env->subprog_cnt == subprog)
1509 subprog_end = insn_cnt;
1511 subprog_end = env->subprog_starts[subprog];
1512 for (; i < subprog_end; i++) {
1513 if (insn[i].code != (BPF_JMP | BPF_CALL))
1515 if (insn[i].src_reg != BPF_PSEUDO_CALL)
1517 /* remember insn and function to return to */
1518 ret_insn[frame] = i + 1;
1519 ret_prog[frame] = subprog;
1521 /* find the callee */
1522 i = i + insn[i].imm + 1;
1523 subprog = find_subprog(env, i);
1525 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
1531 if (frame >= MAX_CALL_FRAMES) {
1532 WARN_ONCE(1, "verifier bug. Call stack is too deep\n");
1537 /* end of for() loop means the last insn of the 'subprog'
1538 * was reached. Doesn't matter whether it was JA or EXIT
1542 depth -= round_up(max_t(u32, env->subprog_stack_depth[subprog], 1), 32);
1544 i = ret_insn[frame];
1545 subprog = ret_prog[frame];
1549 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
1550 static int get_callee_stack_depth(struct bpf_verifier_env *env,
1551 const struct bpf_insn *insn, int idx)
1553 int start = idx + insn->imm + 1, subprog;
1555 subprog = find_subprog(env, start);
1557 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
1562 return env->subprog_stack_depth[subprog];
1566 /* truncate register to smaller size (in bytes)
1567 * must be called with size < BPF_REG_SIZE
1569 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
1573 /* clear high bits in bit representation */
1574 reg->var_off = tnum_cast(reg->var_off, size);
1576 /* fix arithmetic bounds */
1577 mask = ((u64)1 << (size * 8)) - 1;
1578 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
1579 reg->umin_value &= mask;
1580 reg->umax_value &= mask;
1582 reg->umin_value = 0;
1583 reg->umax_value = mask;
1585 reg->smin_value = reg->umin_value;
1586 reg->smax_value = reg->umax_value;
1589 /* check whether memory at (regno + off) is accessible for t = (read | write)
1590 * if t==write, value_regno is a register which value is stored into memory
1591 * if t==read, value_regno is a register which will receive the value from memory
1592 * if t==write && value_regno==-1, some unknown value is stored into memory
1593 * if t==read && value_regno==-1, don't care what we read from memory
1595 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
1596 int off, int bpf_size, enum bpf_access_type t,
1597 int value_regno, bool strict_alignment_once)
1599 struct bpf_reg_state *regs = cur_regs(env);
1600 struct bpf_reg_state *reg = regs + regno;
1601 struct bpf_func_state *state;
1604 size = bpf_size_to_bytes(bpf_size);
1608 /* alignment checks will add in reg->off themselves */
1609 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
1613 /* for access checks, reg->off is just part of off */
1616 if (reg->type == PTR_TO_MAP_VALUE) {
1617 if (t == BPF_WRITE && value_regno >= 0 &&
1618 is_pointer_value(env, value_regno)) {
1619 verbose(env, "R%d leaks addr into map\n", value_regno);
1623 err = check_map_access(env, regno, off, size, false);
1624 if (!err && t == BPF_READ && value_regno >= 0)
1625 mark_reg_unknown(env, regs, value_regno);
1627 } else if (reg->type == PTR_TO_CTX) {
1628 enum bpf_reg_type reg_type = SCALAR_VALUE;
1630 if (t == BPF_WRITE && value_regno >= 0 &&
1631 is_pointer_value(env, value_regno)) {
1632 verbose(env, "R%d leaks addr into ctx\n", value_regno);
1635 /* ctx accesses must be at a fixed offset, so that we can
1636 * determine what type of data were returned.
1640 "dereference of modified ctx ptr R%d off=%d+%d, ctx+const is allowed, ctx+const+const is not\n",
1641 regno, reg->off, off - reg->off);
1644 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
1647 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
1649 "variable ctx access var_off=%s off=%d size=%d",
1653 err = check_ctx_access(env, insn_idx, off, size, t, ®_type);
1654 if (!err && t == BPF_READ && value_regno >= 0) {
1655 /* ctx access returns either a scalar, or a
1656 * PTR_TO_PACKET[_META,_END]. In the latter
1657 * case, we know the offset is zero.
1659 if (reg_type == SCALAR_VALUE)
1660 mark_reg_unknown(env, regs, value_regno);
1662 mark_reg_known_zero(env, regs,
1664 regs[value_regno].id = 0;
1665 regs[value_regno].off = 0;
1666 regs[value_regno].range = 0;
1667 regs[value_regno].type = reg_type;
1670 } else if (reg->type == PTR_TO_STACK) {
1671 /* stack accesses must be at a fixed offset, so that we can
1672 * determine what type of data were returned.
1673 * See check_stack_read().
1675 if (!tnum_is_const(reg->var_off)) {
1678 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
1679 verbose(env, "variable stack access var_off=%s off=%d size=%d",
1683 off += reg->var_off.value;
1684 if (off >= 0 || off < -MAX_BPF_STACK) {
1685 verbose(env, "invalid stack off=%d size=%d\n", off,
1690 state = func(env, reg);
1691 err = update_stack_depth(env, state, off);
1696 err = check_stack_write(env, state, off, size,
1699 err = check_stack_read(env, state, off, size,
1701 } else if (reg_is_pkt_pointer(reg)) {
1702 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
1703 verbose(env, "cannot write into packet\n");
1706 if (t == BPF_WRITE && value_regno >= 0 &&
1707 is_pointer_value(env, value_regno)) {
1708 verbose(env, "R%d leaks addr into packet\n",
1712 err = check_packet_access(env, regno, off, size, false);
1713 if (!err && t == BPF_READ && value_regno >= 0)
1714 mark_reg_unknown(env, regs, value_regno);
1716 verbose(env, "R%d invalid mem access '%s'\n", regno,
1717 reg_type_str[reg->type]);
1721 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
1722 regs[value_regno].type == SCALAR_VALUE) {
1723 /* b/h/w load zero-extends, mark upper bits as known 0 */
1724 coerce_reg_to_size(®s[value_regno], size);
1729 static int check_xadd(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
1733 if ((BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) ||
1735 verbose(env, "BPF_XADD uses reserved fields\n");
1739 /* check src1 operand */
1740 err = check_reg_arg(env, insn->src_reg, SRC_OP);
1744 /* check src2 operand */
1745 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
1749 if (is_pointer_value(env, insn->src_reg)) {
1750 verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
1754 if (is_ctx_reg(env, insn->dst_reg) ||
1755 is_pkt_reg(env, insn->dst_reg)) {
1756 verbose(env, "BPF_XADD stores into R%d %s is not allowed\n",
1757 insn->dst_reg, is_ctx_reg(env, insn->dst_reg) ?
1758 "context" : "packet");
1762 /* check whether atomic_add can read the memory */
1763 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
1764 BPF_SIZE(insn->code), BPF_READ, -1, true);
1768 /* check whether atomic_add can write into the same memory */
1769 return check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
1770 BPF_SIZE(insn->code), BPF_WRITE, -1, true);
1773 /* when register 'regno' is passed into function that will read 'access_size'
1774 * bytes from that pointer, make sure that it's within stack boundary
1775 * and all elements of stack are initialized.
1776 * Unlike most pointer bounds-checking functions, this one doesn't take an
1777 * 'off' argument, so it has to add in reg->off itself.
1779 static int check_stack_boundary(struct bpf_verifier_env *env, int regno,
1780 int access_size, bool zero_size_allowed,
1781 struct bpf_call_arg_meta *meta)
1783 struct bpf_reg_state *reg = cur_regs(env) + regno;
1784 struct bpf_func_state *state = func(env, reg);
1785 int off, i, slot, spi;
1787 if (reg->type != PTR_TO_STACK) {
1788 /* Allow zero-byte read from NULL, regardless of pointer type */
1789 if (zero_size_allowed && access_size == 0 &&
1790 register_is_null(reg))
1793 verbose(env, "R%d type=%s expected=%s\n", regno,
1794 reg_type_str[reg->type],
1795 reg_type_str[PTR_TO_STACK]);
1799 /* Only allow fixed-offset stack reads */
1800 if (!tnum_is_const(reg->var_off)) {
1803 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
1804 verbose(env, "invalid variable stack read R%d var_off=%s\n",
1808 off = reg->off + reg->var_off.value;
1809 if (off >= 0 || off < -MAX_BPF_STACK || off + access_size > 0 ||
1810 access_size < 0 || (access_size == 0 && !zero_size_allowed)) {
1811 verbose(env, "invalid stack type R%d off=%d access_size=%d\n",
1812 regno, off, access_size);
1816 if (meta && meta->raw_mode) {
1817 meta->access_size = access_size;
1818 meta->regno = regno;
1822 for (i = 0; i < access_size; i++) {
1825 slot = -(off + i) - 1;
1826 spi = slot / BPF_REG_SIZE;
1827 if (state->allocated_stack <= slot)
1829 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
1830 if (*stype == STACK_MISC)
1832 if (*stype == STACK_ZERO) {
1833 /* helper can write anything into the stack */
1834 *stype = STACK_MISC;
1838 verbose(env, "invalid indirect read from stack off %d+%d size %d\n",
1839 off, i, access_size);
1842 /* reading any byte out of 8-byte 'spill_slot' will cause
1843 * the whole slot to be marked as 'read'
1845 mark_stack_slot_read(env, env->cur_state, env->cur_state->parent,
1846 spi, state->frameno);
1848 return update_stack_depth(env, state, off);
1851 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
1852 int access_size, bool zero_size_allowed,
1853 struct bpf_call_arg_meta *meta)
1855 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
1857 switch (reg->type) {
1859 case PTR_TO_PACKET_META:
1860 return check_packet_access(env, regno, reg->off, access_size,
1862 case PTR_TO_MAP_VALUE:
1863 return check_map_access(env, regno, reg->off, access_size,
1865 default: /* scalar_value|ptr_to_stack or invalid ptr */
1866 return check_stack_boundary(env, regno, access_size,
1867 zero_size_allowed, meta);
1871 static bool arg_type_is_mem_ptr(enum bpf_arg_type type)
1873 return type == ARG_PTR_TO_MEM ||
1874 type == ARG_PTR_TO_MEM_OR_NULL ||
1875 type == ARG_PTR_TO_UNINIT_MEM;
1878 static bool arg_type_is_mem_size(enum bpf_arg_type type)
1880 return type == ARG_CONST_SIZE ||
1881 type == ARG_CONST_SIZE_OR_ZERO;
1884 static int check_func_arg(struct bpf_verifier_env *env, u32 regno,
1885 enum bpf_arg_type arg_type,
1886 struct bpf_call_arg_meta *meta)
1888 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
1889 enum bpf_reg_type expected_type, type = reg->type;
1892 if (arg_type == ARG_DONTCARE)
1895 err = check_reg_arg(env, regno, SRC_OP);
1899 if (arg_type == ARG_ANYTHING) {
1900 if (is_pointer_value(env, regno)) {
1901 verbose(env, "R%d leaks addr into helper function\n",
1908 if (type_is_pkt_pointer(type) &&
1909 !may_access_direct_pkt_data(env, meta, BPF_READ)) {
1910 verbose(env, "helper access to the packet is not allowed\n");
1914 if (arg_type == ARG_PTR_TO_MAP_KEY ||
1915 arg_type == ARG_PTR_TO_MAP_VALUE) {
1916 expected_type = PTR_TO_STACK;
1917 if (!type_is_pkt_pointer(type) && type != PTR_TO_MAP_VALUE &&
1918 type != expected_type)
1920 } else if (arg_type == ARG_CONST_SIZE ||
1921 arg_type == ARG_CONST_SIZE_OR_ZERO) {
1922 expected_type = SCALAR_VALUE;
1923 if (type != expected_type)
1925 } else if (arg_type == ARG_CONST_MAP_PTR) {
1926 expected_type = CONST_PTR_TO_MAP;
1927 if (type != expected_type)
1929 } else if (arg_type == ARG_PTR_TO_CTX) {
1930 expected_type = PTR_TO_CTX;
1931 if (type != expected_type)
1933 } else if (arg_type_is_mem_ptr(arg_type)) {
1934 expected_type = PTR_TO_STACK;
1935 /* One exception here. In case function allows for NULL to be
1936 * passed in as argument, it's a SCALAR_VALUE type. Final test
1937 * happens during stack boundary checking.
1939 if (register_is_null(reg) &&
1940 arg_type == ARG_PTR_TO_MEM_OR_NULL)
1941 /* final test in check_stack_boundary() */;
1942 else if (!type_is_pkt_pointer(type) &&
1943 type != PTR_TO_MAP_VALUE &&
1944 type != expected_type)
1946 meta->raw_mode = arg_type == ARG_PTR_TO_UNINIT_MEM;
1948 verbose(env, "unsupported arg_type %d\n", arg_type);
1952 if (arg_type == ARG_CONST_MAP_PTR) {
1953 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
1954 meta->map_ptr = reg->map_ptr;
1955 } else if (arg_type == ARG_PTR_TO_MAP_KEY) {
1956 /* bpf_map_xxx(..., map_ptr, ..., key) call:
1957 * check that [key, key + map->key_size) are within
1958 * stack limits and initialized
1960 if (!meta->map_ptr) {
1961 /* in function declaration map_ptr must come before
1962 * map_key, so that it's verified and known before
1963 * we have to check map_key here. Otherwise it means
1964 * that kernel subsystem misconfigured verifier
1966 verbose(env, "invalid map_ptr to access map->key\n");
1969 err = check_helper_mem_access(env, regno,
1970 meta->map_ptr->key_size, false,
1972 } else if (arg_type == ARG_PTR_TO_MAP_VALUE) {
1973 /* bpf_map_xxx(..., map_ptr, ..., value) call:
1974 * check [value, value + map->value_size) validity
1976 if (!meta->map_ptr) {
1977 /* kernel subsystem misconfigured verifier */
1978 verbose(env, "invalid map_ptr to access map->value\n");
1981 err = check_helper_mem_access(env, regno,
1982 meta->map_ptr->value_size, false,
1984 } else if (arg_type_is_mem_size(arg_type)) {
1985 bool zero_size_allowed = (arg_type == ARG_CONST_SIZE_OR_ZERO);
1987 /* The register is SCALAR_VALUE; the access check
1988 * happens using its boundaries.
1990 if (!tnum_is_const(reg->var_off))
1991 /* For unprivileged variable accesses, disable raw
1992 * mode so that the program is required to
1993 * initialize all the memory that the helper could
1994 * just partially fill up.
1998 if (reg->smin_value < 0) {
1999 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
2004 if (reg->umin_value == 0) {
2005 err = check_helper_mem_access(env, regno - 1, 0,
2012 if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
2013 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
2017 err = check_helper_mem_access(env, regno - 1,
2019 zero_size_allowed, meta);
2024 verbose(env, "R%d type=%s expected=%s\n", regno,
2025 reg_type_str[type], reg_type_str[expected_type]);
2029 static int check_map_func_compatibility(struct bpf_verifier_env *env,
2030 struct bpf_map *map, int func_id)
2035 /* We need a two way check, first is from map perspective ... */
2036 switch (map->map_type) {
2037 case BPF_MAP_TYPE_PROG_ARRAY:
2038 if (func_id != BPF_FUNC_tail_call)
2041 case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
2042 if (func_id != BPF_FUNC_perf_event_read &&
2043 func_id != BPF_FUNC_perf_event_output &&
2044 func_id != BPF_FUNC_perf_event_read_value)
2047 case BPF_MAP_TYPE_STACK_TRACE:
2048 if (func_id != BPF_FUNC_get_stackid)
2051 case BPF_MAP_TYPE_CGROUP_ARRAY:
2052 if (func_id != BPF_FUNC_skb_under_cgroup &&
2053 func_id != BPF_FUNC_current_task_under_cgroup)
2056 /* devmap returns a pointer to a live net_device ifindex that we cannot
2057 * allow to be modified from bpf side. So do not allow lookup elements
2060 case BPF_MAP_TYPE_DEVMAP:
2061 if (func_id != BPF_FUNC_redirect_map)
2064 /* Restrict bpf side of cpumap, open when use-cases appear */
2065 case BPF_MAP_TYPE_CPUMAP:
2066 if (func_id != BPF_FUNC_redirect_map)
2069 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
2070 case BPF_MAP_TYPE_HASH_OF_MAPS:
2071 if (func_id != BPF_FUNC_map_lookup_elem)
2074 case BPF_MAP_TYPE_SOCKMAP:
2075 if (func_id != BPF_FUNC_sk_redirect_map &&
2076 func_id != BPF_FUNC_sock_map_update &&
2077 func_id != BPF_FUNC_map_delete_elem &&
2078 func_id != BPF_FUNC_msg_redirect_map)
2085 /* ... and second from the function itself. */
2087 case BPF_FUNC_tail_call:
2088 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
2090 if (env->subprog_cnt) {
2091 verbose(env, "tail_calls are not allowed in programs with bpf-to-bpf calls\n");
2095 case BPF_FUNC_perf_event_read:
2096 case BPF_FUNC_perf_event_output:
2097 case BPF_FUNC_perf_event_read_value:
2098 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
2101 case BPF_FUNC_get_stackid:
2102 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
2105 case BPF_FUNC_current_task_under_cgroup:
2106 case BPF_FUNC_skb_under_cgroup:
2107 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
2110 case BPF_FUNC_redirect_map:
2111 if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
2112 map->map_type != BPF_MAP_TYPE_CPUMAP)
2115 case BPF_FUNC_sk_redirect_map:
2116 case BPF_FUNC_msg_redirect_map:
2117 if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
2120 case BPF_FUNC_sock_map_update:
2121 if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
2130 verbose(env, "cannot pass map_type %d into func %s#%d\n",
2131 map->map_type, func_id_name(func_id), func_id);
2135 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
2139 if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
2141 if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
2143 if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
2145 if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
2147 if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
2150 /* We only support one arg being in raw mode at the moment,
2151 * which is sufficient for the helper functions we have
2157 static bool check_args_pair_invalid(enum bpf_arg_type arg_curr,
2158 enum bpf_arg_type arg_next)
2160 return (arg_type_is_mem_ptr(arg_curr) &&
2161 !arg_type_is_mem_size(arg_next)) ||
2162 (!arg_type_is_mem_ptr(arg_curr) &&
2163 arg_type_is_mem_size(arg_next));
2166 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
2168 /* bpf_xxx(..., buf, len) call will access 'len'
2169 * bytes from memory 'buf'. Both arg types need
2170 * to be paired, so make sure there's no buggy
2171 * helper function specification.
2173 if (arg_type_is_mem_size(fn->arg1_type) ||
2174 arg_type_is_mem_ptr(fn->arg5_type) ||
2175 check_args_pair_invalid(fn->arg1_type, fn->arg2_type) ||
2176 check_args_pair_invalid(fn->arg2_type, fn->arg3_type) ||
2177 check_args_pair_invalid(fn->arg3_type, fn->arg4_type) ||
2178 check_args_pair_invalid(fn->arg4_type, fn->arg5_type))
2184 static int check_func_proto(const struct bpf_func_proto *fn)
2186 return check_raw_mode_ok(fn) &&
2187 check_arg_pair_ok(fn) ? 0 : -EINVAL;
2190 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
2191 * are now invalid, so turn them into unknown SCALAR_VALUE.
2193 static void __clear_all_pkt_pointers(struct bpf_verifier_env *env,
2194 struct bpf_func_state *state)
2196 struct bpf_reg_state *regs = state->regs, *reg;
2199 for (i = 0; i < MAX_BPF_REG; i++)
2200 if (reg_is_pkt_pointer_any(®s[i]))
2201 mark_reg_unknown(env, regs, i);
2203 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
2204 if (state->stack[i].slot_type[0] != STACK_SPILL)
2206 reg = &state->stack[i].spilled_ptr;
2207 if (reg_is_pkt_pointer_any(reg))
2208 __mark_reg_unknown(reg);
2212 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
2214 struct bpf_verifier_state *vstate = env->cur_state;
2217 for (i = 0; i <= vstate->curframe; i++)
2218 __clear_all_pkt_pointers(env, vstate->frame[i]);
2221 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
2224 struct bpf_verifier_state *state = env->cur_state;
2225 struct bpf_func_state *caller, *callee;
2226 int i, subprog, target_insn;
2228 if (state->curframe + 1 >= MAX_CALL_FRAMES) {
2229 verbose(env, "the call stack of %d frames is too deep\n",
2230 state->curframe + 2);
2234 target_insn = *insn_idx + insn->imm;
2235 subprog = find_subprog(env, target_insn + 1);
2237 verbose(env, "verifier bug. No program starts at insn %d\n",
2242 caller = state->frame[state->curframe];
2243 if (state->frame[state->curframe + 1]) {
2244 verbose(env, "verifier bug. Frame %d already allocated\n",
2245 state->curframe + 1);
2249 callee = kzalloc(sizeof(*callee), GFP_KERNEL);
2252 state->frame[state->curframe + 1] = callee;
2254 /* callee cannot access r0, r6 - r9 for reading and has to write
2255 * into its own stack before reading from it.
2256 * callee can read/write into caller's stack
2258 init_func_state(env, callee,
2259 /* remember the callsite, it will be used by bpf_exit */
2260 *insn_idx /* callsite */,
2261 state->curframe + 1 /* frameno within this callchain */,
2262 subprog + 1 /* subprog number within this prog */);
2264 /* copy r1 - r5 args that callee can access */
2265 for (i = BPF_REG_1; i <= BPF_REG_5; i++)
2266 callee->regs[i] = caller->regs[i];
2268 /* after the call regsiters r0 - r5 were scratched */
2269 for (i = 0; i < CALLER_SAVED_REGS; i++) {
2270 mark_reg_not_init(env, caller->regs, caller_saved[i]);
2271 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
2274 /* only increment it after check_reg_arg() finished */
2277 /* and go analyze first insn of the callee */
2278 *insn_idx = target_insn;
2280 if (env->log.level) {
2281 verbose(env, "caller:\n");
2282 print_verifier_state(env, caller);
2283 verbose(env, "callee:\n");
2284 print_verifier_state(env, callee);
2289 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
2291 struct bpf_verifier_state *state = env->cur_state;
2292 struct bpf_func_state *caller, *callee;
2293 struct bpf_reg_state *r0;
2295 callee = state->frame[state->curframe];
2296 r0 = &callee->regs[BPF_REG_0];
2297 if (r0->type == PTR_TO_STACK) {
2298 /* technically it's ok to return caller's stack pointer
2299 * (or caller's caller's pointer) back to the caller,
2300 * since these pointers are valid. Only current stack
2301 * pointer will be invalid as soon as function exits,
2302 * but let's be conservative
2304 verbose(env, "cannot return stack pointer to the caller\n");
2309 caller = state->frame[state->curframe];
2310 /* return to the caller whatever r0 had in the callee */
2311 caller->regs[BPF_REG_0] = *r0;
2313 *insn_idx = callee->callsite + 1;
2314 if (env->log.level) {
2315 verbose(env, "returning from callee:\n");
2316 print_verifier_state(env, callee);
2317 verbose(env, "to caller at %d:\n", *insn_idx);
2318 print_verifier_state(env, caller);
2320 /* clear everything in the callee */
2321 free_func_state(callee);
2322 state->frame[state->curframe + 1] = NULL;
2326 static int check_helper_call(struct bpf_verifier_env *env, int func_id, int insn_idx)
2328 const struct bpf_func_proto *fn = NULL;
2329 struct bpf_reg_state *regs;
2330 struct bpf_call_arg_meta meta;
2334 /* find function prototype */
2335 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
2336 verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
2341 if (env->ops->get_func_proto)
2342 fn = env->ops->get_func_proto(func_id, env->prog);
2344 verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
2349 /* eBPF programs must be GPL compatible to use GPL-ed functions */
2350 if (!env->prog->gpl_compatible && fn->gpl_only) {
2351 verbose(env, "cannot call GPL only function from proprietary program\n");
2355 /* With LD_ABS/IND some JITs save/restore skb from r1. */
2356 changes_data = bpf_helper_changes_pkt_data(fn->func);
2357 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
2358 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
2359 func_id_name(func_id), func_id);
2363 memset(&meta, 0, sizeof(meta));
2364 meta.pkt_access = fn->pkt_access;
2366 err = check_func_proto(fn);
2368 verbose(env, "kernel subsystem misconfigured func %s#%d\n",
2369 func_id_name(func_id), func_id);
2374 err = check_func_arg(env, BPF_REG_1, fn->arg1_type, &meta);
2377 err = check_func_arg(env, BPF_REG_2, fn->arg2_type, &meta);
2380 if (func_id == BPF_FUNC_tail_call) {
2381 if (meta.map_ptr == NULL) {
2382 verbose(env, "verifier bug\n");
2385 env->insn_aux_data[insn_idx].map_ptr = meta.map_ptr;
2387 err = check_func_arg(env, BPF_REG_3, fn->arg3_type, &meta);
2390 err = check_func_arg(env, BPF_REG_4, fn->arg4_type, &meta);
2393 err = check_func_arg(env, BPF_REG_5, fn->arg5_type, &meta);
2397 /* Mark slots with STACK_MISC in case of raw mode, stack offset
2398 * is inferred from register state.
2400 for (i = 0; i < meta.access_size; i++) {
2401 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
2402 BPF_WRITE, -1, false);
2407 regs = cur_regs(env);
2408 /* reset caller saved regs */
2409 for (i = 0; i < CALLER_SAVED_REGS; i++) {
2410 mark_reg_not_init(env, regs, caller_saved[i]);
2411 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
2414 /* update return register (already marked as written above) */
2415 if (fn->ret_type == RET_INTEGER) {
2416 /* sets type to SCALAR_VALUE */
2417 mark_reg_unknown(env, regs, BPF_REG_0);
2418 } else if (fn->ret_type == RET_VOID) {
2419 regs[BPF_REG_0].type = NOT_INIT;
2420 } else if (fn->ret_type == RET_PTR_TO_MAP_VALUE_OR_NULL) {
2421 struct bpf_insn_aux_data *insn_aux;
2423 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE_OR_NULL;
2424 /* There is no offset yet applied, variable or fixed */
2425 mark_reg_known_zero(env, regs, BPF_REG_0);
2426 regs[BPF_REG_0].off = 0;
2427 /* remember map_ptr, so that check_map_access()
2428 * can check 'value_size' boundary of memory access
2429 * to map element returned from bpf_map_lookup_elem()
2431 if (meta.map_ptr == NULL) {
2433 "kernel subsystem misconfigured verifier\n");
2436 regs[BPF_REG_0].map_ptr = meta.map_ptr;
2437 regs[BPF_REG_0].id = ++env->id_gen;
2438 insn_aux = &env->insn_aux_data[insn_idx];
2439 if (!insn_aux->map_ptr)
2440 insn_aux->map_ptr = meta.map_ptr;
2441 else if (insn_aux->map_ptr != meta.map_ptr)
2442 insn_aux->map_ptr = BPF_MAP_PTR_POISON;
2444 verbose(env, "unknown return type %d of func %s#%d\n",
2445 fn->ret_type, func_id_name(func_id), func_id);
2449 err = check_map_func_compatibility(env, meta.map_ptr, func_id);
2454 clear_all_pkt_pointers(env);
2458 static bool signed_add_overflows(s64 a, s64 b)
2460 /* Do the add in u64, where overflow is well-defined */
2461 s64 res = (s64)((u64)a + (u64)b);
2468 static bool signed_sub_overflows(s64 a, s64 b)
2470 /* Do the sub in u64, where overflow is well-defined */
2471 s64 res = (s64)((u64)a - (u64)b);
2478 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
2479 const struct bpf_reg_state *reg,
2480 enum bpf_reg_type type)
2482 bool known = tnum_is_const(reg->var_off);
2483 s64 val = reg->var_off.value;
2484 s64 smin = reg->smin_value;
2486 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
2487 verbose(env, "math between %s pointer and %lld is not allowed\n",
2488 reg_type_str[type], val);
2492 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
2493 verbose(env, "%s pointer offset %d is not allowed\n",
2494 reg_type_str[type], reg->off);
2498 if (smin == S64_MIN) {
2499 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
2500 reg_type_str[type]);
2504 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
2505 verbose(env, "value %lld makes %s pointer be out of bounds\n",
2506 smin, reg_type_str[type]);
2513 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
2514 * Caller should also handle BPF_MOV case separately.
2515 * If we return -EACCES, caller may want to try again treating pointer as a
2516 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks.
2518 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
2519 struct bpf_insn *insn,
2520 const struct bpf_reg_state *ptr_reg,
2521 const struct bpf_reg_state *off_reg)
2523 struct bpf_verifier_state *vstate = env->cur_state;
2524 struct bpf_func_state *state = vstate->frame[vstate->curframe];
2525 struct bpf_reg_state *regs = state->regs, *dst_reg;
2526 bool known = tnum_is_const(off_reg->var_off);
2527 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
2528 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
2529 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
2530 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
2531 u8 opcode = BPF_OP(insn->code);
2532 u32 dst = insn->dst_reg;
2534 dst_reg = ®s[dst];
2536 if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
2537 smin_val > smax_val || umin_val > umax_val) {
2538 /* Taint dst register if offset had invalid bounds derived from
2539 * e.g. dead branches.
2541 __mark_reg_unknown(dst_reg);
2545 if (BPF_CLASS(insn->code) != BPF_ALU64) {
2546 /* 32-bit ALU ops on pointers produce (meaningless) scalars */
2548 "R%d 32-bit pointer arithmetic prohibited\n",
2553 if (ptr_reg->type == PTR_TO_MAP_VALUE_OR_NULL) {
2554 verbose(env, "R%d pointer arithmetic on PTR_TO_MAP_VALUE_OR_NULL prohibited, null-check it first\n",
2558 if (ptr_reg->type == CONST_PTR_TO_MAP) {
2559 verbose(env, "R%d pointer arithmetic on CONST_PTR_TO_MAP prohibited\n",
2563 if (ptr_reg->type == PTR_TO_PACKET_END) {
2564 verbose(env, "R%d pointer arithmetic on PTR_TO_PACKET_END prohibited\n",
2569 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
2570 * The id may be overwritten later if we create a new variable offset.
2572 dst_reg->type = ptr_reg->type;
2573 dst_reg->id = ptr_reg->id;
2575 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
2576 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
2581 /* We can take a fixed offset as long as it doesn't overflow
2582 * the s32 'off' field
2584 if (known && (ptr_reg->off + smin_val ==
2585 (s64)(s32)(ptr_reg->off + smin_val))) {
2586 /* pointer += K. Accumulate it into fixed offset */
2587 dst_reg->smin_value = smin_ptr;
2588 dst_reg->smax_value = smax_ptr;
2589 dst_reg->umin_value = umin_ptr;
2590 dst_reg->umax_value = umax_ptr;
2591 dst_reg->var_off = ptr_reg->var_off;
2592 dst_reg->off = ptr_reg->off + smin_val;
2593 dst_reg->range = ptr_reg->range;
2596 /* A new variable offset is created. Note that off_reg->off
2597 * == 0, since it's a scalar.
2598 * dst_reg gets the pointer type and since some positive
2599 * integer value was added to the pointer, give it a new 'id'
2600 * if it's a PTR_TO_PACKET.
2601 * this creates a new 'base' pointer, off_reg (variable) gets
2602 * added into the variable offset, and we copy the fixed offset
2605 if (signed_add_overflows(smin_ptr, smin_val) ||
2606 signed_add_overflows(smax_ptr, smax_val)) {
2607 dst_reg->smin_value = S64_MIN;
2608 dst_reg->smax_value = S64_MAX;
2610 dst_reg->smin_value = smin_ptr + smin_val;
2611 dst_reg->smax_value = smax_ptr + smax_val;
2613 if (umin_ptr + umin_val < umin_ptr ||
2614 umax_ptr + umax_val < umax_ptr) {
2615 dst_reg->umin_value = 0;
2616 dst_reg->umax_value = U64_MAX;
2618 dst_reg->umin_value = umin_ptr + umin_val;
2619 dst_reg->umax_value = umax_ptr + umax_val;
2621 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
2622 dst_reg->off = ptr_reg->off;
2623 if (reg_is_pkt_pointer(ptr_reg)) {
2624 dst_reg->id = ++env->id_gen;
2625 /* something was added to pkt_ptr, set range to zero */
2630 if (dst_reg == off_reg) {
2631 /* scalar -= pointer. Creates an unknown scalar */
2632 verbose(env, "R%d tried to subtract pointer from scalar\n",
2636 /* We don't allow subtraction from FP, because (according to
2637 * test_verifier.c test "invalid fp arithmetic", JITs might not
2638 * be able to deal with it.
2640 if (ptr_reg->type == PTR_TO_STACK) {
2641 verbose(env, "R%d subtraction from stack pointer prohibited\n",
2645 if (known && (ptr_reg->off - smin_val ==
2646 (s64)(s32)(ptr_reg->off - smin_val))) {
2647 /* pointer -= K. Subtract it from fixed offset */
2648 dst_reg->smin_value = smin_ptr;
2649 dst_reg->smax_value = smax_ptr;
2650 dst_reg->umin_value = umin_ptr;
2651 dst_reg->umax_value = umax_ptr;
2652 dst_reg->var_off = ptr_reg->var_off;
2653 dst_reg->id = ptr_reg->id;
2654 dst_reg->off = ptr_reg->off - smin_val;
2655 dst_reg->range = ptr_reg->range;
2658 /* A new variable offset is created. If the subtrahend is known
2659 * nonnegative, then any reg->range we had before is still good.
2661 if (signed_sub_overflows(smin_ptr, smax_val) ||
2662 signed_sub_overflows(smax_ptr, smin_val)) {
2663 /* Overflow possible, we know nothing */
2664 dst_reg->smin_value = S64_MIN;
2665 dst_reg->smax_value = S64_MAX;
2667 dst_reg->smin_value = smin_ptr - smax_val;
2668 dst_reg->smax_value = smax_ptr - smin_val;
2670 if (umin_ptr < umax_val) {
2671 /* Overflow possible, we know nothing */
2672 dst_reg->umin_value = 0;
2673 dst_reg->umax_value = U64_MAX;
2675 /* Cannot overflow (as long as bounds are consistent) */
2676 dst_reg->umin_value = umin_ptr - umax_val;
2677 dst_reg->umax_value = umax_ptr - umin_val;
2679 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
2680 dst_reg->off = ptr_reg->off;
2681 if (reg_is_pkt_pointer(ptr_reg)) {
2682 dst_reg->id = ++env->id_gen;
2683 /* something was added to pkt_ptr, set range to zero */
2691 /* bitwise ops on pointers are troublesome, prohibit. */
2692 verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
2693 dst, bpf_alu_string[opcode >> 4]);
2696 /* other operators (e.g. MUL,LSH) produce non-pointer results */
2697 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
2698 dst, bpf_alu_string[opcode >> 4]);
2702 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
2705 __update_reg_bounds(dst_reg);
2706 __reg_deduce_bounds(dst_reg);
2707 __reg_bound_offset(dst_reg);
2711 /* WARNING: This function does calculations on 64-bit values, but the actual
2712 * execution may occur on 32-bit values. Therefore, things like bitshifts
2713 * need extra checks in the 32-bit case.
2715 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
2716 struct bpf_insn *insn,
2717 struct bpf_reg_state *dst_reg,
2718 struct bpf_reg_state src_reg)
2720 struct bpf_reg_state *regs = cur_regs(env);
2721 u8 opcode = BPF_OP(insn->code);
2722 bool src_known, dst_known;
2723 s64 smin_val, smax_val;
2724 u64 umin_val, umax_val;
2725 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
2727 smin_val = src_reg.smin_value;
2728 smax_val = src_reg.smax_value;
2729 umin_val = src_reg.umin_value;
2730 umax_val = src_reg.umax_value;
2731 src_known = tnum_is_const(src_reg.var_off);
2732 dst_known = tnum_is_const(dst_reg->var_off);
2734 if ((src_known && (smin_val != smax_val || umin_val != umax_val)) ||
2735 smin_val > smax_val || umin_val > umax_val) {
2736 /* Taint dst register if offset had invalid bounds derived from
2737 * e.g. dead branches.
2739 __mark_reg_unknown(dst_reg);
2744 opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
2745 __mark_reg_unknown(dst_reg);
2751 if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
2752 signed_add_overflows(dst_reg->smax_value, smax_val)) {
2753 dst_reg->smin_value = S64_MIN;
2754 dst_reg->smax_value = S64_MAX;
2756 dst_reg->smin_value += smin_val;
2757 dst_reg->smax_value += smax_val;
2759 if (dst_reg->umin_value + umin_val < umin_val ||
2760 dst_reg->umax_value + umax_val < umax_val) {
2761 dst_reg->umin_value = 0;
2762 dst_reg->umax_value = U64_MAX;
2764 dst_reg->umin_value += umin_val;
2765 dst_reg->umax_value += umax_val;
2767 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
2770 if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
2771 signed_sub_overflows(dst_reg->smax_value, smin_val)) {
2772 /* Overflow possible, we know nothing */
2773 dst_reg->smin_value = S64_MIN;
2774 dst_reg->smax_value = S64_MAX;
2776 dst_reg->smin_value -= smax_val;
2777 dst_reg->smax_value -= smin_val;
2779 if (dst_reg->umin_value < umax_val) {
2780 /* Overflow possible, we know nothing */
2781 dst_reg->umin_value = 0;
2782 dst_reg->umax_value = U64_MAX;
2784 /* Cannot overflow (as long as bounds are consistent) */
2785 dst_reg->umin_value -= umax_val;
2786 dst_reg->umax_value -= umin_val;
2788 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
2791 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
2792 if (smin_val < 0 || dst_reg->smin_value < 0) {
2793 /* Ain't nobody got time to multiply that sign */
2794 __mark_reg_unbounded(dst_reg);
2795 __update_reg_bounds(dst_reg);
2798 /* Both values are positive, so we can work with unsigned and
2799 * copy the result to signed (unless it exceeds S64_MAX).
2801 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
2802 /* Potential overflow, we know nothing */
2803 __mark_reg_unbounded(dst_reg);
2804 /* (except what we can learn from the var_off) */
2805 __update_reg_bounds(dst_reg);
2808 dst_reg->umin_value *= umin_val;
2809 dst_reg->umax_value *= umax_val;
2810 if (dst_reg->umax_value > S64_MAX) {
2811 /* Overflow possible, we know nothing */
2812 dst_reg->smin_value = S64_MIN;
2813 dst_reg->smax_value = S64_MAX;
2815 dst_reg->smin_value = dst_reg->umin_value;
2816 dst_reg->smax_value = dst_reg->umax_value;
2820 if (src_known && dst_known) {
2821 __mark_reg_known(dst_reg, dst_reg->var_off.value &
2822 src_reg.var_off.value);
2825 /* We get our minimum from the var_off, since that's inherently
2826 * bitwise. Our maximum is the minimum of the operands' maxima.
2828 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
2829 dst_reg->umin_value = dst_reg->var_off.value;
2830 dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
2831 if (dst_reg->smin_value < 0 || smin_val < 0) {
2832 /* Lose signed bounds when ANDing negative numbers,
2833 * ain't nobody got time for that.
2835 dst_reg->smin_value = S64_MIN;
2836 dst_reg->smax_value = S64_MAX;
2838 /* ANDing two positives gives a positive, so safe to
2839 * cast result into s64.
2841 dst_reg->smin_value = dst_reg->umin_value;
2842 dst_reg->smax_value = dst_reg->umax_value;
2844 /* We may learn something more from the var_off */
2845 __update_reg_bounds(dst_reg);
2848 if (src_known && dst_known) {
2849 __mark_reg_known(dst_reg, dst_reg->var_off.value |
2850 src_reg.var_off.value);
2853 /* We get our maximum from the var_off, and our minimum is the
2854 * maximum of the operands' minima
2856 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
2857 dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
2858 dst_reg->umax_value = dst_reg->var_off.value |
2859 dst_reg->var_off.mask;
2860 if (dst_reg->smin_value < 0 || smin_val < 0) {
2861 /* Lose signed bounds when ORing negative numbers,
2862 * ain't nobody got time for that.
2864 dst_reg->smin_value = S64_MIN;
2865 dst_reg->smax_value = S64_MAX;
2867 /* ORing two positives gives a positive, so safe to
2868 * cast result into s64.
2870 dst_reg->smin_value = dst_reg->umin_value;
2871 dst_reg->smax_value = dst_reg->umax_value;
2873 /* We may learn something more from the var_off */
2874 __update_reg_bounds(dst_reg);
2877 if (umax_val >= insn_bitness) {
2878 /* Shifts greater than 31 or 63 are undefined.
2879 * This includes shifts by a negative number.
2881 mark_reg_unknown(env, regs, insn->dst_reg);
2884 /* We lose all sign bit information (except what we can pick
2887 dst_reg->smin_value = S64_MIN;
2888 dst_reg->smax_value = S64_MAX;
2889 /* If we might shift our top bit out, then we know nothing */
2890 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
2891 dst_reg->umin_value = 0;
2892 dst_reg->umax_value = U64_MAX;
2894 dst_reg->umin_value <<= umin_val;
2895 dst_reg->umax_value <<= umax_val;
2898 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
2900 dst_reg->var_off = tnum_lshift(tnum_unknown, umin_val);
2901 /* We may learn something more from the var_off */
2902 __update_reg_bounds(dst_reg);
2905 if (umax_val >= insn_bitness) {
2906 /* Shifts greater than 31 or 63 are undefined.
2907 * This includes shifts by a negative number.
2909 mark_reg_unknown(env, regs, insn->dst_reg);
2912 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
2913 * be negative, then either:
2914 * 1) src_reg might be zero, so the sign bit of the result is
2915 * unknown, so we lose our signed bounds
2916 * 2) it's known negative, thus the unsigned bounds capture the
2918 * 3) the signed bounds cross zero, so they tell us nothing
2920 * If the value in dst_reg is known nonnegative, then again the
2921 * unsigned bounts capture the signed bounds.
2922 * Thus, in all cases it suffices to blow away our signed bounds
2923 * and rely on inferring new ones from the unsigned bounds and
2924 * var_off of the result.
2926 dst_reg->smin_value = S64_MIN;
2927 dst_reg->smax_value = S64_MAX;
2929 dst_reg->var_off = tnum_rshift(dst_reg->var_off,
2932 dst_reg->var_off = tnum_rshift(tnum_unknown, umin_val);
2933 dst_reg->umin_value >>= umax_val;
2934 dst_reg->umax_value >>= umin_val;
2935 /* We may learn something more from the var_off */
2936 __update_reg_bounds(dst_reg);
2939 mark_reg_unknown(env, regs, insn->dst_reg);
2943 if (BPF_CLASS(insn->code) != BPF_ALU64) {
2944 /* 32-bit ALU ops are (32,32)->32 */
2945 coerce_reg_to_size(dst_reg, 4);
2946 coerce_reg_to_size(&src_reg, 4);
2949 __reg_deduce_bounds(dst_reg);
2950 __reg_bound_offset(dst_reg);
2954 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
2957 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
2958 struct bpf_insn *insn)
2960 struct bpf_verifier_state *vstate = env->cur_state;
2961 struct bpf_func_state *state = vstate->frame[vstate->curframe];
2962 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
2963 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
2964 u8 opcode = BPF_OP(insn->code);
2966 dst_reg = ®s[insn->dst_reg];
2968 if (dst_reg->type != SCALAR_VALUE)
2970 if (BPF_SRC(insn->code) == BPF_X) {
2971 src_reg = ®s[insn->src_reg];
2972 if (src_reg->type != SCALAR_VALUE) {
2973 if (dst_reg->type != SCALAR_VALUE) {
2974 /* Combining two pointers by any ALU op yields
2975 * an arbitrary scalar. Disallow all math except
2976 * pointer subtraction
2978 if (opcode == BPF_SUB){
2979 mark_reg_unknown(env, regs, insn->dst_reg);
2982 verbose(env, "R%d pointer %s pointer prohibited\n",
2984 bpf_alu_string[opcode >> 4]);
2987 /* scalar += pointer
2988 * This is legal, but we have to reverse our
2989 * src/dest handling in computing the range
2991 return adjust_ptr_min_max_vals(env, insn,
2994 } else if (ptr_reg) {
2995 /* pointer += scalar */
2996 return adjust_ptr_min_max_vals(env, insn,
3000 /* Pretend the src is a reg with a known value, since we only
3001 * need to be able to read from this state.
3003 off_reg.type = SCALAR_VALUE;
3004 __mark_reg_known(&off_reg, insn->imm);
3006 if (ptr_reg) /* pointer += K */
3007 return adjust_ptr_min_max_vals(env, insn,
3011 /* Got here implies adding two SCALAR_VALUEs */
3012 if (WARN_ON_ONCE(ptr_reg)) {
3013 print_verifier_state(env, state);
3014 verbose(env, "verifier internal error: unexpected ptr_reg\n");
3017 if (WARN_ON(!src_reg)) {
3018 print_verifier_state(env, state);
3019 verbose(env, "verifier internal error: no src_reg\n");
3022 return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
3025 /* check validity of 32-bit and 64-bit arithmetic operations */
3026 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
3028 struct bpf_reg_state *regs = cur_regs(env);
3029 u8 opcode = BPF_OP(insn->code);
3032 if (opcode == BPF_END || opcode == BPF_NEG) {
3033 if (opcode == BPF_NEG) {
3034 if (BPF_SRC(insn->code) != 0 ||
3035 insn->src_reg != BPF_REG_0 ||
3036 insn->off != 0 || insn->imm != 0) {
3037 verbose(env, "BPF_NEG uses reserved fields\n");
3041 if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
3042 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
3043 BPF_CLASS(insn->code) == BPF_ALU64) {
3044 verbose(env, "BPF_END uses reserved fields\n");
3049 /* check src operand */
3050 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
3054 if (is_pointer_value(env, insn->dst_reg)) {
3055 verbose(env, "R%d pointer arithmetic prohibited\n",
3060 /* check dest operand */
3061 err = check_reg_arg(env, insn->dst_reg, DST_OP);
3065 } else if (opcode == BPF_MOV) {
3067 if (BPF_SRC(insn->code) == BPF_X) {
3068 if (insn->imm != 0 || insn->off != 0) {
3069 verbose(env, "BPF_MOV uses reserved fields\n");
3073 /* check src operand */
3074 err = check_reg_arg(env, insn->src_reg, SRC_OP);
3078 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
3079 verbose(env, "BPF_MOV uses reserved fields\n");
3084 /* check dest operand */
3085 err = check_reg_arg(env, insn->dst_reg, DST_OP);
3089 if (BPF_SRC(insn->code) == BPF_X) {
3090 if (BPF_CLASS(insn->code) == BPF_ALU64) {
3092 * copy register state to dest reg
3094 regs[insn->dst_reg] = regs[insn->src_reg];
3095 regs[insn->dst_reg].live |= REG_LIVE_WRITTEN;
3098 if (is_pointer_value(env, insn->src_reg)) {
3100 "R%d partial copy of pointer\n",
3104 mark_reg_unknown(env, regs, insn->dst_reg);
3105 coerce_reg_to_size(®s[insn->dst_reg], 4);
3109 * remember the value we stored into this reg
3111 regs[insn->dst_reg].type = SCALAR_VALUE;
3112 if (BPF_CLASS(insn->code) == BPF_ALU64) {
3113 __mark_reg_known(regs + insn->dst_reg,
3116 __mark_reg_known(regs + insn->dst_reg,
3121 } else if (opcode > BPF_END) {
3122 verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
3125 } else { /* all other ALU ops: and, sub, xor, add, ... */
3127 if (BPF_SRC(insn->code) == BPF_X) {
3128 if (insn->imm != 0 || insn->off != 0) {
3129 verbose(env, "BPF_ALU uses reserved fields\n");
3132 /* check src1 operand */
3133 err = check_reg_arg(env, insn->src_reg, SRC_OP);
3137 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
3138 verbose(env, "BPF_ALU uses reserved fields\n");
3143 /* check src2 operand */
3144 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
3148 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
3149 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
3150 verbose(env, "div by zero\n");
3154 if (opcode == BPF_ARSH && BPF_CLASS(insn->code) != BPF_ALU64) {
3155 verbose(env, "BPF_ARSH not supported for 32 bit ALU\n");
3159 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
3160 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
3161 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
3163 if (insn->imm < 0 || insn->imm >= size) {
3164 verbose(env, "invalid shift %d\n", insn->imm);
3169 /* check dest operand */
3170 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
3174 return adjust_reg_min_max_vals(env, insn);
3180 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
3181 struct bpf_reg_state *dst_reg,
3182 enum bpf_reg_type type,
3183 bool range_right_open)
3185 struct bpf_func_state *state = vstate->frame[vstate->curframe];
3186 struct bpf_reg_state *regs = state->regs, *reg;
3190 if (dst_reg->off < 0 ||
3191 (dst_reg->off == 0 && range_right_open))
3192 /* This doesn't give us any range */
3195 if (dst_reg->umax_value > MAX_PACKET_OFF ||
3196 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
3197 /* Risk of overflow. For instance, ptr + (1<<63) may be less
3198 * than pkt_end, but that's because it's also less than pkt.
3202 new_range = dst_reg->off;
3203 if (range_right_open)
3206 /* Examples for register markings:
3208 * pkt_data in dst register:
3212 * if (r2 > pkt_end) goto <handle exception>
3217 * if (r2 < pkt_end) goto <access okay>
3218 * <handle exception>
3221 * r2 == dst_reg, pkt_end == src_reg
3222 * r2=pkt(id=n,off=8,r=0)
3223 * r3=pkt(id=n,off=0,r=0)
3225 * pkt_data in src register:
3229 * if (pkt_end >= r2) goto <access okay>
3230 * <handle exception>
3234 * if (pkt_end <= r2) goto <handle exception>
3238 * pkt_end == dst_reg, r2 == src_reg
3239 * r2=pkt(id=n,off=8,r=0)
3240 * r3=pkt(id=n,off=0,r=0)
3242 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
3243 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
3244 * and [r3, r3 + 8-1) respectively is safe to access depending on
3248 /* If our ids match, then we must have the same max_value. And we
3249 * don't care about the other reg's fixed offset, since if it's too big
3250 * the range won't allow anything.
3251 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
3253 for (i = 0; i < MAX_BPF_REG; i++)
3254 if (regs[i].type == type && regs[i].id == dst_reg->id)
3255 /* keep the maximum range already checked */
3256 regs[i].range = max(regs[i].range, new_range);
3258 for (j = 0; j <= vstate->curframe; j++) {
3259 state = vstate->frame[j];
3260 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
3261 if (state->stack[i].slot_type[0] != STACK_SPILL)
3263 reg = &state->stack[i].spilled_ptr;
3264 if (reg->type == type && reg->id == dst_reg->id)
3265 reg->range = max(reg->range, new_range);
3270 /* Adjusts the register min/max values in the case that the dst_reg is the
3271 * variable register that we are working on, and src_reg is a constant or we're
3272 * simply doing a BPF_K check.
3273 * In JEQ/JNE cases we also adjust the var_off values.
3275 static void reg_set_min_max(struct bpf_reg_state *true_reg,
3276 struct bpf_reg_state *false_reg, u64 val,
3279 /* If the dst_reg is a pointer, we can't learn anything about its
3280 * variable offset from the compare (unless src_reg were a pointer into
3281 * the same object, but we don't bother with that.
3282 * Since false_reg and true_reg have the same type by construction, we
3283 * only need to check one of them for pointerness.
3285 if (__is_pointer_value(false, false_reg))
3290 /* If this is false then we know nothing Jon Snow, but if it is
3291 * true then we know for sure.
3293 __mark_reg_known(true_reg, val);
3296 /* If this is true we know nothing Jon Snow, but if it is false
3297 * we know the value for sure;
3299 __mark_reg_known(false_reg, val);
3302 false_reg->umax_value = min(false_reg->umax_value, val);
3303 true_reg->umin_value = max(true_reg->umin_value, val + 1);
3306 false_reg->smax_value = min_t(s64, false_reg->smax_value, val);
3307 true_reg->smin_value = max_t(s64, true_reg->smin_value, val + 1);
3310 false_reg->umin_value = max(false_reg->umin_value, val);
3311 true_reg->umax_value = min(true_reg->umax_value, val - 1);
3314 false_reg->smin_value = max_t(s64, false_reg->smin_value, val);
3315 true_reg->smax_value = min_t(s64, true_reg->smax_value, val - 1);
3318 false_reg->umax_value = min(false_reg->umax_value, val - 1);
3319 true_reg->umin_value = max(true_reg->umin_value, val);
3322 false_reg->smax_value = min_t(s64, false_reg->smax_value, val - 1);
3323 true_reg->smin_value = max_t(s64, true_reg->smin_value, val);
3326 false_reg->umin_value = max(false_reg->umin_value, val + 1);
3327 true_reg->umax_value = min(true_reg->umax_value, val);
3330 false_reg->smin_value = max_t(s64, false_reg->smin_value, val + 1);
3331 true_reg->smax_value = min_t(s64, true_reg->smax_value, val);
3337 __reg_deduce_bounds(false_reg);
3338 __reg_deduce_bounds(true_reg);
3339 /* We might have learned some bits from the bounds. */
3340 __reg_bound_offset(false_reg);
3341 __reg_bound_offset(true_reg);
3342 /* Intersecting with the old var_off might have improved our bounds
3343 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
3344 * then new var_off is (0; 0x7f...fc) which improves our umax.
3346 __update_reg_bounds(false_reg);
3347 __update_reg_bounds(true_reg);
3350 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
3353 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
3354 struct bpf_reg_state *false_reg, u64 val,
3357 if (__is_pointer_value(false, false_reg))
3362 /* If this is false then we know nothing Jon Snow, but if it is
3363 * true then we know for sure.
3365 __mark_reg_known(true_reg, val);
3368 /* If this is true we know nothing Jon Snow, but if it is false
3369 * we know the value for sure;
3371 __mark_reg_known(false_reg, val);
3374 true_reg->umax_value = min(true_reg->umax_value, val - 1);
3375 false_reg->umin_value = max(false_reg->umin_value, val);
3378 true_reg->smax_value = min_t(s64, true_reg->smax_value, val - 1);
3379 false_reg->smin_value = max_t(s64, false_reg->smin_value, val);
3382 true_reg->umin_value = max(true_reg->umin_value, val + 1);
3383 false_reg->umax_value = min(false_reg->umax_value, val);
3386 true_reg->smin_value = max_t(s64, true_reg->smin_value, val + 1);
3387 false_reg->smax_value = min_t(s64, false_reg->smax_value, val);
3390 true_reg->umax_value = min(true_reg->umax_value, val);
3391 false_reg->umin_value = max(false_reg->umin_value, val + 1);
3394 true_reg->smax_value = min_t(s64, true_reg->smax_value, val);
3395 false_reg->smin_value = max_t(s64, false_reg->smin_value, val + 1);
3398 true_reg->umin_value = max(true_reg->umin_value, val);
3399 false_reg->umax_value = min(false_reg->umax_value, val - 1);
3402 true_reg->smin_value = max_t(s64, true_reg->smin_value, val);
3403 false_reg->smax_value = min_t(s64, false_reg->smax_value, val - 1);
3409 __reg_deduce_bounds(false_reg);
3410 __reg_deduce_bounds(true_reg);
3411 /* We might have learned some bits from the bounds. */
3412 __reg_bound_offset(false_reg);
3413 __reg_bound_offset(true_reg);
3414 /* Intersecting with the old var_off might have improved our bounds
3415 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
3416 * then new var_off is (0; 0x7f...fc) which improves our umax.
3418 __update_reg_bounds(false_reg);
3419 __update_reg_bounds(true_reg);
3422 /* Regs are known to be equal, so intersect their min/max/var_off */
3423 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
3424 struct bpf_reg_state *dst_reg)
3426 src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
3427 dst_reg->umin_value);
3428 src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
3429 dst_reg->umax_value);
3430 src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
3431 dst_reg->smin_value);
3432 src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
3433 dst_reg->smax_value);
3434 src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
3436 /* We might have learned new bounds from the var_off. */
3437 __update_reg_bounds(src_reg);
3438 __update_reg_bounds(dst_reg);
3439 /* We might have learned something about the sign bit. */
3440 __reg_deduce_bounds(src_reg);
3441 __reg_deduce_bounds(dst_reg);
3442 /* We might have learned some bits from the bounds. */
3443 __reg_bound_offset(src_reg);
3444 __reg_bound_offset(dst_reg);
3445 /* Intersecting with the old var_off might have improved our bounds
3446 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
3447 * then new var_off is (0; 0x7f...fc) which improves our umax.
3449 __update_reg_bounds(src_reg);
3450 __update_reg_bounds(dst_reg);
3453 static void reg_combine_min_max(struct bpf_reg_state *true_src,
3454 struct bpf_reg_state *true_dst,
3455 struct bpf_reg_state *false_src,
3456 struct bpf_reg_state *false_dst,
3461 __reg_combine_min_max(true_src, true_dst);
3464 __reg_combine_min_max(false_src, false_dst);
3469 static void mark_map_reg(struct bpf_reg_state *regs, u32 regno, u32 id,
3472 struct bpf_reg_state *reg = ®s[regno];
3474 if (reg->type == PTR_TO_MAP_VALUE_OR_NULL && reg->id == id) {
3475 /* Old offset (both fixed and variable parts) should
3476 * have been known-zero, because we don't allow pointer
3477 * arithmetic on pointers that might be NULL.
3479 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value ||
3480 !tnum_equals_const(reg->var_off, 0) ||
3482 __mark_reg_known_zero(reg);
3486 reg->type = SCALAR_VALUE;
3487 } else if (reg->map_ptr->inner_map_meta) {
3488 reg->type = CONST_PTR_TO_MAP;
3489 reg->map_ptr = reg->map_ptr->inner_map_meta;
3491 reg->type = PTR_TO_MAP_VALUE;
3493 /* We don't need id from this point onwards anymore, thus we
3494 * should better reset it, so that state pruning has chances
3501 /* The logic is similar to find_good_pkt_pointers(), both could eventually
3502 * be folded together at some point.
3504 static void mark_map_regs(struct bpf_verifier_state *vstate, u32 regno,
3507 struct bpf_func_state *state = vstate->frame[vstate->curframe];
3508 struct bpf_reg_state *regs = state->regs;
3509 u32 id = regs[regno].id;
3512 for (i = 0; i < MAX_BPF_REG; i++)
3513 mark_map_reg(regs, i, id, is_null);
3515 for (j = 0; j <= vstate->curframe; j++) {
3516 state = vstate->frame[j];
3517 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
3518 if (state->stack[i].slot_type[0] != STACK_SPILL)
3520 mark_map_reg(&state->stack[i].spilled_ptr, 0, id, is_null);
3525 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
3526 struct bpf_reg_state *dst_reg,
3527 struct bpf_reg_state *src_reg,
3528 struct bpf_verifier_state *this_branch,
3529 struct bpf_verifier_state *other_branch)
3531 if (BPF_SRC(insn->code) != BPF_X)
3534 switch (BPF_OP(insn->code)) {
3536 if ((dst_reg->type == PTR_TO_PACKET &&
3537 src_reg->type == PTR_TO_PACKET_END) ||
3538 (dst_reg->type == PTR_TO_PACKET_META &&
3539 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
3540 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
3541 find_good_pkt_pointers(this_branch, dst_reg,
3542 dst_reg->type, false);
3543 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
3544 src_reg->type == PTR_TO_PACKET) ||
3545 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
3546 src_reg->type == PTR_TO_PACKET_META)) {
3547 /* pkt_end > pkt_data', pkt_data > pkt_meta' */
3548 find_good_pkt_pointers(other_branch, src_reg,
3549 src_reg->type, true);
3555 if ((dst_reg->type == PTR_TO_PACKET &&
3556 src_reg->type == PTR_TO_PACKET_END) ||
3557 (dst_reg->type == PTR_TO_PACKET_META &&
3558 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
3559 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
3560 find_good_pkt_pointers(other_branch, dst_reg,
3561 dst_reg->type, true);
3562 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
3563 src_reg->type == PTR_TO_PACKET) ||
3564 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
3565 src_reg->type == PTR_TO_PACKET_META)) {
3566 /* pkt_end < pkt_data', pkt_data > pkt_meta' */
3567 find_good_pkt_pointers(this_branch, src_reg,
3568 src_reg->type, false);
3574 if ((dst_reg->type == PTR_TO_PACKET &&
3575 src_reg->type == PTR_TO_PACKET_END) ||
3576 (dst_reg->type == PTR_TO_PACKET_META &&
3577 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
3578 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
3579 find_good_pkt_pointers(this_branch, dst_reg,
3580 dst_reg->type, true);
3581 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
3582 src_reg->type == PTR_TO_PACKET) ||
3583 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
3584 src_reg->type == PTR_TO_PACKET_META)) {
3585 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
3586 find_good_pkt_pointers(other_branch, src_reg,
3587 src_reg->type, false);
3593 if ((dst_reg->type == PTR_TO_PACKET &&
3594 src_reg->type == PTR_TO_PACKET_END) ||
3595 (dst_reg->type == PTR_TO_PACKET_META &&
3596 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
3597 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
3598 find_good_pkt_pointers(other_branch, dst_reg,
3599 dst_reg->type, false);
3600 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
3601 src_reg->type == PTR_TO_PACKET) ||
3602 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
3603 src_reg->type == PTR_TO_PACKET_META)) {
3604 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
3605 find_good_pkt_pointers(this_branch, src_reg,
3606 src_reg->type, true);
3618 static int check_cond_jmp_op(struct bpf_verifier_env *env,
3619 struct bpf_insn *insn, int *insn_idx)
3621 struct bpf_verifier_state *this_branch = env->cur_state;
3622 struct bpf_verifier_state *other_branch;
3623 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
3624 struct bpf_reg_state *dst_reg, *other_branch_regs;
3625 u8 opcode = BPF_OP(insn->code);
3628 if (opcode > BPF_JSLE) {
3629 verbose(env, "invalid BPF_JMP opcode %x\n", opcode);
3633 if (BPF_SRC(insn->code) == BPF_X) {
3634 if (insn->imm != 0) {
3635 verbose(env, "BPF_JMP uses reserved fields\n");
3639 /* check src1 operand */
3640 err = check_reg_arg(env, insn->src_reg, SRC_OP);
3644 if (is_pointer_value(env, insn->src_reg)) {
3645 verbose(env, "R%d pointer comparison prohibited\n",
3650 if (insn->src_reg != BPF_REG_0) {
3651 verbose(env, "BPF_JMP uses reserved fields\n");
3656 /* check src2 operand */
3657 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
3661 dst_reg = ®s[insn->dst_reg];
3663 /* detect if R == 0 where R was initialized to zero earlier */
3664 if (BPF_SRC(insn->code) == BPF_K &&
3665 (opcode == BPF_JEQ || opcode == BPF_JNE) &&
3666 dst_reg->type == SCALAR_VALUE &&
3667 tnum_is_const(dst_reg->var_off)) {
3668 if ((opcode == BPF_JEQ && dst_reg->var_off.value == insn->imm) ||
3669 (opcode == BPF_JNE && dst_reg->var_off.value != insn->imm)) {
3670 /* if (imm == imm) goto pc+off;
3671 * only follow the goto, ignore fall-through
3673 *insn_idx += insn->off;
3676 /* if (imm != imm) goto pc+off;
3677 * only follow fall-through branch, since
3678 * that's where the program will go
3684 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx);
3687 other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
3689 /* detect if we are comparing against a constant value so we can adjust
3690 * our min/max values for our dst register.
3691 * this is only legit if both are scalars (or pointers to the same
3692 * object, I suppose, but we don't support that right now), because
3693 * otherwise the different base pointers mean the offsets aren't
3696 if (BPF_SRC(insn->code) == BPF_X) {
3697 if (dst_reg->type == SCALAR_VALUE &&
3698 regs[insn->src_reg].type == SCALAR_VALUE) {
3699 if (tnum_is_const(regs[insn->src_reg].var_off))
3700 reg_set_min_max(&other_branch_regs[insn->dst_reg],
3701 dst_reg, regs[insn->src_reg].var_off.value,
3703 else if (tnum_is_const(dst_reg->var_off))
3704 reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
3705 ®s[insn->src_reg],
3706 dst_reg->var_off.value, opcode);
3707 else if (opcode == BPF_JEQ || opcode == BPF_JNE)
3708 /* Comparing for equality, we can combine knowledge */
3709 reg_combine_min_max(&other_branch_regs[insn->src_reg],
3710 &other_branch_regs[insn->dst_reg],
3711 ®s[insn->src_reg],
3712 ®s[insn->dst_reg], opcode);
3714 } else if (dst_reg->type == SCALAR_VALUE) {
3715 reg_set_min_max(&other_branch_regs[insn->dst_reg],
3716 dst_reg, insn->imm, opcode);
3719 /* detect if R == 0 where R is returned from bpf_map_lookup_elem() */
3720 if (BPF_SRC(insn->code) == BPF_K &&
3721 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
3722 dst_reg->type == PTR_TO_MAP_VALUE_OR_NULL) {
3723 /* Mark all identical map registers in each branch as either
3724 * safe or unknown depending R == 0 or R != 0 conditional.
3726 mark_map_regs(this_branch, insn->dst_reg, opcode == BPF_JNE);
3727 mark_map_regs(other_branch, insn->dst_reg, opcode == BPF_JEQ);
3728 } else if (!try_match_pkt_pointers(insn, dst_reg, ®s[insn->src_reg],
3729 this_branch, other_branch) &&
3730 is_pointer_value(env, insn->dst_reg)) {
3731 verbose(env, "R%d pointer comparison prohibited\n",
3736 print_verifier_state(env, this_branch->frame[this_branch->curframe]);
3740 /* return the map pointer stored inside BPF_LD_IMM64 instruction */
3741 static struct bpf_map *ld_imm64_to_map_ptr(struct bpf_insn *insn)
3743 u64 imm64 = ((u64) (u32) insn[0].imm) | ((u64) (u32) insn[1].imm) << 32;
3745 return (struct bpf_map *) (unsigned long) imm64;
3748 /* verify BPF_LD_IMM64 instruction */
3749 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
3751 struct bpf_reg_state *regs = cur_regs(env);
3754 if (BPF_SIZE(insn->code) != BPF_DW) {
3755 verbose(env, "invalid BPF_LD_IMM insn\n");
3758 if (insn->off != 0) {
3759 verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
3763 err = check_reg_arg(env, insn->dst_reg, DST_OP);
3767 if (insn->src_reg == 0) {
3768 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
3770 regs[insn->dst_reg].type = SCALAR_VALUE;
3771 __mark_reg_known(®s[insn->dst_reg], imm);
3775 /* replace_map_fd_with_map_ptr() should have caught bad ld_imm64 */
3776 BUG_ON(insn->src_reg != BPF_PSEUDO_MAP_FD);
3778 regs[insn->dst_reg].type = CONST_PTR_TO_MAP;
3779 regs[insn->dst_reg].map_ptr = ld_imm64_to_map_ptr(insn);
3783 static bool may_access_skb(enum bpf_prog_type type)
3786 case BPF_PROG_TYPE_SOCKET_FILTER:
3787 case BPF_PROG_TYPE_SCHED_CLS:
3788 case BPF_PROG_TYPE_SCHED_ACT:
3795 /* verify safety of LD_ABS|LD_IND instructions:
3796 * - they can only appear in the programs where ctx == skb
3797 * - since they are wrappers of function calls, they scratch R1-R5 registers,
3798 * preserve R6-R9, and store return value into R0
3801 * ctx == skb == R6 == CTX
3804 * SRC == any register
3805 * IMM == 32-bit immediate
3808 * R0 - 8/16/32-bit skb data converted to cpu endianness
3810 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
3812 struct bpf_reg_state *regs = cur_regs(env);
3813 u8 mode = BPF_MODE(insn->code);
3816 if (!may_access_skb(env->prog->type)) {
3817 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
3821 if (env->subprog_cnt) {
3822 /* when program has LD_ABS insn JITs and interpreter assume
3823 * that r1 == ctx == skb which is not the case for callees
3824 * that can have arbitrary arguments. It's problematic
3825 * for main prog as well since JITs would need to analyze
3826 * all functions in order to make proper register save/restore
3827 * decisions in the main prog. Hence disallow LD_ABS with calls
3829 verbose(env, "BPF_LD_[ABS|IND] instructions cannot be mixed with bpf-to-bpf calls\n");
3833 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
3834 BPF_SIZE(insn->code) == BPF_DW ||
3835 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
3836 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
3840 /* check whether implicit source operand (register R6) is readable */
3841 err = check_reg_arg(env, BPF_REG_6, SRC_OP);
3845 if (regs[BPF_REG_6].type != PTR_TO_CTX) {
3847 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
3851 if (mode == BPF_IND) {
3852 /* check explicit source operand */
3853 err = check_reg_arg(env, insn->src_reg, SRC_OP);
3858 /* reset caller saved regs to unreadable */
3859 for (i = 0; i < CALLER_SAVED_REGS; i++) {
3860 mark_reg_not_init(env, regs, caller_saved[i]);
3861 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
3864 /* mark destination R0 register as readable, since it contains
3865 * the value fetched from the packet.
3866 * Already marked as written above.
3868 mark_reg_unknown(env, regs, BPF_REG_0);
3872 static int check_return_code(struct bpf_verifier_env *env)
3874 struct bpf_reg_state *reg;
3875 struct tnum range = tnum_range(0, 1);
3877 switch (env->prog->type) {
3878 case BPF_PROG_TYPE_CGROUP_SKB:
3879 case BPF_PROG_TYPE_CGROUP_SOCK:
3880 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
3881 case BPF_PROG_TYPE_SOCK_OPS:
3882 case BPF_PROG_TYPE_CGROUP_DEVICE:
3888 reg = cur_regs(env) + BPF_REG_0;
3889 if (reg->type != SCALAR_VALUE) {
3890 verbose(env, "At program exit the register R0 is not a known value (%s)\n",
3891 reg_type_str[reg->type]);
3895 if (!tnum_in(range, reg->var_off)) {
3896 verbose(env, "At program exit the register R0 ");
3897 if (!tnum_is_unknown(reg->var_off)) {
3900 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3901 verbose(env, "has value %s", tn_buf);
3903 verbose(env, "has unknown scalar value");
3905 verbose(env, " should have been 0 or 1\n");
3911 /* non-recursive DFS pseudo code
3912 * 1 procedure DFS-iterative(G,v):
3913 * 2 label v as discovered
3914 * 3 let S be a stack
3916 * 5 while S is not empty
3918 * 7 if t is what we're looking for:
3920 * 9 for all edges e in G.adjacentEdges(t) do
3921 * 10 if edge e is already labelled
3922 * 11 continue with the next edge
3923 * 12 w <- G.adjacentVertex(t,e)
3924 * 13 if vertex w is not discovered and not explored
3925 * 14 label e as tree-edge
3926 * 15 label w as discovered
3929 * 18 else if vertex w is discovered
3930 * 19 label e as back-edge
3932 * 21 // vertex w is explored
3933 * 22 label e as forward- or cross-edge
3934 * 23 label t as explored
3939 * 0x11 - discovered and fall-through edge labelled
3940 * 0x12 - discovered and fall-through and branch edges labelled
3951 #define STATE_LIST_MARK ((struct bpf_verifier_state_list *) -1L)
3953 static int *insn_stack; /* stack of insns to process */
3954 static int cur_stack; /* current stack index */
3955 static int *insn_state;
3957 /* t, w, e - match pseudo-code above:
3958 * t - index of current instruction
3959 * w - next instruction
3962 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env)
3964 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
3967 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
3970 if (w < 0 || w >= env->prog->len) {
3971 verbose(env, "jump out of range from insn %d to %d\n", t, w);
3976 /* mark branch target for state pruning */
3977 env->explored_states[w] = STATE_LIST_MARK;
3979 if (insn_state[w] == 0) {
3981 insn_state[t] = DISCOVERED | e;
3982 insn_state[w] = DISCOVERED;
3983 if (cur_stack >= env->prog->len)
3985 insn_stack[cur_stack++] = w;
3987 } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
3988 verbose(env, "back-edge from insn %d to %d\n", t, w);
3990 } else if (insn_state[w] == EXPLORED) {
3991 /* forward- or cross-edge */
3992 insn_state[t] = DISCOVERED | e;
3994 verbose(env, "insn state internal bug\n");
4000 /* non-recursive depth-first-search to detect loops in BPF program
4001 * loop == back-edge in directed graph
4003 static int check_cfg(struct bpf_verifier_env *env)
4005 struct bpf_insn *insns = env->prog->insnsi;
4006 int insn_cnt = env->prog->len;
4010 ret = check_subprogs(env);
4014 insn_state = kcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
4018 insn_stack = kcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
4024 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
4025 insn_stack[0] = 0; /* 0 is the first instruction */
4031 t = insn_stack[cur_stack - 1];
4033 if (BPF_CLASS(insns[t].code) == BPF_JMP) {
4034 u8 opcode = BPF_OP(insns[t].code);
4036 if (opcode == BPF_EXIT) {
4038 } else if (opcode == BPF_CALL) {
4039 ret = push_insn(t, t + 1, FALLTHROUGH, env);
4044 if (t + 1 < insn_cnt)
4045 env->explored_states[t + 1] = STATE_LIST_MARK;
4046 if (insns[t].src_reg == BPF_PSEUDO_CALL) {
4047 env->explored_states[t] = STATE_LIST_MARK;
4048 ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env);
4054 } else if (opcode == BPF_JA) {
4055 if (BPF_SRC(insns[t].code) != BPF_K) {
4059 /* unconditional jump with single edge */
4060 ret = push_insn(t, t + insns[t].off + 1,
4066 /* tell verifier to check for equivalent states
4067 * after every call and jump
4069 if (t + 1 < insn_cnt)
4070 env->explored_states[t + 1] = STATE_LIST_MARK;
4072 /* conditional jump with two edges */
4073 env->explored_states[t] = STATE_LIST_MARK;
4074 ret = push_insn(t, t + 1, FALLTHROUGH, env);
4080 ret = push_insn(t, t + insns[t].off + 1, BRANCH, env);
4087 /* all other non-branch instructions with single
4090 ret = push_insn(t, t + 1, FALLTHROUGH, env);
4098 insn_state[t] = EXPLORED;
4099 if (cur_stack-- <= 0) {
4100 verbose(env, "pop stack internal bug\n");
4107 for (i = 0; i < insn_cnt; i++) {
4108 if (insn_state[i] != EXPLORED) {
4109 verbose(env, "unreachable insn %d\n", i);
4114 ret = 0; /* cfg looks good */
4122 /* check %cur's range satisfies %old's */
4123 static bool range_within(struct bpf_reg_state *old,
4124 struct bpf_reg_state *cur)
4126 return old->umin_value <= cur->umin_value &&
4127 old->umax_value >= cur->umax_value &&
4128 old->smin_value <= cur->smin_value &&
4129 old->smax_value >= cur->smax_value;
4132 /* Maximum number of register states that can exist at once */
4133 #define ID_MAP_SIZE (MAX_BPF_REG + MAX_BPF_STACK / BPF_REG_SIZE)
4139 /* If in the old state two registers had the same id, then they need to have
4140 * the same id in the new state as well. But that id could be different from
4141 * the old state, so we need to track the mapping from old to new ids.
4142 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
4143 * regs with old id 5 must also have new id 9 for the new state to be safe. But
4144 * regs with a different old id could still have new id 9, we don't care about
4146 * So we look through our idmap to see if this old id has been seen before. If
4147 * so, we require the new id to match; otherwise, we add the id pair to the map.
4149 static bool check_ids(u32 old_id, u32 cur_id, struct idpair *idmap)
4153 for (i = 0; i < ID_MAP_SIZE; i++) {
4154 if (!idmap[i].old) {
4155 /* Reached an empty slot; haven't seen this id before */
4156 idmap[i].old = old_id;
4157 idmap[i].cur = cur_id;
4160 if (idmap[i].old == old_id)
4161 return idmap[i].cur == cur_id;
4163 /* We ran out of idmap slots, which should be impossible */
4168 /* Returns true if (rold safe implies rcur safe) */
4169 static bool regsafe(struct bpf_reg_state *rold, struct bpf_reg_state *rcur,
4170 struct idpair *idmap)
4174 if (!(rold->live & REG_LIVE_READ))
4175 /* explored state didn't use this */
4178 equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, frameno)) == 0;
4180 if (rold->type == PTR_TO_STACK)
4181 /* two stack pointers are equal only if they're pointing to
4182 * the same stack frame, since fp-8 in foo != fp-8 in bar
4184 return equal && rold->frameno == rcur->frameno;
4189 if (rold->type == NOT_INIT)
4190 /* explored state can't have used this */
4192 if (rcur->type == NOT_INIT)
4194 switch (rold->type) {
4196 if (rcur->type == SCALAR_VALUE) {
4197 /* new val must satisfy old val knowledge */
4198 return range_within(rold, rcur) &&
4199 tnum_in(rold->var_off, rcur->var_off);
4201 /* We're trying to use a pointer in place of a scalar.
4202 * Even if the scalar was unbounded, this could lead to
4203 * pointer leaks because scalars are allowed to leak
4204 * while pointers are not. We could make this safe in
4205 * special cases if root is calling us, but it's
4206 * probably not worth the hassle.
4210 case PTR_TO_MAP_VALUE:
4211 /* If the new min/max/var_off satisfy the old ones and
4212 * everything else matches, we are OK.
4213 * We don't care about the 'id' value, because nothing
4214 * uses it for PTR_TO_MAP_VALUE (only for ..._OR_NULL)
4216 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
4217 range_within(rold, rcur) &&
4218 tnum_in(rold->var_off, rcur->var_off);
4219 case PTR_TO_MAP_VALUE_OR_NULL:
4220 /* a PTR_TO_MAP_VALUE could be safe to use as a
4221 * PTR_TO_MAP_VALUE_OR_NULL into the same map.
4222 * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
4223 * checked, doing so could have affected others with the same
4224 * id, and we can't check for that because we lost the id when
4225 * we converted to a PTR_TO_MAP_VALUE.
4227 if (rcur->type != PTR_TO_MAP_VALUE_OR_NULL)
4229 if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
4231 /* Check our ids match any regs they're supposed to */
4232 return check_ids(rold->id, rcur->id, idmap);
4233 case PTR_TO_PACKET_META:
4235 if (rcur->type != rold->type)
4237 /* We must have at least as much range as the old ptr
4238 * did, so that any accesses which were safe before are
4239 * still safe. This is true even if old range < old off,
4240 * since someone could have accessed through (ptr - k), or
4241 * even done ptr -= k in a register, to get a safe access.
4243 if (rold->range > rcur->range)
4245 /* If the offsets don't match, we can't trust our alignment;
4246 * nor can we be sure that we won't fall out of range.
4248 if (rold->off != rcur->off)
4250 /* id relations must be preserved */
4251 if (rold->id && !check_ids(rold->id, rcur->id, idmap))
4253 /* new val must satisfy old val knowledge */
4254 return range_within(rold, rcur) &&
4255 tnum_in(rold->var_off, rcur->var_off);
4257 case CONST_PTR_TO_MAP:
4258 case PTR_TO_PACKET_END:
4259 /* Only valid matches are exact, which memcmp() above
4260 * would have accepted
4263 /* Don't know what's going on, just say it's not safe */
4267 /* Shouldn't get here; if we do, say it's not safe */
4272 static bool stacksafe(struct bpf_func_state *old,
4273 struct bpf_func_state *cur,
4274 struct idpair *idmap)
4278 /* if explored stack has more populated slots than current stack
4279 * such stacks are not equivalent
4281 if (old->allocated_stack > cur->allocated_stack)
4284 /* walk slots of the explored stack and ignore any additional
4285 * slots in the current stack, since explored(safe) state
4288 for (i = 0; i < old->allocated_stack; i++) {
4289 spi = i / BPF_REG_SIZE;
4291 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ))
4292 /* explored state didn't use this */
4295 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
4297 /* if old state was safe with misc data in the stack
4298 * it will be safe with zero-initialized stack.
4299 * The opposite is not true
4301 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
4302 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
4304 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
4305 cur->stack[spi].slot_type[i % BPF_REG_SIZE])
4306 /* Ex: old explored (safe) state has STACK_SPILL in
4307 * this stack slot, but current has has STACK_MISC ->
4308 * this verifier states are not equivalent,
4309 * return false to continue verification of this path
4312 if (i % BPF_REG_SIZE)
4314 if (old->stack[spi].slot_type[0] != STACK_SPILL)
4316 if (!regsafe(&old->stack[spi].spilled_ptr,
4317 &cur->stack[spi].spilled_ptr,
4319 /* when explored and current stack slot are both storing
4320 * spilled registers, check that stored pointers types
4321 * are the same as well.
4322 * Ex: explored safe path could have stored
4323 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
4324 * but current path has stored:
4325 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
4326 * such verifier states are not equivalent.
4327 * return false to continue verification of this path
4334 /* compare two verifier states
4336 * all states stored in state_list are known to be valid, since
4337 * verifier reached 'bpf_exit' instruction through them
4339 * this function is called when verifier exploring different branches of
4340 * execution popped from the state stack. If it sees an old state that has
4341 * more strict register state and more strict stack state then this execution
4342 * branch doesn't need to be explored further, since verifier already
4343 * concluded that more strict state leads to valid finish.
4345 * Therefore two states are equivalent if register state is more conservative
4346 * and explored stack state is more conservative than the current one.
4349 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
4350 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
4352 * In other words if current stack state (one being explored) has more
4353 * valid slots than old one that already passed validation, it means
4354 * the verifier can stop exploring and conclude that current state is valid too
4356 * Similarly with registers. If explored state has register type as invalid
4357 * whereas register type in current state is meaningful, it means that
4358 * the current state will reach 'bpf_exit' instruction safely
4360 static bool func_states_equal(struct bpf_func_state *old,
4361 struct bpf_func_state *cur)
4363 struct idpair *idmap;
4367 idmap = kcalloc(ID_MAP_SIZE, sizeof(struct idpair), GFP_KERNEL);
4368 /* If we failed to allocate the idmap, just say it's not safe */
4372 for (i = 0; i < MAX_BPF_REG; i++) {
4373 if (!regsafe(&old->regs[i], &cur->regs[i], idmap))
4377 if (!stacksafe(old, cur, idmap))
4385 static bool states_equal(struct bpf_verifier_env *env,
4386 struct bpf_verifier_state *old,
4387 struct bpf_verifier_state *cur)
4391 if (old->curframe != cur->curframe)
4394 /* for states to be equal callsites have to be the same
4395 * and all frame states need to be equivalent
4397 for (i = 0; i <= old->curframe; i++) {
4398 if (old->frame[i]->callsite != cur->frame[i]->callsite)
4400 if (!func_states_equal(old->frame[i], cur->frame[i]))
4406 /* A write screens off any subsequent reads; but write marks come from the
4407 * straight-line code between a state and its parent. When we arrive at an
4408 * equivalent state (jump target or such) we didn't arrive by the straight-line
4409 * code, so read marks in the state must propagate to the parent regardless
4410 * of the state's write marks. That's what 'parent == state->parent' comparison
4411 * in mark_reg_read() and mark_stack_slot_read() is for.
4413 static int propagate_liveness(struct bpf_verifier_env *env,
4414 const struct bpf_verifier_state *vstate,
4415 struct bpf_verifier_state *vparent)
4417 int i, frame, err = 0;
4418 struct bpf_func_state *state, *parent;
4420 if (vparent->curframe != vstate->curframe) {
4421 WARN(1, "propagate_live: parent frame %d current frame %d\n",
4422 vparent->curframe, vstate->curframe);
4425 /* Propagate read liveness of registers... */
4426 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
4427 /* We don't need to worry about FP liveness because it's read-only */
4428 for (i = 0; i < BPF_REG_FP; i++) {
4429 if (vparent->frame[vparent->curframe]->regs[i].live & REG_LIVE_READ)
4431 if (vstate->frame[vstate->curframe]->regs[i].live & REG_LIVE_READ) {
4432 err = mark_reg_read(env, vstate, vparent, i);
4438 /* ... and stack slots */
4439 for (frame = 0; frame <= vstate->curframe; frame++) {
4440 state = vstate->frame[frame];
4441 parent = vparent->frame[frame];
4442 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
4443 i < parent->allocated_stack / BPF_REG_SIZE; i++) {
4444 if (parent->stack[i].spilled_ptr.live & REG_LIVE_READ)
4446 if (state->stack[i].spilled_ptr.live & REG_LIVE_READ)
4447 mark_stack_slot_read(env, vstate, vparent, i, frame);
4453 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
4455 struct bpf_verifier_state_list *new_sl;
4456 struct bpf_verifier_state_list *sl;
4457 struct bpf_verifier_state *cur = env->cur_state;
4460 sl = env->explored_states[insn_idx];
4462 /* this 'insn_idx' instruction wasn't marked, so we will not
4463 * be doing state search here
4467 while (sl != STATE_LIST_MARK) {
4468 if (states_equal(env, &sl->state, cur)) {
4469 /* reached equivalent register/stack state,
4471 * Registers read by the continuation are read by us.
4472 * If we have any write marks in env->cur_state, they
4473 * will prevent corresponding reads in the continuation
4474 * from reaching our parent (an explored_state). Our
4475 * own state will get the read marks recorded, but
4476 * they'll be immediately forgotten as we're pruning
4477 * this state and will pop a new one.
4479 err = propagate_liveness(env, &sl->state, cur);
4487 /* there were no equivalent states, remember current one.
4488 * technically the current state is not proven to be safe yet,
4489 * but it will either reach outer most bpf_exit (which means it's safe)
4490 * or it will be rejected. Since there are no loops, we won't be
4491 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
4492 * again on the way to bpf_exit
4494 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
4498 /* add new state to the head of linked list */
4499 err = copy_verifier_state(&new_sl->state, cur);
4501 free_verifier_state(&new_sl->state, false);
4505 new_sl->next = env->explored_states[insn_idx];
4506 env->explored_states[insn_idx] = new_sl;
4507 /* connect new state to parentage chain */
4508 cur->parent = &new_sl->state;
4509 /* clear write marks in current state: the writes we did are not writes
4510 * our child did, so they don't screen off its reads from us.
4511 * (There are no read marks in current state, because reads always mark
4512 * their parent and current state never has children yet. Only
4513 * explored_states can get read marks.)
4515 for (i = 0; i < BPF_REG_FP; i++)
4516 cur->frame[cur->curframe]->regs[i].live = REG_LIVE_NONE;
4518 /* all stack frames are accessible from callee, clear them all */
4519 for (j = 0; j <= cur->curframe; j++) {
4520 struct bpf_func_state *frame = cur->frame[j];
4522 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++)
4523 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
4528 static int do_check(struct bpf_verifier_env *env)
4530 struct bpf_verifier_state *state;
4531 struct bpf_insn *insns = env->prog->insnsi;
4532 struct bpf_reg_state *regs;
4533 int insn_cnt = env->prog->len, i;
4534 int insn_idx, prev_insn_idx = 0;
4535 int insn_processed = 0;
4536 bool do_print_state = false;
4538 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
4541 state->curframe = 0;
4542 state->parent = NULL;
4543 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
4544 if (!state->frame[0]) {
4548 env->cur_state = state;
4549 init_func_state(env, state->frame[0],
4550 BPF_MAIN_FUNC /* callsite */,
4552 0 /* subprogno, zero == main subprog */);
4555 struct bpf_insn *insn;
4559 if (insn_idx >= insn_cnt) {
4560 verbose(env, "invalid insn idx %d insn_cnt %d\n",
4561 insn_idx, insn_cnt);
4565 insn = &insns[insn_idx];
4566 class = BPF_CLASS(insn->code);
4568 if (++insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
4570 "BPF program is too large. Processed %d insn\n",
4575 err = is_state_visited(env, insn_idx);
4579 /* found equivalent state, can prune the search */
4580 if (env->log.level) {
4582 verbose(env, "\nfrom %d to %d: safe\n",
4583 prev_insn_idx, insn_idx);
4585 verbose(env, "%d: safe\n", insn_idx);
4587 goto process_bpf_exit;
4593 if (env->log.level > 1 || (env->log.level && do_print_state)) {
4594 if (env->log.level > 1)
4595 verbose(env, "%d:", insn_idx);
4597 verbose(env, "\nfrom %d to %d:",
4598 prev_insn_idx, insn_idx);
4599 print_verifier_state(env, state->frame[state->curframe]);
4600 do_print_state = false;
4603 if (env->log.level) {
4604 const struct bpf_insn_cbs cbs = {
4605 .cb_print = verbose,
4606 .private_data = env,
4609 verbose(env, "%d: ", insn_idx);
4610 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
4613 if (bpf_prog_is_dev_bound(env->prog->aux)) {
4614 err = bpf_prog_offload_verify_insn(env, insn_idx,
4620 regs = cur_regs(env);
4621 env->insn_aux_data[insn_idx].seen = true;
4622 if (class == BPF_ALU || class == BPF_ALU64) {
4623 err = check_alu_op(env, insn);
4627 } else if (class == BPF_LDX) {
4628 enum bpf_reg_type *prev_src_type, src_reg_type;
4630 /* check for reserved fields is already done */
4632 /* check src operand */
4633 err = check_reg_arg(env, insn->src_reg, SRC_OP);
4637 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
4641 src_reg_type = regs[insn->src_reg].type;
4643 /* check that memory (src_reg + off) is readable,
4644 * the state of dst_reg will be updated by this func
4646 err = check_mem_access(env, insn_idx, insn->src_reg, insn->off,
4647 BPF_SIZE(insn->code), BPF_READ,
4648 insn->dst_reg, false);
4652 prev_src_type = &env->insn_aux_data[insn_idx].ptr_type;
4654 if (*prev_src_type == NOT_INIT) {
4656 * dst_reg = *(u32 *)(src_reg + off)
4657 * save type to validate intersecting paths
4659 *prev_src_type = src_reg_type;
4661 } else if (src_reg_type != *prev_src_type &&
4662 (src_reg_type == PTR_TO_CTX ||
4663 *prev_src_type == PTR_TO_CTX)) {
4664 /* ABuser program is trying to use the same insn
4665 * dst_reg = *(u32*) (src_reg + off)
4666 * with different pointer types:
4667 * src_reg == ctx in one branch and
4668 * src_reg == stack|map in some other branch.
4671 verbose(env, "same insn cannot be used with different pointers\n");
4675 } else if (class == BPF_STX) {
4676 enum bpf_reg_type *prev_dst_type, dst_reg_type;
4678 if (BPF_MODE(insn->code) == BPF_XADD) {
4679 err = check_xadd(env, insn_idx, insn);
4686 /* check src1 operand */
4687 err = check_reg_arg(env, insn->src_reg, SRC_OP);
4690 /* check src2 operand */
4691 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
4695 dst_reg_type = regs[insn->dst_reg].type;
4697 /* check that memory (dst_reg + off) is writeable */
4698 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
4699 BPF_SIZE(insn->code), BPF_WRITE,
4700 insn->src_reg, false);
4704 prev_dst_type = &env->insn_aux_data[insn_idx].ptr_type;
4706 if (*prev_dst_type == NOT_INIT) {
4707 *prev_dst_type = dst_reg_type;
4708 } else if (dst_reg_type != *prev_dst_type &&
4709 (dst_reg_type == PTR_TO_CTX ||
4710 *prev_dst_type == PTR_TO_CTX)) {
4711 verbose(env, "same insn cannot be used with different pointers\n");
4715 } else if (class == BPF_ST) {
4716 if (BPF_MODE(insn->code) != BPF_MEM ||
4717 insn->src_reg != BPF_REG_0) {
4718 verbose(env, "BPF_ST uses reserved fields\n");
4721 /* check src operand */
4722 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
4726 if (is_ctx_reg(env, insn->dst_reg)) {
4727 verbose(env, "BPF_ST stores into R%d context is not allowed\n",
4732 /* check that memory (dst_reg + off) is writeable */
4733 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
4734 BPF_SIZE(insn->code), BPF_WRITE,
4739 } else if (class == BPF_JMP) {
4740 u8 opcode = BPF_OP(insn->code);
4742 if (opcode == BPF_CALL) {
4743 if (BPF_SRC(insn->code) != BPF_K ||
4745 (insn->src_reg != BPF_REG_0 &&
4746 insn->src_reg != BPF_PSEUDO_CALL) ||
4747 insn->dst_reg != BPF_REG_0) {
4748 verbose(env, "BPF_CALL uses reserved fields\n");
4752 if (insn->src_reg == BPF_PSEUDO_CALL)
4753 err = check_func_call(env, insn, &insn_idx);
4755 err = check_helper_call(env, insn->imm, insn_idx);
4759 } else if (opcode == BPF_JA) {
4760 if (BPF_SRC(insn->code) != BPF_K ||
4762 insn->src_reg != BPF_REG_0 ||
4763 insn->dst_reg != BPF_REG_0) {
4764 verbose(env, "BPF_JA uses reserved fields\n");
4768 insn_idx += insn->off + 1;
4771 } else if (opcode == BPF_EXIT) {
4772 if (BPF_SRC(insn->code) != BPF_K ||
4774 insn->src_reg != BPF_REG_0 ||
4775 insn->dst_reg != BPF_REG_0) {
4776 verbose(env, "BPF_EXIT uses reserved fields\n");
4780 if (state->curframe) {
4781 /* exit from nested function */
4782 prev_insn_idx = insn_idx;
4783 err = prepare_func_exit(env, &insn_idx);
4786 do_print_state = true;
4790 /* eBPF calling convetion is such that R0 is used
4791 * to return the value from eBPF program.
4792 * Make sure that it's readable at this time
4793 * of bpf_exit, which means that program wrote
4794 * something into it earlier
4796 err = check_reg_arg(env, BPF_REG_0, SRC_OP);
4800 if (is_pointer_value(env, BPF_REG_0)) {
4801 verbose(env, "R0 leaks addr as return value\n");
4805 err = check_return_code(env);
4809 err = pop_stack(env, &prev_insn_idx, &insn_idx);
4815 do_print_state = true;
4819 err = check_cond_jmp_op(env, insn, &insn_idx);
4823 } else if (class == BPF_LD) {
4824 u8 mode = BPF_MODE(insn->code);
4826 if (mode == BPF_ABS || mode == BPF_IND) {
4827 err = check_ld_abs(env, insn);
4831 } else if (mode == BPF_IMM) {
4832 err = check_ld_imm(env, insn);
4837 env->insn_aux_data[insn_idx].seen = true;
4839 verbose(env, "invalid BPF_LD mode\n");
4843 verbose(env, "unknown insn class %d\n", class);
4850 verbose(env, "processed %d insns (limit %d), stack depth ",
4851 insn_processed, BPF_COMPLEXITY_LIMIT_INSNS);
4852 for (i = 0; i < env->subprog_cnt + 1; i++) {
4853 u32 depth = env->subprog_stack_depth[i];
4855 verbose(env, "%d", depth);
4856 if (i + 1 < env->subprog_cnt + 1)
4860 env->prog->aux->stack_depth = env->subprog_stack_depth[0];
4864 static int check_map_prealloc(struct bpf_map *map)
4866 return (map->map_type != BPF_MAP_TYPE_HASH &&
4867 map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
4868 map->map_type != BPF_MAP_TYPE_HASH_OF_MAPS) ||
4869 !(map->map_flags & BPF_F_NO_PREALLOC);
4872 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
4873 struct bpf_map *map,
4874 struct bpf_prog *prog)
4877 /* Make sure that BPF_PROG_TYPE_PERF_EVENT programs only use
4878 * preallocated hash maps, since doing memory allocation
4879 * in overflow_handler can crash depending on where nmi got
4882 if (prog->type == BPF_PROG_TYPE_PERF_EVENT) {
4883 if (!check_map_prealloc(map)) {
4884 verbose(env, "perf_event programs can only use preallocated hash map\n");
4887 if (map->inner_map_meta &&
4888 !check_map_prealloc(map->inner_map_meta)) {
4889 verbose(env, "perf_event programs can only use preallocated inner hash map\n");
4894 if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) &&
4895 !bpf_offload_dev_match(prog, map)) {
4896 verbose(env, "offload device mismatch between prog and map\n");
4903 /* look for pseudo eBPF instructions that access map FDs and
4904 * replace them with actual map pointers
4906 static int replace_map_fd_with_map_ptr(struct bpf_verifier_env *env)
4908 struct bpf_insn *insn = env->prog->insnsi;
4909 int insn_cnt = env->prog->len;
4912 err = bpf_prog_calc_tag(env->prog);
4916 for (i = 0; i < insn_cnt; i++, insn++) {
4917 if (BPF_CLASS(insn->code) == BPF_LDX &&
4918 (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
4919 verbose(env, "BPF_LDX uses reserved fields\n");
4923 if (BPF_CLASS(insn->code) == BPF_STX &&
4924 ((BPF_MODE(insn->code) != BPF_MEM &&
4925 BPF_MODE(insn->code) != BPF_XADD) || insn->imm != 0)) {
4926 verbose(env, "BPF_STX uses reserved fields\n");
4930 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
4931 struct bpf_map *map;
4934 if (i == insn_cnt - 1 || insn[1].code != 0 ||
4935 insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
4937 verbose(env, "invalid bpf_ld_imm64 insn\n");
4941 if (insn->src_reg == 0)
4942 /* valid generic load 64-bit imm */
4945 if (insn->src_reg != BPF_PSEUDO_MAP_FD) {
4947 "unrecognized bpf_ld_imm64 insn\n");
4951 f = fdget(insn->imm);
4952 map = __bpf_map_get(f);
4954 verbose(env, "fd %d is not pointing to valid bpf_map\n",
4956 return PTR_ERR(map);
4959 err = check_map_prog_compatibility(env, map, env->prog);
4965 /* store map pointer inside BPF_LD_IMM64 instruction */
4966 insn[0].imm = (u32) (unsigned long) map;
4967 insn[1].imm = ((u64) (unsigned long) map) >> 32;
4969 /* check whether we recorded this map already */
4970 for (j = 0; j < env->used_map_cnt; j++)
4971 if (env->used_maps[j] == map) {
4976 if (env->used_map_cnt >= MAX_USED_MAPS) {
4981 /* hold the map. If the program is rejected by verifier,
4982 * the map will be released by release_maps() or it
4983 * will be used by the valid program until it's unloaded
4984 * and all maps are released in free_bpf_prog_info()
4986 map = bpf_map_inc(map, false);
4989 return PTR_ERR(map);
4991 env->used_maps[env->used_map_cnt++] = map;
5000 /* Basic sanity check before we invest more work here. */
5001 if (!bpf_opcode_in_insntable(insn->code)) {
5002 verbose(env, "unknown opcode %02x\n", insn->code);
5007 /* now all pseudo BPF_LD_IMM64 instructions load valid
5008 * 'struct bpf_map *' into a register instead of user map_fd.
5009 * These pointers will be used later by verifier to validate map access.
5014 /* drop refcnt of maps used by the rejected program */
5015 static void release_maps(struct bpf_verifier_env *env)
5019 for (i = 0; i < env->used_map_cnt; i++)
5020 bpf_map_put(env->used_maps[i]);
5023 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
5024 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
5026 struct bpf_insn *insn = env->prog->insnsi;
5027 int insn_cnt = env->prog->len;
5030 for (i = 0; i < insn_cnt; i++, insn++)
5031 if (insn->code == (BPF_LD | BPF_IMM | BPF_DW))
5035 /* single env->prog->insni[off] instruction was replaced with the range
5036 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying
5037 * [0, off) and [off, end) to new locations, so the patched range stays zero
5039 static int adjust_insn_aux_data(struct bpf_verifier_env *env, u32 prog_len,
5042 struct bpf_insn_aux_data *new_data, *old_data = env->insn_aux_data;
5047 new_data = vzalloc(sizeof(struct bpf_insn_aux_data) * prog_len);
5050 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
5051 memcpy(new_data + off + cnt - 1, old_data + off,
5052 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
5053 for (i = off; i < off + cnt - 1; i++)
5054 new_data[i].seen = true;
5055 env->insn_aux_data = new_data;
5060 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
5066 for (i = 0; i < env->subprog_cnt; i++) {
5067 if (env->subprog_starts[i] < off)
5069 env->subprog_starts[i] += len - 1;
5073 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
5074 const struct bpf_insn *patch, u32 len)
5076 struct bpf_prog *new_prog;
5078 new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
5081 if (adjust_insn_aux_data(env, new_prog->len, off, len))
5083 adjust_subprog_starts(env, off, len);
5087 /* The verifier does more data flow analysis than llvm and will not
5088 * explore branches that are dead at run time. Malicious programs can
5089 * have dead code too. Therefore replace all dead at-run-time code
5092 * Just nops are not optimal, e.g. if they would sit at the end of the
5093 * program and through another bug we would manage to jump there, then
5094 * we'd execute beyond program memory otherwise. Returning exception
5095 * code also wouldn't work since we can have subprogs where the dead
5096 * code could be located.
5098 static void sanitize_dead_code(struct bpf_verifier_env *env)
5100 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
5101 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
5102 struct bpf_insn *insn = env->prog->insnsi;
5103 const int insn_cnt = env->prog->len;
5106 for (i = 0; i < insn_cnt; i++) {
5107 if (aux_data[i].seen)
5109 memcpy(insn + i, &trap, sizeof(trap));
5113 /* convert load instructions that access fields of 'struct __sk_buff'
5114 * into sequence of instructions that access fields of 'struct sk_buff'
5116 static int convert_ctx_accesses(struct bpf_verifier_env *env)
5118 const struct bpf_verifier_ops *ops = env->ops;
5119 int i, cnt, size, ctx_field_size, delta = 0;
5120 const int insn_cnt = env->prog->len;
5121 struct bpf_insn insn_buf[16], *insn;
5122 struct bpf_prog *new_prog;
5123 enum bpf_access_type type;
5124 bool is_narrower_load;
5127 if (ops->gen_prologue) {
5128 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
5130 if (cnt >= ARRAY_SIZE(insn_buf)) {
5131 verbose(env, "bpf verifier is misconfigured\n");
5134 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
5138 env->prog = new_prog;
5143 if (!ops->convert_ctx_access)
5146 insn = env->prog->insnsi + delta;
5148 for (i = 0; i < insn_cnt; i++, insn++) {
5149 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
5150 insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
5151 insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
5152 insn->code == (BPF_LDX | BPF_MEM | BPF_DW))
5154 else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
5155 insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
5156 insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
5157 insn->code == (BPF_STX | BPF_MEM | BPF_DW))
5162 if (env->insn_aux_data[i + delta].ptr_type != PTR_TO_CTX)
5165 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
5166 size = BPF_LDST_BYTES(insn);
5168 /* If the read access is a narrower load of the field,
5169 * convert to a 4/8-byte load, to minimum program type specific
5170 * convert_ctx_access changes. If conversion is successful,
5171 * we will apply proper mask to the result.
5173 is_narrower_load = size < ctx_field_size;
5174 if (is_narrower_load) {
5175 u32 off = insn->off;
5178 if (type == BPF_WRITE) {
5179 verbose(env, "bpf verifier narrow ctx access misconfigured\n");
5184 if (ctx_field_size == 4)
5186 else if (ctx_field_size == 8)
5189 insn->off = off & ~(ctx_field_size - 1);
5190 insn->code = BPF_LDX | BPF_MEM | size_code;
5194 cnt = ops->convert_ctx_access(type, insn, insn_buf, env->prog,
5196 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
5197 (ctx_field_size && !target_size)) {
5198 verbose(env, "bpf verifier is misconfigured\n");
5202 if (is_narrower_load && size < target_size) {
5203 if (ctx_field_size <= 4)
5204 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
5205 (1 << size * 8) - 1);
5207 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
5208 (1 << size * 8) - 1);
5211 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
5217 /* keep walking new program and skip insns we just inserted */
5218 env->prog = new_prog;
5219 insn = new_prog->insnsi + i + delta;
5225 static int jit_subprogs(struct bpf_verifier_env *env)
5227 struct bpf_prog *prog = env->prog, **func, *tmp;
5228 int i, j, subprog_start, subprog_end = 0, len, subprog;
5229 struct bpf_insn *insn;
5233 if (env->subprog_cnt == 0)
5236 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
5237 if (insn->code != (BPF_JMP | BPF_CALL) ||
5238 insn->src_reg != BPF_PSEUDO_CALL)
5240 subprog = find_subprog(env, i + insn->imm + 1);
5242 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
5246 /* temporarily remember subprog id inside insn instead of
5247 * aux_data, since next loop will split up all insns into funcs
5249 insn->off = subprog + 1;
5250 /* remember original imm in case JIT fails and fallback
5251 * to interpreter will be needed
5253 env->insn_aux_data[i].call_imm = insn->imm;
5254 /* point imm to __bpf_call_base+1 from JITs point of view */
5258 func = kzalloc(sizeof(prog) * (env->subprog_cnt + 1), GFP_KERNEL);
5262 for (i = 0; i <= env->subprog_cnt; i++) {
5263 subprog_start = subprog_end;
5264 if (env->subprog_cnt == i)
5265 subprog_end = prog->len;
5267 subprog_end = env->subprog_starts[i];
5269 len = subprog_end - subprog_start;
5270 func[i] = bpf_prog_alloc(bpf_prog_size(len), GFP_USER);
5273 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
5274 len * sizeof(struct bpf_insn));
5275 func[i]->type = prog->type;
5277 if (bpf_prog_calc_tag(func[i]))
5279 func[i]->is_func = 1;
5280 /* Use bpf_prog_F_tag to indicate functions in stack traces.
5281 * Long term would need debug info to populate names
5283 func[i]->aux->name[0] = 'F';
5284 func[i]->aux->stack_depth = env->subprog_stack_depth[i];
5285 func[i]->jit_requested = 1;
5286 func[i] = bpf_int_jit_compile(func[i]);
5287 if (!func[i]->jited) {
5293 /* at this point all bpf functions were successfully JITed
5294 * now populate all bpf_calls with correct addresses and
5295 * run last pass of JIT
5297 for (i = 0; i <= env->subprog_cnt; i++) {
5298 insn = func[i]->insnsi;
5299 for (j = 0; j < func[i]->len; j++, insn++) {
5300 if (insn->code != (BPF_JMP | BPF_CALL) ||
5301 insn->src_reg != BPF_PSEUDO_CALL)
5303 subprog = insn->off;
5305 insn->imm = (u64 (*)(u64, u64, u64, u64, u64))
5306 func[subprog]->bpf_func -
5310 for (i = 0; i <= env->subprog_cnt; i++) {
5311 old_bpf_func = func[i]->bpf_func;
5312 tmp = bpf_int_jit_compile(func[i]);
5313 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
5314 verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
5321 /* finally lock prog and jit images for all functions and
5324 for (i = 0; i <= env->subprog_cnt; i++) {
5325 bpf_prog_lock_ro(func[i]);
5326 bpf_prog_kallsyms_add(func[i]);
5329 /* Last step: make now unused interpreter insns from main
5330 * prog consistent for later dump requests, so they can
5331 * later look the same as if they were interpreted only.
5333 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
5336 if (insn->code != (BPF_JMP | BPF_CALL) ||
5337 insn->src_reg != BPF_PSEUDO_CALL)
5339 insn->off = env->insn_aux_data[i].call_imm;
5340 subprog = find_subprog(env, i + insn->off + 1);
5341 addr = (unsigned long)func[subprog + 1]->bpf_func;
5343 insn->imm = (u64 (*)(u64, u64, u64, u64, u64))
5344 addr - __bpf_call_base;
5348 prog->bpf_func = func[0]->bpf_func;
5349 prog->aux->func = func;
5350 prog->aux->func_cnt = env->subprog_cnt + 1;
5353 for (i = 0; i <= env->subprog_cnt; i++)
5355 bpf_jit_free(func[i]);
5357 /* cleanup main prog to be interpreted */
5358 prog->jit_requested = 0;
5359 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
5360 if (insn->code != (BPF_JMP | BPF_CALL) ||
5361 insn->src_reg != BPF_PSEUDO_CALL)
5364 insn->imm = env->insn_aux_data[i].call_imm;
5369 static int fixup_call_args(struct bpf_verifier_env *env)
5371 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
5372 struct bpf_prog *prog = env->prog;
5373 struct bpf_insn *insn = prog->insnsi;
5379 if (env->prog->jit_requested) {
5380 err = jit_subprogs(env);
5384 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
5385 for (i = 0; i < prog->len; i++, insn++) {
5386 if (insn->code != (BPF_JMP | BPF_CALL) ||
5387 insn->src_reg != BPF_PSEUDO_CALL)
5389 depth = get_callee_stack_depth(env, insn, i);
5392 bpf_patch_call_args(insn, depth);
5399 /* fixup insn->imm field of bpf_call instructions
5400 * and inline eligible helpers as explicit sequence of BPF instructions
5402 * this function is called after eBPF program passed verification
5404 static int fixup_bpf_calls(struct bpf_verifier_env *env)
5406 struct bpf_prog *prog = env->prog;
5407 struct bpf_insn *insn = prog->insnsi;
5408 const struct bpf_func_proto *fn;
5409 const int insn_cnt = prog->len;
5410 struct bpf_insn insn_buf[16];
5411 struct bpf_prog *new_prog;
5412 struct bpf_map *map_ptr;
5413 int i, cnt, delta = 0;
5415 for (i = 0; i < insn_cnt; i++, insn++) {
5416 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
5417 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
5418 insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
5419 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
5420 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
5421 struct bpf_insn mask_and_div[] = {
5422 BPF_MOV32_REG(insn->src_reg, insn->src_reg),
5424 BPF_JMP_IMM(BPF_JNE, insn->src_reg, 0, 2),
5425 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
5426 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
5429 struct bpf_insn mask_and_mod[] = {
5430 BPF_MOV32_REG(insn->src_reg, insn->src_reg),
5431 /* Rx mod 0 -> Rx */
5432 BPF_JMP_IMM(BPF_JEQ, insn->src_reg, 0, 1),
5435 struct bpf_insn *patchlet;
5437 if (insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
5438 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
5439 patchlet = mask_and_div + (is64 ? 1 : 0);
5440 cnt = ARRAY_SIZE(mask_and_div) - (is64 ? 1 : 0);
5442 patchlet = mask_and_mod + (is64 ? 1 : 0);
5443 cnt = ARRAY_SIZE(mask_and_mod) - (is64 ? 1 : 0);
5446 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
5451 env->prog = prog = new_prog;
5452 insn = new_prog->insnsi + i + delta;
5456 if (insn->code != (BPF_JMP | BPF_CALL))
5458 if (insn->src_reg == BPF_PSEUDO_CALL)
5461 if (insn->imm == BPF_FUNC_get_route_realm)
5462 prog->dst_needed = 1;
5463 if (insn->imm == BPF_FUNC_get_prandom_u32)
5464 bpf_user_rnd_init_once();
5465 if (insn->imm == BPF_FUNC_override_return)
5466 prog->kprobe_override = 1;
5467 if (insn->imm == BPF_FUNC_tail_call) {
5468 /* If we tail call into other programs, we
5469 * cannot make any assumptions since they can
5470 * be replaced dynamically during runtime in
5471 * the program array.
5473 prog->cb_access = 1;
5474 env->prog->aux->stack_depth = MAX_BPF_STACK;
5476 /* mark bpf_tail_call as different opcode to avoid
5477 * conditional branch in the interpeter for every normal
5478 * call and to prevent accidental JITing by JIT compiler
5479 * that doesn't support bpf_tail_call yet
5482 insn->code = BPF_JMP | BPF_TAIL_CALL;
5484 /* instead of changing every JIT dealing with tail_call
5485 * emit two extra insns:
5486 * if (index >= max_entries) goto out;
5487 * index &= array->index_mask;
5488 * to avoid out-of-bounds cpu speculation
5490 map_ptr = env->insn_aux_data[i + delta].map_ptr;
5491 if (map_ptr == BPF_MAP_PTR_POISON) {
5492 verbose(env, "tail_call abusing map_ptr\n");
5495 if (!map_ptr->unpriv_array)
5497 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
5498 map_ptr->max_entries, 2);
5499 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
5500 container_of(map_ptr,
5503 insn_buf[2] = *insn;
5505 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
5510 env->prog = prog = new_prog;
5511 insn = new_prog->insnsi + i + delta;
5515 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
5516 * handlers are currently limited to 64 bit only.
5518 if (prog->jit_requested && BITS_PER_LONG == 64 &&
5519 insn->imm == BPF_FUNC_map_lookup_elem) {
5520 map_ptr = env->insn_aux_data[i + delta].map_ptr;
5521 if (map_ptr == BPF_MAP_PTR_POISON ||
5522 !map_ptr->ops->map_gen_lookup)
5523 goto patch_call_imm;
5525 cnt = map_ptr->ops->map_gen_lookup(map_ptr, insn_buf);
5526 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
5527 verbose(env, "bpf verifier is misconfigured\n");
5531 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
5538 /* keep walking new program and skip insns we just inserted */
5539 env->prog = prog = new_prog;
5540 insn = new_prog->insnsi + i + delta;
5544 if (insn->imm == BPF_FUNC_redirect_map) {
5545 /* Note, we cannot use prog directly as imm as subsequent
5546 * rewrites would still change the prog pointer. The only
5547 * stable address we can use is aux, which also works with
5548 * prog clones during blinding.
5550 u64 addr = (unsigned long)prog->aux;
5551 struct bpf_insn r4_ld[] = {
5552 BPF_LD_IMM64(BPF_REG_4, addr),
5555 cnt = ARRAY_SIZE(r4_ld);
5557 new_prog = bpf_patch_insn_data(env, i + delta, r4_ld, cnt);
5562 env->prog = prog = new_prog;
5563 insn = new_prog->insnsi + i + delta;
5566 fn = env->ops->get_func_proto(insn->imm, env->prog);
5567 /* all functions that have prototype and verifier allowed
5568 * programs to call them, must be real in-kernel functions
5572 "kernel subsystem misconfigured func %s#%d\n",
5573 func_id_name(insn->imm), insn->imm);
5576 insn->imm = fn->func - __bpf_call_base;
5582 static void free_states(struct bpf_verifier_env *env)
5584 struct bpf_verifier_state_list *sl, *sln;
5587 if (!env->explored_states)
5590 for (i = 0; i < env->prog->len; i++) {
5591 sl = env->explored_states[i];
5594 while (sl != STATE_LIST_MARK) {
5596 free_verifier_state(&sl->state, false);
5602 kfree(env->explored_states);
5605 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr)
5607 struct bpf_verifier_env *env;
5608 struct bpf_verifier_log *log;
5611 /* no program is valid */
5612 if (ARRAY_SIZE(bpf_verifier_ops) == 0)
5615 /* 'struct bpf_verifier_env' can be global, but since it's not small,
5616 * allocate/free it every time bpf_check() is called
5618 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
5623 env->insn_aux_data = vzalloc(sizeof(struct bpf_insn_aux_data) *
5626 if (!env->insn_aux_data)
5629 env->ops = bpf_verifier_ops[env->prog->type];
5631 /* grab the mutex to protect few globals used by verifier */
5632 mutex_lock(&bpf_verifier_lock);
5634 if (attr->log_level || attr->log_buf || attr->log_size) {
5635 /* user requested verbose verifier output
5636 * and supplied buffer to store the verification trace
5638 log->level = attr->log_level;
5639 log->ubuf = (char __user *) (unsigned long) attr->log_buf;
5640 log->len_total = attr->log_size;
5643 /* log attributes have to be sane */
5644 if (log->len_total < 128 || log->len_total > UINT_MAX >> 8 ||
5645 !log->level || !log->ubuf)
5649 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
5650 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
5651 env->strict_alignment = true;
5653 if (bpf_prog_is_dev_bound(env->prog->aux)) {
5654 ret = bpf_prog_offload_verifier_prep(env);
5659 ret = replace_map_fd_with_map_ptr(env);
5661 goto skip_full_check;
5663 env->explored_states = kcalloc(env->prog->len,
5664 sizeof(struct bpf_verifier_state_list *),
5667 if (!env->explored_states)
5668 goto skip_full_check;
5670 env->allow_ptr_leaks = capable(CAP_SYS_ADMIN);
5672 ret = check_cfg(env);
5674 goto skip_full_check;
5676 ret = do_check(env);
5677 if (env->cur_state) {
5678 free_verifier_state(env->cur_state, true);
5679 env->cur_state = NULL;
5683 while (!pop_stack(env, NULL, NULL));
5687 sanitize_dead_code(env);
5690 ret = check_max_stack_depth(env);
5693 /* program is valid, convert *(u32*)(ctx + off) accesses */
5694 ret = convert_ctx_accesses(env);
5697 ret = fixup_bpf_calls(env);
5700 ret = fixup_call_args(env);
5702 if (log->level && bpf_verifier_log_full(log))
5704 if (log->level && !log->ubuf) {
5706 goto err_release_maps;
5709 if (ret == 0 && env->used_map_cnt) {
5710 /* if program passed verifier, update used_maps in bpf_prog_info */
5711 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
5712 sizeof(env->used_maps[0]),
5715 if (!env->prog->aux->used_maps) {
5717 goto err_release_maps;
5720 memcpy(env->prog->aux->used_maps, env->used_maps,
5721 sizeof(env->used_maps[0]) * env->used_map_cnt);
5722 env->prog->aux->used_map_cnt = env->used_map_cnt;
5724 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
5725 * bpf_ld_imm64 instructions
5727 convert_pseudo_ld_imm64(env);
5731 if (!env->prog->aux->used_maps)
5732 /* if we didn't copy map pointers into bpf_prog_info, release
5733 * them now. Otherwise free_bpf_prog_info() will release them.
5738 mutex_unlock(&bpf_verifier_lock);
5739 vfree(env->insn_aux_data);