1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com
3 * Copyright (c) 2016 Facebook
4 * Copyright (c) 2018 Covalent IO, Inc. http://covalent.io
6 #include <uapi/linux/btf.h>
7 #include <linux/kernel.h>
8 #include <linux/types.h>
9 #include <linux/slab.h>
10 #include <linux/bpf.h>
11 #include <linux/btf.h>
12 #include <linux/bpf_verifier.h>
13 #include <linux/filter.h>
14 #include <net/netlink.h>
15 #include <linux/file.h>
16 #include <linux/vmalloc.h>
17 #include <linux/stringify.h>
18 #include <linux/bsearch.h>
19 #include <linux/sort.h>
20 #include <linux/perf_event.h>
21 #include <linux/ctype.h>
22 #include <linux/error-injection.h>
23 #include <linux/bpf_lsm.h>
27 static const struct bpf_verifier_ops
* const bpf_verifier_ops
[] = {
28 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
29 [_id] = & _name ## _verifier_ops,
30 #define BPF_MAP_TYPE(_id, _ops)
31 #include <linux/bpf_types.h>
36 /* bpf_check() is a static code analyzer that walks eBPF program
37 * instruction by instruction and updates register/stack state.
38 * All paths of conditional branches are analyzed until 'bpf_exit' insn.
40 * The first pass is depth-first-search to check that the program is a DAG.
41 * It rejects the following programs:
42 * - larger than BPF_MAXINSNS insns
43 * - if loop is present (detected via back-edge)
44 * - unreachable insns exist (shouldn't be a forest. program = one function)
45 * - out of bounds or malformed jumps
46 * The second pass is all possible path descent from the 1st insn.
47 * Since it's analyzing all pathes through the program, the length of the
48 * analysis is limited to 64k insn, which may be hit even if total number of
49 * insn is less then 4K, but there are too many branches that change stack/regs.
50 * Number of 'branches to be analyzed' is limited to 1k
52 * On entry to each instruction, each register has a type, and the instruction
53 * changes the types of the registers depending on instruction semantics.
54 * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
57 * All registers are 64-bit.
58 * R0 - return register
59 * R1-R5 argument passing registers
60 * R6-R9 callee saved registers
61 * R10 - frame pointer read-only
63 * At the start of BPF program the register R1 contains a pointer to bpf_context
64 * and has type PTR_TO_CTX.
66 * Verifier tracks arithmetic operations on pointers in case:
67 * BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
68 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
69 * 1st insn copies R10 (which has FRAME_PTR) type into R1
70 * and 2nd arithmetic instruction is pattern matched to recognize
71 * that it wants to construct a pointer to some element within stack.
72 * So after 2nd insn, the register R1 has type PTR_TO_STACK
73 * (and -20 constant is saved for further stack bounds checking).
74 * Meaning that this reg is a pointer to stack plus known immediate constant.
76 * Most of the time the registers have SCALAR_VALUE type, which
77 * means the register has some value, but it's not a valid pointer.
78 * (like pointer plus pointer becomes SCALAR_VALUE type)
80 * When verifier sees load or store instructions the type of base register
81 * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are
82 * four pointer types recognized by check_mem_access() function.
84 * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
85 * and the range of [ptr, ptr + map's value_size) is accessible.
87 * registers used to pass values to function calls are checked against
88 * function argument constraints.
90 * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
91 * It means that the register type passed to this function must be
92 * PTR_TO_STACK and it will be used inside the function as
93 * 'pointer to map element key'
95 * For example the argument constraints for bpf_map_lookup_elem():
96 * .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
97 * .arg1_type = ARG_CONST_MAP_PTR,
98 * .arg2_type = ARG_PTR_TO_MAP_KEY,
100 * ret_type says that this function returns 'pointer to map elem value or null'
101 * function expects 1st argument to be a const pointer to 'struct bpf_map' and
102 * 2nd argument should be a pointer to stack, which will be used inside
103 * the helper function as a pointer to map element key.
105 * On the kernel side the helper function looks like:
106 * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
108 * struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
109 * void *key = (void *) (unsigned long) r2;
112 * here kernel can access 'key' and 'map' pointers safely, knowing that
113 * [key, key + map->key_size) bytes are valid and were initialized on
114 * the stack of eBPF program.
117 * Corresponding eBPF program may look like:
118 * BPF_MOV64_REG(BPF_REG_2, BPF_REG_10), // after this insn R2 type is FRAME_PTR
119 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
120 * BPF_LD_MAP_FD(BPF_REG_1, map_fd), // after this insn R1 type is CONST_PTR_TO_MAP
121 * BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
122 * here verifier looks at prototype of map_lookup_elem() and sees:
123 * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
124 * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
126 * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
127 * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
128 * and were initialized prior to this call.
129 * If it's ok, then verifier allows this BPF_CALL insn and looks at
130 * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
131 * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
132 * returns ether pointer to map value or NULL.
134 * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
135 * insn, the register holding that pointer in the true branch changes state to
136 * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
137 * branch. See check_cond_jmp_op().
139 * After the call R0 is set to return type of the function and registers R1-R5
140 * are set to NOT_INIT to indicate that they are no longer readable.
142 * The following reference types represent a potential reference to a kernel
143 * resource which, after first being allocated, must be checked and freed by
145 * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET
147 * When the verifier sees a helper call return a reference type, it allocates a
148 * pointer id for the reference and stores it in the current function state.
149 * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into
150 * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type
151 * passes through a NULL-check conditional. For the branch wherein the state is
152 * changed to CONST_IMM, the verifier releases the reference.
154 * For each helper function that allocates a reference, such as
155 * bpf_sk_lookup_tcp(), there is a corresponding release function, such as
156 * bpf_sk_release(). When a reference type passes into the release function,
157 * the verifier also releases the reference. If any unchecked or unreleased
158 * reference remains at the end of the program, the verifier rejects it.
161 /* verifier_state + insn_idx are pushed to stack when branch is encountered */
162 struct bpf_verifier_stack_elem
{
163 /* verifer state is 'st'
164 * before processing instruction 'insn_idx'
165 * and after processing instruction 'prev_insn_idx'
167 struct bpf_verifier_state st
;
170 struct bpf_verifier_stack_elem
*next
;
173 #define BPF_COMPLEXITY_LIMIT_JMP_SEQ 8192
174 #define BPF_COMPLEXITY_LIMIT_STATES 64
176 #define BPF_MAP_KEY_POISON (1ULL << 63)
177 #define BPF_MAP_KEY_SEEN (1ULL << 62)
179 #define BPF_MAP_PTR_UNPRIV 1UL
180 #define BPF_MAP_PTR_POISON ((void *)((0xeB9FUL << 1) + \
181 POISON_POINTER_DELTA))
182 #define BPF_MAP_PTR(X) ((struct bpf_map *)((X) & ~BPF_MAP_PTR_UNPRIV))
184 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data
*aux
)
186 return BPF_MAP_PTR(aux
->map_ptr_state
) == BPF_MAP_PTR_POISON
;
189 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data
*aux
)
191 return aux
->map_ptr_state
& BPF_MAP_PTR_UNPRIV
;
194 static void bpf_map_ptr_store(struct bpf_insn_aux_data
*aux
,
195 const struct bpf_map
*map
, bool unpriv
)
197 BUILD_BUG_ON((unsigned long)BPF_MAP_PTR_POISON
& BPF_MAP_PTR_UNPRIV
);
198 unpriv
|= bpf_map_ptr_unpriv(aux
);
199 aux
->map_ptr_state
= (unsigned long)map
|
200 (unpriv
? BPF_MAP_PTR_UNPRIV
: 0UL);
203 static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data
*aux
)
205 return aux
->map_key_state
& BPF_MAP_KEY_POISON
;
208 static bool bpf_map_key_unseen(const struct bpf_insn_aux_data
*aux
)
210 return !(aux
->map_key_state
& BPF_MAP_KEY_SEEN
);
213 static u64
bpf_map_key_immediate(const struct bpf_insn_aux_data
*aux
)
215 return aux
->map_key_state
& ~(BPF_MAP_KEY_SEEN
| BPF_MAP_KEY_POISON
);
218 static void bpf_map_key_store(struct bpf_insn_aux_data
*aux
, u64 state
)
220 bool poisoned
= bpf_map_key_poisoned(aux
);
222 aux
->map_key_state
= state
| BPF_MAP_KEY_SEEN
|
223 (poisoned
? BPF_MAP_KEY_POISON
: 0ULL);
226 struct bpf_call_arg_meta
{
227 struct bpf_map
*map_ptr
;
238 struct btf
*btf_vmlinux
;
240 static DEFINE_MUTEX(bpf_verifier_lock
);
242 static const struct bpf_line_info
*
243 find_linfo(const struct bpf_verifier_env
*env
, u32 insn_off
)
245 const struct bpf_line_info
*linfo
;
246 const struct bpf_prog
*prog
;
250 nr_linfo
= prog
->aux
->nr_linfo
;
252 if (!nr_linfo
|| insn_off
>= prog
->len
)
255 linfo
= prog
->aux
->linfo
;
256 for (i
= 1; i
< nr_linfo
; i
++)
257 if (insn_off
< linfo
[i
].insn_off
)
260 return &linfo
[i
- 1];
263 void bpf_verifier_vlog(struct bpf_verifier_log
*log
, const char *fmt
,
268 n
= vscnprintf(log
->kbuf
, BPF_VERIFIER_TMP_LOG_SIZE
, fmt
, args
);
270 WARN_ONCE(n
>= BPF_VERIFIER_TMP_LOG_SIZE
- 1,
271 "verifier log line truncated - local buffer too short\n");
273 n
= min(log
->len_total
- log
->len_used
- 1, n
);
276 if (log
->level
== BPF_LOG_KERNEL
) {
277 pr_err("BPF:%s\n", log
->kbuf
);
280 if (!copy_to_user(log
->ubuf
+ log
->len_used
, log
->kbuf
, n
+ 1))
286 /* log_level controls verbosity level of eBPF verifier.
287 * bpf_verifier_log_write() is used to dump the verification trace to the log,
288 * so the user can figure out what's wrong with the program
290 __printf(2, 3) void bpf_verifier_log_write(struct bpf_verifier_env
*env
,
291 const char *fmt
, ...)
295 if (!bpf_verifier_log_needed(&env
->log
))
299 bpf_verifier_vlog(&env
->log
, fmt
, args
);
302 EXPORT_SYMBOL_GPL(bpf_verifier_log_write
);
304 __printf(2, 3) static void verbose(void *private_data
, const char *fmt
, ...)
306 struct bpf_verifier_env
*env
= private_data
;
309 if (!bpf_verifier_log_needed(&env
->log
))
313 bpf_verifier_vlog(&env
->log
, fmt
, args
);
317 __printf(2, 3) void bpf_log(struct bpf_verifier_log
*log
,
318 const char *fmt
, ...)
322 if (!bpf_verifier_log_needed(log
))
326 bpf_verifier_vlog(log
, fmt
, args
);
330 static const char *ltrim(const char *s
)
338 __printf(3, 4) static void verbose_linfo(struct bpf_verifier_env
*env
,
340 const char *prefix_fmt
, ...)
342 const struct bpf_line_info
*linfo
;
344 if (!bpf_verifier_log_needed(&env
->log
))
347 linfo
= find_linfo(env
, insn_off
);
348 if (!linfo
|| linfo
== env
->prev_linfo
)
354 va_start(args
, prefix_fmt
);
355 bpf_verifier_vlog(&env
->log
, prefix_fmt
, args
);
360 ltrim(btf_name_by_offset(env
->prog
->aux
->btf
,
363 env
->prev_linfo
= linfo
;
366 static bool type_is_pkt_pointer(enum bpf_reg_type type
)
368 return type
== PTR_TO_PACKET
||
369 type
== PTR_TO_PACKET_META
;
372 static bool type_is_sk_pointer(enum bpf_reg_type type
)
374 return type
== PTR_TO_SOCKET
||
375 type
== PTR_TO_SOCK_COMMON
||
376 type
== PTR_TO_TCP_SOCK
||
377 type
== PTR_TO_XDP_SOCK
;
380 static bool reg_type_may_be_null(enum bpf_reg_type type
)
382 return type
== PTR_TO_MAP_VALUE_OR_NULL
||
383 type
== PTR_TO_SOCKET_OR_NULL
||
384 type
== PTR_TO_SOCK_COMMON_OR_NULL
||
385 type
== PTR_TO_TCP_SOCK_OR_NULL
;
388 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state
*reg
)
390 return reg
->type
== PTR_TO_MAP_VALUE
&&
391 map_value_has_spin_lock(reg
->map_ptr
);
394 static bool reg_type_may_be_refcounted_or_null(enum bpf_reg_type type
)
396 return type
== PTR_TO_SOCKET
||
397 type
== PTR_TO_SOCKET_OR_NULL
||
398 type
== PTR_TO_TCP_SOCK
||
399 type
== PTR_TO_TCP_SOCK_OR_NULL
;
402 static bool arg_type_may_be_refcounted(enum bpf_arg_type type
)
404 return type
== ARG_PTR_TO_SOCK_COMMON
;
407 /* Determine whether the function releases some resources allocated by another
408 * function call. The first reference type argument will be assumed to be
409 * released by release_reference().
411 static bool is_release_function(enum bpf_func_id func_id
)
413 return func_id
== BPF_FUNC_sk_release
;
416 static bool is_acquire_function(enum bpf_func_id func_id
)
418 return func_id
== BPF_FUNC_sk_lookup_tcp
||
419 func_id
== BPF_FUNC_sk_lookup_udp
||
420 func_id
== BPF_FUNC_skc_lookup_tcp
;
423 static bool is_ptr_cast_function(enum bpf_func_id func_id
)
425 return func_id
== BPF_FUNC_tcp_sock
||
426 func_id
== BPF_FUNC_sk_fullsock
;
429 /* string representation of 'enum bpf_reg_type' */
430 static const char * const reg_type_str
[] = {
432 [SCALAR_VALUE
] = "inv",
433 [PTR_TO_CTX
] = "ctx",
434 [CONST_PTR_TO_MAP
] = "map_ptr",
435 [PTR_TO_MAP_VALUE
] = "map_value",
436 [PTR_TO_MAP_VALUE_OR_NULL
] = "map_value_or_null",
437 [PTR_TO_STACK
] = "fp",
438 [PTR_TO_PACKET
] = "pkt",
439 [PTR_TO_PACKET_META
] = "pkt_meta",
440 [PTR_TO_PACKET_END
] = "pkt_end",
441 [PTR_TO_FLOW_KEYS
] = "flow_keys",
442 [PTR_TO_SOCKET
] = "sock",
443 [PTR_TO_SOCKET_OR_NULL
] = "sock_or_null",
444 [PTR_TO_SOCK_COMMON
] = "sock_common",
445 [PTR_TO_SOCK_COMMON_OR_NULL
] = "sock_common_or_null",
446 [PTR_TO_TCP_SOCK
] = "tcp_sock",
447 [PTR_TO_TCP_SOCK_OR_NULL
] = "tcp_sock_or_null",
448 [PTR_TO_TP_BUFFER
] = "tp_buffer",
449 [PTR_TO_XDP_SOCK
] = "xdp_sock",
450 [PTR_TO_BTF_ID
] = "ptr_",
453 static char slot_type_char
[] = {
454 [STACK_INVALID
] = '?',
460 static void print_liveness(struct bpf_verifier_env
*env
,
461 enum bpf_reg_liveness live
)
463 if (live
& (REG_LIVE_READ
| REG_LIVE_WRITTEN
| REG_LIVE_DONE
))
465 if (live
& REG_LIVE_READ
)
467 if (live
& REG_LIVE_WRITTEN
)
469 if (live
& REG_LIVE_DONE
)
473 static struct bpf_func_state
*func(struct bpf_verifier_env
*env
,
474 const struct bpf_reg_state
*reg
)
476 struct bpf_verifier_state
*cur
= env
->cur_state
;
478 return cur
->frame
[reg
->frameno
];
481 const char *kernel_type_name(u32 id
)
483 return btf_name_by_offset(btf_vmlinux
,
484 btf_type_by_id(btf_vmlinux
, id
)->name_off
);
487 static void print_verifier_state(struct bpf_verifier_env
*env
,
488 const struct bpf_func_state
*state
)
490 const struct bpf_reg_state
*reg
;
495 verbose(env
, " frame%d:", state
->frameno
);
496 for (i
= 0; i
< MAX_BPF_REG
; i
++) {
497 reg
= &state
->regs
[i
];
501 verbose(env
, " R%d", i
);
502 print_liveness(env
, reg
->live
);
503 verbose(env
, "=%s", reg_type_str
[t
]);
504 if (t
== SCALAR_VALUE
&& reg
->precise
)
506 if ((t
== SCALAR_VALUE
|| t
== PTR_TO_STACK
) &&
507 tnum_is_const(reg
->var_off
)) {
508 /* reg->off should be 0 for SCALAR_VALUE */
509 verbose(env
, "%lld", reg
->var_off
.value
+ reg
->off
);
511 if (t
== PTR_TO_BTF_ID
)
512 verbose(env
, "%s", kernel_type_name(reg
->btf_id
));
513 verbose(env
, "(id=%d", reg
->id
);
514 if (reg_type_may_be_refcounted_or_null(t
))
515 verbose(env
, ",ref_obj_id=%d", reg
->ref_obj_id
);
516 if (t
!= SCALAR_VALUE
)
517 verbose(env
, ",off=%d", reg
->off
);
518 if (type_is_pkt_pointer(t
))
519 verbose(env
, ",r=%d", reg
->range
);
520 else if (t
== CONST_PTR_TO_MAP
||
521 t
== PTR_TO_MAP_VALUE
||
522 t
== PTR_TO_MAP_VALUE_OR_NULL
)
523 verbose(env
, ",ks=%d,vs=%d",
524 reg
->map_ptr
->key_size
,
525 reg
->map_ptr
->value_size
);
526 if (tnum_is_const(reg
->var_off
)) {
527 /* Typically an immediate SCALAR_VALUE, but
528 * could be a pointer whose offset is too big
531 verbose(env
, ",imm=%llx", reg
->var_off
.value
);
533 if (reg
->smin_value
!= reg
->umin_value
&&
534 reg
->smin_value
!= S64_MIN
)
535 verbose(env
, ",smin_value=%lld",
536 (long long)reg
->smin_value
);
537 if (reg
->smax_value
!= reg
->umax_value
&&
538 reg
->smax_value
!= S64_MAX
)
539 verbose(env
, ",smax_value=%lld",
540 (long long)reg
->smax_value
);
541 if (reg
->umin_value
!= 0)
542 verbose(env
, ",umin_value=%llu",
543 (unsigned long long)reg
->umin_value
);
544 if (reg
->umax_value
!= U64_MAX
)
545 verbose(env
, ",umax_value=%llu",
546 (unsigned long long)reg
->umax_value
);
547 if (!tnum_is_unknown(reg
->var_off
)) {
550 tnum_strn(tn_buf
, sizeof(tn_buf
), reg
->var_off
);
551 verbose(env
, ",var_off=%s", tn_buf
);
553 if (reg
->s32_min_value
!= reg
->smin_value
&&
554 reg
->s32_min_value
!= S32_MIN
)
555 verbose(env
, ",s32_min_value=%d",
556 (int)(reg
->s32_min_value
));
557 if (reg
->s32_max_value
!= reg
->smax_value
&&
558 reg
->s32_max_value
!= S32_MAX
)
559 verbose(env
, ",s32_max_value=%d",
560 (int)(reg
->s32_max_value
));
561 if (reg
->u32_min_value
!= reg
->umin_value
&&
562 reg
->u32_min_value
!= U32_MIN
)
563 verbose(env
, ",u32_min_value=%d",
564 (int)(reg
->u32_min_value
));
565 if (reg
->u32_max_value
!= reg
->umax_value
&&
566 reg
->u32_max_value
!= U32_MAX
)
567 verbose(env
, ",u32_max_value=%d",
568 (int)(reg
->u32_max_value
));
573 for (i
= 0; i
< state
->allocated_stack
/ BPF_REG_SIZE
; i
++) {
574 char types_buf
[BPF_REG_SIZE
+ 1];
578 for (j
= 0; j
< BPF_REG_SIZE
; j
++) {
579 if (state
->stack
[i
].slot_type
[j
] != STACK_INVALID
)
581 types_buf
[j
] = slot_type_char
[
582 state
->stack
[i
].slot_type
[j
]];
584 types_buf
[BPF_REG_SIZE
] = 0;
587 verbose(env
, " fp%d", (-i
- 1) * BPF_REG_SIZE
);
588 print_liveness(env
, state
->stack
[i
].spilled_ptr
.live
);
589 if (state
->stack
[i
].slot_type
[0] == STACK_SPILL
) {
590 reg
= &state
->stack
[i
].spilled_ptr
;
592 verbose(env
, "=%s", reg_type_str
[t
]);
593 if (t
== SCALAR_VALUE
&& reg
->precise
)
595 if (t
== SCALAR_VALUE
&& tnum_is_const(reg
->var_off
))
596 verbose(env
, "%lld", reg
->var_off
.value
+ reg
->off
);
598 verbose(env
, "=%s", types_buf
);
601 if (state
->acquired_refs
&& state
->refs
[0].id
) {
602 verbose(env
, " refs=%d", state
->refs
[0].id
);
603 for (i
= 1; i
< state
->acquired_refs
; i
++)
604 if (state
->refs
[i
].id
)
605 verbose(env
, ",%d", state
->refs
[i
].id
);
610 #define COPY_STATE_FN(NAME, COUNT, FIELD, SIZE) \
611 static int copy_##NAME##_state(struct bpf_func_state *dst, \
612 const struct bpf_func_state *src) \
616 if (WARN_ON_ONCE(dst->COUNT < src->COUNT)) { \
617 /* internal bug, make state invalid to reject the program */ \
618 memset(dst, 0, sizeof(*dst)); \
621 memcpy(dst->FIELD, src->FIELD, \
622 sizeof(*src->FIELD) * (src->COUNT / SIZE)); \
625 /* copy_reference_state() */
626 COPY_STATE_FN(reference
, acquired_refs
, refs
, 1)
627 /* copy_stack_state() */
628 COPY_STATE_FN(stack
, allocated_stack
, stack
, BPF_REG_SIZE
)
631 #define REALLOC_STATE_FN(NAME, COUNT, FIELD, SIZE) \
632 static int realloc_##NAME##_state(struct bpf_func_state *state, int size, \
635 u32 old_size = state->COUNT; \
636 struct bpf_##NAME##_state *new_##FIELD; \
637 int slot = size / SIZE; \
639 if (size <= old_size || !size) { \
642 state->COUNT = slot * SIZE; \
643 if (!size && old_size) { \
644 kfree(state->FIELD); \
645 state->FIELD = NULL; \
649 new_##FIELD = kmalloc_array(slot, sizeof(struct bpf_##NAME##_state), \
655 memcpy(new_##FIELD, state->FIELD, \
656 sizeof(*new_##FIELD) * (old_size / SIZE)); \
657 memset(new_##FIELD + old_size / SIZE, 0, \
658 sizeof(*new_##FIELD) * (size - old_size) / SIZE); \
660 state->COUNT = slot * SIZE; \
661 kfree(state->FIELD); \
662 state->FIELD = new_##FIELD; \
665 /* realloc_reference_state() */
666 REALLOC_STATE_FN(reference
, acquired_refs
, refs
, 1)
667 /* realloc_stack_state() */
668 REALLOC_STATE_FN(stack
, allocated_stack
, stack
, BPF_REG_SIZE
)
669 #undef REALLOC_STATE_FN
671 /* do_check() starts with zero-sized stack in struct bpf_verifier_state to
672 * make it consume minimal amount of memory. check_stack_write() access from
673 * the program calls into realloc_func_state() to grow the stack size.
674 * Note there is a non-zero 'parent' pointer inside bpf_verifier_state
675 * which realloc_stack_state() copies over. It points to previous
676 * bpf_verifier_state which is never reallocated.
678 static int realloc_func_state(struct bpf_func_state
*state
, int stack_size
,
679 int refs_size
, bool copy_old
)
681 int err
= realloc_reference_state(state
, refs_size
, copy_old
);
684 return realloc_stack_state(state
, stack_size
, copy_old
);
687 /* Acquire a pointer id from the env and update the state->refs to include
688 * this new pointer reference.
689 * On success, returns a valid pointer id to associate with the register
690 * On failure, returns a negative errno.
692 static int acquire_reference_state(struct bpf_verifier_env
*env
, int insn_idx
)
694 struct bpf_func_state
*state
= cur_func(env
);
695 int new_ofs
= state
->acquired_refs
;
698 err
= realloc_reference_state(state
, state
->acquired_refs
+ 1, true);
702 state
->refs
[new_ofs
].id
= id
;
703 state
->refs
[new_ofs
].insn_idx
= insn_idx
;
708 /* release function corresponding to acquire_reference_state(). Idempotent. */
709 static int release_reference_state(struct bpf_func_state
*state
, int ptr_id
)
713 last_idx
= state
->acquired_refs
- 1;
714 for (i
= 0; i
< state
->acquired_refs
; i
++) {
715 if (state
->refs
[i
].id
== ptr_id
) {
716 if (last_idx
&& i
!= last_idx
)
717 memcpy(&state
->refs
[i
], &state
->refs
[last_idx
],
718 sizeof(*state
->refs
));
719 memset(&state
->refs
[last_idx
], 0, sizeof(*state
->refs
));
720 state
->acquired_refs
--;
727 static int transfer_reference_state(struct bpf_func_state
*dst
,
728 struct bpf_func_state
*src
)
730 int err
= realloc_reference_state(dst
, src
->acquired_refs
, false);
733 err
= copy_reference_state(dst
, src
);
739 static void free_func_state(struct bpf_func_state
*state
)
748 static void clear_jmp_history(struct bpf_verifier_state
*state
)
750 kfree(state
->jmp_history
);
751 state
->jmp_history
= NULL
;
752 state
->jmp_history_cnt
= 0;
755 static void free_verifier_state(struct bpf_verifier_state
*state
,
760 for (i
= 0; i
<= state
->curframe
; i
++) {
761 free_func_state(state
->frame
[i
]);
762 state
->frame
[i
] = NULL
;
764 clear_jmp_history(state
);
769 /* copy verifier state from src to dst growing dst stack space
770 * when necessary to accommodate larger src stack
772 static int copy_func_state(struct bpf_func_state
*dst
,
773 const struct bpf_func_state
*src
)
777 err
= realloc_func_state(dst
, src
->allocated_stack
, src
->acquired_refs
,
781 memcpy(dst
, src
, offsetof(struct bpf_func_state
, acquired_refs
));
782 err
= copy_reference_state(dst
, src
);
785 return copy_stack_state(dst
, src
);
788 static int copy_verifier_state(struct bpf_verifier_state
*dst_state
,
789 const struct bpf_verifier_state
*src
)
791 struct bpf_func_state
*dst
;
792 u32 jmp_sz
= sizeof(struct bpf_idx_pair
) * src
->jmp_history_cnt
;
795 if (dst_state
->jmp_history_cnt
< src
->jmp_history_cnt
) {
796 kfree(dst_state
->jmp_history
);
797 dst_state
->jmp_history
= kmalloc(jmp_sz
, GFP_USER
);
798 if (!dst_state
->jmp_history
)
801 memcpy(dst_state
->jmp_history
, src
->jmp_history
, jmp_sz
);
802 dst_state
->jmp_history_cnt
= src
->jmp_history_cnt
;
804 /* if dst has more stack frames then src frame, free them */
805 for (i
= src
->curframe
+ 1; i
<= dst_state
->curframe
; i
++) {
806 free_func_state(dst_state
->frame
[i
]);
807 dst_state
->frame
[i
] = NULL
;
809 dst_state
->speculative
= src
->speculative
;
810 dst_state
->curframe
= src
->curframe
;
811 dst_state
->active_spin_lock
= src
->active_spin_lock
;
812 dst_state
->branches
= src
->branches
;
813 dst_state
->parent
= src
->parent
;
814 dst_state
->first_insn_idx
= src
->first_insn_idx
;
815 dst_state
->last_insn_idx
= src
->last_insn_idx
;
816 for (i
= 0; i
<= src
->curframe
; i
++) {
817 dst
= dst_state
->frame
[i
];
819 dst
= kzalloc(sizeof(*dst
), GFP_KERNEL
);
822 dst_state
->frame
[i
] = dst
;
824 err
= copy_func_state(dst
, src
->frame
[i
]);
831 static void update_branch_counts(struct bpf_verifier_env
*env
, struct bpf_verifier_state
*st
)
834 u32 br
= --st
->branches
;
836 /* WARN_ON(br > 1) technically makes sense here,
837 * but see comment in push_stack(), hence:
839 WARN_ONCE((int)br
< 0,
840 "BUG update_branch_counts:branches_to_explore=%d\n",
848 static int pop_stack(struct bpf_verifier_env
*env
, int *prev_insn_idx
,
851 struct bpf_verifier_state
*cur
= env
->cur_state
;
852 struct bpf_verifier_stack_elem
*elem
, *head
= env
->head
;
855 if (env
->head
== NULL
)
859 err
= copy_verifier_state(cur
, &head
->st
);
864 *insn_idx
= head
->insn_idx
;
866 *prev_insn_idx
= head
->prev_insn_idx
;
868 free_verifier_state(&head
->st
, false);
875 static struct bpf_verifier_state
*push_stack(struct bpf_verifier_env
*env
,
876 int insn_idx
, int prev_insn_idx
,
879 struct bpf_verifier_state
*cur
= env
->cur_state
;
880 struct bpf_verifier_stack_elem
*elem
;
883 elem
= kzalloc(sizeof(struct bpf_verifier_stack_elem
), GFP_KERNEL
);
887 elem
->insn_idx
= insn_idx
;
888 elem
->prev_insn_idx
= prev_insn_idx
;
889 elem
->next
= env
->head
;
892 err
= copy_verifier_state(&elem
->st
, cur
);
895 elem
->st
.speculative
|= speculative
;
896 if (env
->stack_size
> BPF_COMPLEXITY_LIMIT_JMP_SEQ
) {
897 verbose(env
, "The sequence of %d jumps is too complex.\n",
901 if (elem
->st
.parent
) {
902 ++elem
->st
.parent
->branches
;
903 /* WARN_ON(branches > 2) technically makes sense here,
905 * 1. speculative states will bump 'branches' for non-branch
907 * 2. is_state_visited() heuristics may decide not to create
908 * a new state for a sequence of branches and all such current
909 * and cloned states will be pointing to a single parent state
910 * which might have large 'branches' count.
915 free_verifier_state(env
->cur_state
, true);
916 env
->cur_state
= NULL
;
917 /* pop all elements and return */
918 while (!pop_stack(env
, NULL
, NULL
));
922 #define CALLER_SAVED_REGS 6
923 static const int caller_saved
[CALLER_SAVED_REGS
] = {
924 BPF_REG_0
, BPF_REG_1
, BPF_REG_2
, BPF_REG_3
, BPF_REG_4
, BPF_REG_5
927 static void __mark_reg_not_init(const struct bpf_verifier_env
*env
,
928 struct bpf_reg_state
*reg
);
930 /* Mark the unknown part of a register (variable offset or scalar value) as
931 * known to have the value @imm.
933 static void __mark_reg_known(struct bpf_reg_state
*reg
, u64 imm
)
935 /* Clear id, off, and union(map_ptr, range) */
936 memset(((u8
*)reg
) + sizeof(reg
->type
), 0,
937 offsetof(struct bpf_reg_state
, var_off
) - sizeof(reg
->type
));
938 reg
->var_off
= tnum_const(imm
);
939 reg
->smin_value
= (s64
)imm
;
940 reg
->smax_value
= (s64
)imm
;
941 reg
->umin_value
= imm
;
942 reg
->umax_value
= imm
;
944 reg
->s32_min_value
= (s32
)imm
;
945 reg
->s32_max_value
= (s32
)imm
;
946 reg
->u32_min_value
= (u32
)imm
;
947 reg
->u32_max_value
= (u32
)imm
;
950 static void __mark_reg32_known(struct bpf_reg_state
*reg
, u64 imm
)
952 reg
->var_off
= tnum_const_subreg(reg
->var_off
, imm
);
953 reg
->s32_min_value
= (s32
)imm
;
954 reg
->s32_max_value
= (s32
)imm
;
955 reg
->u32_min_value
= (u32
)imm
;
956 reg
->u32_max_value
= (u32
)imm
;
959 /* Mark the 'variable offset' part of a register as zero. This should be
960 * used only on registers holding a pointer type.
962 static void __mark_reg_known_zero(struct bpf_reg_state
*reg
)
964 __mark_reg_known(reg
, 0);
967 static void __mark_reg_const_zero(struct bpf_reg_state
*reg
)
969 __mark_reg_known(reg
, 0);
970 reg
->type
= SCALAR_VALUE
;
973 static void mark_reg_known_zero(struct bpf_verifier_env
*env
,
974 struct bpf_reg_state
*regs
, u32 regno
)
976 if (WARN_ON(regno
>= MAX_BPF_REG
)) {
977 verbose(env
, "mark_reg_known_zero(regs, %u)\n", regno
);
978 /* Something bad happened, let's kill all regs */
979 for (regno
= 0; regno
< MAX_BPF_REG
; regno
++)
980 __mark_reg_not_init(env
, regs
+ regno
);
983 __mark_reg_known_zero(regs
+ regno
);
986 static bool reg_is_pkt_pointer(const struct bpf_reg_state
*reg
)
988 return type_is_pkt_pointer(reg
->type
);
991 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state
*reg
)
993 return reg_is_pkt_pointer(reg
) ||
994 reg
->type
== PTR_TO_PACKET_END
;
997 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
998 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state
*reg
,
999 enum bpf_reg_type which
)
1001 /* The register can already have a range from prior markings.
1002 * This is fine as long as it hasn't been advanced from its
1005 return reg
->type
== which
&&
1008 tnum_equals_const(reg
->var_off
, 0);
1011 /* Reset the min/max bounds of a register */
1012 static void __mark_reg_unbounded(struct bpf_reg_state
*reg
)
1014 reg
->smin_value
= S64_MIN
;
1015 reg
->smax_value
= S64_MAX
;
1016 reg
->umin_value
= 0;
1017 reg
->umax_value
= U64_MAX
;
1019 reg
->s32_min_value
= S32_MIN
;
1020 reg
->s32_max_value
= S32_MAX
;
1021 reg
->u32_min_value
= 0;
1022 reg
->u32_max_value
= U32_MAX
;
1025 static void __mark_reg64_unbounded(struct bpf_reg_state
*reg
)
1027 reg
->smin_value
= S64_MIN
;
1028 reg
->smax_value
= S64_MAX
;
1029 reg
->umin_value
= 0;
1030 reg
->umax_value
= U64_MAX
;
1033 static void __mark_reg32_unbounded(struct bpf_reg_state
*reg
)
1035 reg
->s32_min_value
= S32_MIN
;
1036 reg
->s32_max_value
= S32_MAX
;
1037 reg
->u32_min_value
= 0;
1038 reg
->u32_max_value
= U32_MAX
;
1041 static void __update_reg32_bounds(struct bpf_reg_state
*reg
)
1043 struct tnum var32_off
= tnum_subreg(reg
->var_off
);
1045 /* min signed is max(sign bit) | min(other bits) */
1046 reg
->s32_min_value
= max_t(s32
, reg
->s32_min_value
,
1047 var32_off
.value
| (var32_off
.mask
& S32_MIN
));
1048 /* max signed is min(sign bit) | max(other bits) */
1049 reg
->s32_max_value
= min_t(s32
, reg
->s32_max_value
,
1050 var32_off
.value
| (var32_off
.mask
& S32_MAX
));
1051 reg
->u32_min_value
= max_t(u32
, reg
->u32_min_value
, (u32
)var32_off
.value
);
1052 reg
->u32_max_value
= min(reg
->u32_max_value
,
1053 (u32
)(var32_off
.value
| var32_off
.mask
));
1056 static void __update_reg64_bounds(struct bpf_reg_state
*reg
)
1058 /* min signed is max(sign bit) | min(other bits) */
1059 reg
->smin_value
= max_t(s64
, reg
->smin_value
,
1060 reg
->var_off
.value
| (reg
->var_off
.mask
& S64_MIN
));
1061 /* max signed is min(sign bit) | max(other bits) */
1062 reg
->smax_value
= min_t(s64
, reg
->smax_value
,
1063 reg
->var_off
.value
| (reg
->var_off
.mask
& S64_MAX
));
1064 reg
->umin_value
= max(reg
->umin_value
, reg
->var_off
.value
);
1065 reg
->umax_value
= min(reg
->umax_value
,
1066 reg
->var_off
.value
| reg
->var_off
.mask
);
1069 static void __update_reg_bounds(struct bpf_reg_state
*reg
)
1071 __update_reg32_bounds(reg
);
1072 __update_reg64_bounds(reg
);
1075 /* Uses signed min/max values to inform unsigned, and vice-versa */
1076 static void __reg32_deduce_bounds(struct bpf_reg_state
*reg
)
1078 /* Learn sign from signed bounds.
1079 * If we cannot cross the sign boundary, then signed and unsigned bounds
1080 * are the same, so combine. This works even in the negative case, e.g.
1081 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1083 if (reg
->s32_min_value
>= 0 || reg
->s32_max_value
< 0) {
1084 reg
->s32_min_value
= reg
->u32_min_value
=
1085 max_t(u32
, reg
->s32_min_value
, reg
->u32_min_value
);
1086 reg
->s32_max_value
= reg
->u32_max_value
=
1087 min_t(u32
, reg
->s32_max_value
, reg
->u32_max_value
);
1090 /* Learn sign from unsigned bounds. Signed bounds cross the sign
1091 * boundary, so we must be careful.
1093 if ((s32
)reg
->u32_max_value
>= 0) {
1094 /* Positive. We can't learn anything from the smin, but smax
1095 * is positive, hence safe.
1097 reg
->s32_min_value
= reg
->u32_min_value
;
1098 reg
->s32_max_value
= reg
->u32_max_value
=
1099 min_t(u32
, reg
->s32_max_value
, reg
->u32_max_value
);
1100 } else if ((s32
)reg
->u32_min_value
< 0) {
1101 /* Negative. We can't learn anything from the smax, but smin
1102 * is negative, hence safe.
1104 reg
->s32_min_value
= reg
->u32_min_value
=
1105 max_t(u32
, reg
->s32_min_value
, reg
->u32_min_value
);
1106 reg
->s32_max_value
= reg
->u32_max_value
;
1110 static void __reg64_deduce_bounds(struct bpf_reg_state
*reg
)
1112 /* Learn sign from signed bounds.
1113 * If we cannot cross the sign boundary, then signed and unsigned bounds
1114 * are the same, so combine. This works even in the negative case, e.g.
1115 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1117 if (reg
->smin_value
>= 0 || reg
->smax_value
< 0) {
1118 reg
->smin_value
= reg
->umin_value
= max_t(u64
, reg
->smin_value
,
1120 reg
->smax_value
= reg
->umax_value
= min_t(u64
, reg
->smax_value
,
1124 /* Learn sign from unsigned bounds. Signed bounds cross the sign
1125 * boundary, so we must be careful.
1127 if ((s64
)reg
->umax_value
>= 0) {
1128 /* Positive. We can't learn anything from the smin, but smax
1129 * is positive, hence safe.
1131 reg
->smin_value
= reg
->umin_value
;
1132 reg
->smax_value
= reg
->umax_value
= min_t(u64
, reg
->smax_value
,
1134 } else if ((s64
)reg
->umin_value
< 0) {
1135 /* Negative. We can't learn anything from the smax, but smin
1136 * is negative, hence safe.
1138 reg
->smin_value
= reg
->umin_value
= max_t(u64
, reg
->smin_value
,
1140 reg
->smax_value
= reg
->umax_value
;
1144 static void __reg_deduce_bounds(struct bpf_reg_state
*reg
)
1146 __reg32_deduce_bounds(reg
);
1147 __reg64_deduce_bounds(reg
);
1150 /* Attempts to improve var_off based on unsigned min/max information */
1151 static void __reg_bound_offset(struct bpf_reg_state
*reg
)
1153 struct tnum var64_off
= tnum_intersect(reg
->var_off
,
1154 tnum_range(reg
->umin_value
,
1156 struct tnum var32_off
= tnum_intersect(tnum_subreg(reg
->var_off
),
1157 tnum_range(reg
->u32_min_value
,
1158 reg
->u32_max_value
));
1160 reg
->var_off
= tnum_or(tnum_clear_subreg(var64_off
), var32_off
);
1163 static void __reg_assign_32_into_64(struct bpf_reg_state
*reg
)
1165 reg
->umin_value
= reg
->u32_min_value
;
1166 reg
->umax_value
= reg
->u32_max_value
;
1167 /* Attempt to pull 32-bit signed bounds into 64-bit bounds
1168 * but must be positive otherwise set to worse case bounds
1169 * and refine later from tnum.
1171 if (reg
->s32_min_value
> 0)
1172 reg
->smin_value
= reg
->s32_min_value
;
1174 reg
->smin_value
= 0;
1175 if (reg
->s32_max_value
> 0)
1176 reg
->smax_value
= reg
->s32_max_value
;
1178 reg
->smax_value
= U32_MAX
;
1181 static void __reg_combine_32_into_64(struct bpf_reg_state
*reg
)
1183 /* special case when 64-bit register has upper 32-bit register
1184 * zeroed. Typically happens after zext or <<32, >>32 sequence
1185 * allowing us to use 32-bit bounds directly,
1187 if (tnum_equals_const(tnum_clear_subreg(reg
->var_off
), 0)) {
1188 __reg_assign_32_into_64(reg
);
1190 /* Otherwise the best we can do is push lower 32bit known and
1191 * unknown bits into register (var_off set from jmp logic)
1192 * then learn as much as possible from the 64-bit tnum
1193 * known and unknown bits. The previous smin/smax bounds are
1194 * invalid here because of jmp32 compare so mark them unknown
1195 * so they do not impact tnum bounds calculation.
1197 __mark_reg64_unbounded(reg
);
1198 __update_reg_bounds(reg
);
1201 /* Intersecting with the old var_off might have improved our bounds
1202 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1203 * then new var_off is (0; 0x7f...fc) which improves our umax.
1205 __reg_deduce_bounds(reg
);
1206 __reg_bound_offset(reg
);
1207 __update_reg_bounds(reg
);
1210 static bool __reg64_bound_s32(s64 a
)
1212 if (a
> S32_MIN
&& a
< S32_MAX
)
1217 static bool __reg64_bound_u32(u64 a
)
1219 if (a
> U32_MIN
&& a
< U32_MAX
)
1224 static void __reg_combine_64_into_32(struct bpf_reg_state
*reg
)
1226 __mark_reg32_unbounded(reg
);
1228 if (__reg64_bound_s32(reg
->smin_value
))
1229 reg
->s32_min_value
= (s32
)reg
->smin_value
;
1230 if (__reg64_bound_s32(reg
->smax_value
))
1231 reg
->s32_max_value
= (s32
)reg
->smax_value
;
1232 if (__reg64_bound_u32(reg
->umin_value
))
1233 reg
->u32_min_value
= (u32
)reg
->umin_value
;
1234 if (__reg64_bound_u32(reg
->umax_value
))
1235 reg
->u32_max_value
= (u32
)reg
->umax_value
;
1237 /* Intersecting with the old var_off might have improved our bounds
1238 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1239 * then new var_off is (0; 0x7f...fc) which improves our umax.
1241 __reg_deduce_bounds(reg
);
1242 __reg_bound_offset(reg
);
1243 __update_reg_bounds(reg
);
1246 /* Mark a register as having a completely unknown (scalar) value. */
1247 static void __mark_reg_unknown(const struct bpf_verifier_env
*env
,
1248 struct bpf_reg_state
*reg
)
1251 * Clear type, id, off, and union(map_ptr, range) and
1252 * padding between 'type' and union
1254 memset(reg
, 0, offsetof(struct bpf_reg_state
, var_off
));
1255 reg
->type
= SCALAR_VALUE
;
1256 reg
->var_off
= tnum_unknown
;
1258 reg
->precise
= env
->subprog_cnt
> 1 || !env
->allow_ptr_leaks
;
1259 __mark_reg_unbounded(reg
);
1262 static void mark_reg_unknown(struct bpf_verifier_env
*env
,
1263 struct bpf_reg_state
*regs
, u32 regno
)
1265 if (WARN_ON(regno
>= MAX_BPF_REG
)) {
1266 verbose(env
, "mark_reg_unknown(regs, %u)\n", regno
);
1267 /* Something bad happened, let's kill all regs except FP */
1268 for (regno
= 0; regno
< BPF_REG_FP
; regno
++)
1269 __mark_reg_not_init(env
, regs
+ regno
);
1272 __mark_reg_unknown(env
, regs
+ regno
);
1275 static void __mark_reg_not_init(const struct bpf_verifier_env
*env
,
1276 struct bpf_reg_state
*reg
)
1278 __mark_reg_unknown(env
, reg
);
1279 reg
->type
= NOT_INIT
;
1282 static void mark_reg_not_init(struct bpf_verifier_env
*env
,
1283 struct bpf_reg_state
*regs
, u32 regno
)
1285 if (WARN_ON(regno
>= MAX_BPF_REG
)) {
1286 verbose(env
, "mark_reg_not_init(regs, %u)\n", regno
);
1287 /* Something bad happened, let's kill all regs except FP */
1288 for (regno
= 0; regno
< BPF_REG_FP
; regno
++)
1289 __mark_reg_not_init(env
, regs
+ regno
);
1292 __mark_reg_not_init(env
, regs
+ regno
);
1295 #define DEF_NOT_SUBREG (0)
1296 static void init_reg_state(struct bpf_verifier_env
*env
,
1297 struct bpf_func_state
*state
)
1299 struct bpf_reg_state
*regs
= state
->regs
;
1302 for (i
= 0; i
< MAX_BPF_REG
; i
++) {
1303 mark_reg_not_init(env
, regs
, i
);
1304 regs
[i
].live
= REG_LIVE_NONE
;
1305 regs
[i
].parent
= NULL
;
1306 regs
[i
].subreg_def
= DEF_NOT_SUBREG
;
1310 regs
[BPF_REG_FP
].type
= PTR_TO_STACK
;
1311 mark_reg_known_zero(env
, regs
, BPF_REG_FP
);
1312 regs
[BPF_REG_FP
].frameno
= state
->frameno
;
1315 #define BPF_MAIN_FUNC (-1)
1316 static void init_func_state(struct bpf_verifier_env
*env
,
1317 struct bpf_func_state
*state
,
1318 int callsite
, int frameno
, int subprogno
)
1320 state
->callsite
= callsite
;
1321 state
->frameno
= frameno
;
1322 state
->subprogno
= subprogno
;
1323 init_reg_state(env
, state
);
1327 SRC_OP
, /* register is used as source operand */
1328 DST_OP
, /* register is used as destination operand */
1329 DST_OP_NO_MARK
/* same as above, check only, don't mark */
1332 static int cmp_subprogs(const void *a
, const void *b
)
1334 return ((struct bpf_subprog_info
*)a
)->start
-
1335 ((struct bpf_subprog_info
*)b
)->start
;
1338 static int find_subprog(struct bpf_verifier_env
*env
, int off
)
1340 struct bpf_subprog_info
*p
;
1342 p
= bsearch(&off
, env
->subprog_info
, env
->subprog_cnt
,
1343 sizeof(env
->subprog_info
[0]), cmp_subprogs
);
1346 return p
- env
->subprog_info
;
1350 static int add_subprog(struct bpf_verifier_env
*env
, int off
)
1352 int insn_cnt
= env
->prog
->len
;
1355 if (off
>= insn_cnt
|| off
< 0) {
1356 verbose(env
, "call to invalid destination\n");
1359 ret
= find_subprog(env
, off
);
1362 if (env
->subprog_cnt
>= BPF_MAX_SUBPROGS
) {
1363 verbose(env
, "too many subprograms\n");
1366 env
->subprog_info
[env
->subprog_cnt
++].start
= off
;
1367 sort(env
->subprog_info
, env
->subprog_cnt
,
1368 sizeof(env
->subprog_info
[0]), cmp_subprogs
, NULL
);
1372 static int check_subprogs(struct bpf_verifier_env
*env
)
1374 int i
, ret
, subprog_start
, subprog_end
, off
, cur_subprog
= 0;
1375 struct bpf_subprog_info
*subprog
= env
->subprog_info
;
1376 struct bpf_insn
*insn
= env
->prog
->insnsi
;
1377 int insn_cnt
= env
->prog
->len
;
1379 /* Add entry function. */
1380 ret
= add_subprog(env
, 0);
1384 /* determine subprog starts. The end is one before the next starts */
1385 for (i
= 0; i
< insn_cnt
; i
++) {
1386 if (insn
[i
].code
!= (BPF_JMP
| BPF_CALL
))
1388 if (insn
[i
].src_reg
!= BPF_PSEUDO_CALL
)
1390 if (!env
->allow_ptr_leaks
) {
1391 verbose(env
, "function calls to other bpf functions are allowed for root only\n");
1394 ret
= add_subprog(env
, i
+ insn
[i
].imm
+ 1);
1399 /* Add a fake 'exit' subprog which could simplify subprog iteration
1400 * logic. 'subprog_cnt' should not be increased.
1402 subprog
[env
->subprog_cnt
].start
= insn_cnt
;
1404 if (env
->log
.level
& BPF_LOG_LEVEL2
)
1405 for (i
= 0; i
< env
->subprog_cnt
; i
++)
1406 verbose(env
, "func#%d @%d\n", i
, subprog
[i
].start
);
1408 /* now check that all jumps are within the same subprog */
1409 subprog_start
= subprog
[cur_subprog
].start
;
1410 subprog_end
= subprog
[cur_subprog
+ 1].start
;
1411 for (i
= 0; i
< insn_cnt
; i
++) {
1412 u8 code
= insn
[i
].code
;
1414 if (BPF_CLASS(code
) != BPF_JMP
&& BPF_CLASS(code
) != BPF_JMP32
)
1416 if (BPF_OP(code
) == BPF_EXIT
|| BPF_OP(code
) == BPF_CALL
)
1418 off
= i
+ insn
[i
].off
+ 1;
1419 if (off
< subprog_start
|| off
>= subprog_end
) {
1420 verbose(env
, "jump out of range from insn %d to %d\n", i
, off
);
1424 if (i
== subprog_end
- 1) {
1425 /* to avoid fall-through from one subprog into another
1426 * the last insn of the subprog should be either exit
1427 * or unconditional jump back
1429 if (code
!= (BPF_JMP
| BPF_EXIT
) &&
1430 code
!= (BPF_JMP
| BPF_JA
)) {
1431 verbose(env
, "last insn is not an exit or jmp\n");
1434 subprog_start
= subprog_end
;
1436 if (cur_subprog
< env
->subprog_cnt
)
1437 subprog_end
= subprog
[cur_subprog
+ 1].start
;
1443 /* Parentage chain of this register (or stack slot) should take care of all
1444 * issues like callee-saved registers, stack slot allocation time, etc.
1446 static int mark_reg_read(struct bpf_verifier_env
*env
,
1447 const struct bpf_reg_state
*state
,
1448 struct bpf_reg_state
*parent
, u8 flag
)
1450 bool writes
= parent
== state
->parent
; /* Observe write marks */
1454 /* if read wasn't screened by an earlier write ... */
1455 if (writes
&& state
->live
& REG_LIVE_WRITTEN
)
1457 if (parent
->live
& REG_LIVE_DONE
) {
1458 verbose(env
, "verifier BUG type %s var_off %lld off %d\n",
1459 reg_type_str
[parent
->type
],
1460 parent
->var_off
.value
, parent
->off
);
1463 /* The first condition is more likely to be true than the
1464 * second, checked it first.
1466 if ((parent
->live
& REG_LIVE_READ
) == flag
||
1467 parent
->live
& REG_LIVE_READ64
)
1468 /* The parentage chain never changes and
1469 * this parent was already marked as LIVE_READ.
1470 * There is no need to keep walking the chain again and
1471 * keep re-marking all parents as LIVE_READ.
1472 * This case happens when the same register is read
1473 * multiple times without writes into it in-between.
1474 * Also, if parent has the stronger REG_LIVE_READ64 set,
1475 * then no need to set the weak REG_LIVE_READ32.
1478 /* ... then we depend on parent's value */
1479 parent
->live
|= flag
;
1480 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
1481 if (flag
== REG_LIVE_READ64
)
1482 parent
->live
&= ~REG_LIVE_READ32
;
1484 parent
= state
->parent
;
1489 if (env
->longest_mark_read_walk
< cnt
)
1490 env
->longest_mark_read_walk
= cnt
;
1494 /* This function is supposed to be used by the following 32-bit optimization
1495 * code only. It returns TRUE if the source or destination register operates
1496 * on 64-bit, otherwise return FALSE.
1498 static bool is_reg64(struct bpf_verifier_env
*env
, struct bpf_insn
*insn
,
1499 u32 regno
, struct bpf_reg_state
*reg
, enum reg_arg_type t
)
1504 class = BPF_CLASS(code
);
1506 if (class == BPF_JMP
) {
1507 /* BPF_EXIT for "main" will reach here. Return TRUE
1512 if (op
== BPF_CALL
) {
1513 /* BPF to BPF call will reach here because of marking
1514 * caller saved clobber with DST_OP_NO_MARK for which we
1515 * don't care the register def because they are anyway
1516 * marked as NOT_INIT already.
1518 if (insn
->src_reg
== BPF_PSEUDO_CALL
)
1520 /* Helper call will reach here because of arg type
1521 * check, conservatively return TRUE.
1530 if (class == BPF_ALU64
|| class == BPF_JMP
||
1531 /* BPF_END always use BPF_ALU class. */
1532 (class == BPF_ALU
&& op
== BPF_END
&& insn
->imm
== 64))
1535 if (class == BPF_ALU
|| class == BPF_JMP32
)
1538 if (class == BPF_LDX
) {
1540 return BPF_SIZE(code
) == BPF_DW
;
1541 /* LDX source must be ptr. */
1545 if (class == BPF_STX
) {
1546 if (reg
->type
!= SCALAR_VALUE
)
1548 return BPF_SIZE(code
) == BPF_DW
;
1551 if (class == BPF_LD
) {
1552 u8 mode
= BPF_MODE(code
);
1555 if (mode
== BPF_IMM
)
1558 /* Both LD_IND and LD_ABS return 32-bit data. */
1562 /* Implicit ctx ptr. */
1563 if (regno
== BPF_REG_6
)
1566 /* Explicit source could be any width. */
1570 if (class == BPF_ST
)
1571 /* The only source register for BPF_ST is a ptr. */
1574 /* Conservatively return true at default. */
1578 /* Return TRUE if INSN doesn't have explicit value define. */
1579 static bool insn_no_def(struct bpf_insn
*insn
)
1581 u8
class = BPF_CLASS(insn
->code
);
1583 return (class == BPF_JMP
|| class == BPF_JMP32
||
1584 class == BPF_STX
|| class == BPF_ST
);
1587 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
1588 static bool insn_has_def32(struct bpf_verifier_env
*env
, struct bpf_insn
*insn
)
1590 if (insn_no_def(insn
))
1593 return !is_reg64(env
, insn
, insn
->dst_reg
, NULL
, DST_OP
);
1596 static void mark_insn_zext(struct bpf_verifier_env
*env
,
1597 struct bpf_reg_state
*reg
)
1599 s32 def_idx
= reg
->subreg_def
;
1601 if (def_idx
== DEF_NOT_SUBREG
)
1604 env
->insn_aux_data
[def_idx
- 1].zext_dst
= true;
1605 /* The dst will be zero extended, so won't be sub-register anymore. */
1606 reg
->subreg_def
= DEF_NOT_SUBREG
;
1609 static int check_reg_arg(struct bpf_verifier_env
*env
, u32 regno
,
1610 enum reg_arg_type t
)
1612 struct bpf_verifier_state
*vstate
= env
->cur_state
;
1613 struct bpf_func_state
*state
= vstate
->frame
[vstate
->curframe
];
1614 struct bpf_insn
*insn
= env
->prog
->insnsi
+ env
->insn_idx
;
1615 struct bpf_reg_state
*reg
, *regs
= state
->regs
;
1618 if (regno
>= MAX_BPF_REG
) {
1619 verbose(env
, "R%d is invalid\n", regno
);
1624 rw64
= is_reg64(env
, insn
, regno
, reg
, t
);
1626 /* check whether register used as source operand can be read */
1627 if (reg
->type
== NOT_INIT
) {
1628 verbose(env
, "R%d !read_ok\n", regno
);
1631 /* We don't need to worry about FP liveness because it's read-only */
1632 if (regno
== BPF_REG_FP
)
1636 mark_insn_zext(env
, reg
);
1638 return mark_reg_read(env
, reg
, reg
->parent
,
1639 rw64
? REG_LIVE_READ64
: REG_LIVE_READ32
);
1641 /* check whether register used as dest operand can be written to */
1642 if (regno
== BPF_REG_FP
) {
1643 verbose(env
, "frame pointer is read only\n");
1646 reg
->live
|= REG_LIVE_WRITTEN
;
1647 reg
->subreg_def
= rw64
? DEF_NOT_SUBREG
: env
->insn_idx
+ 1;
1649 mark_reg_unknown(env
, regs
, regno
);
1654 /* for any branch, call, exit record the history of jmps in the given state */
1655 static int push_jmp_history(struct bpf_verifier_env
*env
,
1656 struct bpf_verifier_state
*cur
)
1658 u32 cnt
= cur
->jmp_history_cnt
;
1659 struct bpf_idx_pair
*p
;
1662 p
= krealloc(cur
->jmp_history
, cnt
* sizeof(*p
), GFP_USER
);
1665 p
[cnt
- 1].idx
= env
->insn_idx
;
1666 p
[cnt
- 1].prev_idx
= env
->prev_insn_idx
;
1667 cur
->jmp_history
= p
;
1668 cur
->jmp_history_cnt
= cnt
;
1672 /* Backtrack one insn at a time. If idx is not at the top of recorded
1673 * history then previous instruction came from straight line execution.
1675 static int get_prev_insn_idx(struct bpf_verifier_state
*st
, int i
,
1680 if (cnt
&& st
->jmp_history
[cnt
- 1].idx
== i
) {
1681 i
= st
->jmp_history
[cnt
- 1].prev_idx
;
1689 /* For given verifier state backtrack_insn() is called from the last insn to
1690 * the first insn. Its purpose is to compute a bitmask of registers and
1691 * stack slots that needs precision in the parent verifier state.
1693 static int backtrack_insn(struct bpf_verifier_env
*env
, int idx
,
1694 u32
*reg_mask
, u64
*stack_mask
)
1696 const struct bpf_insn_cbs cbs
= {
1697 .cb_print
= verbose
,
1698 .private_data
= env
,
1700 struct bpf_insn
*insn
= env
->prog
->insnsi
+ idx
;
1701 u8
class = BPF_CLASS(insn
->code
);
1702 u8 opcode
= BPF_OP(insn
->code
);
1703 u8 mode
= BPF_MODE(insn
->code
);
1704 u32 dreg
= 1u << insn
->dst_reg
;
1705 u32 sreg
= 1u << insn
->src_reg
;
1708 if (insn
->code
== 0)
1710 if (env
->log
.level
& BPF_LOG_LEVEL
) {
1711 verbose(env
, "regs=%x stack=%llx before ", *reg_mask
, *stack_mask
);
1712 verbose(env
, "%d: ", idx
);
1713 print_bpf_insn(&cbs
, insn
, env
->allow_ptr_leaks
);
1716 if (class == BPF_ALU
|| class == BPF_ALU64
) {
1717 if (!(*reg_mask
& dreg
))
1719 if (opcode
== BPF_MOV
) {
1720 if (BPF_SRC(insn
->code
) == BPF_X
) {
1722 * dreg needs precision after this insn
1723 * sreg needs precision before this insn
1729 * dreg needs precision after this insn.
1730 * Corresponding register is already marked
1731 * as precise=true in this verifier state.
1732 * No further markings in parent are necessary
1737 if (BPF_SRC(insn
->code
) == BPF_X
) {
1739 * both dreg and sreg need precision
1744 * dreg still needs precision before this insn
1747 } else if (class == BPF_LDX
) {
1748 if (!(*reg_mask
& dreg
))
1752 /* scalars can only be spilled into stack w/o losing precision.
1753 * Load from any other memory can be zero extended.
1754 * The desire to keep that precision is already indicated
1755 * by 'precise' mark in corresponding register of this state.
1756 * No further tracking necessary.
1758 if (insn
->src_reg
!= BPF_REG_FP
)
1760 if (BPF_SIZE(insn
->code
) != BPF_DW
)
1763 /* dreg = *(u64 *)[fp - off] was a fill from the stack.
1764 * that [fp - off] slot contains scalar that needs to be
1765 * tracked with precision
1767 spi
= (-insn
->off
- 1) / BPF_REG_SIZE
;
1769 verbose(env
, "BUG spi %d\n", spi
);
1770 WARN_ONCE(1, "verifier backtracking bug");
1773 *stack_mask
|= 1ull << spi
;
1774 } else if (class == BPF_STX
|| class == BPF_ST
) {
1775 if (*reg_mask
& dreg
)
1776 /* stx & st shouldn't be using _scalar_ dst_reg
1777 * to access memory. It means backtracking
1778 * encountered a case of pointer subtraction.
1781 /* scalars can only be spilled into stack */
1782 if (insn
->dst_reg
!= BPF_REG_FP
)
1784 if (BPF_SIZE(insn
->code
) != BPF_DW
)
1786 spi
= (-insn
->off
- 1) / BPF_REG_SIZE
;
1788 verbose(env
, "BUG spi %d\n", spi
);
1789 WARN_ONCE(1, "verifier backtracking bug");
1792 if (!(*stack_mask
& (1ull << spi
)))
1794 *stack_mask
&= ~(1ull << spi
);
1795 if (class == BPF_STX
)
1797 } else if (class == BPF_JMP
|| class == BPF_JMP32
) {
1798 if (opcode
== BPF_CALL
) {
1799 if (insn
->src_reg
== BPF_PSEUDO_CALL
)
1801 /* regular helper call sets R0 */
1803 if (*reg_mask
& 0x3f) {
1804 /* if backtracing was looking for registers R1-R5
1805 * they should have been found already.
1807 verbose(env
, "BUG regs %x\n", *reg_mask
);
1808 WARN_ONCE(1, "verifier backtracking bug");
1811 } else if (opcode
== BPF_EXIT
) {
1814 } else if (class == BPF_LD
) {
1815 if (!(*reg_mask
& dreg
))
1818 /* It's ld_imm64 or ld_abs or ld_ind.
1819 * For ld_imm64 no further tracking of precision
1820 * into parent is necessary
1822 if (mode
== BPF_IND
|| mode
== BPF_ABS
)
1823 /* to be analyzed */
1829 /* the scalar precision tracking algorithm:
1830 * . at the start all registers have precise=false.
1831 * . scalar ranges are tracked as normal through alu and jmp insns.
1832 * . once precise value of the scalar register is used in:
1833 * . ptr + scalar alu
1834 * . if (scalar cond K|scalar)
1835 * . helper_call(.., scalar, ...) where ARG_CONST is expected
1836 * backtrack through the verifier states and mark all registers and
1837 * stack slots with spilled constants that these scalar regisers
1838 * should be precise.
1839 * . during state pruning two registers (or spilled stack slots)
1840 * are equivalent if both are not precise.
1842 * Note the verifier cannot simply walk register parentage chain,
1843 * since many different registers and stack slots could have been
1844 * used to compute single precise scalar.
1846 * The approach of starting with precise=true for all registers and then
1847 * backtrack to mark a register as not precise when the verifier detects
1848 * that program doesn't care about specific value (e.g., when helper
1849 * takes register as ARG_ANYTHING parameter) is not safe.
1851 * It's ok to walk single parentage chain of the verifier states.
1852 * It's possible that this backtracking will go all the way till 1st insn.
1853 * All other branches will be explored for needing precision later.
1855 * The backtracking needs to deal with cases like:
1856 * R8=map_value(id=0,off=0,ks=4,vs=1952,imm=0) R9_w=map_value(id=0,off=40,ks=4,vs=1952,imm=0)
1859 * if r5 > 0x79f goto pc+7
1860 * R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
1863 * call bpf_perf_event_output#25
1864 * where .arg5_type = ARG_CONST_SIZE_OR_ZERO
1868 * call foo // uses callee's r6 inside to compute r0
1872 * to track above reg_mask/stack_mask needs to be independent for each frame.
1874 * Also if parent's curframe > frame where backtracking started,
1875 * the verifier need to mark registers in both frames, otherwise callees
1876 * may incorrectly prune callers. This is similar to
1877 * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
1879 * For now backtracking falls back into conservative marking.
1881 static void mark_all_scalars_precise(struct bpf_verifier_env
*env
,
1882 struct bpf_verifier_state
*st
)
1884 struct bpf_func_state
*func
;
1885 struct bpf_reg_state
*reg
;
1888 /* big hammer: mark all scalars precise in this path.
1889 * pop_stack may still get !precise scalars.
1891 for (; st
; st
= st
->parent
)
1892 for (i
= 0; i
<= st
->curframe
; i
++) {
1893 func
= st
->frame
[i
];
1894 for (j
= 0; j
< BPF_REG_FP
; j
++) {
1895 reg
= &func
->regs
[j
];
1896 if (reg
->type
!= SCALAR_VALUE
)
1898 reg
->precise
= true;
1900 for (j
= 0; j
< func
->allocated_stack
/ BPF_REG_SIZE
; j
++) {
1901 if (func
->stack
[j
].slot_type
[0] != STACK_SPILL
)
1903 reg
= &func
->stack
[j
].spilled_ptr
;
1904 if (reg
->type
!= SCALAR_VALUE
)
1906 reg
->precise
= true;
1911 static int __mark_chain_precision(struct bpf_verifier_env
*env
, int regno
,
1914 struct bpf_verifier_state
*st
= env
->cur_state
;
1915 int first_idx
= st
->first_insn_idx
;
1916 int last_idx
= env
->insn_idx
;
1917 struct bpf_func_state
*func
;
1918 struct bpf_reg_state
*reg
;
1919 u32 reg_mask
= regno
>= 0 ? 1u << regno
: 0;
1920 u64 stack_mask
= spi
>= 0 ? 1ull << spi
: 0;
1921 bool skip_first
= true;
1922 bool new_marks
= false;
1925 if (!env
->allow_ptr_leaks
)
1926 /* backtracking is root only for now */
1929 func
= st
->frame
[st
->curframe
];
1931 reg
= &func
->regs
[regno
];
1932 if (reg
->type
!= SCALAR_VALUE
) {
1933 WARN_ONCE(1, "backtracing misuse");
1940 reg
->precise
= true;
1944 if (func
->stack
[spi
].slot_type
[0] != STACK_SPILL
) {
1948 reg
= &func
->stack
[spi
].spilled_ptr
;
1949 if (reg
->type
!= SCALAR_VALUE
) {
1957 reg
->precise
= true;
1963 if (!reg_mask
&& !stack_mask
)
1966 DECLARE_BITMAP(mask
, 64);
1967 u32 history
= st
->jmp_history_cnt
;
1969 if (env
->log
.level
& BPF_LOG_LEVEL
)
1970 verbose(env
, "last_idx %d first_idx %d\n", last_idx
, first_idx
);
1971 for (i
= last_idx
;;) {
1976 err
= backtrack_insn(env
, i
, ®_mask
, &stack_mask
);
1978 if (err
== -ENOTSUPP
) {
1979 mark_all_scalars_precise(env
, st
);
1984 if (!reg_mask
&& !stack_mask
)
1985 /* Found assignment(s) into tracked register in this state.
1986 * Since this state is already marked, just return.
1987 * Nothing to be tracked further in the parent state.
1992 i
= get_prev_insn_idx(st
, i
, &history
);
1993 if (i
>= env
->prog
->len
) {
1994 /* This can happen if backtracking reached insn 0
1995 * and there are still reg_mask or stack_mask
1997 * It means the backtracking missed the spot where
1998 * particular register was initialized with a constant.
2000 verbose(env
, "BUG backtracking idx %d\n", i
);
2001 WARN_ONCE(1, "verifier backtracking bug");
2010 func
= st
->frame
[st
->curframe
];
2011 bitmap_from_u64(mask
, reg_mask
);
2012 for_each_set_bit(i
, mask
, 32) {
2013 reg
= &func
->regs
[i
];
2014 if (reg
->type
!= SCALAR_VALUE
) {
2015 reg_mask
&= ~(1u << i
);
2020 reg
->precise
= true;
2023 bitmap_from_u64(mask
, stack_mask
);
2024 for_each_set_bit(i
, mask
, 64) {
2025 if (i
>= func
->allocated_stack
/ BPF_REG_SIZE
) {
2026 /* the sequence of instructions:
2028 * 3: (7b) *(u64 *)(r3 -8) = r0
2029 * 4: (79) r4 = *(u64 *)(r10 -8)
2030 * doesn't contain jmps. It's backtracked
2031 * as a single block.
2032 * During backtracking insn 3 is not recognized as
2033 * stack access, so at the end of backtracking
2034 * stack slot fp-8 is still marked in stack_mask.
2035 * However the parent state may not have accessed
2036 * fp-8 and it's "unallocated" stack space.
2037 * In such case fallback to conservative.
2039 mark_all_scalars_precise(env
, st
);
2043 if (func
->stack
[i
].slot_type
[0] != STACK_SPILL
) {
2044 stack_mask
&= ~(1ull << i
);
2047 reg
= &func
->stack
[i
].spilled_ptr
;
2048 if (reg
->type
!= SCALAR_VALUE
) {
2049 stack_mask
&= ~(1ull << i
);
2054 reg
->precise
= true;
2056 if (env
->log
.level
& BPF_LOG_LEVEL
) {
2057 print_verifier_state(env
, func
);
2058 verbose(env
, "parent %s regs=%x stack=%llx marks\n",
2059 new_marks
? "didn't have" : "already had",
2060 reg_mask
, stack_mask
);
2063 if (!reg_mask
&& !stack_mask
)
2068 last_idx
= st
->last_insn_idx
;
2069 first_idx
= st
->first_insn_idx
;
2074 static int mark_chain_precision(struct bpf_verifier_env
*env
, int regno
)
2076 return __mark_chain_precision(env
, regno
, -1);
2079 static int mark_chain_precision_stack(struct bpf_verifier_env
*env
, int spi
)
2081 return __mark_chain_precision(env
, -1, spi
);
2084 static bool is_spillable_regtype(enum bpf_reg_type type
)
2087 case PTR_TO_MAP_VALUE
:
2088 case PTR_TO_MAP_VALUE_OR_NULL
:
2092 case PTR_TO_PACKET_META
:
2093 case PTR_TO_PACKET_END
:
2094 case PTR_TO_FLOW_KEYS
:
2095 case CONST_PTR_TO_MAP
:
2097 case PTR_TO_SOCKET_OR_NULL
:
2098 case PTR_TO_SOCK_COMMON
:
2099 case PTR_TO_SOCK_COMMON_OR_NULL
:
2100 case PTR_TO_TCP_SOCK
:
2101 case PTR_TO_TCP_SOCK_OR_NULL
:
2102 case PTR_TO_XDP_SOCK
:
2110 /* Does this register contain a constant zero? */
2111 static bool register_is_null(struct bpf_reg_state
*reg
)
2113 return reg
->type
== SCALAR_VALUE
&& tnum_equals_const(reg
->var_off
, 0);
2116 static bool register_is_const(struct bpf_reg_state
*reg
)
2118 return reg
->type
== SCALAR_VALUE
&& tnum_is_const(reg
->var_off
);
2121 static bool __is_pointer_value(bool allow_ptr_leaks
,
2122 const struct bpf_reg_state
*reg
)
2124 if (allow_ptr_leaks
)
2127 return reg
->type
!= SCALAR_VALUE
;
2130 static void save_register_state(struct bpf_func_state
*state
,
2131 int spi
, struct bpf_reg_state
*reg
)
2135 state
->stack
[spi
].spilled_ptr
= *reg
;
2136 state
->stack
[spi
].spilled_ptr
.live
|= REG_LIVE_WRITTEN
;
2138 for (i
= 0; i
< BPF_REG_SIZE
; i
++)
2139 state
->stack
[spi
].slot_type
[i
] = STACK_SPILL
;
2142 /* check_stack_read/write functions track spill/fill of registers,
2143 * stack boundary and alignment are checked in check_mem_access()
2145 static int check_stack_write(struct bpf_verifier_env
*env
,
2146 struct bpf_func_state
*state
, /* func where register points to */
2147 int off
, int size
, int value_regno
, int insn_idx
)
2149 struct bpf_func_state
*cur
; /* state of the current function */
2150 int i
, slot
= -off
- 1, spi
= slot
/ BPF_REG_SIZE
, err
;
2151 u32 dst_reg
= env
->prog
->insnsi
[insn_idx
].dst_reg
;
2152 struct bpf_reg_state
*reg
= NULL
;
2154 err
= realloc_func_state(state
, round_up(slot
+ 1, BPF_REG_SIZE
),
2155 state
->acquired_refs
, true);
2158 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
2159 * so it's aligned access and [off, off + size) are within stack limits
2161 if (!env
->allow_ptr_leaks
&&
2162 state
->stack
[spi
].slot_type
[0] == STACK_SPILL
&&
2163 size
!= BPF_REG_SIZE
) {
2164 verbose(env
, "attempt to corrupt spilled pointer on stack\n");
2168 cur
= env
->cur_state
->frame
[env
->cur_state
->curframe
];
2169 if (value_regno
>= 0)
2170 reg
= &cur
->regs
[value_regno
];
2172 if (reg
&& size
== BPF_REG_SIZE
&& register_is_const(reg
) &&
2173 !register_is_null(reg
) && env
->allow_ptr_leaks
) {
2174 if (dst_reg
!= BPF_REG_FP
) {
2175 /* The backtracking logic can only recognize explicit
2176 * stack slot address like [fp - 8]. Other spill of
2177 * scalar via different register has to be conervative.
2178 * Backtrack from here and mark all registers as precise
2179 * that contributed into 'reg' being a constant.
2181 err
= mark_chain_precision(env
, value_regno
);
2185 save_register_state(state
, spi
, reg
);
2186 } else if (reg
&& is_spillable_regtype(reg
->type
)) {
2187 /* register containing pointer is being spilled into stack */
2188 if (size
!= BPF_REG_SIZE
) {
2189 verbose_linfo(env
, insn_idx
, "; ");
2190 verbose(env
, "invalid size of register spill\n");
2194 if (state
!= cur
&& reg
->type
== PTR_TO_STACK
) {
2195 verbose(env
, "cannot spill pointers to stack into stack frame of the caller\n");
2199 if (!env
->allow_ptr_leaks
) {
2200 bool sanitize
= false;
2202 if (state
->stack
[spi
].slot_type
[0] == STACK_SPILL
&&
2203 register_is_const(&state
->stack
[spi
].spilled_ptr
))
2205 for (i
= 0; i
< BPF_REG_SIZE
; i
++)
2206 if (state
->stack
[spi
].slot_type
[i
] == STACK_MISC
) {
2211 int *poff
= &env
->insn_aux_data
[insn_idx
].sanitize_stack_off
;
2212 int soff
= (-spi
- 1) * BPF_REG_SIZE
;
2214 /* detected reuse of integer stack slot with a pointer
2215 * which means either llvm is reusing stack slot or
2216 * an attacker is trying to exploit CVE-2018-3639
2217 * (speculative store bypass)
2218 * Have to sanitize that slot with preemptive
2221 if (*poff
&& *poff
!= soff
) {
2222 /* disallow programs where single insn stores
2223 * into two different stack slots, since verifier
2224 * cannot sanitize them
2227 "insn %d cannot access two stack slots fp%d and fp%d",
2228 insn_idx
, *poff
, soff
);
2234 save_register_state(state
, spi
, reg
);
2236 u8 type
= STACK_MISC
;
2238 /* regular write of data into stack destroys any spilled ptr */
2239 state
->stack
[spi
].spilled_ptr
.type
= NOT_INIT
;
2240 /* Mark slots as STACK_MISC if they belonged to spilled ptr. */
2241 if (state
->stack
[spi
].slot_type
[0] == STACK_SPILL
)
2242 for (i
= 0; i
< BPF_REG_SIZE
; i
++)
2243 state
->stack
[spi
].slot_type
[i
] = STACK_MISC
;
2245 /* only mark the slot as written if all 8 bytes were written
2246 * otherwise read propagation may incorrectly stop too soon
2247 * when stack slots are partially written.
2248 * This heuristic means that read propagation will be
2249 * conservative, since it will add reg_live_read marks
2250 * to stack slots all the way to first state when programs
2251 * writes+reads less than 8 bytes
2253 if (size
== BPF_REG_SIZE
)
2254 state
->stack
[spi
].spilled_ptr
.live
|= REG_LIVE_WRITTEN
;
2256 /* when we zero initialize stack slots mark them as such */
2257 if (reg
&& register_is_null(reg
)) {
2258 /* backtracking doesn't work for STACK_ZERO yet. */
2259 err
= mark_chain_precision(env
, value_regno
);
2265 /* Mark slots affected by this stack write. */
2266 for (i
= 0; i
< size
; i
++)
2267 state
->stack
[spi
].slot_type
[(slot
- i
) % BPF_REG_SIZE
] =
2273 static int check_stack_read(struct bpf_verifier_env
*env
,
2274 struct bpf_func_state
*reg_state
/* func where register points to */,
2275 int off
, int size
, int value_regno
)
2277 struct bpf_verifier_state
*vstate
= env
->cur_state
;
2278 struct bpf_func_state
*state
= vstate
->frame
[vstate
->curframe
];
2279 int i
, slot
= -off
- 1, spi
= slot
/ BPF_REG_SIZE
;
2280 struct bpf_reg_state
*reg
;
2283 if (reg_state
->allocated_stack
<= slot
) {
2284 verbose(env
, "invalid read from stack off %d+0 size %d\n",
2288 stype
= reg_state
->stack
[spi
].slot_type
;
2289 reg
= ®_state
->stack
[spi
].spilled_ptr
;
2291 if (stype
[0] == STACK_SPILL
) {
2292 if (size
!= BPF_REG_SIZE
) {
2293 if (reg
->type
!= SCALAR_VALUE
) {
2294 verbose_linfo(env
, env
->insn_idx
, "; ");
2295 verbose(env
, "invalid size of register fill\n");
2298 if (value_regno
>= 0) {
2299 mark_reg_unknown(env
, state
->regs
, value_regno
);
2300 state
->regs
[value_regno
].live
|= REG_LIVE_WRITTEN
;
2302 mark_reg_read(env
, reg
, reg
->parent
, REG_LIVE_READ64
);
2305 for (i
= 1; i
< BPF_REG_SIZE
; i
++) {
2306 if (stype
[(slot
- i
) % BPF_REG_SIZE
] != STACK_SPILL
) {
2307 verbose(env
, "corrupted spill memory\n");
2312 if (value_regno
>= 0) {
2313 /* restore register state from stack */
2314 state
->regs
[value_regno
] = *reg
;
2315 /* mark reg as written since spilled pointer state likely
2316 * has its liveness marks cleared by is_state_visited()
2317 * which resets stack/reg liveness for state transitions
2319 state
->regs
[value_regno
].live
|= REG_LIVE_WRITTEN
;
2320 } else if (__is_pointer_value(env
->allow_ptr_leaks
, reg
)) {
2321 /* If value_regno==-1, the caller is asking us whether
2322 * it is acceptable to use this value as a SCALAR_VALUE
2324 * We must not allow unprivileged callers to do that
2325 * with spilled pointers.
2327 verbose(env
, "leaking pointer from stack off %d\n",
2331 mark_reg_read(env
, reg
, reg
->parent
, REG_LIVE_READ64
);
2335 for (i
= 0; i
< size
; i
++) {
2336 if (stype
[(slot
- i
) % BPF_REG_SIZE
] == STACK_MISC
)
2338 if (stype
[(slot
- i
) % BPF_REG_SIZE
] == STACK_ZERO
) {
2342 verbose(env
, "invalid read from stack off %d+%d size %d\n",
2346 mark_reg_read(env
, reg
, reg
->parent
, REG_LIVE_READ64
);
2347 if (value_regno
>= 0) {
2348 if (zeros
== size
) {
2349 /* any size read into register is zero extended,
2350 * so the whole register == const_zero
2352 __mark_reg_const_zero(&state
->regs
[value_regno
]);
2353 /* backtracking doesn't support STACK_ZERO yet,
2354 * so mark it precise here, so that later
2355 * backtracking can stop here.
2356 * Backtracking may not need this if this register
2357 * doesn't participate in pointer adjustment.
2358 * Forward propagation of precise flag is not
2359 * necessary either. This mark is only to stop
2360 * backtracking. Any register that contributed
2361 * to const 0 was marked precise before spill.
2363 state
->regs
[value_regno
].precise
= true;
2365 /* have read misc data from the stack */
2366 mark_reg_unknown(env
, state
->regs
, value_regno
);
2368 state
->regs
[value_regno
].live
|= REG_LIVE_WRITTEN
;
2374 static int check_stack_access(struct bpf_verifier_env
*env
,
2375 const struct bpf_reg_state
*reg
,
2378 /* Stack accesses must be at a fixed offset, so that we
2379 * can determine what type of data were returned. See
2380 * check_stack_read().
2382 if (!tnum_is_const(reg
->var_off
)) {
2385 tnum_strn(tn_buf
, sizeof(tn_buf
), reg
->var_off
);
2386 verbose(env
, "variable stack access var_off=%s off=%d size=%d\n",
2391 if (off
>= 0 || off
< -MAX_BPF_STACK
) {
2392 verbose(env
, "invalid stack off=%d size=%d\n", off
, size
);
2399 static int check_map_access_type(struct bpf_verifier_env
*env
, u32 regno
,
2400 int off
, int size
, enum bpf_access_type type
)
2402 struct bpf_reg_state
*regs
= cur_regs(env
);
2403 struct bpf_map
*map
= regs
[regno
].map_ptr
;
2404 u32 cap
= bpf_map_flags_to_cap(map
);
2406 if (type
== BPF_WRITE
&& !(cap
& BPF_MAP_CAN_WRITE
)) {
2407 verbose(env
, "write into map forbidden, value_size=%d off=%d size=%d\n",
2408 map
->value_size
, off
, size
);
2412 if (type
== BPF_READ
&& !(cap
& BPF_MAP_CAN_READ
)) {
2413 verbose(env
, "read from map forbidden, value_size=%d off=%d size=%d\n",
2414 map
->value_size
, off
, size
);
2421 /* check read/write into map element returned by bpf_map_lookup_elem() */
2422 static int __check_map_access(struct bpf_verifier_env
*env
, u32 regno
, int off
,
2423 int size
, bool zero_size_allowed
)
2425 struct bpf_reg_state
*regs
= cur_regs(env
);
2426 struct bpf_map
*map
= regs
[regno
].map_ptr
;
2428 if (off
< 0 || size
< 0 || (size
== 0 && !zero_size_allowed
) ||
2429 off
+ size
> map
->value_size
) {
2430 verbose(env
, "invalid access to map value, value_size=%d off=%d size=%d\n",
2431 map
->value_size
, off
, size
);
2437 /* check read/write into a map element with possible variable offset */
2438 static int check_map_access(struct bpf_verifier_env
*env
, u32 regno
,
2439 int off
, int size
, bool zero_size_allowed
)
2441 struct bpf_verifier_state
*vstate
= env
->cur_state
;
2442 struct bpf_func_state
*state
= vstate
->frame
[vstate
->curframe
];
2443 struct bpf_reg_state
*reg
= &state
->regs
[regno
];
2446 /* We may have adjusted the register to this map value, so we
2447 * need to try adding each of min_value and max_value to off
2448 * to make sure our theoretical access will be safe.
2450 if (env
->log
.level
& BPF_LOG_LEVEL
)
2451 print_verifier_state(env
, state
);
2453 /* The minimum value is only important with signed
2454 * comparisons where we can't assume the floor of a
2455 * value is 0. If we are using signed variables for our
2456 * index'es we need to make sure that whatever we use
2457 * will have a set floor within our range.
2459 if (reg
->smin_value
< 0 &&
2460 (reg
->smin_value
== S64_MIN
||
2461 (off
+ reg
->smin_value
!= (s64
)(s32
)(off
+ reg
->smin_value
)) ||
2462 reg
->smin_value
+ off
< 0)) {
2463 verbose(env
, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
2467 err
= __check_map_access(env
, regno
, reg
->smin_value
+ off
, size
,
2470 verbose(env
, "R%d min value is outside of the array range\n",
2475 /* If we haven't set a max value then we need to bail since we can't be
2476 * sure we won't do bad things.
2477 * If reg->umax_value + off could overflow, treat that as unbounded too.
2479 if (reg
->umax_value
>= BPF_MAX_VAR_OFF
) {
2480 verbose(env
, "R%d unbounded memory access, make sure to bounds check any array access into a map\n",
2484 err
= __check_map_access(env
, regno
, reg
->umax_value
+ off
, size
,
2487 verbose(env
, "R%d max value is outside of the array range\n",
2490 if (map_value_has_spin_lock(reg
->map_ptr
)) {
2491 u32 lock
= reg
->map_ptr
->spin_lock_off
;
2493 /* if any part of struct bpf_spin_lock can be touched by
2494 * load/store reject this program.
2495 * To check that [x1, x2) overlaps with [y1, y2)
2496 * it is sufficient to check x1 < y2 && y1 < x2.
2498 if (reg
->smin_value
+ off
< lock
+ sizeof(struct bpf_spin_lock
) &&
2499 lock
< reg
->umax_value
+ off
+ size
) {
2500 verbose(env
, "bpf_spin_lock cannot be accessed directly by load/store\n");
2507 #define MAX_PACKET_OFF 0xffff
2509 static bool may_access_direct_pkt_data(struct bpf_verifier_env
*env
,
2510 const struct bpf_call_arg_meta
*meta
,
2511 enum bpf_access_type t
)
2513 switch (env
->prog
->type
) {
2514 /* Program types only with direct read access go here! */
2515 case BPF_PROG_TYPE_LWT_IN
:
2516 case BPF_PROG_TYPE_LWT_OUT
:
2517 case BPF_PROG_TYPE_LWT_SEG6LOCAL
:
2518 case BPF_PROG_TYPE_SK_REUSEPORT
:
2519 case BPF_PROG_TYPE_FLOW_DISSECTOR
:
2520 case BPF_PROG_TYPE_CGROUP_SKB
:
2525 /* Program types with direct read + write access go here! */
2526 case BPF_PROG_TYPE_SCHED_CLS
:
2527 case BPF_PROG_TYPE_SCHED_ACT
:
2528 case BPF_PROG_TYPE_XDP
:
2529 case BPF_PROG_TYPE_LWT_XMIT
:
2530 case BPF_PROG_TYPE_SK_SKB
:
2531 case BPF_PROG_TYPE_SK_MSG
:
2533 return meta
->pkt_access
;
2535 env
->seen_direct_write
= true;
2538 case BPF_PROG_TYPE_CGROUP_SOCKOPT
:
2540 env
->seen_direct_write
= true;
2549 static int __check_packet_access(struct bpf_verifier_env
*env
, u32 regno
,
2550 int off
, int size
, bool zero_size_allowed
)
2552 struct bpf_reg_state
*regs
= cur_regs(env
);
2553 struct bpf_reg_state
*reg
= ®s
[regno
];
2555 if (off
< 0 || size
< 0 || (size
== 0 && !zero_size_allowed
) ||
2556 (u64
)off
+ size
> reg
->range
) {
2557 verbose(env
, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
2558 off
, size
, regno
, reg
->id
, reg
->off
, reg
->range
);
2564 static int check_packet_access(struct bpf_verifier_env
*env
, u32 regno
, int off
,
2565 int size
, bool zero_size_allowed
)
2567 struct bpf_reg_state
*regs
= cur_regs(env
);
2568 struct bpf_reg_state
*reg
= ®s
[regno
];
2571 /* We may have added a variable offset to the packet pointer; but any
2572 * reg->range we have comes after that. We are only checking the fixed
2576 /* We don't allow negative numbers, because we aren't tracking enough
2577 * detail to prove they're safe.
2579 if (reg
->smin_value
< 0) {
2580 verbose(env
, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
2584 err
= __check_packet_access(env
, regno
, off
, size
, zero_size_allowed
);
2586 verbose(env
, "R%d offset is outside of the packet\n", regno
);
2590 /* __check_packet_access has made sure "off + size - 1" is within u16.
2591 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
2592 * otherwise find_good_pkt_pointers would have refused to set range info
2593 * that __check_packet_access would have rejected this pkt access.
2594 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
2596 env
->prog
->aux
->max_pkt_offset
=
2597 max_t(u32
, env
->prog
->aux
->max_pkt_offset
,
2598 off
+ reg
->umax_value
+ size
- 1);
2603 /* check access to 'struct bpf_context' fields. Supports fixed offsets only */
2604 static int check_ctx_access(struct bpf_verifier_env
*env
, int insn_idx
, int off
, int size
,
2605 enum bpf_access_type t
, enum bpf_reg_type
*reg_type
,
2608 struct bpf_insn_access_aux info
= {
2609 .reg_type
= *reg_type
,
2613 if (env
->ops
->is_valid_access
&&
2614 env
->ops
->is_valid_access(off
, size
, t
, env
->prog
, &info
)) {
2615 /* A non zero info.ctx_field_size indicates that this field is a
2616 * candidate for later verifier transformation to load the whole
2617 * field and then apply a mask when accessed with a narrower
2618 * access than actual ctx access size. A zero info.ctx_field_size
2619 * will only allow for whole field access and rejects any other
2620 * type of narrower access.
2622 *reg_type
= info
.reg_type
;
2624 if (*reg_type
== PTR_TO_BTF_ID
)
2625 *btf_id
= info
.btf_id
;
2627 env
->insn_aux_data
[insn_idx
].ctx_field_size
= info
.ctx_field_size
;
2628 /* remember the offset of last byte accessed in ctx */
2629 if (env
->prog
->aux
->max_ctx_offset
< off
+ size
)
2630 env
->prog
->aux
->max_ctx_offset
= off
+ size
;
2634 verbose(env
, "invalid bpf_context access off=%d size=%d\n", off
, size
);
2638 static int check_flow_keys_access(struct bpf_verifier_env
*env
, int off
,
2641 if (size
< 0 || off
< 0 ||
2642 (u64
)off
+ size
> sizeof(struct bpf_flow_keys
)) {
2643 verbose(env
, "invalid access to flow keys off=%d size=%d\n",
2650 static int check_sock_access(struct bpf_verifier_env
*env
, int insn_idx
,
2651 u32 regno
, int off
, int size
,
2652 enum bpf_access_type t
)
2654 struct bpf_reg_state
*regs
= cur_regs(env
);
2655 struct bpf_reg_state
*reg
= ®s
[regno
];
2656 struct bpf_insn_access_aux info
= {};
2659 if (reg
->smin_value
< 0) {
2660 verbose(env
, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
2665 switch (reg
->type
) {
2666 case PTR_TO_SOCK_COMMON
:
2667 valid
= bpf_sock_common_is_valid_access(off
, size
, t
, &info
);
2670 valid
= bpf_sock_is_valid_access(off
, size
, t
, &info
);
2672 case PTR_TO_TCP_SOCK
:
2673 valid
= bpf_tcp_sock_is_valid_access(off
, size
, t
, &info
);
2675 case PTR_TO_XDP_SOCK
:
2676 valid
= bpf_xdp_sock_is_valid_access(off
, size
, t
, &info
);
2684 env
->insn_aux_data
[insn_idx
].ctx_field_size
=
2685 info
.ctx_field_size
;
2689 verbose(env
, "R%d invalid %s access off=%d size=%d\n",
2690 regno
, reg_type_str
[reg
->type
], off
, size
);
2695 static struct bpf_reg_state
*reg_state(struct bpf_verifier_env
*env
, int regno
)
2697 return cur_regs(env
) + regno
;
2700 static bool is_pointer_value(struct bpf_verifier_env
*env
, int regno
)
2702 return __is_pointer_value(env
->allow_ptr_leaks
, reg_state(env
, regno
));
2705 static bool is_ctx_reg(struct bpf_verifier_env
*env
, int regno
)
2707 const struct bpf_reg_state
*reg
= reg_state(env
, regno
);
2709 return reg
->type
== PTR_TO_CTX
;
2712 static bool is_sk_reg(struct bpf_verifier_env
*env
, int regno
)
2714 const struct bpf_reg_state
*reg
= reg_state(env
, regno
);
2716 return type_is_sk_pointer(reg
->type
);
2719 static bool is_pkt_reg(struct bpf_verifier_env
*env
, int regno
)
2721 const struct bpf_reg_state
*reg
= reg_state(env
, regno
);
2723 return type_is_pkt_pointer(reg
->type
);
2726 static bool is_flow_key_reg(struct bpf_verifier_env
*env
, int regno
)
2728 const struct bpf_reg_state
*reg
= reg_state(env
, regno
);
2730 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
2731 return reg
->type
== PTR_TO_FLOW_KEYS
;
2734 static int check_pkt_ptr_alignment(struct bpf_verifier_env
*env
,
2735 const struct bpf_reg_state
*reg
,
2736 int off
, int size
, bool strict
)
2738 struct tnum reg_off
;
2741 /* Byte size accesses are always allowed. */
2742 if (!strict
|| size
== 1)
2745 /* For platforms that do not have a Kconfig enabling
2746 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
2747 * NET_IP_ALIGN is universally set to '2'. And on platforms
2748 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
2749 * to this code only in strict mode where we want to emulate
2750 * the NET_IP_ALIGN==2 checking. Therefore use an
2751 * unconditional IP align value of '2'.
2755 reg_off
= tnum_add(reg
->var_off
, tnum_const(ip_align
+ reg
->off
+ off
));
2756 if (!tnum_is_aligned(reg_off
, size
)) {
2759 tnum_strn(tn_buf
, sizeof(tn_buf
), reg
->var_off
);
2761 "misaligned packet access off %d+%s+%d+%d size %d\n",
2762 ip_align
, tn_buf
, reg
->off
, off
, size
);
2769 static int check_generic_ptr_alignment(struct bpf_verifier_env
*env
,
2770 const struct bpf_reg_state
*reg
,
2771 const char *pointer_desc
,
2772 int off
, int size
, bool strict
)
2774 struct tnum reg_off
;
2776 /* Byte size accesses are always allowed. */
2777 if (!strict
|| size
== 1)
2780 reg_off
= tnum_add(reg
->var_off
, tnum_const(reg
->off
+ off
));
2781 if (!tnum_is_aligned(reg_off
, size
)) {
2784 tnum_strn(tn_buf
, sizeof(tn_buf
), reg
->var_off
);
2785 verbose(env
, "misaligned %saccess off %s+%d+%d size %d\n",
2786 pointer_desc
, tn_buf
, reg
->off
, off
, size
);
2793 static int check_ptr_alignment(struct bpf_verifier_env
*env
,
2794 const struct bpf_reg_state
*reg
, int off
,
2795 int size
, bool strict_alignment_once
)
2797 bool strict
= env
->strict_alignment
|| strict_alignment_once
;
2798 const char *pointer_desc
= "";
2800 switch (reg
->type
) {
2802 case PTR_TO_PACKET_META
:
2803 /* Special case, because of NET_IP_ALIGN. Given metadata sits
2804 * right in front, treat it the very same way.
2806 return check_pkt_ptr_alignment(env
, reg
, off
, size
, strict
);
2807 case PTR_TO_FLOW_KEYS
:
2808 pointer_desc
= "flow keys ";
2810 case PTR_TO_MAP_VALUE
:
2811 pointer_desc
= "value ";
2814 pointer_desc
= "context ";
2817 pointer_desc
= "stack ";
2818 /* The stack spill tracking logic in check_stack_write()
2819 * and check_stack_read() relies on stack accesses being
2825 pointer_desc
= "sock ";
2827 case PTR_TO_SOCK_COMMON
:
2828 pointer_desc
= "sock_common ";
2830 case PTR_TO_TCP_SOCK
:
2831 pointer_desc
= "tcp_sock ";
2833 case PTR_TO_XDP_SOCK
:
2834 pointer_desc
= "xdp_sock ";
2839 return check_generic_ptr_alignment(env
, reg
, pointer_desc
, off
, size
,
2843 static int update_stack_depth(struct bpf_verifier_env
*env
,
2844 const struct bpf_func_state
*func
,
2847 u16 stack
= env
->subprog_info
[func
->subprogno
].stack_depth
;
2852 /* update known max for given subprogram */
2853 env
->subprog_info
[func
->subprogno
].stack_depth
= -off
;
2857 /* starting from main bpf function walk all instructions of the function
2858 * and recursively walk all callees that given function can call.
2859 * Ignore jump and exit insns.
2860 * Since recursion is prevented by check_cfg() this algorithm
2861 * only needs a local stack of MAX_CALL_FRAMES to remember callsites
2863 static int check_max_stack_depth(struct bpf_verifier_env
*env
)
2865 int depth
= 0, frame
= 0, idx
= 0, i
= 0, subprog_end
;
2866 struct bpf_subprog_info
*subprog
= env
->subprog_info
;
2867 struct bpf_insn
*insn
= env
->prog
->insnsi
;
2868 int ret_insn
[MAX_CALL_FRAMES
];
2869 int ret_prog
[MAX_CALL_FRAMES
];
2872 /* round up to 32-bytes, since this is granularity
2873 * of interpreter stack size
2875 depth
+= round_up(max_t(u32
, subprog
[idx
].stack_depth
, 1), 32);
2876 if (depth
> MAX_BPF_STACK
) {
2877 verbose(env
, "combined stack size of %d calls is %d. Too large\n",
2882 subprog_end
= subprog
[idx
+ 1].start
;
2883 for (; i
< subprog_end
; i
++) {
2884 if (insn
[i
].code
!= (BPF_JMP
| BPF_CALL
))
2886 if (insn
[i
].src_reg
!= BPF_PSEUDO_CALL
)
2888 /* remember insn and function to return to */
2889 ret_insn
[frame
] = i
+ 1;
2890 ret_prog
[frame
] = idx
;
2892 /* find the callee */
2893 i
= i
+ insn
[i
].imm
+ 1;
2894 idx
= find_subprog(env
, i
);
2896 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
2901 if (frame
>= MAX_CALL_FRAMES
) {
2902 verbose(env
, "the call stack of %d frames is too deep !\n",
2908 /* end of for() loop means the last insn of the 'subprog'
2909 * was reached. Doesn't matter whether it was JA or EXIT
2913 depth
-= round_up(max_t(u32
, subprog
[idx
].stack_depth
, 1), 32);
2915 i
= ret_insn
[frame
];
2916 idx
= ret_prog
[frame
];
2920 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
2921 static int get_callee_stack_depth(struct bpf_verifier_env
*env
,
2922 const struct bpf_insn
*insn
, int idx
)
2924 int start
= idx
+ insn
->imm
+ 1, subprog
;
2926 subprog
= find_subprog(env
, start
);
2928 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
2932 return env
->subprog_info
[subprog
].stack_depth
;
2936 int check_ctx_reg(struct bpf_verifier_env
*env
,
2937 const struct bpf_reg_state
*reg
, int regno
)
2939 /* Access to ctx or passing it to a helper is only allowed in
2940 * its original, unmodified form.
2944 verbose(env
, "dereference of modified ctx ptr R%d off=%d disallowed\n",
2949 if (!tnum_is_const(reg
->var_off
) || reg
->var_off
.value
) {
2952 tnum_strn(tn_buf
, sizeof(tn_buf
), reg
->var_off
);
2953 verbose(env
, "variable ctx access var_off=%s disallowed\n", tn_buf
);
2960 static int check_tp_buffer_access(struct bpf_verifier_env
*env
,
2961 const struct bpf_reg_state
*reg
,
2962 int regno
, int off
, int size
)
2966 "R%d invalid tracepoint buffer access: off=%d, size=%d",
2970 if (!tnum_is_const(reg
->var_off
) || reg
->var_off
.value
) {
2973 tnum_strn(tn_buf
, sizeof(tn_buf
), reg
->var_off
);
2975 "R%d invalid variable buffer offset: off=%d, var_off=%s",
2976 regno
, off
, tn_buf
);
2979 if (off
+ size
> env
->prog
->aux
->max_tp_access
)
2980 env
->prog
->aux
->max_tp_access
= off
+ size
;
2985 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
2986 static void zext_32_to_64(struct bpf_reg_state
*reg
)
2988 reg
->var_off
= tnum_subreg(reg
->var_off
);
2989 __reg_assign_32_into_64(reg
);
2992 /* truncate register to smaller size (in bytes)
2993 * must be called with size < BPF_REG_SIZE
2995 static void coerce_reg_to_size(struct bpf_reg_state
*reg
, int size
)
2999 /* clear high bits in bit representation */
3000 reg
->var_off
= tnum_cast(reg
->var_off
, size
);
3002 /* fix arithmetic bounds */
3003 mask
= ((u64
)1 << (size
* 8)) - 1;
3004 if ((reg
->umin_value
& ~mask
) == (reg
->umax_value
& ~mask
)) {
3005 reg
->umin_value
&= mask
;
3006 reg
->umax_value
&= mask
;
3008 reg
->umin_value
= 0;
3009 reg
->umax_value
= mask
;
3011 reg
->smin_value
= reg
->umin_value
;
3012 reg
->smax_value
= reg
->umax_value
;
3014 /* If size is smaller than 32bit register the 32bit register
3015 * values are also truncated so we push 64-bit bounds into
3016 * 32-bit bounds. Above were truncated < 32-bits already.
3020 __reg_combine_64_into_32(reg
);
3023 static bool bpf_map_is_rdonly(const struct bpf_map
*map
)
3025 return (map
->map_flags
& BPF_F_RDONLY_PROG
) && map
->frozen
;
3028 static int bpf_map_direct_read(struct bpf_map
*map
, int off
, int size
, u64
*val
)
3034 err
= map
->ops
->map_direct_value_addr(map
, &addr
, off
);
3037 ptr
= (void *)(long)addr
+ off
;
3041 *val
= (u64
)*(u8
*)ptr
;
3044 *val
= (u64
)*(u16
*)ptr
;
3047 *val
= (u64
)*(u32
*)ptr
;
3058 static int check_ptr_to_btf_access(struct bpf_verifier_env
*env
,
3059 struct bpf_reg_state
*regs
,
3060 int regno
, int off
, int size
,
3061 enum bpf_access_type atype
,
3064 struct bpf_reg_state
*reg
= regs
+ regno
;
3065 const struct btf_type
*t
= btf_type_by_id(btf_vmlinux
, reg
->btf_id
);
3066 const char *tname
= btf_name_by_offset(btf_vmlinux
, t
->name_off
);
3072 "R%d is ptr_%s invalid negative access: off=%d\n",
3076 if (!tnum_is_const(reg
->var_off
) || reg
->var_off
.value
) {
3079 tnum_strn(tn_buf
, sizeof(tn_buf
), reg
->var_off
);
3081 "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
3082 regno
, tname
, off
, tn_buf
);
3086 if (env
->ops
->btf_struct_access
) {
3087 ret
= env
->ops
->btf_struct_access(&env
->log
, t
, off
, size
,
3090 if (atype
!= BPF_READ
) {
3091 verbose(env
, "only read is supported\n");
3095 ret
= btf_struct_access(&env
->log
, t
, off
, size
, atype
,
3102 if (atype
== BPF_READ
&& value_regno
>= 0) {
3103 if (ret
== SCALAR_VALUE
) {
3104 mark_reg_unknown(env
, regs
, value_regno
);
3107 mark_reg_known_zero(env
, regs
, value_regno
);
3108 regs
[value_regno
].type
= PTR_TO_BTF_ID
;
3109 regs
[value_regno
].btf_id
= btf_id
;
3115 /* check whether memory at (regno + off) is accessible for t = (read | write)
3116 * if t==write, value_regno is a register which value is stored into memory
3117 * if t==read, value_regno is a register which will receive the value from memory
3118 * if t==write && value_regno==-1, some unknown value is stored into memory
3119 * if t==read && value_regno==-1, don't care what we read from memory
3121 static int check_mem_access(struct bpf_verifier_env
*env
, int insn_idx
, u32 regno
,
3122 int off
, int bpf_size
, enum bpf_access_type t
,
3123 int value_regno
, bool strict_alignment_once
)
3125 struct bpf_reg_state
*regs
= cur_regs(env
);
3126 struct bpf_reg_state
*reg
= regs
+ regno
;
3127 struct bpf_func_state
*state
;
3130 size
= bpf_size_to_bytes(bpf_size
);
3134 /* alignment checks will add in reg->off themselves */
3135 err
= check_ptr_alignment(env
, reg
, off
, size
, strict_alignment_once
);
3139 /* for access checks, reg->off is just part of off */
3142 if (reg
->type
== PTR_TO_MAP_VALUE
) {
3143 if (t
== BPF_WRITE
&& value_regno
>= 0 &&
3144 is_pointer_value(env
, value_regno
)) {
3145 verbose(env
, "R%d leaks addr into map\n", value_regno
);
3148 err
= check_map_access_type(env
, regno
, off
, size
, t
);
3151 err
= check_map_access(env
, regno
, off
, size
, false);
3152 if (!err
&& t
== BPF_READ
&& value_regno
>= 0) {
3153 struct bpf_map
*map
= reg
->map_ptr
;
3155 /* if map is read-only, track its contents as scalars */
3156 if (tnum_is_const(reg
->var_off
) &&
3157 bpf_map_is_rdonly(map
) &&
3158 map
->ops
->map_direct_value_addr
) {
3159 int map_off
= off
+ reg
->var_off
.value
;
3162 err
= bpf_map_direct_read(map
, map_off
, size
,
3167 regs
[value_regno
].type
= SCALAR_VALUE
;
3168 __mark_reg_known(®s
[value_regno
], val
);
3170 mark_reg_unknown(env
, regs
, value_regno
);
3173 } else if (reg
->type
== PTR_TO_CTX
) {
3174 enum bpf_reg_type reg_type
= SCALAR_VALUE
;
3177 if (t
== BPF_WRITE
&& value_regno
>= 0 &&
3178 is_pointer_value(env
, value_regno
)) {
3179 verbose(env
, "R%d leaks addr into ctx\n", value_regno
);
3183 err
= check_ctx_reg(env
, reg
, regno
);
3187 err
= check_ctx_access(env
, insn_idx
, off
, size
, t
, ®_type
, &btf_id
);
3189 verbose_linfo(env
, insn_idx
, "; ");
3190 if (!err
&& t
== BPF_READ
&& value_regno
>= 0) {
3191 /* ctx access returns either a scalar, or a
3192 * PTR_TO_PACKET[_META,_END]. In the latter
3193 * case, we know the offset is zero.
3195 if (reg_type
== SCALAR_VALUE
) {
3196 mark_reg_unknown(env
, regs
, value_regno
);
3198 mark_reg_known_zero(env
, regs
,
3200 if (reg_type_may_be_null(reg_type
))
3201 regs
[value_regno
].id
= ++env
->id_gen
;
3202 /* A load of ctx field could have different
3203 * actual load size with the one encoded in the
3204 * insn. When the dst is PTR, it is for sure not
3207 regs
[value_regno
].subreg_def
= DEF_NOT_SUBREG
;
3208 if (reg_type
== PTR_TO_BTF_ID
)
3209 regs
[value_regno
].btf_id
= btf_id
;
3211 regs
[value_regno
].type
= reg_type
;
3214 } else if (reg
->type
== PTR_TO_STACK
) {
3215 off
+= reg
->var_off
.value
;
3216 err
= check_stack_access(env
, reg
, off
, size
);
3220 state
= func(env
, reg
);
3221 err
= update_stack_depth(env
, state
, off
);
3226 err
= check_stack_write(env
, state
, off
, size
,
3227 value_regno
, insn_idx
);
3229 err
= check_stack_read(env
, state
, off
, size
,
3231 } else if (reg_is_pkt_pointer(reg
)) {
3232 if (t
== BPF_WRITE
&& !may_access_direct_pkt_data(env
, NULL
, t
)) {
3233 verbose(env
, "cannot write into packet\n");
3236 if (t
== BPF_WRITE
&& value_regno
>= 0 &&
3237 is_pointer_value(env
, value_regno
)) {
3238 verbose(env
, "R%d leaks addr into packet\n",
3242 err
= check_packet_access(env
, regno
, off
, size
, false);
3243 if (!err
&& t
== BPF_READ
&& value_regno
>= 0)
3244 mark_reg_unknown(env
, regs
, value_regno
);
3245 } else if (reg
->type
== PTR_TO_FLOW_KEYS
) {
3246 if (t
== BPF_WRITE
&& value_regno
>= 0 &&
3247 is_pointer_value(env
, value_regno
)) {
3248 verbose(env
, "R%d leaks addr into flow keys\n",
3253 err
= check_flow_keys_access(env
, off
, size
);
3254 if (!err
&& t
== BPF_READ
&& value_regno
>= 0)
3255 mark_reg_unknown(env
, regs
, value_regno
);
3256 } else if (type_is_sk_pointer(reg
->type
)) {
3257 if (t
== BPF_WRITE
) {
3258 verbose(env
, "R%d cannot write into %s\n",
3259 regno
, reg_type_str
[reg
->type
]);
3262 err
= check_sock_access(env
, insn_idx
, regno
, off
, size
, t
);
3263 if (!err
&& value_regno
>= 0)
3264 mark_reg_unknown(env
, regs
, value_regno
);
3265 } else if (reg
->type
== PTR_TO_TP_BUFFER
) {
3266 err
= check_tp_buffer_access(env
, reg
, regno
, off
, size
);
3267 if (!err
&& t
== BPF_READ
&& value_regno
>= 0)
3268 mark_reg_unknown(env
, regs
, value_regno
);
3269 } else if (reg
->type
== PTR_TO_BTF_ID
) {
3270 err
= check_ptr_to_btf_access(env
, regs
, regno
, off
, size
, t
,
3273 verbose(env
, "R%d invalid mem access '%s'\n", regno
,
3274 reg_type_str
[reg
->type
]);
3278 if (!err
&& size
< BPF_REG_SIZE
&& value_regno
>= 0 && t
== BPF_READ
&&
3279 regs
[value_regno
].type
== SCALAR_VALUE
) {
3280 /* b/h/w load zero-extends, mark upper bits as known 0 */
3281 coerce_reg_to_size(®s
[value_regno
], size
);
3286 static int check_xadd(struct bpf_verifier_env
*env
, int insn_idx
, struct bpf_insn
*insn
)
3290 if ((BPF_SIZE(insn
->code
) != BPF_W
&& BPF_SIZE(insn
->code
) != BPF_DW
) ||
3292 verbose(env
, "BPF_XADD uses reserved fields\n");
3296 /* check src1 operand */
3297 err
= check_reg_arg(env
, insn
->src_reg
, SRC_OP
);
3301 /* check src2 operand */
3302 err
= check_reg_arg(env
, insn
->dst_reg
, SRC_OP
);
3306 if (is_pointer_value(env
, insn
->src_reg
)) {
3307 verbose(env
, "R%d leaks addr into mem\n", insn
->src_reg
);
3311 if (is_ctx_reg(env
, insn
->dst_reg
) ||
3312 is_pkt_reg(env
, insn
->dst_reg
) ||
3313 is_flow_key_reg(env
, insn
->dst_reg
) ||
3314 is_sk_reg(env
, insn
->dst_reg
)) {
3315 verbose(env
, "BPF_XADD stores into R%d %s is not allowed\n",
3317 reg_type_str
[reg_state(env
, insn
->dst_reg
)->type
]);
3321 /* check whether atomic_add can read the memory */
3322 err
= check_mem_access(env
, insn_idx
, insn
->dst_reg
, insn
->off
,
3323 BPF_SIZE(insn
->code
), BPF_READ
, -1, true);
3327 /* check whether atomic_add can write into the same memory */
3328 return check_mem_access(env
, insn_idx
, insn
->dst_reg
, insn
->off
,
3329 BPF_SIZE(insn
->code
), BPF_WRITE
, -1, true);
3332 static int __check_stack_boundary(struct bpf_verifier_env
*env
, u32 regno
,
3333 int off
, int access_size
,
3334 bool zero_size_allowed
)
3336 struct bpf_reg_state
*reg
= reg_state(env
, regno
);
3338 if (off
>= 0 || off
< -MAX_BPF_STACK
|| off
+ access_size
> 0 ||
3339 access_size
< 0 || (access_size
== 0 && !zero_size_allowed
)) {
3340 if (tnum_is_const(reg
->var_off
)) {
3341 verbose(env
, "invalid stack type R%d off=%d access_size=%d\n",
3342 regno
, off
, access_size
);
3346 tnum_strn(tn_buf
, sizeof(tn_buf
), reg
->var_off
);
3347 verbose(env
, "invalid stack type R%d var_off=%s access_size=%d\n",
3348 regno
, tn_buf
, access_size
);
3355 /* when register 'regno' is passed into function that will read 'access_size'
3356 * bytes from that pointer, make sure that it's within stack boundary
3357 * and all elements of stack are initialized.
3358 * Unlike most pointer bounds-checking functions, this one doesn't take an
3359 * 'off' argument, so it has to add in reg->off itself.
3361 static int check_stack_boundary(struct bpf_verifier_env
*env
, int regno
,
3362 int access_size
, bool zero_size_allowed
,
3363 struct bpf_call_arg_meta
*meta
)
3365 struct bpf_reg_state
*reg
= reg_state(env
, regno
);
3366 struct bpf_func_state
*state
= func(env
, reg
);
3367 int err
, min_off
, max_off
, i
, j
, slot
, spi
;
3369 if (reg
->type
!= PTR_TO_STACK
) {
3370 /* Allow zero-byte read from NULL, regardless of pointer type */
3371 if (zero_size_allowed
&& access_size
== 0 &&
3372 register_is_null(reg
))
3375 verbose(env
, "R%d type=%s expected=%s\n", regno
,
3376 reg_type_str
[reg
->type
],
3377 reg_type_str
[PTR_TO_STACK
]);
3381 if (tnum_is_const(reg
->var_off
)) {
3382 min_off
= max_off
= reg
->var_off
.value
+ reg
->off
;
3383 err
= __check_stack_boundary(env
, regno
, min_off
, access_size
,
3388 /* Variable offset is prohibited for unprivileged mode for
3389 * simplicity since it requires corresponding support in
3390 * Spectre masking for stack ALU.
3391 * See also retrieve_ptr_limit().
3393 if (!env
->allow_ptr_leaks
) {
3396 tnum_strn(tn_buf
, sizeof(tn_buf
), reg
->var_off
);
3397 verbose(env
, "R%d indirect variable offset stack access prohibited for !root, var_off=%s\n",
3401 /* Only initialized buffer on stack is allowed to be accessed
3402 * with variable offset. With uninitialized buffer it's hard to
3403 * guarantee that whole memory is marked as initialized on
3404 * helper return since specific bounds are unknown what may
3405 * cause uninitialized stack leaking.
3407 if (meta
&& meta
->raw_mode
)
3410 if (reg
->smax_value
>= BPF_MAX_VAR_OFF
||
3411 reg
->smax_value
<= -BPF_MAX_VAR_OFF
) {
3412 verbose(env
, "R%d unbounded indirect variable offset stack access\n",
3416 min_off
= reg
->smin_value
+ reg
->off
;
3417 max_off
= reg
->smax_value
+ reg
->off
;
3418 err
= __check_stack_boundary(env
, regno
, min_off
, access_size
,
3421 verbose(env
, "R%d min value is outside of stack bound\n",
3425 err
= __check_stack_boundary(env
, regno
, max_off
, access_size
,
3428 verbose(env
, "R%d max value is outside of stack bound\n",
3434 if (meta
&& meta
->raw_mode
) {
3435 meta
->access_size
= access_size
;
3436 meta
->regno
= regno
;
3440 for (i
= min_off
; i
< max_off
+ access_size
; i
++) {
3444 spi
= slot
/ BPF_REG_SIZE
;
3445 if (state
->allocated_stack
<= slot
)
3447 stype
= &state
->stack
[spi
].slot_type
[slot
% BPF_REG_SIZE
];
3448 if (*stype
== STACK_MISC
)
3450 if (*stype
== STACK_ZERO
) {
3451 /* helper can write anything into the stack */
3452 *stype
= STACK_MISC
;
3455 if (state
->stack
[spi
].slot_type
[0] == STACK_SPILL
&&
3456 state
->stack
[spi
].spilled_ptr
.type
== SCALAR_VALUE
) {
3457 __mark_reg_unknown(env
, &state
->stack
[spi
].spilled_ptr
);
3458 for (j
= 0; j
< BPF_REG_SIZE
; j
++)
3459 state
->stack
[spi
].slot_type
[j
] = STACK_MISC
;
3464 if (tnum_is_const(reg
->var_off
)) {
3465 verbose(env
, "invalid indirect read from stack off %d+%d size %d\n",
3466 min_off
, i
- min_off
, access_size
);
3470 tnum_strn(tn_buf
, sizeof(tn_buf
), reg
->var_off
);
3471 verbose(env
, "invalid indirect read from stack var_off %s+%d size %d\n",
3472 tn_buf
, i
- min_off
, access_size
);
3476 /* reading any byte out of 8-byte 'spill_slot' will cause
3477 * the whole slot to be marked as 'read'
3479 mark_reg_read(env
, &state
->stack
[spi
].spilled_ptr
,
3480 state
->stack
[spi
].spilled_ptr
.parent
,
3483 return update_stack_depth(env
, state
, min_off
);
3486 static int check_helper_mem_access(struct bpf_verifier_env
*env
, int regno
,
3487 int access_size
, bool zero_size_allowed
,
3488 struct bpf_call_arg_meta
*meta
)
3490 struct bpf_reg_state
*regs
= cur_regs(env
), *reg
= ®s
[regno
];
3492 switch (reg
->type
) {
3494 case PTR_TO_PACKET_META
:
3495 return check_packet_access(env
, regno
, reg
->off
, access_size
,
3497 case PTR_TO_MAP_VALUE
:
3498 if (check_map_access_type(env
, regno
, reg
->off
, access_size
,
3499 meta
&& meta
->raw_mode
? BPF_WRITE
:
3502 return check_map_access(env
, regno
, reg
->off
, access_size
,
3504 default: /* scalar_value|ptr_to_stack or invalid ptr */
3505 return check_stack_boundary(env
, regno
, access_size
,
3506 zero_size_allowed
, meta
);
3510 /* Implementation details:
3511 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL
3512 * Two bpf_map_lookups (even with the same key) will have different reg->id.
3513 * For traditional PTR_TO_MAP_VALUE the verifier clears reg->id after
3514 * value_or_null->value transition, since the verifier only cares about
3515 * the range of access to valid map value pointer and doesn't care about actual
3516 * address of the map element.
3517 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
3518 * reg->id > 0 after value_or_null->value transition. By doing so
3519 * two bpf_map_lookups will be considered two different pointers that
3520 * point to different bpf_spin_locks.
3521 * The verifier allows taking only one bpf_spin_lock at a time to avoid
3523 * Since only one bpf_spin_lock is allowed the checks are simpler than
3524 * reg_is_refcounted() logic. The verifier needs to remember only
3525 * one spin_lock instead of array of acquired_refs.
3526 * cur_state->active_spin_lock remembers which map value element got locked
3527 * and clears it after bpf_spin_unlock.
3529 static int process_spin_lock(struct bpf_verifier_env
*env
, int regno
,
3532 struct bpf_reg_state
*regs
= cur_regs(env
), *reg
= ®s
[regno
];
3533 struct bpf_verifier_state
*cur
= env
->cur_state
;
3534 bool is_const
= tnum_is_const(reg
->var_off
);
3535 struct bpf_map
*map
= reg
->map_ptr
;
3536 u64 val
= reg
->var_off
.value
;
3538 if (reg
->type
!= PTR_TO_MAP_VALUE
) {
3539 verbose(env
, "R%d is not a pointer to map_value\n", regno
);
3544 "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
3550 "map '%s' has to have BTF in order to use bpf_spin_lock\n",
3554 if (!map_value_has_spin_lock(map
)) {
3555 if (map
->spin_lock_off
== -E2BIG
)
3557 "map '%s' has more than one 'struct bpf_spin_lock'\n",
3559 else if (map
->spin_lock_off
== -ENOENT
)
3561 "map '%s' doesn't have 'struct bpf_spin_lock'\n",
3565 "map '%s' is not a struct type or bpf_spin_lock is mangled\n",
3569 if (map
->spin_lock_off
!= val
+ reg
->off
) {
3570 verbose(env
, "off %lld doesn't point to 'struct bpf_spin_lock'\n",
3575 if (cur
->active_spin_lock
) {
3577 "Locking two bpf_spin_locks are not allowed\n");
3580 cur
->active_spin_lock
= reg
->id
;
3582 if (!cur
->active_spin_lock
) {
3583 verbose(env
, "bpf_spin_unlock without taking a lock\n");
3586 if (cur
->active_spin_lock
!= reg
->id
) {
3587 verbose(env
, "bpf_spin_unlock of different lock\n");
3590 cur
->active_spin_lock
= 0;
3595 static bool arg_type_is_mem_ptr(enum bpf_arg_type type
)
3597 return type
== ARG_PTR_TO_MEM
||
3598 type
== ARG_PTR_TO_MEM_OR_NULL
||
3599 type
== ARG_PTR_TO_UNINIT_MEM
;
3602 static bool arg_type_is_mem_size(enum bpf_arg_type type
)
3604 return type
== ARG_CONST_SIZE
||
3605 type
== ARG_CONST_SIZE_OR_ZERO
;
3608 static bool arg_type_is_int_ptr(enum bpf_arg_type type
)
3610 return type
== ARG_PTR_TO_INT
||
3611 type
== ARG_PTR_TO_LONG
;
3614 static int int_ptr_type_to_size(enum bpf_arg_type type
)
3616 if (type
== ARG_PTR_TO_INT
)
3618 else if (type
== ARG_PTR_TO_LONG
)
3624 static int check_func_arg(struct bpf_verifier_env
*env
, u32 regno
,
3625 enum bpf_arg_type arg_type
,
3626 struct bpf_call_arg_meta
*meta
)
3628 struct bpf_reg_state
*regs
= cur_regs(env
), *reg
= ®s
[regno
];
3629 enum bpf_reg_type expected_type
, type
= reg
->type
;
3632 if (arg_type
== ARG_DONTCARE
)
3635 err
= check_reg_arg(env
, regno
, SRC_OP
);
3639 if (arg_type
== ARG_ANYTHING
) {
3640 if (is_pointer_value(env
, regno
)) {
3641 verbose(env
, "R%d leaks addr into helper function\n",
3648 if (type_is_pkt_pointer(type
) &&
3649 !may_access_direct_pkt_data(env
, meta
, BPF_READ
)) {
3650 verbose(env
, "helper access to the packet is not allowed\n");
3654 if (arg_type
== ARG_PTR_TO_MAP_KEY
||
3655 arg_type
== ARG_PTR_TO_MAP_VALUE
||
3656 arg_type
== ARG_PTR_TO_UNINIT_MAP_VALUE
||
3657 arg_type
== ARG_PTR_TO_MAP_VALUE_OR_NULL
) {
3658 expected_type
= PTR_TO_STACK
;
3659 if (register_is_null(reg
) &&
3660 arg_type
== ARG_PTR_TO_MAP_VALUE_OR_NULL
)
3661 /* final test in check_stack_boundary() */;
3662 else if (!type_is_pkt_pointer(type
) &&
3663 type
!= PTR_TO_MAP_VALUE
&&
3664 type
!= expected_type
)
3666 } else if (arg_type
== ARG_CONST_SIZE
||
3667 arg_type
== ARG_CONST_SIZE_OR_ZERO
) {
3668 expected_type
= SCALAR_VALUE
;
3669 if (type
!= expected_type
)
3671 } else if (arg_type
== ARG_CONST_MAP_PTR
) {
3672 expected_type
= CONST_PTR_TO_MAP
;
3673 if (type
!= expected_type
)
3675 } else if (arg_type
== ARG_PTR_TO_CTX
||
3676 arg_type
== ARG_PTR_TO_CTX_OR_NULL
) {
3677 expected_type
= PTR_TO_CTX
;
3678 if (!(register_is_null(reg
) &&
3679 arg_type
== ARG_PTR_TO_CTX_OR_NULL
)) {
3680 if (type
!= expected_type
)
3682 err
= check_ctx_reg(env
, reg
, regno
);
3686 } else if (arg_type
== ARG_PTR_TO_SOCK_COMMON
) {
3687 expected_type
= PTR_TO_SOCK_COMMON
;
3688 /* Any sk pointer can be ARG_PTR_TO_SOCK_COMMON */
3689 if (!type_is_sk_pointer(type
))
3691 if (reg
->ref_obj_id
) {
3692 if (meta
->ref_obj_id
) {
3693 verbose(env
, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
3694 regno
, reg
->ref_obj_id
,
3698 meta
->ref_obj_id
= reg
->ref_obj_id
;
3700 } else if (arg_type
== ARG_PTR_TO_SOCKET
) {
3701 expected_type
= PTR_TO_SOCKET
;
3702 if (type
!= expected_type
)
3704 } else if (arg_type
== ARG_PTR_TO_BTF_ID
) {
3705 expected_type
= PTR_TO_BTF_ID
;
3706 if (type
!= expected_type
)
3708 if (reg
->btf_id
!= meta
->btf_id
) {
3709 verbose(env
, "Helper has type %s got %s in R%d\n",
3710 kernel_type_name(meta
->btf_id
),
3711 kernel_type_name(reg
->btf_id
), regno
);
3715 if (!tnum_is_const(reg
->var_off
) || reg
->var_off
.value
|| reg
->off
) {
3716 verbose(env
, "R%d is a pointer to in-kernel struct with non-zero offset\n",
3720 } else if (arg_type
== ARG_PTR_TO_SPIN_LOCK
) {
3721 if (meta
->func_id
== BPF_FUNC_spin_lock
) {
3722 if (process_spin_lock(env
, regno
, true))
3724 } else if (meta
->func_id
== BPF_FUNC_spin_unlock
) {
3725 if (process_spin_lock(env
, regno
, false))
3728 verbose(env
, "verifier internal error\n");
3731 } else if (arg_type_is_mem_ptr(arg_type
)) {
3732 expected_type
= PTR_TO_STACK
;
3733 /* One exception here. In case function allows for NULL to be
3734 * passed in as argument, it's a SCALAR_VALUE type. Final test
3735 * happens during stack boundary checking.
3737 if (register_is_null(reg
) &&
3738 arg_type
== ARG_PTR_TO_MEM_OR_NULL
)
3739 /* final test in check_stack_boundary() */;
3740 else if (!type_is_pkt_pointer(type
) &&
3741 type
!= PTR_TO_MAP_VALUE
&&
3742 type
!= expected_type
)
3744 meta
->raw_mode
= arg_type
== ARG_PTR_TO_UNINIT_MEM
;
3745 } else if (arg_type_is_int_ptr(arg_type
)) {
3746 expected_type
= PTR_TO_STACK
;
3747 if (!type_is_pkt_pointer(type
) &&
3748 type
!= PTR_TO_MAP_VALUE
&&
3749 type
!= expected_type
)
3752 verbose(env
, "unsupported arg_type %d\n", arg_type
);
3756 if (arg_type
== ARG_CONST_MAP_PTR
) {
3757 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
3758 meta
->map_ptr
= reg
->map_ptr
;
3759 } else if (arg_type
== ARG_PTR_TO_MAP_KEY
) {
3760 /* bpf_map_xxx(..., map_ptr, ..., key) call:
3761 * check that [key, key + map->key_size) are within
3762 * stack limits and initialized
3764 if (!meta
->map_ptr
) {
3765 /* in function declaration map_ptr must come before
3766 * map_key, so that it's verified and known before
3767 * we have to check map_key here. Otherwise it means
3768 * that kernel subsystem misconfigured verifier
3770 verbose(env
, "invalid map_ptr to access map->key\n");
3773 err
= check_helper_mem_access(env
, regno
,
3774 meta
->map_ptr
->key_size
, false,
3776 } else if (arg_type
== ARG_PTR_TO_MAP_VALUE
||
3777 (arg_type
== ARG_PTR_TO_MAP_VALUE_OR_NULL
&&
3778 !register_is_null(reg
)) ||
3779 arg_type
== ARG_PTR_TO_UNINIT_MAP_VALUE
) {
3780 /* bpf_map_xxx(..., map_ptr, ..., value) call:
3781 * check [value, value + map->value_size) validity
3783 if (!meta
->map_ptr
) {
3784 /* kernel subsystem misconfigured verifier */
3785 verbose(env
, "invalid map_ptr to access map->value\n");
3788 meta
->raw_mode
= (arg_type
== ARG_PTR_TO_UNINIT_MAP_VALUE
);
3789 err
= check_helper_mem_access(env
, regno
,
3790 meta
->map_ptr
->value_size
, false,
3792 } else if (arg_type_is_mem_size(arg_type
)) {
3793 bool zero_size_allowed
= (arg_type
== ARG_CONST_SIZE_OR_ZERO
);
3795 /* This is used to refine r0 return value bounds for helpers
3796 * that enforce this value as an upper bound on return values.
3797 * See do_refine_retval_range() for helpers that can refine
3798 * the return value. C type of helper is u32 so we pull register
3799 * bound from umax_value however, if negative verifier errors
3800 * out. Only upper bounds can be learned because retval is an
3801 * int type and negative retvals are allowed.
3803 meta
->msize_max_value
= reg
->umax_value
;
3805 /* The register is SCALAR_VALUE; the access check
3806 * happens using its boundaries.
3808 if (!tnum_is_const(reg
->var_off
))
3809 /* For unprivileged variable accesses, disable raw
3810 * mode so that the program is required to
3811 * initialize all the memory that the helper could
3812 * just partially fill up.
3816 if (reg
->smin_value
< 0) {
3817 verbose(env
, "R%d min value is negative, either use unsigned or 'var &= const'\n",
3822 if (reg
->umin_value
== 0) {
3823 err
= check_helper_mem_access(env
, regno
- 1, 0,
3830 if (reg
->umax_value
>= BPF_MAX_VAR_SIZ
) {
3831 verbose(env
, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
3835 err
= check_helper_mem_access(env
, regno
- 1,
3837 zero_size_allowed
, meta
);
3839 err
= mark_chain_precision(env
, regno
);
3840 } else if (arg_type_is_int_ptr(arg_type
)) {
3841 int size
= int_ptr_type_to_size(arg_type
);
3843 err
= check_helper_mem_access(env
, regno
, size
, false, meta
);
3846 err
= check_ptr_alignment(env
, reg
, 0, size
, true);
3851 verbose(env
, "R%d type=%s expected=%s\n", regno
,
3852 reg_type_str
[type
], reg_type_str
[expected_type
]);
3856 static int check_map_func_compatibility(struct bpf_verifier_env
*env
,
3857 struct bpf_map
*map
, int func_id
)
3862 /* We need a two way check, first is from map perspective ... */
3863 switch (map
->map_type
) {
3864 case BPF_MAP_TYPE_PROG_ARRAY
:
3865 if (func_id
!= BPF_FUNC_tail_call
)
3868 case BPF_MAP_TYPE_PERF_EVENT_ARRAY
:
3869 if (func_id
!= BPF_FUNC_perf_event_read
&&
3870 func_id
!= BPF_FUNC_perf_event_output
&&
3871 func_id
!= BPF_FUNC_skb_output
&&
3872 func_id
!= BPF_FUNC_perf_event_read_value
&&
3873 func_id
!= BPF_FUNC_xdp_output
)
3876 case BPF_MAP_TYPE_STACK_TRACE
:
3877 if (func_id
!= BPF_FUNC_get_stackid
)
3880 case BPF_MAP_TYPE_CGROUP_ARRAY
:
3881 if (func_id
!= BPF_FUNC_skb_under_cgroup
&&
3882 func_id
!= BPF_FUNC_current_task_under_cgroup
)
3885 case BPF_MAP_TYPE_CGROUP_STORAGE
:
3886 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE
:
3887 if (func_id
!= BPF_FUNC_get_local_storage
)
3890 case BPF_MAP_TYPE_DEVMAP
:
3891 case BPF_MAP_TYPE_DEVMAP_HASH
:
3892 if (func_id
!= BPF_FUNC_redirect_map
&&
3893 func_id
!= BPF_FUNC_map_lookup_elem
)
3896 /* Restrict bpf side of cpumap and xskmap, open when use-cases
3899 case BPF_MAP_TYPE_CPUMAP
:
3900 if (func_id
!= BPF_FUNC_redirect_map
)
3903 case BPF_MAP_TYPE_XSKMAP
:
3904 if (func_id
!= BPF_FUNC_redirect_map
&&
3905 func_id
!= BPF_FUNC_map_lookup_elem
)
3908 case BPF_MAP_TYPE_ARRAY_OF_MAPS
:
3909 case BPF_MAP_TYPE_HASH_OF_MAPS
:
3910 if (func_id
!= BPF_FUNC_map_lookup_elem
)
3913 case BPF_MAP_TYPE_SOCKMAP
:
3914 if (func_id
!= BPF_FUNC_sk_redirect_map
&&
3915 func_id
!= BPF_FUNC_sock_map_update
&&
3916 func_id
!= BPF_FUNC_map_delete_elem
&&
3917 func_id
!= BPF_FUNC_msg_redirect_map
&&
3918 func_id
!= BPF_FUNC_sk_select_reuseport
)
3921 case BPF_MAP_TYPE_SOCKHASH
:
3922 if (func_id
!= BPF_FUNC_sk_redirect_hash
&&
3923 func_id
!= BPF_FUNC_sock_hash_update
&&
3924 func_id
!= BPF_FUNC_map_delete_elem
&&
3925 func_id
!= BPF_FUNC_msg_redirect_hash
&&
3926 func_id
!= BPF_FUNC_sk_select_reuseport
)
3929 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY
:
3930 if (func_id
!= BPF_FUNC_sk_select_reuseport
)
3933 case BPF_MAP_TYPE_QUEUE
:
3934 case BPF_MAP_TYPE_STACK
:
3935 if (func_id
!= BPF_FUNC_map_peek_elem
&&
3936 func_id
!= BPF_FUNC_map_pop_elem
&&
3937 func_id
!= BPF_FUNC_map_push_elem
)
3940 case BPF_MAP_TYPE_SK_STORAGE
:
3941 if (func_id
!= BPF_FUNC_sk_storage_get
&&
3942 func_id
!= BPF_FUNC_sk_storage_delete
)
3949 /* ... and second from the function itself. */
3951 case BPF_FUNC_tail_call
:
3952 if (map
->map_type
!= BPF_MAP_TYPE_PROG_ARRAY
)
3954 if (env
->subprog_cnt
> 1) {
3955 verbose(env
, "tail_calls are not allowed in programs with bpf-to-bpf calls\n");
3959 case BPF_FUNC_perf_event_read
:
3960 case BPF_FUNC_perf_event_output
:
3961 case BPF_FUNC_perf_event_read_value
:
3962 case BPF_FUNC_skb_output
:
3963 case BPF_FUNC_xdp_output
:
3964 if (map
->map_type
!= BPF_MAP_TYPE_PERF_EVENT_ARRAY
)
3967 case BPF_FUNC_get_stackid
:
3968 if (map
->map_type
!= BPF_MAP_TYPE_STACK_TRACE
)
3971 case BPF_FUNC_current_task_under_cgroup
:
3972 case BPF_FUNC_skb_under_cgroup
:
3973 if (map
->map_type
!= BPF_MAP_TYPE_CGROUP_ARRAY
)
3976 case BPF_FUNC_redirect_map
:
3977 if (map
->map_type
!= BPF_MAP_TYPE_DEVMAP
&&
3978 map
->map_type
!= BPF_MAP_TYPE_DEVMAP_HASH
&&
3979 map
->map_type
!= BPF_MAP_TYPE_CPUMAP
&&
3980 map
->map_type
!= BPF_MAP_TYPE_XSKMAP
)
3983 case BPF_FUNC_sk_redirect_map
:
3984 case BPF_FUNC_msg_redirect_map
:
3985 case BPF_FUNC_sock_map_update
:
3986 if (map
->map_type
!= BPF_MAP_TYPE_SOCKMAP
)
3989 case BPF_FUNC_sk_redirect_hash
:
3990 case BPF_FUNC_msg_redirect_hash
:
3991 case BPF_FUNC_sock_hash_update
:
3992 if (map
->map_type
!= BPF_MAP_TYPE_SOCKHASH
)
3995 case BPF_FUNC_get_local_storage
:
3996 if (map
->map_type
!= BPF_MAP_TYPE_CGROUP_STORAGE
&&
3997 map
->map_type
!= BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE
)
4000 case BPF_FUNC_sk_select_reuseport
:
4001 if (map
->map_type
!= BPF_MAP_TYPE_REUSEPORT_SOCKARRAY
&&
4002 map
->map_type
!= BPF_MAP_TYPE_SOCKMAP
&&
4003 map
->map_type
!= BPF_MAP_TYPE_SOCKHASH
)
4006 case BPF_FUNC_map_peek_elem
:
4007 case BPF_FUNC_map_pop_elem
:
4008 case BPF_FUNC_map_push_elem
:
4009 if (map
->map_type
!= BPF_MAP_TYPE_QUEUE
&&
4010 map
->map_type
!= BPF_MAP_TYPE_STACK
)
4013 case BPF_FUNC_sk_storage_get
:
4014 case BPF_FUNC_sk_storage_delete
:
4015 if (map
->map_type
!= BPF_MAP_TYPE_SK_STORAGE
)
4024 verbose(env
, "cannot pass map_type %d into func %s#%d\n",
4025 map
->map_type
, func_id_name(func_id
), func_id
);
4029 static bool check_raw_mode_ok(const struct bpf_func_proto
*fn
)
4033 if (fn
->arg1_type
== ARG_PTR_TO_UNINIT_MEM
)
4035 if (fn
->arg2_type
== ARG_PTR_TO_UNINIT_MEM
)
4037 if (fn
->arg3_type
== ARG_PTR_TO_UNINIT_MEM
)
4039 if (fn
->arg4_type
== ARG_PTR_TO_UNINIT_MEM
)
4041 if (fn
->arg5_type
== ARG_PTR_TO_UNINIT_MEM
)
4044 /* We only support one arg being in raw mode at the moment,
4045 * which is sufficient for the helper functions we have
4051 static bool check_args_pair_invalid(enum bpf_arg_type arg_curr
,
4052 enum bpf_arg_type arg_next
)
4054 return (arg_type_is_mem_ptr(arg_curr
) &&
4055 !arg_type_is_mem_size(arg_next
)) ||
4056 (!arg_type_is_mem_ptr(arg_curr
) &&
4057 arg_type_is_mem_size(arg_next
));
4060 static bool check_arg_pair_ok(const struct bpf_func_proto
*fn
)
4062 /* bpf_xxx(..., buf, len) call will access 'len'
4063 * bytes from memory 'buf'. Both arg types need
4064 * to be paired, so make sure there's no buggy
4065 * helper function specification.
4067 if (arg_type_is_mem_size(fn
->arg1_type
) ||
4068 arg_type_is_mem_ptr(fn
->arg5_type
) ||
4069 check_args_pair_invalid(fn
->arg1_type
, fn
->arg2_type
) ||
4070 check_args_pair_invalid(fn
->arg2_type
, fn
->arg3_type
) ||
4071 check_args_pair_invalid(fn
->arg3_type
, fn
->arg4_type
) ||
4072 check_args_pair_invalid(fn
->arg4_type
, fn
->arg5_type
))
4078 static bool check_refcount_ok(const struct bpf_func_proto
*fn
, int func_id
)
4082 if (arg_type_may_be_refcounted(fn
->arg1_type
))
4084 if (arg_type_may_be_refcounted(fn
->arg2_type
))
4086 if (arg_type_may_be_refcounted(fn
->arg3_type
))
4088 if (arg_type_may_be_refcounted(fn
->arg4_type
))
4090 if (arg_type_may_be_refcounted(fn
->arg5_type
))
4093 /* A reference acquiring function cannot acquire
4094 * another refcounted ptr.
4096 if (is_acquire_function(func_id
) && count
)
4099 /* We only support one arg being unreferenced at the moment,
4100 * which is sufficient for the helper functions we have right now.
4105 static int check_func_proto(const struct bpf_func_proto
*fn
, int func_id
)
4107 return check_raw_mode_ok(fn
) &&
4108 check_arg_pair_ok(fn
) &&
4109 check_refcount_ok(fn
, func_id
) ? 0 : -EINVAL
;
4112 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
4113 * are now invalid, so turn them into unknown SCALAR_VALUE.
4115 static void __clear_all_pkt_pointers(struct bpf_verifier_env
*env
,
4116 struct bpf_func_state
*state
)
4118 struct bpf_reg_state
*regs
= state
->regs
, *reg
;
4121 for (i
= 0; i
< MAX_BPF_REG
; i
++)
4122 if (reg_is_pkt_pointer_any(®s
[i
]))
4123 mark_reg_unknown(env
, regs
, i
);
4125 bpf_for_each_spilled_reg(i
, state
, reg
) {
4128 if (reg_is_pkt_pointer_any(reg
))
4129 __mark_reg_unknown(env
, reg
);
4133 static void clear_all_pkt_pointers(struct bpf_verifier_env
*env
)
4135 struct bpf_verifier_state
*vstate
= env
->cur_state
;
4138 for (i
= 0; i
<= vstate
->curframe
; i
++)
4139 __clear_all_pkt_pointers(env
, vstate
->frame
[i
]);
4142 static void release_reg_references(struct bpf_verifier_env
*env
,
4143 struct bpf_func_state
*state
,
4146 struct bpf_reg_state
*regs
= state
->regs
, *reg
;
4149 for (i
= 0; i
< MAX_BPF_REG
; i
++)
4150 if (regs
[i
].ref_obj_id
== ref_obj_id
)
4151 mark_reg_unknown(env
, regs
, i
);
4153 bpf_for_each_spilled_reg(i
, state
, reg
) {
4156 if (reg
->ref_obj_id
== ref_obj_id
)
4157 __mark_reg_unknown(env
, reg
);
4161 /* The pointer with the specified id has released its reference to kernel
4162 * resources. Identify all copies of the same pointer and clear the reference.
4164 static int release_reference(struct bpf_verifier_env
*env
,
4167 struct bpf_verifier_state
*vstate
= env
->cur_state
;
4171 err
= release_reference_state(cur_func(env
), ref_obj_id
);
4175 for (i
= 0; i
<= vstate
->curframe
; i
++)
4176 release_reg_references(env
, vstate
->frame
[i
], ref_obj_id
);
4181 static void clear_caller_saved_regs(struct bpf_verifier_env
*env
,
4182 struct bpf_reg_state
*regs
)
4186 /* after the call registers r0 - r5 were scratched */
4187 for (i
= 0; i
< CALLER_SAVED_REGS
; i
++) {
4188 mark_reg_not_init(env
, regs
, caller_saved
[i
]);
4189 check_reg_arg(env
, caller_saved
[i
], DST_OP_NO_MARK
);
4193 static int check_func_call(struct bpf_verifier_env
*env
, struct bpf_insn
*insn
,
4196 struct bpf_verifier_state
*state
= env
->cur_state
;
4197 struct bpf_func_info_aux
*func_info_aux
;
4198 struct bpf_func_state
*caller
, *callee
;
4199 int i
, err
, subprog
, target_insn
;
4200 bool is_global
= false;
4202 if (state
->curframe
+ 1 >= MAX_CALL_FRAMES
) {
4203 verbose(env
, "the call stack of %d frames is too deep\n",
4204 state
->curframe
+ 2);
4208 target_insn
= *insn_idx
+ insn
->imm
;
4209 subprog
= find_subprog(env
, target_insn
+ 1);
4211 verbose(env
, "verifier bug. No program starts at insn %d\n",
4216 caller
= state
->frame
[state
->curframe
];
4217 if (state
->frame
[state
->curframe
+ 1]) {
4218 verbose(env
, "verifier bug. Frame %d already allocated\n",
4219 state
->curframe
+ 1);
4223 func_info_aux
= env
->prog
->aux
->func_info_aux
;
4225 is_global
= func_info_aux
[subprog
].linkage
== BTF_FUNC_GLOBAL
;
4226 err
= btf_check_func_arg_match(env
, subprog
, caller
->regs
);
4231 verbose(env
, "Caller passes invalid args into func#%d\n",
4235 if (env
->log
.level
& BPF_LOG_LEVEL
)
4237 "Func#%d is global and valid. Skipping.\n",
4239 clear_caller_saved_regs(env
, caller
->regs
);
4241 /* All global functions return SCALAR_VALUE */
4242 mark_reg_unknown(env
, caller
->regs
, BPF_REG_0
);
4244 /* continue with next insn after call */
4249 callee
= kzalloc(sizeof(*callee
), GFP_KERNEL
);
4252 state
->frame
[state
->curframe
+ 1] = callee
;
4254 /* callee cannot access r0, r6 - r9 for reading and has to write
4255 * into its own stack before reading from it.
4256 * callee can read/write into caller's stack
4258 init_func_state(env
, callee
,
4259 /* remember the callsite, it will be used by bpf_exit */
4260 *insn_idx
/* callsite */,
4261 state
->curframe
+ 1 /* frameno within this callchain */,
4262 subprog
/* subprog number within this prog */);
4264 /* Transfer references to the callee */
4265 err
= transfer_reference_state(callee
, caller
);
4269 /* copy r1 - r5 args that callee can access. The copy includes parent
4270 * pointers, which connects us up to the liveness chain
4272 for (i
= BPF_REG_1
; i
<= BPF_REG_5
; i
++)
4273 callee
->regs
[i
] = caller
->regs
[i
];
4275 clear_caller_saved_regs(env
, caller
->regs
);
4277 /* only increment it after check_reg_arg() finished */
4280 /* and go analyze first insn of the callee */
4281 *insn_idx
= target_insn
;
4283 if (env
->log
.level
& BPF_LOG_LEVEL
) {
4284 verbose(env
, "caller:\n");
4285 print_verifier_state(env
, caller
);
4286 verbose(env
, "callee:\n");
4287 print_verifier_state(env
, callee
);
4292 static int prepare_func_exit(struct bpf_verifier_env
*env
, int *insn_idx
)
4294 struct bpf_verifier_state
*state
= env
->cur_state
;
4295 struct bpf_func_state
*caller
, *callee
;
4296 struct bpf_reg_state
*r0
;
4299 callee
= state
->frame
[state
->curframe
];
4300 r0
= &callee
->regs
[BPF_REG_0
];
4301 if (r0
->type
== PTR_TO_STACK
) {
4302 /* technically it's ok to return caller's stack pointer
4303 * (or caller's caller's pointer) back to the caller,
4304 * since these pointers are valid. Only current stack
4305 * pointer will be invalid as soon as function exits,
4306 * but let's be conservative
4308 verbose(env
, "cannot return stack pointer to the caller\n");
4313 caller
= state
->frame
[state
->curframe
];
4314 /* return to the caller whatever r0 had in the callee */
4315 caller
->regs
[BPF_REG_0
] = *r0
;
4317 /* Transfer references to the caller */
4318 err
= transfer_reference_state(caller
, callee
);
4322 *insn_idx
= callee
->callsite
+ 1;
4323 if (env
->log
.level
& BPF_LOG_LEVEL
) {
4324 verbose(env
, "returning from callee:\n");
4325 print_verifier_state(env
, callee
);
4326 verbose(env
, "to caller at %d:\n", *insn_idx
);
4327 print_verifier_state(env
, caller
);
4329 /* clear everything in the callee */
4330 free_func_state(callee
);
4331 state
->frame
[state
->curframe
+ 1] = NULL
;
4335 static void do_refine_retval_range(struct bpf_reg_state
*regs
, int ret_type
,
4337 struct bpf_call_arg_meta
*meta
)
4339 struct bpf_reg_state
*ret_reg
= ®s
[BPF_REG_0
];
4341 if (ret_type
!= RET_INTEGER
||
4342 (func_id
!= BPF_FUNC_get_stack
&&
4343 func_id
!= BPF_FUNC_probe_read_str
&&
4344 func_id
!= BPF_FUNC_probe_read_kernel_str
&&
4345 func_id
!= BPF_FUNC_probe_read_user_str
))
4348 ret_reg
->smax_value
= meta
->msize_max_value
;
4349 ret_reg
->s32_max_value
= meta
->msize_max_value
;
4350 __reg_deduce_bounds(ret_reg
);
4351 __reg_bound_offset(ret_reg
);
4352 __update_reg_bounds(ret_reg
);
4356 record_func_map(struct bpf_verifier_env
*env
, struct bpf_call_arg_meta
*meta
,
4357 int func_id
, int insn_idx
)
4359 struct bpf_insn_aux_data
*aux
= &env
->insn_aux_data
[insn_idx
];
4360 struct bpf_map
*map
= meta
->map_ptr
;
4362 if (func_id
!= BPF_FUNC_tail_call
&&
4363 func_id
!= BPF_FUNC_map_lookup_elem
&&
4364 func_id
!= BPF_FUNC_map_update_elem
&&
4365 func_id
!= BPF_FUNC_map_delete_elem
&&
4366 func_id
!= BPF_FUNC_map_push_elem
&&
4367 func_id
!= BPF_FUNC_map_pop_elem
&&
4368 func_id
!= BPF_FUNC_map_peek_elem
)
4372 verbose(env
, "kernel subsystem misconfigured verifier\n");
4376 /* In case of read-only, some additional restrictions
4377 * need to be applied in order to prevent altering the
4378 * state of the map from program side.
4380 if ((map
->map_flags
& BPF_F_RDONLY_PROG
) &&
4381 (func_id
== BPF_FUNC_map_delete_elem
||
4382 func_id
== BPF_FUNC_map_update_elem
||
4383 func_id
== BPF_FUNC_map_push_elem
||
4384 func_id
== BPF_FUNC_map_pop_elem
)) {
4385 verbose(env
, "write into map forbidden\n");
4389 if (!BPF_MAP_PTR(aux
->map_ptr_state
))
4390 bpf_map_ptr_store(aux
, meta
->map_ptr
,
4391 meta
->map_ptr
->unpriv_array
);
4392 else if (BPF_MAP_PTR(aux
->map_ptr_state
) != meta
->map_ptr
)
4393 bpf_map_ptr_store(aux
, BPF_MAP_PTR_POISON
,
4394 meta
->map_ptr
->unpriv_array
);
4399 record_func_key(struct bpf_verifier_env
*env
, struct bpf_call_arg_meta
*meta
,
4400 int func_id
, int insn_idx
)
4402 struct bpf_insn_aux_data
*aux
= &env
->insn_aux_data
[insn_idx
];
4403 struct bpf_reg_state
*regs
= cur_regs(env
), *reg
;
4404 struct bpf_map
*map
= meta
->map_ptr
;
4409 if (func_id
!= BPF_FUNC_tail_call
)
4411 if (!map
|| map
->map_type
!= BPF_MAP_TYPE_PROG_ARRAY
) {
4412 verbose(env
, "kernel subsystem misconfigured verifier\n");
4416 range
= tnum_range(0, map
->max_entries
- 1);
4417 reg
= ®s
[BPF_REG_3
];
4419 if (!register_is_const(reg
) || !tnum_in(range
, reg
->var_off
)) {
4420 bpf_map_key_store(aux
, BPF_MAP_KEY_POISON
);
4424 err
= mark_chain_precision(env
, BPF_REG_3
);
4428 val
= reg
->var_off
.value
;
4429 if (bpf_map_key_unseen(aux
))
4430 bpf_map_key_store(aux
, val
);
4431 else if (!bpf_map_key_poisoned(aux
) &&
4432 bpf_map_key_immediate(aux
) != val
)
4433 bpf_map_key_store(aux
, BPF_MAP_KEY_POISON
);
4437 static int check_reference_leak(struct bpf_verifier_env
*env
)
4439 struct bpf_func_state
*state
= cur_func(env
);
4442 for (i
= 0; i
< state
->acquired_refs
; i
++) {
4443 verbose(env
, "Unreleased reference id=%d alloc_insn=%d\n",
4444 state
->refs
[i
].id
, state
->refs
[i
].insn_idx
);
4446 return state
->acquired_refs
? -EINVAL
: 0;
4449 static int check_helper_call(struct bpf_verifier_env
*env
, int func_id
, int insn_idx
)
4451 const struct bpf_func_proto
*fn
= NULL
;
4452 struct bpf_reg_state
*regs
;
4453 struct bpf_call_arg_meta meta
;
4457 /* find function prototype */
4458 if (func_id
< 0 || func_id
>= __BPF_FUNC_MAX_ID
) {
4459 verbose(env
, "invalid func %s#%d\n", func_id_name(func_id
),
4464 if (env
->ops
->get_func_proto
)
4465 fn
= env
->ops
->get_func_proto(func_id
, env
->prog
);
4467 verbose(env
, "unknown func %s#%d\n", func_id_name(func_id
),
4472 /* eBPF programs must be GPL compatible to use GPL-ed functions */
4473 if (!env
->prog
->gpl_compatible
&& fn
->gpl_only
) {
4474 verbose(env
, "cannot call GPL-restricted function from non-GPL compatible program\n");
4478 /* With LD_ABS/IND some JITs save/restore skb from r1. */
4479 changes_data
= bpf_helper_changes_pkt_data(fn
->func
);
4480 if (changes_data
&& fn
->arg1_type
!= ARG_PTR_TO_CTX
) {
4481 verbose(env
, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
4482 func_id_name(func_id
), func_id
);
4486 memset(&meta
, 0, sizeof(meta
));
4487 meta
.pkt_access
= fn
->pkt_access
;
4489 err
= check_func_proto(fn
, func_id
);
4491 verbose(env
, "kernel subsystem misconfigured func %s#%d\n",
4492 func_id_name(func_id
), func_id
);
4496 meta
.func_id
= func_id
;
4498 for (i
= 0; i
< 5; i
++) {
4499 err
= btf_resolve_helper_id(&env
->log
, fn
, i
);
4502 err
= check_func_arg(env
, BPF_REG_1
+ i
, fn
->arg_type
[i
], &meta
);
4507 err
= record_func_map(env
, &meta
, func_id
, insn_idx
);
4511 err
= record_func_key(env
, &meta
, func_id
, insn_idx
);
4515 /* Mark slots with STACK_MISC in case of raw mode, stack offset
4516 * is inferred from register state.
4518 for (i
= 0; i
< meta
.access_size
; i
++) {
4519 err
= check_mem_access(env
, insn_idx
, meta
.regno
, i
, BPF_B
,
4520 BPF_WRITE
, -1, false);
4525 if (func_id
== BPF_FUNC_tail_call
) {
4526 err
= check_reference_leak(env
);
4528 verbose(env
, "tail_call would lead to reference leak\n");
4531 } else if (is_release_function(func_id
)) {
4532 err
= release_reference(env
, meta
.ref_obj_id
);
4534 verbose(env
, "func %s#%d reference has not been acquired before\n",
4535 func_id_name(func_id
), func_id
);
4540 regs
= cur_regs(env
);
4542 /* check that flags argument in get_local_storage(map, flags) is 0,
4543 * this is required because get_local_storage() can't return an error.
4545 if (func_id
== BPF_FUNC_get_local_storage
&&
4546 !register_is_null(®s
[BPF_REG_2
])) {
4547 verbose(env
, "get_local_storage() doesn't support non-zero flags\n");
4551 /* reset caller saved regs */
4552 for (i
= 0; i
< CALLER_SAVED_REGS
; i
++) {
4553 mark_reg_not_init(env
, regs
, caller_saved
[i
]);
4554 check_reg_arg(env
, caller_saved
[i
], DST_OP_NO_MARK
);
4557 /* helper call returns 64-bit value. */
4558 regs
[BPF_REG_0
].subreg_def
= DEF_NOT_SUBREG
;
4560 /* update return register (already marked as written above) */
4561 if (fn
->ret_type
== RET_INTEGER
) {
4562 /* sets type to SCALAR_VALUE */
4563 mark_reg_unknown(env
, regs
, BPF_REG_0
);
4564 } else if (fn
->ret_type
== RET_VOID
) {
4565 regs
[BPF_REG_0
].type
= NOT_INIT
;
4566 } else if (fn
->ret_type
== RET_PTR_TO_MAP_VALUE_OR_NULL
||
4567 fn
->ret_type
== RET_PTR_TO_MAP_VALUE
) {
4568 /* There is no offset yet applied, variable or fixed */
4569 mark_reg_known_zero(env
, regs
, BPF_REG_0
);
4570 /* remember map_ptr, so that check_map_access()
4571 * can check 'value_size' boundary of memory access
4572 * to map element returned from bpf_map_lookup_elem()
4574 if (meta
.map_ptr
== NULL
) {
4576 "kernel subsystem misconfigured verifier\n");
4579 regs
[BPF_REG_0
].map_ptr
= meta
.map_ptr
;
4580 if (fn
->ret_type
== RET_PTR_TO_MAP_VALUE
) {
4581 regs
[BPF_REG_0
].type
= PTR_TO_MAP_VALUE
;
4582 if (map_value_has_spin_lock(meta
.map_ptr
))
4583 regs
[BPF_REG_0
].id
= ++env
->id_gen
;
4585 regs
[BPF_REG_0
].type
= PTR_TO_MAP_VALUE_OR_NULL
;
4586 regs
[BPF_REG_0
].id
= ++env
->id_gen
;
4588 } else if (fn
->ret_type
== RET_PTR_TO_SOCKET_OR_NULL
) {
4589 mark_reg_known_zero(env
, regs
, BPF_REG_0
);
4590 regs
[BPF_REG_0
].type
= PTR_TO_SOCKET_OR_NULL
;
4591 regs
[BPF_REG_0
].id
= ++env
->id_gen
;
4592 } else if (fn
->ret_type
== RET_PTR_TO_SOCK_COMMON_OR_NULL
) {
4593 mark_reg_known_zero(env
, regs
, BPF_REG_0
);
4594 regs
[BPF_REG_0
].type
= PTR_TO_SOCK_COMMON_OR_NULL
;
4595 regs
[BPF_REG_0
].id
= ++env
->id_gen
;
4596 } else if (fn
->ret_type
== RET_PTR_TO_TCP_SOCK_OR_NULL
) {
4597 mark_reg_known_zero(env
, regs
, BPF_REG_0
);
4598 regs
[BPF_REG_0
].type
= PTR_TO_TCP_SOCK_OR_NULL
;
4599 regs
[BPF_REG_0
].id
= ++env
->id_gen
;
4601 verbose(env
, "unknown return type %d of func %s#%d\n",
4602 fn
->ret_type
, func_id_name(func_id
), func_id
);
4606 if (is_ptr_cast_function(func_id
)) {
4607 /* For release_reference() */
4608 regs
[BPF_REG_0
].ref_obj_id
= meta
.ref_obj_id
;
4609 } else if (is_acquire_function(func_id
)) {
4610 int id
= acquire_reference_state(env
, insn_idx
);
4614 /* For mark_ptr_or_null_reg() */
4615 regs
[BPF_REG_0
].id
= id
;
4616 /* For release_reference() */
4617 regs
[BPF_REG_0
].ref_obj_id
= id
;
4620 do_refine_retval_range(regs
, fn
->ret_type
, func_id
, &meta
);
4622 err
= check_map_func_compatibility(env
, meta
.map_ptr
, func_id
);
4626 if (func_id
== BPF_FUNC_get_stack
&& !env
->prog
->has_callchain_buf
) {
4627 const char *err_str
;
4629 #ifdef CONFIG_PERF_EVENTS
4630 err
= get_callchain_buffers(sysctl_perf_event_max_stack
);
4631 err_str
= "cannot get callchain buffer for func %s#%d\n";
4634 err_str
= "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
4637 verbose(env
, err_str
, func_id_name(func_id
), func_id
);
4641 env
->prog
->has_callchain_buf
= true;
4645 clear_all_pkt_pointers(env
);
4649 static bool signed_add_overflows(s64 a
, s64 b
)
4651 /* Do the add in u64, where overflow is well-defined */
4652 s64 res
= (s64
)((u64
)a
+ (u64
)b
);
4659 static bool signed_add32_overflows(s64 a
, s64 b
)
4661 /* Do the add in u32, where overflow is well-defined */
4662 s32 res
= (s32
)((u32
)a
+ (u32
)b
);
4669 static bool signed_sub_overflows(s32 a
, s32 b
)
4671 /* Do the sub in u64, where overflow is well-defined */
4672 s64 res
= (s64
)((u64
)a
- (u64
)b
);
4679 static bool signed_sub32_overflows(s32 a
, s32 b
)
4681 /* Do the sub in u64, where overflow is well-defined */
4682 s32 res
= (s32
)((u32
)a
- (u32
)b
);
4689 static bool check_reg_sane_offset(struct bpf_verifier_env
*env
,
4690 const struct bpf_reg_state
*reg
,
4691 enum bpf_reg_type type
)
4693 bool known
= tnum_is_const(reg
->var_off
);
4694 s64 val
= reg
->var_off
.value
;
4695 s64 smin
= reg
->smin_value
;
4697 if (known
&& (val
>= BPF_MAX_VAR_OFF
|| val
<= -BPF_MAX_VAR_OFF
)) {
4698 verbose(env
, "math between %s pointer and %lld is not allowed\n",
4699 reg_type_str
[type
], val
);
4703 if (reg
->off
>= BPF_MAX_VAR_OFF
|| reg
->off
<= -BPF_MAX_VAR_OFF
) {
4704 verbose(env
, "%s pointer offset %d is not allowed\n",
4705 reg_type_str
[type
], reg
->off
);
4709 if (smin
== S64_MIN
) {
4710 verbose(env
, "math between %s pointer and register with unbounded min value is not allowed\n",
4711 reg_type_str
[type
]);
4715 if (smin
>= BPF_MAX_VAR_OFF
|| smin
<= -BPF_MAX_VAR_OFF
) {
4716 verbose(env
, "value %lld makes %s pointer be out of bounds\n",
4717 smin
, reg_type_str
[type
]);
4724 static struct bpf_insn_aux_data
*cur_aux(struct bpf_verifier_env
*env
)
4726 return &env
->insn_aux_data
[env
->insn_idx
];
4729 static int retrieve_ptr_limit(const struct bpf_reg_state
*ptr_reg
,
4730 u32
*ptr_limit
, u8 opcode
, bool off_is_neg
)
4732 bool mask_to_left
= (opcode
== BPF_ADD
&& off_is_neg
) ||
4733 (opcode
== BPF_SUB
&& !off_is_neg
);
4736 switch (ptr_reg
->type
) {
4738 /* Indirect variable offset stack access is prohibited in
4739 * unprivileged mode so it's not handled here.
4741 off
= ptr_reg
->off
+ ptr_reg
->var_off
.value
;
4743 *ptr_limit
= MAX_BPF_STACK
+ off
;
4747 case PTR_TO_MAP_VALUE
:
4749 *ptr_limit
= ptr_reg
->umax_value
+ ptr_reg
->off
;
4751 off
= ptr_reg
->smin_value
+ ptr_reg
->off
;
4752 *ptr_limit
= ptr_reg
->map_ptr
->value_size
- off
;
4760 static bool can_skip_alu_sanitation(const struct bpf_verifier_env
*env
,
4761 const struct bpf_insn
*insn
)
4763 return env
->allow_ptr_leaks
|| BPF_SRC(insn
->code
) == BPF_K
;
4766 static int update_alu_sanitation_state(struct bpf_insn_aux_data
*aux
,
4767 u32 alu_state
, u32 alu_limit
)
4769 /* If we arrived here from different branches with different
4770 * state or limits to sanitize, then this won't work.
4772 if (aux
->alu_state
&&
4773 (aux
->alu_state
!= alu_state
||
4774 aux
->alu_limit
!= alu_limit
))
4777 /* Corresponding fixup done in fixup_bpf_calls(). */
4778 aux
->alu_state
= alu_state
;
4779 aux
->alu_limit
= alu_limit
;
4783 static int sanitize_val_alu(struct bpf_verifier_env
*env
,
4784 struct bpf_insn
*insn
)
4786 struct bpf_insn_aux_data
*aux
= cur_aux(env
);
4788 if (can_skip_alu_sanitation(env
, insn
))
4791 return update_alu_sanitation_state(aux
, BPF_ALU_NON_POINTER
, 0);
4794 static int sanitize_ptr_alu(struct bpf_verifier_env
*env
,
4795 struct bpf_insn
*insn
,
4796 const struct bpf_reg_state
*ptr_reg
,
4797 struct bpf_reg_state
*dst_reg
,
4800 struct bpf_verifier_state
*vstate
= env
->cur_state
;
4801 struct bpf_insn_aux_data
*aux
= cur_aux(env
);
4802 bool ptr_is_dst_reg
= ptr_reg
== dst_reg
;
4803 u8 opcode
= BPF_OP(insn
->code
);
4804 u32 alu_state
, alu_limit
;
4805 struct bpf_reg_state tmp
;
4808 if (can_skip_alu_sanitation(env
, insn
))
4811 /* We already marked aux for masking from non-speculative
4812 * paths, thus we got here in the first place. We only care
4813 * to explore bad access from here.
4815 if (vstate
->speculative
)
4818 alu_state
= off_is_neg
? BPF_ALU_NEG_VALUE
: 0;
4819 alu_state
|= ptr_is_dst_reg
?
4820 BPF_ALU_SANITIZE_SRC
: BPF_ALU_SANITIZE_DST
;
4822 if (retrieve_ptr_limit(ptr_reg
, &alu_limit
, opcode
, off_is_neg
))
4824 if (update_alu_sanitation_state(aux
, alu_state
, alu_limit
))
4827 /* Simulate and find potential out-of-bounds access under
4828 * speculative execution from truncation as a result of
4829 * masking when off was not within expected range. If off
4830 * sits in dst, then we temporarily need to move ptr there
4831 * to simulate dst (== 0) +/-= ptr. Needed, for example,
4832 * for cases where we use K-based arithmetic in one direction
4833 * and truncated reg-based in the other in order to explore
4836 if (!ptr_is_dst_reg
) {
4838 *dst_reg
= *ptr_reg
;
4840 ret
= push_stack(env
, env
->insn_idx
+ 1, env
->insn_idx
, true);
4841 if (!ptr_is_dst_reg
&& ret
)
4843 return !ret
? -EFAULT
: 0;
4846 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
4847 * Caller should also handle BPF_MOV case separately.
4848 * If we return -EACCES, caller may want to try again treating pointer as a
4849 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks.
4851 static int adjust_ptr_min_max_vals(struct bpf_verifier_env
*env
,
4852 struct bpf_insn
*insn
,
4853 const struct bpf_reg_state
*ptr_reg
,
4854 const struct bpf_reg_state
*off_reg
)
4856 struct bpf_verifier_state
*vstate
= env
->cur_state
;
4857 struct bpf_func_state
*state
= vstate
->frame
[vstate
->curframe
];
4858 struct bpf_reg_state
*regs
= state
->regs
, *dst_reg
;
4859 bool known
= tnum_is_const(off_reg
->var_off
);
4860 s64 smin_val
= off_reg
->smin_value
, smax_val
= off_reg
->smax_value
,
4861 smin_ptr
= ptr_reg
->smin_value
, smax_ptr
= ptr_reg
->smax_value
;
4862 u64 umin_val
= off_reg
->umin_value
, umax_val
= off_reg
->umax_value
,
4863 umin_ptr
= ptr_reg
->umin_value
, umax_ptr
= ptr_reg
->umax_value
;
4864 u32 dst
= insn
->dst_reg
, src
= insn
->src_reg
;
4865 u8 opcode
= BPF_OP(insn
->code
);
4868 dst_reg
= ®s
[dst
];
4870 if ((known
&& (smin_val
!= smax_val
|| umin_val
!= umax_val
)) ||
4871 smin_val
> smax_val
|| umin_val
> umax_val
) {
4872 /* Taint dst register if offset had invalid bounds derived from
4873 * e.g. dead branches.
4875 __mark_reg_unknown(env
, dst_reg
);
4879 if (BPF_CLASS(insn
->code
) != BPF_ALU64
) {
4880 /* 32-bit ALU ops on pointers produce (meaningless) scalars */
4882 "R%d 32-bit pointer arithmetic prohibited\n",
4887 switch (ptr_reg
->type
) {
4888 case PTR_TO_MAP_VALUE_OR_NULL
:
4889 verbose(env
, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
4890 dst
, reg_type_str
[ptr_reg
->type
]);
4892 case CONST_PTR_TO_MAP
:
4893 case PTR_TO_PACKET_END
:
4895 case PTR_TO_SOCKET_OR_NULL
:
4896 case PTR_TO_SOCK_COMMON
:
4897 case PTR_TO_SOCK_COMMON_OR_NULL
:
4898 case PTR_TO_TCP_SOCK
:
4899 case PTR_TO_TCP_SOCK_OR_NULL
:
4900 case PTR_TO_XDP_SOCK
:
4901 verbose(env
, "R%d pointer arithmetic on %s prohibited\n",
4902 dst
, reg_type_str
[ptr_reg
->type
]);
4904 case PTR_TO_MAP_VALUE
:
4905 if (!env
->allow_ptr_leaks
&& !known
&& (smin_val
< 0) != (smax_val
< 0)) {
4906 verbose(env
, "R%d has unknown scalar with mixed signed bounds, pointer arithmetic with it prohibited for !root\n",
4907 off_reg
== dst_reg
? dst
: src
);
4915 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
4916 * The id may be overwritten later if we create a new variable offset.
4918 dst_reg
->type
= ptr_reg
->type
;
4919 dst_reg
->id
= ptr_reg
->id
;
4921 if (!check_reg_sane_offset(env
, off_reg
, ptr_reg
->type
) ||
4922 !check_reg_sane_offset(env
, ptr_reg
, ptr_reg
->type
))
4925 /* pointer types do not carry 32-bit bounds at the moment. */
4926 __mark_reg32_unbounded(dst_reg
);
4930 ret
= sanitize_ptr_alu(env
, insn
, ptr_reg
, dst_reg
, smin_val
< 0);
4932 verbose(env
, "R%d tried to add from different maps or paths\n", dst
);
4935 /* We can take a fixed offset as long as it doesn't overflow
4936 * the s32 'off' field
4938 if (known
&& (ptr_reg
->off
+ smin_val
==
4939 (s64
)(s32
)(ptr_reg
->off
+ smin_val
))) {
4940 /* pointer += K. Accumulate it into fixed offset */
4941 dst_reg
->smin_value
= smin_ptr
;
4942 dst_reg
->smax_value
= smax_ptr
;
4943 dst_reg
->umin_value
= umin_ptr
;
4944 dst_reg
->umax_value
= umax_ptr
;
4945 dst_reg
->var_off
= ptr_reg
->var_off
;
4946 dst_reg
->off
= ptr_reg
->off
+ smin_val
;
4947 dst_reg
->raw
= ptr_reg
->raw
;
4950 /* A new variable offset is created. Note that off_reg->off
4951 * == 0, since it's a scalar.
4952 * dst_reg gets the pointer type and since some positive
4953 * integer value was added to the pointer, give it a new 'id'
4954 * if it's a PTR_TO_PACKET.
4955 * this creates a new 'base' pointer, off_reg (variable) gets
4956 * added into the variable offset, and we copy the fixed offset
4959 if (signed_add_overflows(smin_ptr
, smin_val
) ||
4960 signed_add_overflows(smax_ptr
, smax_val
)) {
4961 dst_reg
->smin_value
= S64_MIN
;
4962 dst_reg
->smax_value
= S64_MAX
;
4964 dst_reg
->smin_value
= smin_ptr
+ smin_val
;
4965 dst_reg
->smax_value
= smax_ptr
+ smax_val
;
4967 if (umin_ptr
+ umin_val
< umin_ptr
||
4968 umax_ptr
+ umax_val
< umax_ptr
) {
4969 dst_reg
->umin_value
= 0;
4970 dst_reg
->umax_value
= U64_MAX
;
4972 dst_reg
->umin_value
= umin_ptr
+ umin_val
;
4973 dst_reg
->umax_value
= umax_ptr
+ umax_val
;
4975 dst_reg
->var_off
= tnum_add(ptr_reg
->var_off
, off_reg
->var_off
);
4976 dst_reg
->off
= ptr_reg
->off
;
4977 dst_reg
->raw
= ptr_reg
->raw
;
4978 if (reg_is_pkt_pointer(ptr_reg
)) {
4979 dst_reg
->id
= ++env
->id_gen
;
4980 /* something was added to pkt_ptr, set range to zero */
4985 ret
= sanitize_ptr_alu(env
, insn
, ptr_reg
, dst_reg
, smin_val
< 0);
4987 verbose(env
, "R%d tried to sub from different maps or paths\n", dst
);
4990 if (dst_reg
== off_reg
) {
4991 /* scalar -= pointer. Creates an unknown scalar */
4992 verbose(env
, "R%d tried to subtract pointer from scalar\n",
4996 /* We don't allow subtraction from FP, because (according to
4997 * test_verifier.c test "invalid fp arithmetic", JITs might not
4998 * be able to deal with it.
5000 if (ptr_reg
->type
== PTR_TO_STACK
) {
5001 verbose(env
, "R%d subtraction from stack pointer prohibited\n",
5005 if (known
&& (ptr_reg
->off
- smin_val
==
5006 (s64
)(s32
)(ptr_reg
->off
- smin_val
))) {
5007 /* pointer -= K. Subtract it from fixed offset */
5008 dst_reg
->smin_value
= smin_ptr
;
5009 dst_reg
->smax_value
= smax_ptr
;
5010 dst_reg
->umin_value
= umin_ptr
;
5011 dst_reg
->umax_value
= umax_ptr
;
5012 dst_reg
->var_off
= ptr_reg
->var_off
;
5013 dst_reg
->id
= ptr_reg
->id
;
5014 dst_reg
->off
= ptr_reg
->off
- smin_val
;
5015 dst_reg
->raw
= ptr_reg
->raw
;
5018 /* A new variable offset is created. If the subtrahend is known
5019 * nonnegative, then any reg->range we had before is still good.
5021 if (signed_sub_overflows(smin_ptr
, smax_val
) ||
5022 signed_sub_overflows(smax_ptr
, smin_val
)) {
5023 /* Overflow possible, we know nothing */
5024 dst_reg
->smin_value
= S64_MIN
;
5025 dst_reg
->smax_value
= S64_MAX
;
5027 dst_reg
->smin_value
= smin_ptr
- smax_val
;
5028 dst_reg
->smax_value
= smax_ptr
- smin_val
;
5030 if (umin_ptr
< umax_val
) {
5031 /* Overflow possible, we know nothing */
5032 dst_reg
->umin_value
= 0;
5033 dst_reg
->umax_value
= U64_MAX
;
5035 /* Cannot overflow (as long as bounds are consistent) */
5036 dst_reg
->umin_value
= umin_ptr
- umax_val
;
5037 dst_reg
->umax_value
= umax_ptr
- umin_val
;
5039 dst_reg
->var_off
= tnum_sub(ptr_reg
->var_off
, off_reg
->var_off
);
5040 dst_reg
->off
= ptr_reg
->off
;
5041 dst_reg
->raw
= ptr_reg
->raw
;
5042 if (reg_is_pkt_pointer(ptr_reg
)) {
5043 dst_reg
->id
= ++env
->id_gen
;
5044 /* something was added to pkt_ptr, set range to zero */
5052 /* bitwise ops on pointers are troublesome, prohibit. */
5053 verbose(env
, "R%d bitwise operator %s on pointer prohibited\n",
5054 dst
, bpf_alu_string
[opcode
>> 4]);
5057 /* other operators (e.g. MUL,LSH) produce non-pointer results */
5058 verbose(env
, "R%d pointer arithmetic with %s operator prohibited\n",
5059 dst
, bpf_alu_string
[opcode
>> 4]);
5063 if (!check_reg_sane_offset(env
, dst_reg
, ptr_reg
->type
))
5066 __update_reg_bounds(dst_reg
);
5067 __reg_deduce_bounds(dst_reg
);
5068 __reg_bound_offset(dst_reg
);
5070 /* For unprivileged we require that resulting offset must be in bounds
5071 * in order to be able to sanitize access later on.
5073 if (!env
->allow_ptr_leaks
) {
5074 if (dst_reg
->type
== PTR_TO_MAP_VALUE
&&
5075 check_map_access(env
, dst
, dst_reg
->off
, 1, false)) {
5076 verbose(env
, "R%d pointer arithmetic of map value goes out of range, "
5077 "prohibited for !root\n", dst
);
5079 } else if (dst_reg
->type
== PTR_TO_STACK
&&
5080 check_stack_access(env
, dst_reg
, dst_reg
->off
+
5081 dst_reg
->var_off
.value
, 1)) {
5082 verbose(env
, "R%d stack pointer arithmetic goes out of range, "
5083 "prohibited for !root\n", dst
);
5091 static void scalar32_min_max_add(struct bpf_reg_state
*dst_reg
,
5092 struct bpf_reg_state
*src_reg
)
5094 s32 smin_val
= src_reg
->s32_min_value
;
5095 s32 smax_val
= src_reg
->s32_max_value
;
5096 u32 umin_val
= src_reg
->u32_min_value
;
5097 u32 umax_val
= src_reg
->u32_max_value
;
5099 if (signed_add32_overflows(dst_reg
->s32_min_value
, smin_val
) ||
5100 signed_add32_overflows(dst_reg
->s32_max_value
, smax_val
)) {
5101 dst_reg
->s32_min_value
= S32_MIN
;
5102 dst_reg
->s32_max_value
= S32_MAX
;
5104 dst_reg
->s32_min_value
+= smin_val
;
5105 dst_reg
->s32_max_value
+= smax_val
;
5107 if (dst_reg
->u32_min_value
+ umin_val
< umin_val
||
5108 dst_reg
->u32_max_value
+ umax_val
< umax_val
) {
5109 dst_reg
->u32_min_value
= 0;
5110 dst_reg
->u32_max_value
= U32_MAX
;
5112 dst_reg
->u32_min_value
+= umin_val
;
5113 dst_reg
->u32_max_value
+= umax_val
;
5117 static void scalar_min_max_add(struct bpf_reg_state
*dst_reg
,
5118 struct bpf_reg_state
*src_reg
)
5120 s64 smin_val
= src_reg
->smin_value
;
5121 s64 smax_val
= src_reg
->smax_value
;
5122 u64 umin_val
= src_reg
->umin_value
;
5123 u64 umax_val
= src_reg
->umax_value
;
5125 if (signed_add_overflows(dst_reg
->smin_value
, smin_val
) ||
5126 signed_add_overflows(dst_reg
->smax_value
, smax_val
)) {
5127 dst_reg
->smin_value
= S64_MIN
;
5128 dst_reg
->smax_value
= S64_MAX
;
5130 dst_reg
->smin_value
+= smin_val
;
5131 dst_reg
->smax_value
+= smax_val
;
5133 if (dst_reg
->umin_value
+ umin_val
< umin_val
||
5134 dst_reg
->umax_value
+ umax_val
< umax_val
) {
5135 dst_reg
->umin_value
= 0;
5136 dst_reg
->umax_value
= U64_MAX
;
5138 dst_reg
->umin_value
+= umin_val
;
5139 dst_reg
->umax_value
+= umax_val
;
5143 static void scalar32_min_max_sub(struct bpf_reg_state
*dst_reg
,
5144 struct bpf_reg_state
*src_reg
)
5146 s32 smin_val
= src_reg
->s32_min_value
;
5147 s32 smax_val
= src_reg
->s32_max_value
;
5148 u32 umin_val
= src_reg
->u32_min_value
;
5149 u32 umax_val
= src_reg
->u32_max_value
;
5151 if (signed_sub32_overflows(dst_reg
->s32_min_value
, smax_val
) ||
5152 signed_sub32_overflows(dst_reg
->s32_max_value
, smin_val
)) {
5153 /* Overflow possible, we know nothing */
5154 dst_reg
->s32_min_value
= S32_MIN
;
5155 dst_reg
->s32_max_value
= S32_MAX
;
5157 dst_reg
->s32_min_value
-= smax_val
;
5158 dst_reg
->s32_max_value
-= smin_val
;
5160 if (dst_reg
->u32_min_value
< umax_val
) {
5161 /* Overflow possible, we know nothing */
5162 dst_reg
->u32_min_value
= 0;
5163 dst_reg
->u32_max_value
= U32_MAX
;
5165 /* Cannot overflow (as long as bounds are consistent) */
5166 dst_reg
->u32_min_value
-= umax_val
;
5167 dst_reg
->u32_max_value
-= umin_val
;
5171 static void scalar_min_max_sub(struct bpf_reg_state
*dst_reg
,
5172 struct bpf_reg_state
*src_reg
)
5174 s64 smin_val
= src_reg
->smin_value
;
5175 s64 smax_val
= src_reg
->smax_value
;
5176 u64 umin_val
= src_reg
->umin_value
;
5177 u64 umax_val
= src_reg
->umax_value
;
5179 if (signed_sub_overflows(dst_reg
->smin_value
, smax_val
) ||
5180 signed_sub_overflows(dst_reg
->smax_value
, smin_val
)) {
5181 /* Overflow possible, we know nothing */
5182 dst_reg
->smin_value
= S64_MIN
;
5183 dst_reg
->smax_value
= S64_MAX
;
5185 dst_reg
->smin_value
-= smax_val
;
5186 dst_reg
->smax_value
-= smin_val
;
5188 if (dst_reg
->umin_value
< umax_val
) {
5189 /* Overflow possible, we know nothing */
5190 dst_reg
->umin_value
= 0;
5191 dst_reg
->umax_value
= U64_MAX
;
5193 /* Cannot overflow (as long as bounds are consistent) */
5194 dst_reg
->umin_value
-= umax_val
;
5195 dst_reg
->umax_value
-= umin_val
;
5199 static void scalar32_min_max_mul(struct bpf_reg_state
*dst_reg
,
5200 struct bpf_reg_state
*src_reg
)
5202 s32 smin_val
= src_reg
->s32_min_value
;
5203 u32 umin_val
= src_reg
->u32_min_value
;
5204 u32 umax_val
= src_reg
->u32_max_value
;
5206 if (smin_val
< 0 || dst_reg
->s32_min_value
< 0) {
5207 /* Ain't nobody got time to multiply that sign */
5208 __mark_reg32_unbounded(dst_reg
);
5211 /* Both values are positive, so we can work with unsigned and
5212 * copy the result to signed (unless it exceeds S32_MAX).
5214 if (umax_val
> U16_MAX
|| dst_reg
->u32_max_value
> U16_MAX
) {
5215 /* Potential overflow, we know nothing */
5216 __mark_reg32_unbounded(dst_reg
);
5219 dst_reg
->u32_min_value
*= umin_val
;
5220 dst_reg
->u32_max_value
*= umax_val
;
5221 if (dst_reg
->u32_max_value
> S32_MAX
) {
5222 /* Overflow possible, we know nothing */
5223 dst_reg
->s32_min_value
= S32_MIN
;
5224 dst_reg
->s32_max_value
= S32_MAX
;
5226 dst_reg
->s32_min_value
= dst_reg
->u32_min_value
;
5227 dst_reg
->s32_max_value
= dst_reg
->u32_max_value
;
5231 static void scalar_min_max_mul(struct bpf_reg_state
*dst_reg
,
5232 struct bpf_reg_state
*src_reg
)
5234 s64 smin_val
= src_reg
->smin_value
;
5235 u64 umin_val
= src_reg
->umin_value
;
5236 u64 umax_val
= src_reg
->umax_value
;
5238 if (smin_val
< 0 || dst_reg
->smin_value
< 0) {
5239 /* Ain't nobody got time to multiply that sign */
5240 __mark_reg64_unbounded(dst_reg
);
5243 /* Both values are positive, so we can work with unsigned and
5244 * copy the result to signed (unless it exceeds S64_MAX).
5246 if (umax_val
> U32_MAX
|| dst_reg
->umax_value
> U32_MAX
) {
5247 /* Potential overflow, we know nothing */
5248 __mark_reg64_unbounded(dst_reg
);
5251 dst_reg
->umin_value
*= umin_val
;
5252 dst_reg
->umax_value
*= umax_val
;
5253 if (dst_reg
->umax_value
> S64_MAX
) {
5254 /* Overflow possible, we know nothing */
5255 dst_reg
->smin_value
= S64_MIN
;
5256 dst_reg
->smax_value
= S64_MAX
;
5258 dst_reg
->smin_value
= dst_reg
->umin_value
;
5259 dst_reg
->smax_value
= dst_reg
->umax_value
;
5263 static void scalar32_min_max_and(struct bpf_reg_state
*dst_reg
,
5264 struct bpf_reg_state
*src_reg
)
5266 bool src_known
= tnum_subreg_is_const(src_reg
->var_off
);
5267 bool dst_known
= tnum_subreg_is_const(dst_reg
->var_off
);
5268 struct tnum var32_off
= tnum_subreg(dst_reg
->var_off
);
5269 s32 smin_val
= src_reg
->s32_min_value
;
5270 u32 umax_val
= src_reg
->u32_max_value
;
5272 /* Assuming scalar64_min_max_and will be called so its safe
5273 * to skip updating register for known 32-bit case.
5275 if (src_known
&& dst_known
)
5278 /* We get our minimum from the var_off, since that's inherently
5279 * bitwise. Our maximum is the minimum of the operands' maxima.
5281 dst_reg
->u32_min_value
= var32_off
.value
;
5282 dst_reg
->u32_max_value
= min(dst_reg
->u32_max_value
, umax_val
);
5283 if (dst_reg
->s32_min_value
< 0 || smin_val
< 0) {
5284 /* Lose signed bounds when ANDing negative numbers,
5285 * ain't nobody got time for that.
5287 dst_reg
->s32_min_value
= S32_MIN
;
5288 dst_reg
->s32_max_value
= S32_MAX
;
5290 /* ANDing two positives gives a positive, so safe to
5291 * cast result into s64.
5293 dst_reg
->s32_min_value
= dst_reg
->u32_min_value
;
5294 dst_reg
->s32_max_value
= dst_reg
->u32_max_value
;
5299 static void scalar_min_max_and(struct bpf_reg_state
*dst_reg
,
5300 struct bpf_reg_state
*src_reg
)
5302 bool src_known
= tnum_is_const(src_reg
->var_off
);
5303 bool dst_known
= tnum_is_const(dst_reg
->var_off
);
5304 s64 smin_val
= src_reg
->smin_value
;
5305 u64 umax_val
= src_reg
->umax_value
;
5307 if (src_known
&& dst_known
) {
5308 __mark_reg_known(dst_reg
, dst_reg
->var_off
.value
&
5309 src_reg
->var_off
.value
);
5313 /* We get our minimum from the var_off, since that's inherently
5314 * bitwise. Our maximum is the minimum of the operands' maxima.
5316 dst_reg
->umin_value
= dst_reg
->var_off
.value
;
5317 dst_reg
->umax_value
= min(dst_reg
->umax_value
, umax_val
);
5318 if (dst_reg
->smin_value
< 0 || smin_val
< 0) {
5319 /* Lose signed bounds when ANDing negative numbers,
5320 * ain't nobody got time for that.
5322 dst_reg
->smin_value
= S64_MIN
;
5323 dst_reg
->smax_value
= S64_MAX
;
5325 /* ANDing two positives gives a positive, so safe to
5326 * cast result into s64.
5328 dst_reg
->smin_value
= dst_reg
->umin_value
;
5329 dst_reg
->smax_value
= dst_reg
->umax_value
;
5331 /* We may learn something more from the var_off */
5332 __update_reg_bounds(dst_reg
);
5335 static void scalar32_min_max_or(struct bpf_reg_state
*dst_reg
,
5336 struct bpf_reg_state
*src_reg
)
5338 bool src_known
= tnum_subreg_is_const(src_reg
->var_off
);
5339 bool dst_known
= tnum_subreg_is_const(dst_reg
->var_off
);
5340 struct tnum var32_off
= tnum_subreg(dst_reg
->var_off
);
5341 s32 smin_val
= src_reg
->smin_value
;
5342 u32 umin_val
= src_reg
->umin_value
;
5344 /* Assuming scalar64_min_max_or will be called so it is safe
5345 * to skip updating register for known case.
5347 if (src_known
&& dst_known
)
5350 /* We get our maximum from the var_off, and our minimum is the
5351 * maximum of the operands' minima
5353 dst_reg
->u32_min_value
= max(dst_reg
->u32_min_value
, umin_val
);
5354 dst_reg
->u32_max_value
= var32_off
.value
| var32_off
.mask
;
5355 if (dst_reg
->s32_min_value
< 0 || smin_val
< 0) {
5356 /* Lose signed bounds when ORing negative numbers,
5357 * ain't nobody got time for that.
5359 dst_reg
->s32_min_value
= S32_MIN
;
5360 dst_reg
->s32_max_value
= S32_MAX
;
5362 /* ORing two positives gives a positive, so safe to
5363 * cast result into s64.
5365 dst_reg
->s32_min_value
= dst_reg
->umin_value
;
5366 dst_reg
->s32_max_value
= dst_reg
->umax_value
;
5370 static void scalar_min_max_or(struct bpf_reg_state
*dst_reg
,
5371 struct bpf_reg_state
*src_reg
)
5373 bool src_known
= tnum_is_const(src_reg
->var_off
);
5374 bool dst_known
= tnum_is_const(dst_reg
->var_off
);
5375 s64 smin_val
= src_reg
->smin_value
;
5376 u64 umin_val
= src_reg
->umin_value
;
5378 if (src_known
&& dst_known
) {
5379 __mark_reg_known(dst_reg
, dst_reg
->var_off
.value
|
5380 src_reg
->var_off
.value
);
5384 /* We get our maximum from the var_off, and our minimum is the
5385 * maximum of the operands' minima
5387 dst_reg
->umin_value
= max(dst_reg
->umin_value
, umin_val
);
5388 dst_reg
->umax_value
= dst_reg
->var_off
.value
| dst_reg
->var_off
.mask
;
5389 if (dst_reg
->smin_value
< 0 || smin_val
< 0) {
5390 /* Lose signed bounds when ORing negative numbers,
5391 * ain't nobody got time for that.
5393 dst_reg
->smin_value
= S64_MIN
;
5394 dst_reg
->smax_value
= S64_MAX
;
5396 /* ORing two positives gives a positive, so safe to
5397 * cast result into s64.
5399 dst_reg
->smin_value
= dst_reg
->umin_value
;
5400 dst_reg
->smax_value
= dst_reg
->umax_value
;
5402 /* We may learn something more from the var_off */
5403 __update_reg_bounds(dst_reg
);
5406 static void __scalar32_min_max_lsh(struct bpf_reg_state
*dst_reg
,
5407 u64 umin_val
, u64 umax_val
)
5409 /* We lose all sign bit information (except what we can pick
5412 dst_reg
->s32_min_value
= S32_MIN
;
5413 dst_reg
->s32_max_value
= S32_MAX
;
5414 /* If we might shift our top bit out, then we know nothing */
5415 if (umax_val
> 31 || dst_reg
->u32_max_value
> 1ULL << (31 - umax_val
)) {
5416 dst_reg
->u32_min_value
= 0;
5417 dst_reg
->u32_max_value
= U32_MAX
;
5419 dst_reg
->u32_min_value
<<= umin_val
;
5420 dst_reg
->u32_max_value
<<= umax_val
;
5424 static void scalar32_min_max_lsh(struct bpf_reg_state
*dst_reg
,
5425 struct bpf_reg_state
*src_reg
)
5427 u32 umax_val
= src_reg
->u32_max_value
;
5428 u32 umin_val
= src_reg
->u32_min_value
;
5429 /* u32 alu operation will zext upper bits */
5430 struct tnum subreg
= tnum_subreg(dst_reg
->var_off
);
5432 __scalar32_min_max_lsh(dst_reg
, umin_val
, umax_val
);
5433 dst_reg
->var_off
= tnum_subreg(tnum_lshift(subreg
, umin_val
));
5434 /* Not required but being careful mark reg64 bounds as unknown so
5435 * that we are forced to pick them up from tnum and zext later and
5436 * if some path skips this step we are still safe.
5438 __mark_reg64_unbounded(dst_reg
);
5439 __update_reg32_bounds(dst_reg
);
5442 static void __scalar64_min_max_lsh(struct bpf_reg_state
*dst_reg
,
5443 u64 umin_val
, u64 umax_val
)
5445 /* Special case <<32 because it is a common compiler pattern to sign
5446 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
5447 * positive we know this shift will also be positive so we can track
5448 * bounds correctly. Otherwise we lose all sign bit information except
5449 * what we can pick up from var_off. Perhaps we can generalize this
5450 * later to shifts of any length.
5452 if (umin_val
== 32 && umax_val
== 32 && dst_reg
->s32_max_value
>= 0)
5453 dst_reg
->smax_value
= (s64
)dst_reg
->s32_max_value
<< 32;
5455 dst_reg
->smax_value
= S64_MAX
;
5457 if (umin_val
== 32 && umax_val
== 32 && dst_reg
->s32_min_value
>= 0)
5458 dst_reg
->smin_value
= (s64
)dst_reg
->s32_min_value
<< 32;
5460 dst_reg
->smin_value
= S64_MIN
;
5462 /* If we might shift our top bit out, then we know nothing */
5463 if (dst_reg
->umax_value
> 1ULL << (63 - umax_val
)) {
5464 dst_reg
->umin_value
= 0;
5465 dst_reg
->umax_value
= U64_MAX
;
5467 dst_reg
->umin_value
<<= umin_val
;
5468 dst_reg
->umax_value
<<= umax_val
;
5472 static void scalar_min_max_lsh(struct bpf_reg_state
*dst_reg
,
5473 struct bpf_reg_state
*src_reg
)
5475 u64 umax_val
= src_reg
->umax_value
;
5476 u64 umin_val
= src_reg
->umin_value
;
5478 /* scalar64 calc uses 32bit unshifted bounds so must be called first */
5479 __scalar64_min_max_lsh(dst_reg
, umin_val
, umax_val
);
5480 __scalar32_min_max_lsh(dst_reg
, umin_val
, umax_val
);
5482 dst_reg
->var_off
= tnum_lshift(dst_reg
->var_off
, umin_val
);
5483 /* We may learn something more from the var_off */
5484 __update_reg_bounds(dst_reg
);
5487 static void scalar32_min_max_rsh(struct bpf_reg_state
*dst_reg
,
5488 struct bpf_reg_state
*src_reg
)
5490 struct tnum subreg
= tnum_subreg(dst_reg
->var_off
);
5491 u32 umax_val
= src_reg
->u32_max_value
;
5492 u32 umin_val
= src_reg
->u32_min_value
;
5494 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
5495 * be negative, then either:
5496 * 1) src_reg might be zero, so the sign bit of the result is
5497 * unknown, so we lose our signed bounds
5498 * 2) it's known negative, thus the unsigned bounds capture the
5500 * 3) the signed bounds cross zero, so they tell us nothing
5502 * If the value in dst_reg is known nonnegative, then again the
5503 * unsigned bounts capture the signed bounds.
5504 * Thus, in all cases it suffices to blow away our signed bounds
5505 * and rely on inferring new ones from the unsigned bounds and
5506 * var_off of the result.
5508 dst_reg
->s32_min_value
= S32_MIN
;
5509 dst_reg
->s32_max_value
= S32_MAX
;
5511 dst_reg
->var_off
= tnum_rshift(subreg
, umin_val
);
5512 dst_reg
->u32_min_value
>>= umax_val
;
5513 dst_reg
->u32_max_value
>>= umin_val
;
5515 __mark_reg64_unbounded(dst_reg
);
5516 __update_reg32_bounds(dst_reg
);
5519 static void scalar_min_max_rsh(struct bpf_reg_state
*dst_reg
,
5520 struct bpf_reg_state
*src_reg
)
5522 u64 umax_val
= src_reg
->umax_value
;
5523 u64 umin_val
= src_reg
->umin_value
;
5525 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
5526 * be negative, then either:
5527 * 1) src_reg might be zero, so the sign bit of the result is
5528 * unknown, so we lose our signed bounds
5529 * 2) it's known negative, thus the unsigned bounds capture the
5531 * 3) the signed bounds cross zero, so they tell us nothing
5533 * If the value in dst_reg is known nonnegative, then again the
5534 * unsigned bounts capture the signed bounds.
5535 * Thus, in all cases it suffices to blow away our signed bounds
5536 * and rely on inferring new ones from the unsigned bounds and
5537 * var_off of the result.
5539 dst_reg
->smin_value
= S64_MIN
;
5540 dst_reg
->smax_value
= S64_MAX
;
5541 dst_reg
->var_off
= tnum_rshift(dst_reg
->var_off
, umin_val
);
5542 dst_reg
->umin_value
>>= umax_val
;
5543 dst_reg
->umax_value
>>= umin_val
;
5545 /* Its not easy to operate on alu32 bounds here because it depends
5546 * on bits being shifted in. Take easy way out and mark unbounded
5547 * so we can recalculate later from tnum.
5549 __mark_reg32_unbounded(dst_reg
);
5550 __update_reg_bounds(dst_reg
);
5553 static void scalar32_min_max_arsh(struct bpf_reg_state
*dst_reg
,
5554 struct bpf_reg_state
*src_reg
)
5556 u64 umin_val
= src_reg
->u32_min_value
;
5558 /* Upon reaching here, src_known is true and
5559 * umax_val is equal to umin_val.
5561 dst_reg
->s32_min_value
= (u32
)(((s32
)dst_reg
->s32_min_value
) >> umin_val
);
5562 dst_reg
->s32_max_value
= (u32
)(((s32
)dst_reg
->s32_max_value
) >> umin_val
);
5564 dst_reg
->var_off
= tnum_arshift(tnum_subreg(dst_reg
->var_off
), umin_val
, 32);
5566 /* blow away the dst_reg umin_value/umax_value and rely on
5567 * dst_reg var_off to refine the result.
5569 dst_reg
->u32_min_value
= 0;
5570 dst_reg
->u32_max_value
= U32_MAX
;
5572 __mark_reg64_unbounded(dst_reg
);
5573 __update_reg32_bounds(dst_reg
);
5576 static void scalar_min_max_arsh(struct bpf_reg_state
*dst_reg
,
5577 struct bpf_reg_state
*src_reg
)
5579 u64 umin_val
= src_reg
->umin_value
;
5581 /* Upon reaching here, src_known is true and umax_val is equal
5584 dst_reg
->smin_value
>>= umin_val
;
5585 dst_reg
->smax_value
>>= umin_val
;
5587 dst_reg
->var_off
= tnum_arshift(dst_reg
->var_off
, umin_val
, 64);
5589 /* blow away the dst_reg umin_value/umax_value and rely on
5590 * dst_reg var_off to refine the result.
5592 dst_reg
->umin_value
= 0;
5593 dst_reg
->umax_value
= U64_MAX
;
5595 /* Its not easy to operate on alu32 bounds here because it depends
5596 * on bits being shifted in from upper 32-bits. Take easy way out
5597 * and mark unbounded so we can recalculate later from tnum.
5599 __mark_reg32_unbounded(dst_reg
);
5600 __update_reg_bounds(dst_reg
);
5603 /* WARNING: This function does calculations on 64-bit values, but the actual
5604 * execution may occur on 32-bit values. Therefore, things like bitshifts
5605 * need extra checks in the 32-bit case.
5607 static int adjust_scalar_min_max_vals(struct bpf_verifier_env
*env
,
5608 struct bpf_insn
*insn
,
5609 struct bpf_reg_state
*dst_reg
,
5610 struct bpf_reg_state src_reg
)
5612 struct bpf_reg_state
*regs
= cur_regs(env
);
5613 u8 opcode
= BPF_OP(insn
->code
);
5614 bool src_known
, dst_known
;
5615 s64 smin_val
, smax_val
;
5616 u64 umin_val
, umax_val
;
5617 s32 s32_min_val
, s32_max_val
;
5618 u32 u32_min_val
, u32_max_val
;
5619 u64 insn_bitness
= (BPF_CLASS(insn
->code
) == BPF_ALU64
) ? 64 : 32;
5620 u32 dst
= insn
->dst_reg
;
5622 bool alu32
= (BPF_CLASS(insn
->code
) != BPF_ALU64
);
5624 smin_val
= src_reg
.smin_value
;
5625 smax_val
= src_reg
.smax_value
;
5626 umin_val
= src_reg
.umin_value
;
5627 umax_val
= src_reg
.umax_value
;
5629 s32_min_val
= src_reg
.s32_min_value
;
5630 s32_max_val
= src_reg
.s32_max_value
;
5631 u32_min_val
= src_reg
.u32_min_value
;
5632 u32_max_val
= src_reg
.u32_max_value
;
5635 src_known
= tnum_subreg_is_const(src_reg
.var_off
);
5636 dst_known
= tnum_subreg_is_const(dst_reg
->var_off
);
5638 (s32_min_val
!= s32_max_val
|| u32_min_val
!= u32_max_val
)) ||
5639 s32_min_val
> s32_max_val
|| u32_min_val
> u32_max_val
) {
5640 /* Taint dst register if offset had invalid bounds
5641 * derived from e.g. dead branches.
5643 __mark_reg_unknown(env
, dst_reg
);
5647 src_known
= tnum_is_const(src_reg
.var_off
);
5648 dst_known
= tnum_is_const(dst_reg
->var_off
);
5650 (smin_val
!= smax_val
|| umin_val
!= umax_val
)) ||
5651 smin_val
> smax_val
|| umin_val
> umax_val
) {
5652 /* Taint dst register if offset had invalid bounds
5653 * derived from e.g. dead branches.
5655 __mark_reg_unknown(env
, dst_reg
);
5661 opcode
!= BPF_ADD
&& opcode
!= BPF_SUB
&& opcode
!= BPF_AND
) {
5662 __mark_reg_unknown(env
, dst_reg
);
5666 /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
5667 * There are two classes of instructions: The first class we track both
5668 * alu32 and alu64 sign/unsigned bounds independently this provides the
5669 * greatest amount of precision when alu operations are mixed with jmp32
5670 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
5671 * and BPF_OR. This is possible because these ops have fairly easy to
5672 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
5673 * See alu32 verifier tests for examples. The second class of
5674 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
5675 * with regards to tracking sign/unsigned bounds because the bits may
5676 * cross subreg boundaries in the alu64 case. When this happens we mark
5677 * the reg unbounded in the subreg bound space and use the resulting
5678 * tnum to calculate an approximation of the sign/unsigned bounds.
5682 ret
= sanitize_val_alu(env
, insn
);
5684 verbose(env
, "R%d tried to add from different pointers or scalars\n", dst
);
5687 scalar32_min_max_add(dst_reg
, &src_reg
);
5688 scalar_min_max_add(dst_reg
, &src_reg
);
5689 dst_reg
->var_off
= tnum_add(dst_reg
->var_off
, src_reg
.var_off
);
5692 ret
= sanitize_val_alu(env
, insn
);
5694 verbose(env
, "R%d tried to sub from different pointers or scalars\n", dst
);
5697 scalar32_min_max_sub(dst_reg
, &src_reg
);
5698 scalar_min_max_sub(dst_reg
, &src_reg
);
5699 dst_reg
->var_off
= tnum_sub(dst_reg
->var_off
, src_reg
.var_off
);
5702 dst_reg
->var_off
= tnum_mul(dst_reg
->var_off
, src_reg
.var_off
);
5703 scalar32_min_max_mul(dst_reg
, &src_reg
);
5704 scalar_min_max_mul(dst_reg
, &src_reg
);
5707 dst_reg
->var_off
= tnum_and(dst_reg
->var_off
, src_reg
.var_off
);
5708 scalar32_min_max_and(dst_reg
, &src_reg
);
5709 scalar_min_max_and(dst_reg
, &src_reg
);
5712 dst_reg
->var_off
= tnum_or(dst_reg
->var_off
, src_reg
.var_off
);
5713 scalar32_min_max_or(dst_reg
, &src_reg
);
5714 scalar_min_max_or(dst_reg
, &src_reg
);
5717 if (umax_val
>= insn_bitness
) {
5718 /* Shifts greater than 31 or 63 are undefined.
5719 * This includes shifts by a negative number.
5721 mark_reg_unknown(env
, regs
, insn
->dst_reg
);
5725 scalar32_min_max_lsh(dst_reg
, &src_reg
);
5727 scalar_min_max_lsh(dst_reg
, &src_reg
);
5730 if (umax_val
>= insn_bitness
) {
5731 /* Shifts greater than 31 or 63 are undefined.
5732 * This includes shifts by a negative number.
5734 mark_reg_unknown(env
, regs
, insn
->dst_reg
);
5738 scalar32_min_max_rsh(dst_reg
, &src_reg
);
5740 scalar_min_max_rsh(dst_reg
, &src_reg
);
5743 if (umax_val
>= insn_bitness
) {
5744 /* Shifts greater than 31 or 63 are undefined.
5745 * This includes shifts by a negative number.
5747 mark_reg_unknown(env
, regs
, insn
->dst_reg
);
5751 scalar32_min_max_arsh(dst_reg
, &src_reg
);
5753 scalar_min_max_arsh(dst_reg
, &src_reg
);
5756 mark_reg_unknown(env
, regs
, insn
->dst_reg
);
5760 /* ALU32 ops are zero extended into 64bit register */
5762 zext_32_to_64(dst_reg
);
5764 __update_reg_bounds(dst_reg
);
5765 __reg_deduce_bounds(dst_reg
);
5766 __reg_bound_offset(dst_reg
);
5770 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
5773 static int adjust_reg_min_max_vals(struct bpf_verifier_env
*env
,
5774 struct bpf_insn
*insn
)
5776 struct bpf_verifier_state
*vstate
= env
->cur_state
;
5777 struct bpf_func_state
*state
= vstate
->frame
[vstate
->curframe
];
5778 struct bpf_reg_state
*regs
= state
->regs
, *dst_reg
, *src_reg
;
5779 struct bpf_reg_state
*ptr_reg
= NULL
, off_reg
= {0};
5780 u8 opcode
= BPF_OP(insn
->code
);
5783 dst_reg
= ®s
[insn
->dst_reg
];
5785 if (dst_reg
->type
!= SCALAR_VALUE
)
5787 if (BPF_SRC(insn
->code
) == BPF_X
) {
5788 src_reg
= ®s
[insn
->src_reg
];
5789 if (src_reg
->type
!= SCALAR_VALUE
) {
5790 if (dst_reg
->type
!= SCALAR_VALUE
) {
5791 /* Combining two pointers by any ALU op yields
5792 * an arbitrary scalar. Disallow all math except
5793 * pointer subtraction
5795 if (opcode
== BPF_SUB
&& env
->allow_ptr_leaks
) {
5796 mark_reg_unknown(env
, regs
, insn
->dst_reg
);
5799 verbose(env
, "R%d pointer %s pointer prohibited\n",
5801 bpf_alu_string
[opcode
>> 4]);
5804 /* scalar += pointer
5805 * This is legal, but we have to reverse our
5806 * src/dest handling in computing the range
5808 err
= mark_chain_precision(env
, insn
->dst_reg
);
5811 return adjust_ptr_min_max_vals(env
, insn
,
5814 } else if (ptr_reg
) {
5815 /* pointer += scalar */
5816 err
= mark_chain_precision(env
, insn
->src_reg
);
5819 return adjust_ptr_min_max_vals(env
, insn
,
5823 /* Pretend the src is a reg with a known value, since we only
5824 * need to be able to read from this state.
5826 off_reg
.type
= SCALAR_VALUE
;
5827 __mark_reg_known(&off_reg
, insn
->imm
);
5829 if (ptr_reg
) /* pointer += K */
5830 return adjust_ptr_min_max_vals(env
, insn
,
5834 /* Got here implies adding two SCALAR_VALUEs */
5835 if (WARN_ON_ONCE(ptr_reg
)) {
5836 print_verifier_state(env
, state
);
5837 verbose(env
, "verifier internal error: unexpected ptr_reg\n");
5840 if (WARN_ON(!src_reg
)) {
5841 print_verifier_state(env
, state
);
5842 verbose(env
, "verifier internal error: no src_reg\n");
5845 return adjust_scalar_min_max_vals(env
, insn
, dst_reg
, *src_reg
);
5848 /* check validity of 32-bit and 64-bit arithmetic operations */
5849 static int check_alu_op(struct bpf_verifier_env
*env
, struct bpf_insn
*insn
)
5851 struct bpf_reg_state
*regs
= cur_regs(env
);
5852 u8 opcode
= BPF_OP(insn
->code
);
5855 if (opcode
== BPF_END
|| opcode
== BPF_NEG
) {
5856 if (opcode
== BPF_NEG
) {
5857 if (BPF_SRC(insn
->code
) != 0 ||
5858 insn
->src_reg
!= BPF_REG_0
||
5859 insn
->off
!= 0 || insn
->imm
!= 0) {
5860 verbose(env
, "BPF_NEG uses reserved fields\n");
5864 if (insn
->src_reg
!= BPF_REG_0
|| insn
->off
!= 0 ||
5865 (insn
->imm
!= 16 && insn
->imm
!= 32 && insn
->imm
!= 64) ||
5866 BPF_CLASS(insn
->code
) == BPF_ALU64
) {
5867 verbose(env
, "BPF_END uses reserved fields\n");
5872 /* check src operand */
5873 err
= check_reg_arg(env
, insn
->dst_reg
, SRC_OP
);
5877 if (is_pointer_value(env
, insn
->dst_reg
)) {
5878 verbose(env
, "R%d pointer arithmetic prohibited\n",
5883 /* check dest operand */
5884 err
= check_reg_arg(env
, insn
->dst_reg
, DST_OP
);
5888 } else if (opcode
== BPF_MOV
) {
5890 if (BPF_SRC(insn
->code
) == BPF_X
) {
5891 if (insn
->imm
!= 0 || insn
->off
!= 0) {
5892 verbose(env
, "BPF_MOV uses reserved fields\n");
5896 /* check src operand */
5897 err
= check_reg_arg(env
, insn
->src_reg
, SRC_OP
);
5901 if (insn
->src_reg
!= BPF_REG_0
|| insn
->off
!= 0) {
5902 verbose(env
, "BPF_MOV uses reserved fields\n");
5907 /* check dest operand, mark as required later */
5908 err
= check_reg_arg(env
, insn
->dst_reg
, DST_OP_NO_MARK
);
5912 if (BPF_SRC(insn
->code
) == BPF_X
) {
5913 struct bpf_reg_state
*src_reg
= regs
+ insn
->src_reg
;
5914 struct bpf_reg_state
*dst_reg
= regs
+ insn
->dst_reg
;
5916 if (BPF_CLASS(insn
->code
) == BPF_ALU64
) {
5918 * copy register state to dest reg
5920 *dst_reg
= *src_reg
;
5921 dst_reg
->live
|= REG_LIVE_WRITTEN
;
5922 dst_reg
->subreg_def
= DEF_NOT_SUBREG
;
5925 if (is_pointer_value(env
, insn
->src_reg
)) {
5927 "R%d partial copy of pointer\n",
5930 } else if (src_reg
->type
== SCALAR_VALUE
) {
5931 *dst_reg
= *src_reg
;
5932 dst_reg
->live
|= REG_LIVE_WRITTEN
;
5933 dst_reg
->subreg_def
= env
->insn_idx
+ 1;
5935 mark_reg_unknown(env
, regs
,
5938 zext_32_to_64(dst_reg
);
5942 * remember the value we stored into this reg
5944 /* clear any state __mark_reg_known doesn't set */
5945 mark_reg_unknown(env
, regs
, insn
->dst_reg
);
5946 regs
[insn
->dst_reg
].type
= SCALAR_VALUE
;
5947 if (BPF_CLASS(insn
->code
) == BPF_ALU64
) {
5948 __mark_reg_known(regs
+ insn
->dst_reg
,
5951 __mark_reg_known(regs
+ insn
->dst_reg
,
5956 } else if (opcode
> BPF_END
) {
5957 verbose(env
, "invalid BPF_ALU opcode %x\n", opcode
);
5960 } else { /* all other ALU ops: and, sub, xor, add, ... */
5962 if (BPF_SRC(insn
->code
) == BPF_X
) {
5963 if (insn
->imm
!= 0 || insn
->off
!= 0) {
5964 verbose(env
, "BPF_ALU uses reserved fields\n");
5967 /* check src1 operand */
5968 err
= check_reg_arg(env
, insn
->src_reg
, SRC_OP
);
5972 if (insn
->src_reg
!= BPF_REG_0
|| insn
->off
!= 0) {
5973 verbose(env
, "BPF_ALU uses reserved fields\n");
5978 /* check src2 operand */
5979 err
= check_reg_arg(env
, insn
->dst_reg
, SRC_OP
);
5983 if ((opcode
== BPF_MOD
|| opcode
== BPF_DIV
) &&
5984 BPF_SRC(insn
->code
) == BPF_K
&& insn
->imm
== 0) {
5985 verbose(env
, "div by zero\n");
5989 if ((opcode
== BPF_LSH
|| opcode
== BPF_RSH
||
5990 opcode
== BPF_ARSH
) && BPF_SRC(insn
->code
) == BPF_K
) {
5991 int size
= BPF_CLASS(insn
->code
) == BPF_ALU64
? 64 : 32;
5993 if (insn
->imm
< 0 || insn
->imm
>= size
) {
5994 verbose(env
, "invalid shift %d\n", insn
->imm
);
5999 /* check dest operand */
6000 err
= check_reg_arg(env
, insn
->dst_reg
, DST_OP_NO_MARK
);
6004 return adjust_reg_min_max_vals(env
, insn
);
6010 static void __find_good_pkt_pointers(struct bpf_func_state
*state
,
6011 struct bpf_reg_state
*dst_reg
,
6012 enum bpf_reg_type type
, u16 new_range
)
6014 struct bpf_reg_state
*reg
;
6017 for (i
= 0; i
< MAX_BPF_REG
; i
++) {
6018 reg
= &state
->regs
[i
];
6019 if (reg
->type
== type
&& reg
->id
== dst_reg
->id
)
6020 /* keep the maximum range already checked */
6021 reg
->range
= max(reg
->range
, new_range
);
6024 bpf_for_each_spilled_reg(i
, state
, reg
) {
6027 if (reg
->type
== type
&& reg
->id
== dst_reg
->id
)
6028 reg
->range
= max(reg
->range
, new_range
);
6032 static void find_good_pkt_pointers(struct bpf_verifier_state
*vstate
,
6033 struct bpf_reg_state
*dst_reg
,
6034 enum bpf_reg_type type
,
6035 bool range_right_open
)
6040 if (dst_reg
->off
< 0 ||
6041 (dst_reg
->off
== 0 && range_right_open
))
6042 /* This doesn't give us any range */
6045 if (dst_reg
->umax_value
> MAX_PACKET_OFF
||
6046 dst_reg
->umax_value
+ dst_reg
->off
> MAX_PACKET_OFF
)
6047 /* Risk of overflow. For instance, ptr + (1<<63) may be less
6048 * than pkt_end, but that's because it's also less than pkt.
6052 new_range
= dst_reg
->off
;
6053 if (range_right_open
)
6056 /* Examples for register markings:
6058 * pkt_data in dst register:
6062 * if (r2 > pkt_end) goto <handle exception>
6067 * if (r2 < pkt_end) goto <access okay>
6068 * <handle exception>
6071 * r2 == dst_reg, pkt_end == src_reg
6072 * r2=pkt(id=n,off=8,r=0)
6073 * r3=pkt(id=n,off=0,r=0)
6075 * pkt_data in src register:
6079 * if (pkt_end >= r2) goto <access okay>
6080 * <handle exception>
6084 * if (pkt_end <= r2) goto <handle exception>
6088 * pkt_end == dst_reg, r2 == src_reg
6089 * r2=pkt(id=n,off=8,r=0)
6090 * r3=pkt(id=n,off=0,r=0)
6092 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
6093 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
6094 * and [r3, r3 + 8-1) respectively is safe to access depending on
6098 /* If our ids match, then we must have the same max_value. And we
6099 * don't care about the other reg's fixed offset, since if it's too big
6100 * the range won't allow anything.
6101 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
6103 for (i
= 0; i
<= vstate
->curframe
; i
++)
6104 __find_good_pkt_pointers(vstate
->frame
[i
], dst_reg
, type
,
6108 static int is_branch32_taken(struct bpf_reg_state
*reg
, u32 val
, u8 opcode
)
6110 struct tnum subreg
= tnum_subreg(reg
->var_off
);
6111 s32 sval
= (s32
)val
;
6115 if (tnum_is_const(subreg
))
6116 return !!tnum_equals_const(subreg
, val
);
6119 if (tnum_is_const(subreg
))
6120 return !tnum_equals_const(subreg
, val
);
6123 if ((~subreg
.mask
& subreg
.value
) & val
)
6125 if (!((subreg
.mask
| subreg
.value
) & val
))
6129 if (reg
->u32_min_value
> val
)
6131 else if (reg
->u32_max_value
<= val
)
6135 if (reg
->s32_min_value
> sval
)
6137 else if (reg
->s32_max_value
< sval
)
6141 if (reg
->u32_max_value
< val
)
6143 else if (reg
->u32_min_value
>= val
)
6147 if (reg
->s32_max_value
< sval
)
6149 else if (reg
->s32_min_value
>= sval
)
6153 if (reg
->u32_min_value
>= val
)
6155 else if (reg
->u32_max_value
< val
)
6159 if (reg
->s32_min_value
>= sval
)
6161 else if (reg
->s32_max_value
< sval
)
6165 if (reg
->u32_max_value
<= val
)
6167 else if (reg
->u32_min_value
> val
)
6171 if (reg
->s32_max_value
<= sval
)
6173 else if (reg
->s32_min_value
> sval
)
6182 static int is_branch64_taken(struct bpf_reg_state
*reg
, u64 val
, u8 opcode
)
6184 s64 sval
= (s64
)val
;
6188 if (tnum_is_const(reg
->var_off
))
6189 return !!tnum_equals_const(reg
->var_off
, val
);
6192 if (tnum_is_const(reg
->var_off
))
6193 return !tnum_equals_const(reg
->var_off
, val
);
6196 if ((~reg
->var_off
.mask
& reg
->var_off
.value
) & val
)
6198 if (!((reg
->var_off
.mask
| reg
->var_off
.value
) & val
))
6202 if (reg
->umin_value
> val
)
6204 else if (reg
->umax_value
<= val
)
6208 if (reg
->smin_value
> sval
)
6210 else if (reg
->smax_value
< sval
)
6214 if (reg
->umax_value
< val
)
6216 else if (reg
->umin_value
>= val
)
6220 if (reg
->smax_value
< sval
)
6222 else if (reg
->smin_value
>= sval
)
6226 if (reg
->umin_value
>= val
)
6228 else if (reg
->umax_value
< val
)
6232 if (reg
->smin_value
>= sval
)
6234 else if (reg
->smax_value
< sval
)
6238 if (reg
->umax_value
<= val
)
6240 else if (reg
->umin_value
> val
)
6244 if (reg
->smax_value
<= sval
)
6246 else if (reg
->smin_value
> sval
)
6254 /* compute branch direction of the expression "if (reg opcode val) goto target;"
6256 * 1 - branch will be taken and "goto target" will be executed
6257 * 0 - branch will not be taken and fall-through to next insn
6258 * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
6261 static int is_branch_taken(struct bpf_reg_state
*reg
, u64 val
, u8 opcode
,
6264 if (__is_pointer_value(false, reg
))
6268 return is_branch32_taken(reg
, val
, opcode
);
6269 return is_branch64_taken(reg
, val
, opcode
);
6272 /* Adjusts the register min/max values in the case that the dst_reg is the
6273 * variable register that we are working on, and src_reg is a constant or we're
6274 * simply doing a BPF_K check.
6275 * In JEQ/JNE cases we also adjust the var_off values.
6277 static void reg_set_min_max(struct bpf_reg_state
*true_reg
,
6278 struct bpf_reg_state
*false_reg
,
6280 u8 opcode
, bool is_jmp32
)
6282 struct tnum false_32off
= tnum_subreg(false_reg
->var_off
);
6283 struct tnum false_64off
= false_reg
->var_off
;
6284 struct tnum true_32off
= tnum_subreg(true_reg
->var_off
);
6285 struct tnum true_64off
= true_reg
->var_off
;
6286 s64 sval
= (s64
)val
;
6287 s32 sval32
= (s32
)val32
;
6289 /* If the dst_reg is a pointer, we can't learn anything about its
6290 * variable offset from the compare (unless src_reg were a pointer into
6291 * the same object, but we don't bother with that.
6292 * Since false_reg and true_reg have the same type by construction, we
6293 * only need to check one of them for pointerness.
6295 if (__is_pointer_value(false, false_reg
))
6302 struct bpf_reg_state
*reg
=
6303 opcode
== BPF_JEQ
? true_reg
: false_reg
;
6305 /* For BPF_JEQ, if this is false we know nothing Jon Snow, but
6306 * if it is true we know the value for sure. Likewise for
6310 __mark_reg32_known(reg
, val32
);
6312 __mark_reg_known(reg
, val
);
6317 false_32off
= tnum_and(false_32off
, tnum_const(~val32
));
6318 if (is_power_of_2(val32
))
6319 true_32off
= tnum_or(true_32off
,
6322 false_64off
= tnum_and(false_64off
, tnum_const(~val
));
6323 if (is_power_of_2(val
))
6324 true_64off
= tnum_or(true_64off
,
6332 u32 false_umax
= opcode
== BPF_JGT
? val32
: val32
- 1;
6333 u32 true_umin
= opcode
== BPF_JGT
? val32
+ 1 : val32
;
6335 false_reg
->u32_max_value
= min(false_reg
->u32_max_value
,
6337 true_reg
->u32_min_value
= max(true_reg
->u32_min_value
,
6340 u64 false_umax
= opcode
== BPF_JGT
? val
: val
- 1;
6341 u64 true_umin
= opcode
== BPF_JGT
? val
+ 1 : val
;
6343 false_reg
->umax_value
= min(false_reg
->umax_value
, false_umax
);
6344 true_reg
->umin_value
= max(true_reg
->umin_value
, true_umin
);
6352 s32 false_smax
= opcode
== BPF_JSGT
? sval32
: sval32
- 1;
6353 s32 true_smin
= opcode
== BPF_JSGT
? sval32
+ 1 : sval32
;
6355 false_reg
->s32_max_value
= min(false_reg
->s32_max_value
, false_smax
);
6356 true_reg
->s32_min_value
= max(true_reg
->s32_min_value
, true_smin
);
6358 s64 false_smax
= opcode
== BPF_JSGT
? sval
: sval
- 1;
6359 s64 true_smin
= opcode
== BPF_JSGT
? sval
+ 1 : sval
;
6361 false_reg
->smax_value
= min(false_reg
->smax_value
, false_smax
);
6362 true_reg
->smin_value
= max(true_reg
->smin_value
, true_smin
);
6370 u32 false_umin
= opcode
== BPF_JLT
? val32
: val32
+ 1;
6371 u32 true_umax
= opcode
== BPF_JLT
? val32
- 1 : val32
;
6373 false_reg
->u32_min_value
= max(false_reg
->u32_min_value
,
6375 true_reg
->u32_max_value
= min(true_reg
->u32_max_value
,
6378 u64 false_umin
= opcode
== BPF_JLT
? val
: val
+ 1;
6379 u64 true_umax
= opcode
== BPF_JLT
? val
- 1 : val
;
6381 false_reg
->umin_value
= max(false_reg
->umin_value
, false_umin
);
6382 true_reg
->umax_value
= min(true_reg
->umax_value
, true_umax
);
6390 s32 false_smin
= opcode
== BPF_JSLT
? sval32
: sval32
+ 1;
6391 s32 true_smax
= opcode
== BPF_JSLT
? sval32
- 1 : sval32
;
6393 false_reg
->s32_min_value
= max(false_reg
->s32_min_value
, false_smin
);
6394 true_reg
->s32_max_value
= min(true_reg
->s32_max_value
, true_smax
);
6396 s64 false_smin
= opcode
== BPF_JSLT
? sval
: sval
+ 1;
6397 s64 true_smax
= opcode
== BPF_JSLT
? sval
- 1 : sval
;
6399 false_reg
->smin_value
= max(false_reg
->smin_value
, false_smin
);
6400 true_reg
->smax_value
= min(true_reg
->smax_value
, true_smax
);
6409 false_reg
->var_off
= tnum_or(tnum_clear_subreg(false_64off
),
6410 tnum_subreg(false_32off
));
6411 true_reg
->var_off
= tnum_or(tnum_clear_subreg(true_64off
),
6412 tnum_subreg(true_32off
));
6413 __reg_combine_32_into_64(false_reg
);
6414 __reg_combine_32_into_64(true_reg
);
6416 false_reg
->var_off
= false_64off
;
6417 true_reg
->var_off
= true_64off
;
6418 __reg_combine_64_into_32(false_reg
);
6419 __reg_combine_64_into_32(true_reg
);
6423 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
6426 static void reg_set_min_max_inv(struct bpf_reg_state
*true_reg
,
6427 struct bpf_reg_state
*false_reg
,
6429 u8 opcode
, bool is_jmp32
)
6431 /* How can we transform "a <op> b" into "b <op> a"? */
6432 static const u8 opcode_flip
[16] = {
6433 /* these stay the same */
6434 [BPF_JEQ
>> 4] = BPF_JEQ
,
6435 [BPF_JNE
>> 4] = BPF_JNE
,
6436 [BPF_JSET
>> 4] = BPF_JSET
,
6437 /* these swap "lesser" and "greater" (L and G in the opcodes) */
6438 [BPF_JGE
>> 4] = BPF_JLE
,
6439 [BPF_JGT
>> 4] = BPF_JLT
,
6440 [BPF_JLE
>> 4] = BPF_JGE
,
6441 [BPF_JLT
>> 4] = BPF_JGT
,
6442 [BPF_JSGE
>> 4] = BPF_JSLE
,
6443 [BPF_JSGT
>> 4] = BPF_JSLT
,
6444 [BPF_JSLE
>> 4] = BPF_JSGE
,
6445 [BPF_JSLT
>> 4] = BPF_JSGT
6447 opcode
= opcode_flip
[opcode
>> 4];
6448 /* This uses zero as "not present in table"; luckily the zero opcode,
6449 * BPF_JA, can't get here.
6452 reg_set_min_max(true_reg
, false_reg
, val
, val32
, opcode
, is_jmp32
);
6455 /* Regs are known to be equal, so intersect their min/max/var_off */
6456 static void __reg_combine_min_max(struct bpf_reg_state
*src_reg
,
6457 struct bpf_reg_state
*dst_reg
)
6459 src_reg
->umin_value
= dst_reg
->umin_value
= max(src_reg
->umin_value
,
6460 dst_reg
->umin_value
);
6461 src_reg
->umax_value
= dst_reg
->umax_value
= min(src_reg
->umax_value
,
6462 dst_reg
->umax_value
);
6463 src_reg
->smin_value
= dst_reg
->smin_value
= max(src_reg
->smin_value
,
6464 dst_reg
->smin_value
);
6465 src_reg
->smax_value
= dst_reg
->smax_value
= min(src_reg
->smax_value
,
6466 dst_reg
->smax_value
);
6467 src_reg
->var_off
= dst_reg
->var_off
= tnum_intersect(src_reg
->var_off
,
6469 /* We might have learned new bounds from the var_off. */
6470 __update_reg_bounds(src_reg
);
6471 __update_reg_bounds(dst_reg
);
6472 /* We might have learned something about the sign bit. */
6473 __reg_deduce_bounds(src_reg
);
6474 __reg_deduce_bounds(dst_reg
);
6475 /* We might have learned some bits from the bounds. */
6476 __reg_bound_offset(src_reg
);
6477 __reg_bound_offset(dst_reg
);
6478 /* Intersecting with the old var_off might have improved our bounds
6479 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
6480 * then new var_off is (0; 0x7f...fc) which improves our umax.
6482 __update_reg_bounds(src_reg
);
6483 __update_reg_bounds(dst_reg
);
6486 static void reg_combine_min_max(struct bpf_reg_state
*true_src
,
6487 struct bpf_reg_state
*true_dst
,
6488 struct bpf_reg_state
*false_src
,
6489 struct bpf_reg_state
*false_dst
,
6494 __reg_combine_min_max(true_src
, true_dst
);
6497 __reg_combine_min_max(false_src
, false_dst
);
6502 static void mark_ptr_or_null_reg(struct bpf_func_state
*state
,
6503 struct bpf_reg_state
*reg
, u32 id
,
6506 if (reg_type_may_be_null(reg
->type
) && reg
->id
== id
) {
6507 /* Old offset (both fixed and variable parts) should
6508 * have been known-zero, because we don't allow pointer
6509 * arithmetic on pointers that might be NULL.
6511 if (WARN_ON_ONCE(reg
->smin_value
|| reg
->smax_value
||
6512 !tnum_equals_const(reg
->var_off
, 0) ||
6514 __mark_reg_known_zero(reg
);
6518 reg
->type
= SCALAR_VALUE
;
6519 } else if (reg
->type
== PTR_TO_MAP_VALUE_OR_NULL
) {
6520 if (reg
->map_ptr
->inner_map_meta
) {
6521 reg
->type
= CONST_PTR_TO_MAP
;
6522 reg
->map_ptr
= reg
->map_ptr
->inner_map_meta
;
6523 } else if (reg
->map_ptr
->map_type
==
6524 BPF_MAP_TYPE_XSKMAP
) {
6525 reg
->type
= PTR_TO_XDP_SOCK
;
6527 reg
->type
= PTR_TO_MAP_VALUE
;
6529 } else if (reg
->type
== PTR_TO_SOCKET_OR_NULL
) {
6530 reg
->type
= PTR_TO_SOCKET
;
6531 } else if (reg
->type
== PTR_TO_SOCK_COMMON_OR_NULL
) {
6532 reg
->type
= PTR_TO_SOCK_COMMON
;
6533 } else if (reg
->type
== PTR_TO_TCP_SOCK_OR_NULL
) {
6534 reg
->type
= PTR_TO_TCP_SOCK
;
6537 /* We don't need id and ref_obj_id from this point
6538 * onwards anymore, thus we should better reset it,
6539 * so that state pruning has chances to take effect.
6542 reg
->ref_obj_id
= 0;
6543 } else if (!reg_may_point_to_spin_lock(reg
)) {
6544 /* For not-NULL ptr, reg->ref_obj_id will be reset
6545 * in release_reg_references().
6547 * reg->id is still used by spin_lock ptr. Other
6548 * than spin_lock ptr type, reg->id can be reset.
6555 static void __mark_ptr_or_null_regs(struct bpf_func_state
*state
, u32 id
,
6558 struct bpf_reg_state
*reg
;
6561 for (i
= 0; i
< MAX_BPF_REG
; i
++)
6562 mark_ptr_or_null_reg(state
, &state
->regs
[i
], id
, is_null
);
6564 bpf_for_each_spilled_reg(i
, state
, reg
) {
6567 mark_ptr_or_null_reg(state
, reg
, id
, is_null
);
6571 /* The logic is similar to find_good_pkt_pointers(), both could eventually
6572 * be folded together at some point.
6574 static void mark_ptr_or_null_regs(struct bpf_verifier_state
*vstate
, u32 regno
,
6577 struct bpf_func_state
*state
= vstate
->frame
[vstate
->curframe
];
6578 struct bpf_reg_state
*regs
= state
->regs
;
6579 u32 ref_obj_id
= regs
[regno
].ref_obj_id
;
6580 u32 id
= regs
[regno
].id
;
6583 if (ref_obj_id
&& ref_obj_id
== id
&& is_null
)
6584 /* regs[regno] is in the " == NULL" branch.
6585 * No one could have freed the reference state before
6586 * doing the NULL check.
6588 WARN_ON_ONCE(release_reference_state(state
, id
));
6590 for (i
= 0; i
<= vstate
->curframe
; i
++)
6591 __mark_ptr_or_null_regs(vstate
->frame
[i
], id
, is_null
);
6594 static bool try_match_pkt_pointers(const struct bpf_insn
*insn
,
6595 struct bpf_reg_state
*dst_reg
,
6596 struct bpf_reg_state
*src_reg
,
6597 struct bpf_verifier_state
*this_branch
,
6598 struct bpf_verifier_state
*other_branch
)
6600 if (BPF_SRC(insn
->code
) != BPF_X
)
6603 /* Pointers are always 64-bit. */
6604 if (BPF_CLASS(insn
->code
) == BPF_JMP32
)
6607 switch (BPF_OP(insn
->code
)) {
6609 if ((dst_reg
->type
== PTR_TO_PACKET
&&
6610 src_reg
->type
== PTR_TO_PACKET_END
) ||
6611 (dst_reg
->type
== PTR_TO_PACKET_META
&&
6612 reg_is_init_pkt_pointer(src_reg
, PTR_TO_PACKET
))) {
6613 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
6614 find_good_pkt_pointers(this_branch
, dst_reg
,
6615 dst_reg
->type
, false);
6616 } else if ((dst_reg
->type
== PTR_TO_PACKET_END
&&
6617 src_reg
->type
== PTR_TO_PACKET
) ||
6618 (reg_is_init_pkt_pointer(dst_reg
, PTR_TO_PACKET
) &&
6619 src_reg
->type
== PTR_TO_PACKET_META
)) {
6620 /* pkt_end > pkt_data', pkt_data > pkt_meta' */
6621 find_good_pkt_pointers(other_branch
, src_reg
,
6622 src_reg
->type
, true);
6628 if ((dst_reg
->type
== PTR_TO_PACKET
&&
6629 src_reg
->type
== PTR_TO_PACKET_END
) ||
6630 (dst_reg
->type
== PTR_TO_PACKET_META
&&
6631 reg_is_init_pkt_pointer(src_reg
, PTR_TO_PACKET
))) {
6632 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
6633 find_good_pkt_pointers(other_branch
, dst_reg
,
6634 dst_reg
->type
, true);
6635 } else if ((dst_reg
->type
== PTR_TO_PACKET_END
&&
6636 src_reg
->type
== PTR_TO_PACKET
) ||
6637 (reg_is_init_pkt_pointer(dst_reg
, PTR_TO_PACKET
) &&
6638 src_reg
->type
== PTR_TO_PACKET_META
)) {
6639 /* pkt_end < pkt_data', pkt_data > pkt_meta' */
6640 find_good_pkt_pointers(this_branch
, src_reg
,
6641 src_reg
->type
, false);
6647 if ((dst_reg
->type
== PTR_TO_PACKET
&&
6648 src_reg
->type
== PTR_TO_PACKET_END
) ||
6649 (dst_reg
->type
== PTR_TO_PACKET_META
&&
6650 reg_is_init_pkt_pointer(src_reg
, PTR_TO_PACKET
))) {
6651 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
6652 find_good_pkt_pointers(this_branch
, dst_reg
,
6653 dst_reg
->type
, true);
6654 } else if ((dst_reg
->type
== PTR_TO_PACKET_END
&&
6655 src_reg
->type
== PTR_TO_PACKET
) ||
6656 (reg_is_init_pkt_pointer(dst_reg
, PTR_TO_PACKET
) &&
6657 src_reg
->type
== PTR_TO_PACKET_META
)) {
6658 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
6659 find_good_pkt_pointers(other_branch
, src_reg
,
6660 src_reg
->type
, false);
6666 if ((dst_reg
->type
== PTR_TO_PACKET
&&
6667 src_reg
->type
== PTR_TO_PACKET_END
) ||
6668 (dst_reg
->type
== PTR_TO_PACKET_META
&&
6669 reg_is_init_pkt_pointer(src_reg
, PTR_TO_PACKET
))) {
6670 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
6671 find_good_pkt_pointers(other_branch
, dst_reg
,
6672 dst_reg
->type
, false);
6673 } else if ((dst_reg
->type
== PTR_TO_PACKET_END
&&
6674 src_reg
->type
== PTR_TO_PACKET
) ||
6675 (reg_is_init_pkt_pointer(dst_reg
, PTR_TO_PACKET
) &&
6676 src_reg
->type
== PTR_TO_PACKET_META
)) {
6677 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
6678 find_good_pkt_pointers(this_branch
, src_reg
,
6679 src_reg
->type
, true);
6691 static int check_cond_jmp_op(struct bpf_verifier_env
*env
,
6692 struct bpf_insn
*insn
, int *insn_idx
)
6694 struct bpf_verifier_state
*this_branch
= env
->cur_state
;
6695 struct bpf_verifier_state
*other_branch
;
6696 struct bpf_reg_state
*regs
= this_branch
->frame
[this_branch
->curframe
]->regs
;
6697 struct bpf_reg_state
*dst_reg
, *other_branch_regs
, *src_reg
= NULL
;
6698 u8 opcode
= BPF_OP(insn
->code
);
6703 /* Only conditional jumps are expected to reach here. */
6704 if (opcode
== BPF_JA
|| opcode
> BPF_JSLE
) {
6705 verbose(env
, "invalid BPF_JMP/JMP32 opcode %x\n", opcode
);
6709 if (BPF_SRC(insn
->code
) == BPF_X
) {
6710 if (insn
->imm
!= 0) {
6711 verbose(env
, "BPF_JMP/JMP32 uses reserved fields\n");
6715 /* check src1 operand */
6716 err
= check_reg_arg(env
, insn
->src_reg
, SRC_OP
);
6720 if (is_pointer_value(env
, insn
->src_reg
)) {
6721 verbose(env
, "R%d pointer comparison prohibited\n",
6725 src_reg
= ®s
[insn
->src_reg
];
6727 if (insn
->src_reg
!= BPF_REG_0
) {
6728 verbose(env
, "BPF_JMP/JMP32 uses reserved fields\n");
6733 /* check src2 operand */
6734 err
= check_reg_arg(env
, insn
->dst_reg
, SRC_OP
);
6738 dst_reg
= ®s
[insn
->dst_reg
];
6739 is_jmp32
= BPF_CLASS(insn
->code
) == BPF_JMP32
;
6741 if (BPF_SRC(insn
->code
) == BPF_K
) {
6742 pred
= is_branch_taken(dst_reg
, insn
->imm
, opcode
, is_jmp32
);
6743 } else if (src_reg
->type
== SCALAR_VALUE
&&
6744 is_jmp32
&& tnum_is_const(tnum_subreg(src_reg
->var_off
))) {
6745 pred
= is_branch_taken(dst_reg
,
6746 tnum_subreg(src_reg
->var_off
).value
,
6749 } else if (src_reg
->type
== SCALAR_VALUE
&&
6750 !is_jmp32
&& tnum_is_const(src_reg
->var_off
)) {
6751 pred
= is_branch_taken(dst_reg
,
6752 src_reg
->var_off
.value
,
6758 err
= mark_chain_precision(env
, insn
->dst_reg
);
6759 if (BPF_SRC(insn
->code
) == BPF_X
&& !err
)
6760 err
= mark_chain_precision(env
, insn
->src_reg
);
6765 /* only follow the goto, ignore fall-through */
6766 *insn_idx
+= insn
->off
;
6768 } else if (pred
== 0) {
6769 /* only follow fall-through branch, since
6770 * that's where the program will go
6775 other_branch
= push_stack(env
, *insn_idx
+ insn
->off
+ 1, *insn_idx
,
6779 other_branch_regs
= other_branch
->frame
[other_branch
->curframe
]->regs
;
6781 /* detect if we are comparing against a constant value so we can adjust
6782 * our min/max values for our dst register.
6783 * this is only legit if both are scalars (or pointers to the same
6784 * object, I suppose, but we don't support that right now), because
6785 * otherwise the different base pointers mean the offsets aren't
6788 if (BPF_SRC(insn
->code
) == BPF_X
) {
6789 struct bpf_reg_state
*src_reg
= ®s
[insn
->src_reg
];
6791 if (dst_reg
->type
== SCALAR_VALUE
&&
6792 src_reg
->type
== SCALAR_VALUE
) {
6793 if (tnum_is_const(src_reg
->var_off
) ||
6795 tnum_is_const(tnum_subreg(src_reg
->var_off
))))
6796 reg_set_min_max(&other_branch_regs
[insn
->dst_reg
],
6798 src_reg
->var_off
.value
,
6799 tnum_subreg(src_reg
->var_off
).value
,
6801 else if (tnum_is_const(dst_reg
->var_off
) ||
6803 tnum_is_const(tnum_subreg(dst_reg
->var_off
))))
6804 reg_set_min_max_inv(&other_branch_regs
[insn
->src_reg
],
6806 dst_reg
->var_off
.value
,
6807 tnum_subreg(dst_reg
->var_off
).value
,
6809 else if (!is_jmp32
&&
6810 (opcode
== BPF_JEQ
|| opcode
== BPF_JNE
))
6811 /* Comparing for equality, we can combine knowledge */
6812 reg_combine_min_max(&other_branch_regs
[insn
->src_reg
],
6813 &other_branch_regs
[insn
->dst_reg
],
6814 src_reg
, dst_reg
, opcode
);
6816 } else if (dst_reg
->type
== SCALAR_VALUE
) {
6817 reg_set_min_max(&other_branch_regs
[insn
->dst_reg
],
6818 dst_reg
, insn
->imm
, (u32
)insn
->imm
,
6822 /* detect if R == 0 where R is returned from bpf_map_lookup_elem().
6823 * NOTE: these optimizations below are related with pointer comparison
6824 * which will never be JMP32.
6826 if (!is_jmp32
&& BPF_SRC(insn
->code
) == BPF_K
&&
6827 insn
->imm
== 0 && (opcode
== BPF_JEQ
|| opcode
== BPF_JNE
) &&
6828 reg_type_may_be_null(dst_reg
->type
)) {
6829 /* Mark all identical registers in each branch as either
6830 * safe or unknown depending R == 0 or R != 0 conditional.
6832 mark_ptr_or_null_regs(this_branch
, insn
->dst_reg
,
6834 mark_ptr_or_null_regs(other_branch
, insn
->dst_reg
,
6836 } else if (!try_match_pkt_pointers(insn
, dst_reg
, ®s
[insn
->src_reg
],
6837 this_branch
, other_branch
) &&
6838 is_pointer_value(env
, insn
->dst_reg
)) {
6839 verbose(env
, "R%d pointer comparison prohibited\n",
6843 if (env
->log
.level
& BPF_LOG_LEVEL
)
6844 print_verifier_state(env
, this_branch
->frame
[this_branch
->curframe
]);
6848 /* verify BPF_LD_IMM64 instruction */
6849 static int check_ld_imm(struct bpf_verifier_env
*env
, struct bpf_insn
*insn
)
6851 struct bpf_insn_aux_data
*aux
= cur_aux(env
);
6852 struct bpf_reg_state
*regs
= cur_regs(env
);
6853 struct bpf_map
*map
;
6856 if (BPF_SIZE(insn
->code
) != BPF_DW
) {
6857 verbose(env
, "invalid BPF_LD_IMM insn\n");
6860 if (insn
->off
!= 0) {
6861 verbose(env
, "BPF_LD_IMM64 uses reserved fields\n");
6865 err
= check_reg_arg(env
, insn
->dst_reg
, DST_OP
);
6869 if (insn
->src_reg
== 0) {
6870 u64 imm
= ((u64
)(insn
+ 1)->imm
<< 32) | (u32
)insn
->imm
;
6872 regs
[insn
->dst_reg
].type
= SCALAR_VALUE
;
6873 __mark_reg_known(®s
[insn
->dst_reg
], imm
);
6877 map
= env
->used_maps
[aux
->map_index
];
6878 mark_reg_known_zero(env
, regs
, insn
->dst_reg
);
6879 regs
[insn
->dst_reg
].map_ptr
= map
;
6881 if (insn
->src_reg
== BPF_PSEUDO_MAP_VALUE
) {
6882 regs
[insn
->dst_reg
].type
= PTR_TO_MAP_VALUE
;
6883 regs
[insn
->dst_reg
].off
= aux
->map_off
;
6884 if (map_value_has_spin_lock(map
))
6885 regs
[insn
->dst_reg
].id
= ++env
->id_gen
;
6886 } else if (insn
->src_reg
== BPF_PSEUDO_MAP_FD
) {
6887 regs
[insn
->dst_reg
].type
= CONST_PTR_TO_MAP
;
6889 verbose(env
, "bpf verifier is misconfigured\n");
6896 static bool may_access_skb(enum bpf_prog_type type
)
6899 case BPF_PROG_TYPE_SOCKET_FILTER
:
6900 case BPF_PROG_TYPE_SCHED_CLS
:
6901 case BPF_PROG_TYPE_SCHED_ACT
:
6908 /* verify safety of LD_ABS|LD_IND instructions:
6909 * - they can only appear in the programs where ctx == skb
6910 * - since they are wrappers of function calls, they scratch R1-R5 registers,
6911 * preserve R6-R9, and store return value into R0
6914 * ctx == skb == R6 == CTX
6917 * SRC == any register
6918 * IMM == 32-bit immediate
6921 * R0 - 8/16/32-bit skb data converted to cpu endianness
6923 static int check_ld_abs(struct bpf_verifier_env
*env
, struct bpf_insn
*insn
)
6925 struct bpf_reg_state
*regs
= cur_regs(env
);
6926 static const int ctx_reg
= BPF_REG_6
;
6927 u8 mode
= BPF_MODE(insn
->code
);
6930 if (!may_access_skb(env
->prog
->type
)) {
6931 verbose(env
, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
6935 if (!env
->ops
->gen_ld_abs
) {
6936 verbose(env
, "bpf verifier is misconfigured\n");
6940 if (env
->subprog_cnt
> 1) {
6941 /* when program has LD_ABS insn JITs and interpreter assume
6942 * that r1 == ctx == skb which is not the case for callees
6943 * that can have arbitrary arguments. It's problematic
6944 * for main prog as well since JITs would need to analyze
6945 * all functions in order to make proper register save/restore
6946 * decisions in the main prog. Hence disallow LD_ABS with calls
6948 verbose(env
, "BPF_LD_[ABS|IND] instructions cannot be mixed with bpf-to-bpf calls\n");
6952 if (insn
->dst_reg
!= BPF_REG_0
|| insn
->off
!= 0 ||
6953 BPF_SIZE(insn
->code
) == BPF_DW
||
6954 (mode
== BPF_ABS
&& insn
->src_reg
!= BPF_REG_0
)) {
6955 verbose(env
, "BPF_LD_[ABS|IND] uses reserved fields\n");
6959 /* check whether implicit source operand (register R6) is readable */
6960 err
= check_reg_arg(env
, ctx_reg
, SRC_OP
);
6964 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
6965 * gen_ld_abs() may terminate the program at runtime, leading to
6968 err
= check_reference_leak(env
);
6970 verbose(env
, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
6974 if (env
->cur_state
->active_spin_lock
) {
6975 verbose(env
, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
6979 if (regs
[ctx_reg
].type
!= PTR_TO_CTX
) {
6981 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
6985 if (mode
== BPF_IND
) {
6986 /* check explicit source operand */
6987 err
= check_reg_arg(env
, insn
->src_reg
, SRC_OP
);
6992 err
= check_ctx_reg(env
, ®s
[ctx_reg
], ctx_reg
);
6996 /* reset caller saved regs to unreadable */
6997 for (i
= 0; i
< CALLER_SAVED_REGS
; i
++) {
6998 mark_reg_not_init(env
, regs
, caller_saved
[i
]);
6999 check_reg_arg(env
, caller_saved
[i
], DST_OP_NO_MARK
);
7002 /* mark destination R0 register as readable, since it contains
7003 * the value fetched from the packet.
7004 * Already marked as written above.
7006 mark_reg_unknown(env
, regs
, BPF_REG_0
);
7007 /* ld_abs load up to 32-bit skb data. */
7008 regs
[BPF_REG_0
].subreg_def
= env
->insn_idx
+ 1;
7012 static int check_return_code(struct bpf_verifier_env
*env
)
7014 struct tnum enforce_attach_type_range
= tnum_unknown
;
7015 const struct bpf_prog
*prog
= env
->prog
;
7016 struct bpf_reg_state
*reg
;
7017 struct tnum range
= tnum_range(0, 1);
7020 /* LSM and struct_ops func-ptr's return type could be "void" */
7021 if ((env
->prog
->type
== BPF_PROG_TYPE_STRUCT_OPS
||
7022 env
->prog
->type
== BPF_PROG_TYPE_LSM
) &&
7023 !prog
->aux
->attach_func_proto
->type
)
7026 /* eBPF calling convetion is such that R0 is used
7027 * to return the value from eBPF program.
7028 * Make sure that it's readable at this time
7029 * of bpf_exit, which means that program wrote
7030 * something into it earlier
7032 err
= check_reg_arg(env
, BPF_REG_0
, SRC_OP
);
7036 if (is_pointer_value(env
, BPF_REG_0
)) {
7037 verbose(env
, "R0 leaks addr as return value\n");
7041 switch (env
->prog
->type
) {
7042 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR
:
7043 if (env
->prog
->expected_attach_type
== BPF_CGROUP_UDP4_RECVMSG
||
7044 env
->prog
->expected_attach_type
== BPF_CGROUP_UDP6_RECVMSG
)
7045 range
= tnum_range(1, 1);
7047 case BPF_PROG_TYPE_CGROUP_SKB
:
7048 if (env
->prog
->expected_attach_type
== BPF_CGROUP_INET_EGRESS
) {
7049 range
= tnum_range(0, 3);
7050 enforce_attach_type_range
= tnum_range(2, 3);
7053 case BPF_PROG_TYPE_CGROUP_SOCK
:
7054 case BPF_PROG_TYPE_SOCK_OPS
:
7055 case BPF_PROG_TYPE_CGROUP_DEVICE
:
7056 case BPF_PROG_TYPE_CGROUP_SYSCTL
:
7057 case BPF_PROG_TYPE_CGROUP_SOCKOPT
:
7059 case BPF_PROG_TYPE_RAW_TRACEPOINT
:
7060 if (!env
->prog
->aux
->attach_btf_id
)
7062 range
= tnum_const(0);
7064 case BPF_PROG_TYPE_TRACING
:
7065 switch (env
->prog
->expected_attach_type
) {
7066 case BPF_TRACE_FENTRY
:
7067 case BPF_TRACE_FEXIT
:
7068 range
= tnum_const(0);
7070 case BPF_TRACE_RAW_TP
:
7071 case BPF_MODIFY_RETURN
:
7077 case BPF_PROG_TYPE_EXT
:
7078 /* freplace program can return anything as its return value
7079 * depends on the to-be-replaced kernel func or bpf program.
7085 reg
= cur_regs(env
) + BPF_REG_0
;
7086 if (reg
->type
!= SCALAR_VALUE
) {
7087 verbose(env
, "At program exit the register R0 is not a known value (%s)\n",
7088 reg_type_str
[reg
->type
]);
7092 if (!tnum_in(range
, reg
->var_off
)) {
7095 verbose(env
, "At program exit the register R0 ");
7096 if (!tnum_is_unknown(reg
->var_off
)) {
7097 tnum_strn(tn_buf
, sizeof(tn_buf
), reg
->var_off
);
7098 verbose(env
, "has value %s", tn_buf
);
7100 verbose(env
, "has unknown scalar value");
7102 tnum_strn(tn_buf
, sizeof(tn_buf
), range
);
7103 verbose(env
, " should have been in %s\n", tn_buf
);
7107 if (!tnum_is_unknown(enforce_attach_type_range
) &&
7108 tnum_in(enforce_attach_type_range
, reg
->var_off
))
7109 env
->prog
->enforce_expected_attach_type
= 1;
7113 /* non-recursive DFS pseudo code
7114 * 1 procedure DFS-iterative(G,v):
7115 * 2 label v as discovered
7116 * 3 let S be a stack
7118 * 5 while S is not empty
7120 * 7 if t is what we're looking for:
7122 * 9 for all edges e in G.adjacentEdges(t) do
7123 * 10 if edge e is already labelled
7124 * 11 continue with the next edge
7125 * 12 w <- G.adjacentVertex(t,e)
7126 * 13 if vertex w is not discovered and not explored
7127 * 14 label e as tree-edge
7128 * 15 label w as discovered
7131 * 18 else if vertex w is discovered
7132 * 19 label e as back-edge
7134 * 21 // vertex w is explored
7135 * 22 label e as forward- or cross-edge
7136 * 23 label t as explored
7141 * 0x11 - discovered and fall-through edge labelled
7142 * 0x12 - discovered and fall-through and branch edges labelled
7153 static u32
state_htab_size(struct bpf_verifier_env
*env
)
7155 return env
->prog
->len
;
7158 static struct bpf_verifier_state_list
**explored_state(
7159 struct bpf_verifier_env
*env
,
7162 struct bpf_verifier_state
*cur
= env
->cur_state
;
7163 struct bpf_func_state
*state
= cur
->frame
[cur
->curframe
];
7165 return &env
->explored_states
[(idx
^ state
->callsite
) % state_htab_size(env
)];
7168 static void init_explored_state(struct bpf_verifier_env
*env
, int idx
)
7170 env
->insn_aux_data
[idx
].prune_point
= true;
7173 /* t, w, e - match pseudo-code above:
7174 * t - index of current instruction
7175 * w - next instruction
7178 static int push_insn(int t
, int w
, int e
, struct bpf_verifier_env
*env
,
7181 int *insn_stack
= env
->cfg
.insn_stack
;
7182 int *insn_state
= env
->cfg
.insn_state
;
7184 if (e
== FALLTHROUGH
&& insn_state
[t
] >= (DISCOVERED
| FALLTHROUGH
))
7187 if (e
== BRANCH
&& insn_state
[t
] >= (DISCOVERED
| BRANCH
))
7190 if (w
< 0 || w
>= env
->prog
->len
) {
7191 verbose_linfo(env
, t
, "%d: ", t
);
7192 verbose(env
, "jump out of range from insn %d to %d\n", t
, w
);
7197 /* mark branch target for state pruning */
7198 init_explored_state(env
, w
);
7200 if (insn_state
[w
] == 0) {
7202 insn_state
[t
] = DISCOVERED
| e
;
7203 insn_state
[w
] = DISCOVERED
;
7204 if (env
->cfg
.cur_stack
>= env
->prog
->len
)
7206 insn_stack
[env
->cfg
.cur_stack
++] = w
;
7208 } else if ((insn_state
[w
] & 0xF0) == DISCOVERED
) {
7209 if (loop_ok
&& env
->allow_ptr_leaks
)
7211 verbose_linfo(env
, t
, "%d: ", t
);
7212 verbose_linfo(env
, w
, "%d: ", w
);
7213 verbose(env
, "back-edge from insn %d to %d\n", t
, w
);
7215 } else if (insn_state
[w
] == EXPLORED
) {
7216 /* forward- or cross-edge */
7217 insn_state
[t
] = DISCOVERED
| e
;
7219 verbose(env
, "insn state internal bug\n");
7225 /* non-recursive depth-first-search to detect loops in BPF program
7226 * loop == back-edge in directed graph
7228 static int check_cfg(struct bpf_verifier_env
*env
)
7230 struct bpf_insn
*insns
= env
->prog
->insnsi
;
7231 int insn_cnt
= env
->prog
->len
;
7232 int *insn_stack
, *insn_state
;
7236 insn_state
= env
->cfg
.insn_state
= kvcalloc(insn_cnt
, sizeof(int), GFP_KERNEL
);
7240 insn_stack
= env
->cfg
.insn_stack
= kvcalloc(insn_cnt
, sizeof(int), GFP_KERNEL
);
7246 insn_state
[0] = DISCOVERED
; /* mark 1st insn as discovered */
7247 insn_stack
[0] = 0; /* 0 is the first instruction */
7248 env
->cfg
.cur_stack
= 1;
7251 if (env
->cfg
.cur_stack
== 0)
7253 t
= insn_stack
[env
->cfg
.cur_stack
- 1];
7255 if (BPF_CLASS(insns
[t
].code
) == BPF_JMP
||
7256 BPF_CLASS(insns
[t
].code
) == BPF_JMP32
) {
7257 u8 opcode
= BPF_OP(insns
[t
].code
);
7259 if (opcode
== BPF_EXIT
) {
7261 } else if (opcode
== BPF_CALL
) {
7262 ret
= push_insn(t
, t
+ 1, FALLTHROUGH
, env
, false);
7267 if (t
+ 1 < insn_cnt
)
7268 init_explored_state(env
, t
+ 1);
7269 if (insns
[t
].src_reg
== BPF_PSEUDO_CALL
) {
7270 init_explored_state(env
, t
);
7271 ret
= push_insn(t
, t
+ insns
[t
].imm
+ 1, BRANCH
,
7278 } else if (opcode
== BPF_JA
) {
7279 if (BPF_SRC(insns
[t
].code
) != BPF_K
) {
7283 /* unconditional jump with single edge */
7284 ret
= push_insn(t
, t
+ insns
[t
].off
+ 1,
7285 FALLTHROUGH
, env
, true);
7290 /* unconditional jmp is not a good pruning point,
7291 * but it's marked, since backtracking needs
7292 * to record jmp history in is_state_visited().
7294 init_explored_state(env
, t
+ insns
[t
].off
+ 1);
7295 /* tell verifier to check for equivalent states
7296 * after every call and jump
7298 if (t
+ 1 < insn_cnt
)
7299 init_explored_state(env
, t
+ 1);
7301 /* conditional jump with two edges */
7302 init_explored_state(env
, t
);
7303 ret
= push_insn(t
, t
+ 1, FALLTHROUGH
, env
, true);
7309 ret
= push_insn(t
, t
+ insns
[t
].off
+ 1, BRANCH
, env
, true);
7316 /* all other non-branch instructions with single
7319 ret
= push_insn(t
, t
+ 1, FALLTHROUGH
, env
, false);
7327 insn_state
[t
] = EXPLORED
;
7328 if (env
->cfg
.cur_stack
-- <= 0) {
7329 verbose(env
, "pop stack internal bug\n");
7336 for (i
= 0; i
< insn_cnt
; i
++) {
7337 if (insn_state
[i
] != EXPLORED
) {
7338 verbose(env
, "unreachable insn %d\n", i
);
7343 ret
= 0; /* cfg looks good */
7348 env
->cfg
.insn_state
= env
->cfg
.insn_stack
= NULL
;
7352 /* The minimum supported BTF func info size */
7353 #define MIN_BPF_FUNCINFO_SIZE 8
7354 #define MAX_FUNCINFO_REC_SIZE 252
7356 static int check_btf_func(struct bpf_verifier_env
*env
,
7357 const union bpf_attr
*attr
,
7358 union bpf_attr __user
*uattr
)
7360 u32 i
, nfuncs
, urec_size
, min_size
;
7361 u32 krec_size
= sizeof(struct bpf_func_info
);
7362 struct bpf_func_info
*krecord
;
7363 struct bpf_func_info_aux
*info_aux
= NULL
;
7364 const struct btf_type
*type
;
7365 struct bpf_prog
*prog
;
7366 const struct btf
*btf
;
7367 void __user
*urecord
;
7368 u32 prev_offset
= 0;
7371 nfuncs
= attr
->func_info_cnt
;
7375 if (nfuncs
!= env
->subprog_cnt
) {
7376 verbose(env
, "number of funcs in func_info doesn't match number of subprogs\n");
7380 urec_size
= attr
->func_info_rec_size
;
7381 if (urec_size
< MIN_BPF_FUNCINFO_SIZE
||
7382 urec_size
> MAX_FUNCINFO_REC_SIZE
||
7383 urec_size
% sizeof(u32
)) {
7384 verbose(env
, "invalid func info rec size %u\n", urec_size
);
7389 btf
= prog
->aux
->btf
;
7391 urecord
= u64_to_user_ptr(attr
->func_info
);
7392 min_size
= min_t(u32
, krec_size
, urec_size
);
7394 krecord
= kvcalloc(nfuncs
, krec_size
, GFP_KERNEL
| __GFP_NOWARN
);
7397 info_aux
= kcalloc(nfuncs
, sizeof(*info_aux
), GFP_KERNEL
| __GFP_NOWARN
);
7401 for (i
= 0; i
< nfuncs
; i
++) {
7402 ret
= bpf_check_uarg_tail_zero(urecord
, krec_size
, urec_size
);
7404 if (ret
== -E2BIG
) {
7405 verbose(env
, "nonzero tailing record in func info");
7406 /* set the size kernel expects so loader can zero
7407 * out the rest of the record.
7409 if (put_user(min_size
, &uattr
->func_info_rec_size
))
7415 if (copy_from_user(&krecord
[i
], urecord
, min_size
)) {
7420 /* check insn_off */
7422 if (krecord
[i
].insn_off
) {
7424 "nonzero insn_off %u for the first func info record",
7425 krecord
[i
].insn_off
);
7429 } else if (krecord
[i
].insn_off
<= prev_offset
) {
7431 "same or smaller insn offset (%u) than previous func info record (%u)",
7432 krecord
[i
].insn_off
, prev_offset
);
7437 if (env
->subprog_info
[i
].start
!= krecord
[i
].insn_off
) {
7438 verbose(env
, "func_info BTF section doesn't match subprog layout in BPF program\n");
7444 type
= btf_type_by_id(btf
, krecord
[i
].type_id
);
7445 if (!type
|| !btf_type_is_func(type
)) {
7446 verbose(env
, "invalid type id %d in func info",
7447 krecord
[i
].type_id
);
7451 info_aux
[i
].linkage
= BTF_INFO_VLEN(type
->info
);
7452 prev_offset
= krecord
[i
].insn_off
;
7453 urecord
+= urec_size
;
7456 prog
->aux
->func_info
= krecord
;
7457 prog
->aux
->func_info_cnt
= nfuncs
;
7458 prog
->aux
->func_info_aux
= info_aux
;
7467 static void adjust_btf_func(struct bpf_verifier_env
*env
)
7469 struct bpf_prog_aux
*aux
= env
->prog
->aux
;
7472 if (!aux
->func_info
)
7475 for (i
= 0; i
< env
->subprog_cnt
; i
++)
7476 aux
->func_info
[i
].insn_off
= env
->subprog_info
[i
].start
;
7479 #define MIN_BPF_LINEINFO_SIZE (offsetof(struct bpf_line_info, line_col) + \
7480 sizeof(((struct bpf_line_info *)(0))->line_col))
7481 #define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE
7483 static int check_btf_line(struct bpf_verifier_env
*env
,
7484 const union bpf_attr
*attr
,
7485 union bpf_attr __user
*uattr
)
7487 u32 i
, s
, nr_linfo
, ncopy
, expected_size
, rec_size
, prev_offset
= 0;
7488 struct bpf_subprog_info
*sub
;
7489 struct bpf_line_info
*linfo
;
7490 struct bpf_prog
*prog
;
7491 const struct btf
*btf
;
7492 void __user
*ulinfo
;
7495 nr_linfo
= attr
->line_info_cnt
;
7499 rec_size
= attr
->line_info_rec_size
;
7500 if (rec_size
< MIN_BPF_LINEINFO_SIZE
||
7501 rec_size
> MAX_LINEINFO_REC_SIZE
||
7502 rec_size
& (sizeof(u32
) - 1))
7505 /* Need to zero it in case the userspace may
7506 * pass in a smaller bpf_line_info object.
7508 linfo
= kvcalloc(nr_linfo
, sizeof(struct bpf_line_info
),
7509 GFP_KERNEL
| __GFP_NOWARN
);
7514 btf
= prog
->aux
->btf
;
7517 sub
= env
->subprog_info
;
7518 ulinfo
= u64_to_user_ptr(attr
->line_info
);
7519 expected_size
= sizeof(struct bpf_line_info
);
7520 ncopy
= min_t(u32
, expected_size
, rec_size
);
7521 for (i
= 0; i
< nr_linfo
; i
++) {
7522 err
= bpf_check_uarg_tail_zero(ulinfo
, expected_size
, rec_size
);
7524 if (err
== -E2BIG
) {
7525 verbose(env
, "nonzero tailing record in line_info");
7526 if (put_user(expected_size
,
7527 &uattr
->line_info_rec_size
))
7533 if (copy_from_user(&linfo
[i
], ulinfo
, ncopy
)) {
7539 * Check insn_off to ensure
7540 * 1) strictly increasing AND
7541 * 2) bounded by prog->len
7543 * The linfo[0].insn_off == 0 check logically falls into
7544 * the later "missing bpf_line_info for func..." case
7545 * because the first linfo[0].insn_off must be the
7546 * first sub also and the first sub must have
7547 * subprog_info[0].start == 0.
7549 if ((i
&& linfo
[i
].insn_off
<= prev_offset
) ||
7550 linfo
[i
].insn_off
>= prog
->len
) {
7551 verbose(env
, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
7552 i
, linfo
[i
].insn_off
, prev_offset
,
7558 if (!prog
->insnsi
[linfo
[i
].insn_off
].code
) {
7560 "Invalid insn code at line_info[%u].insn_off\n",
7566 if (!btf_name_by_offset(btf
, linfo
[i
].line_off
) ||
7567 !btf_name_by_offset(btf
, linfo
[i
].file_name_off
)) {
7568 verbose(env
, "Invalid line_info[%u].line_off or .file_name_off\n", i
);
7573 if (s
!= env
->subprog_cnt
) {
7574 if (linfo
[i
].insn_off
== sub
[s
].start
) {
7575 sub
[s
].linfo_idx
= i
;
7577 } else if (sub
[s
].start
< linfo
[i
].insn_off
) {
7578 verbose(env
, "missing bpf_line_info for func#%u\n", s
);
7584 prev_offset
= linfo
[i
].insn_off
;
7588 if (s
!= env
->subprog_cnt
) {
7589 verbose(env
, "missing bpf_line_info for %u funcs starting from func#%u\n",
7590 env
->subprog_cnt
- s
, s
);
7595 prog
->aux
->linfo
= linfo
;
7596 prog
->aux
->nr_linfo
= nr_linfo
;
7605 static int check_btf_info(struct bpf_verifier_env
*env
,
7606 const union bpf_attr
*attr
,
7607 union bpf_attr __user
*uattr
)
7612 if (!attr
->func_info_cnt
&& !attr
->line_info_cnt
)
7615 btf
= btf_get_by_fd(attr
->prog_btf_fd
);
7617 return PTR_ERR(btf
);
7618 env
->prog
->aux
->btf
= btf
;
7620 err
= check_btf_func(env
, attr
, uattr
);
7624 err
= check_btf_line(env
, attr
, uattr
);
7631 /* check %cur's range satisfies %old's */
7632 static bool range_within(struct bpf_reg_state
*old
,
7633 struct bpf_reg_state
*cur
)
7635 return old
->umin_value
<= cur
->umin_value
&&
7636 old
->umax_value
>= cur
->umax_value
&&
7637 old
->smin_value
<= cur
->smin_value
&&
7638 old
->smax_value
>= cur
->smax_value
;
7641 /* Maximum number of register states that can exist at once */
7642 #define ID_MAP_SIZE (MAX_BPF_REG + MAX_BPF_STACK / BPF_REG_SIZE)
7648 /* If in the old state two registers had the same id, then they need to have
7649 * the same id in the new state as well. But that id could be different from
7650 * the old state, so we need to track the mapping from old to new ids.
7651 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
7652 * regs with old id 5 must also have new id 9 for the new state to be safe. But
7653 * regs with a different old id could still have new id 9, we don't care about
7655 * So we look through our idmap to see if this old id has been seen before. If
7656 * so, we require the new id to match; otherwise, we add the id pair to the map.
7658 static bool check_ids(u32 old_id
, u32 cur_id
, struct idpair
*idmap
)
7662 for (i
= 0; i
< ID_MAP_SIZE
; i
++) {
7663 if (!idmap
[i
].old
) {
7664 /* Reached an empty slot; haven't seen this id before */
7665 idmap
[i
].old
= old_id
;
7666 idmap
[i
].cur
= cur_id
;
7669 if (idmap
[i
].old
== old_id
)
7670 return idmap
[i
].cur
== cur_id
;
7672 /* We ran out of idmap slots, which should be impossible */
7677 static void clean_func_state(struct bpf_verifier_env
*env
,
7678 struct bpf_func_state
*st
)
7680 enum bpf_reg_liveness live
;
7683 for (i
= 0; i
< BPF_REG_FP
; i
++) {
7684 live
= st
->regs
[i
].live
;
7685 /* liveness must not touch this register anymore */
7686 st
->regs
[i
].live
|= REG_LIVE_DONE
;
7687 if (!(live
& REG_LIVE_READ
))
7688 /* since the register is unused, clear its state
7689 * to make further comparison simpler
7691 __mark_reg_not_init(env
, &st
->regs
[i
]);
7694 for (i
= 0; i
< st
->allocated_stack
/ BPF_REG_SIZE
; i
++) {
7695 live
= st
->stack
[i
].spilled_ptr
.live
;
7696 /* liveness must not touch this stack slot anymore */
7697 st
->stack
[i
].spilled_ptr
.live
|= REG_LIVE_DONE
;
7698 if (!(live
& REG_LIVE_READ
)) {
7699 __mark_reg_not_init(env
, &st
->stack
[i
].spilled_ptr
);
7700 for (j
= 0; j
< BPF_REG_SIZE
; j
++)
7701 st
->stack
[i
].slot_type
[j
] = STACK_INVALID
;
7706 static void clean_verifier_state(struct bpf_verifier_env
*env
,
7707 struct bpf_verifier_state
*st
)
7711 if (st
->frame
[0]->regs
[0].live
& REG_LIVE_DONE
)
7712 /* all regs in this state in all frames were already marked */
7715 for (i
= 0; i
<= st
->curframe
; i
++)
7716 clean_func_state(env
, st
->frame
[i
]);
7719 /* the parentage chains form a tree.
7720 * the verifier states are added to state lists at given insn and
7721 * pushed into state stack for future exploration.
7722 * when the verifier reaches bpf_exit insn some of the verifer states
7723 * stored in the state lists have their final liveness state already,
7724 * but a lot of states will get revised from liveness point of view when
7725 * the verifier explores other branches.
7728 * 2: if r1 == 100 goto pc+1
7731 * when the verifier reaches exit insn the register r0 in the state list of
7732 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
7733 * of insn 2 and goes exploring further. At the insn 4 it will walk the
7734 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
7736 * Since the verifier pushes the branch states as it sees them while exploring
7737 * the program the condition of walking the branch instruction for the second
7738 * time means that all states below this branch were already explored and
7739 * their final liveness markes are already propagated.
7740 * Hence when the verifier completes the search of state list in is_state_visited()
7741 * we can call this clean_live_states() function to mark all liveness states
7742 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
7744 * This function also clears the registers and stack for states that !READ
7745 * to simplify state merging.
7747 * Important note here that walking the same branch instruction in the callee
7748 * doesn't meant that the states are DONE. The verifier has to compare
7751 static void clean_live_states(struct bpf_verifier_env
*env
, int insn
,
7752 struct bpf_verifier_state
*cur
)
7754 struct bpf_verifier_state_list
*sl
;
7757 sl
= *explored_state(env
, insn
);
7759 if (sl
->state
.branches
)
7761 if (sl
->state
.insn_idx
!= insn
||
7762 sl
->state
.curframe
!= cur
->curframe
)
7764 for (i
= 0; i
<= cur
->curframe
; i
++)
7765 if (sl
->state
.frame
[i
]->callsite
!= cur
->frame
[i
]->callsite
)
7767 clean_verifier_state(env
, &sl
->state
);
7773 /* Returns true if (rold safe implies rcur safe) */
7774 static bool regsafe(struct bpf_reg_state
*rold
, struct bpf_reg_state
*rcur
,
7775 struct idpair
*idmap
)
7779 if (!(rold
->live
& REG_LIVE_READ
))
7780 /* explored state didn't use this */
7783 equal
= memcmp(rold
, rcur
, offsetof(struct bpf_reg_state
, parent
)) == 0;
7785 if (rold
->type
== PTR_TO_STACK
)
7786 /* two stack pointers are equal only if they're pointing to
7787 * the same stack frame, since fp-8 in foo != fp-8 in bar
7789 return equal
&& rold
->frameno
== rcur
->frameno
;
7794 if (rold
->type
== NOT_INIT
)
7795 /* explored state can't have used this */
7797 if (rcur
->type
== NOT_INIT
)
7799 switch (rold
->type
) {
7801 if (rcur
->type
== SCALAR_VALUE
) {
7802 if (!rold
->precise
&& !rcur
->precise
)
7804 /* new val must satisfy old val knowledge */
7805 return range_within(rold
, rcur
) &&
7806 tnum_in(rold
->var_off
, rcur
->var_off
);
7808 /* We're trying to use a pointer in place of a scalar.
7809 * Even if the scalar was unbounded, this could lead to
7810 * pointer leaks because scalars are allowed to leak
7811 * while pointers are not. We could make this safe in
7812 * special cases if root is calling us, but it's
7813 * probably not worth the hassle.
7817 case PTR_TO_MAP_VALUE
:
7818 /* If the new min/max/var_off satisfy the old ones and
7819 * everything else matches, we are OK.
7820 * 'id' is not compared, since it's only used for maps with
7821 * bpf_spin_lock inside map element and in such cases if
7822 * the rest of the prog is valid for one map element then
7823 * it's valid for all map elements regardless of the key
7824 * used in bpf_map_lookup()
7826 return memcmp(rold
, rcur
, offsetof(struct bpf_reg_state
, id
)) == 0 &&
7827 range_within(rold
, rcur
) &&
7828 tnum_in(rold
->var_off
, rcur
->var_off
);
7829 case PTR_TO_MAP_VALUE_OR_NULL
:
7830 /* a PTR_TO_MAP_VALUE could be safe to use as a
7831 * PTR_TO_MAP_VALUE_OR_NULL into the same map.
7832 * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
7833 * checked, doing so could have affected others with the same
7834 * id, and we can't check for that because we lost the id when
7835 * we converted to a PTR_TO_MAP_VALUE.
7837 if (rcur
->type
!= PTR_TO_MAP_VALUE_OR_NULL
)
7839 if (memcmp(rold
, rcur
, offsetof(struct bpf_reg_state
, id
)))
7841 /* Check our ids match any regs they're supposed to */
7842 return check_ids(rold
->id
, rcur
->id
, idmap
);
7843 case PTR_TO_PACKET_META
:
7845 if (rcur
->type
!= rold
->type
)
7847 /* We must have at least as much range as the old ptr
7848 * did, so that any accesses which were safe before are
7849 * still safe. This is true even if old range < old off,
7850 * since someone could have accessed through (ptr - k), or
7851 * even done ptr -= k in a register, to get a safe access.
7853 if (rold
->range
> rcur
->range
)
7855 /* If the offsets don't match, we can't trust our alignment;
7856 * nor can we be sure that we won't fall out of range.
7858 if (rold
->off
!= rcur
->off
)
7860 /* id relations must be preserved */
7861 if (rold
->id
&& !check_ids(rold
->id
, rcur
->id
, idmap
))
7863 /* new val must satisfy old val knowledge */
7864 return range_within(rold
, rcur
) &&
7865 tnum_in(rold
->var_off
, rcur
->var_off
);
7867 case CONST_PTR_TO_MAP
:
7868 case PTR_TO_PACKET_END
:
7869 case PTR_TO_FLOW_KEYS
:
7871 case PTR_TO_SOCKET_OR_NULL
:
7872 case PTR_TO_SOCK_COMMON
:
7873 case PTR_TO_SOCK_COMMON_OR_NULL
:
7874 case PTR_TO_TCP_SOCK
:
7875 case PTR_TO_TCP_SOCK_OR_NULL
:
7876 case PTR_TO_XDP_SOCK
:
7877 /* Only valid matches are exact, which memcmp() above
7878 * would have accepted
7881 /* Don't know what's going on, just say it's not safe */
7885 /* Shouldn't get here; if we do, say it's not safe */
7890 static bool stacksafe(struct bpf_func_state
*old
,
7891 struct bpf_func_state
*cur
,
7892 struct idpair
*idmap
)
7896 /* walk slots of the explored stack and ignore any additional
7897 * slots in the current stack, since explored(safe) state
7900 for (i
= 0; i
< old
->allocated_stack
; i
++) {
7901 spi
= i
/ BPF_REG_SIZE
;
7903 if (!(old
->stack
[spi
].spilled_ptr
.live
& REG_LIVE_READ
)) {
7904 i
+= BPF_REG_SIZE
- 1;
7905 /* explored state didn't use this */
7909 if (old
->stack
[spi
].slot_type
[i
% BPF_REG_SIZE
] == STACK_INVALID
)
7912 /* explored stack has more populated slots than current stack
7913 * and these slots were used
7915 if (i
>= cur
->allocated_stack
)
7918 /* if old state was safe with misc data in the stack
7919 * it will be safe with zero-initialized stack.
7920 * The opposite is not true
7922 if (old
->stack
[spi
].slot_type
[i
% BPF_REG_SIZE
] == STACK_MISC
&&
7923 cur
->stack
[spi
].slot_type
[i
% BPF_REG_SIZE
] == STACK_ZERO
)
7925 if (old
->stack
[spi
].slot_type
[i
% BPF_REG_SIZE
] !=
7926 cur
->stack
[spi
].slot_type
[i
% BPF_REG_SIZE
])
7927 /* Ex: old explored (safe) state has STACK_SPILL in
7928 * this stack slot, but current has has STACK_MISC ->
7929 * this verifier states are not equivalent,
7930 * return false to continue verification of this path
7933 if (i
% BPF_REG_SIZE
)
7935 if (old
->stack
[spi
].slot_type
[0] != STACK_SPILL
)
7937 if (!regsafe(&old
->stack
[spi
].spilled_ptr
,
7938 &cur
->stack
[spi
].spilled_ptr
,
7940 /* when explored and current stack slot are both storing
7941 * spilled registers, check that stored pointers types
7942 * are the same as well.
7943 * Ex: explored safe path could have stored
7944 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
7945 * but current path has stored:
7946 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
7947 * such verifier states are not equivalent.
7948 * return false to continue verification of this path
7955 static bool refsafe(struct bpf_func_state
*old
, struct bpf_func_state
*cur
)
7957 if (old
->acquired_refs
!= cur
->acquired_refs
)
7959 return !memcmp(old
->refs
, cur
->refs
,
7960 sizeof(*old
->refs
) * old
->acquired_refs
);
7963 /* compare two verifier states
7965 * all states stored in state_list are known to be valid, since
7966 * verifier reached 'bpf_exit' instruction through them
7968 * this function is called when verifier exploring different branches of
7969 * execution popped from the state stack. If it sees an old state that has
7970 * more strict register state and more strict stack state then this execution
7971 * branch doesn't need to be explored further, since verifier already
7972 * concluded that more strict state leads to valid finish.
7974 * Therefore two states are equivalent if register state is more conservative
7975 * and explored stack state is more conservative than the current one.
7978 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
7979 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
7981 * In other words if current stack state (one being explored) has more
7982 * valid slots than old one that already passed validation, it means
7983 * the verifier can stop exploring and conclude that current state is valid too
7985 * Similarly with registers. If explored state has register type as invalid
7986 * whereas register type in current state is meaningful, it means that
7987 * the current state will reach 'bpf_exit' instruction safely
7989 static bool func_states_equal(struct bpf_func_state
*old
,
7990 struct bpf_func_state
*cur
)
7992 struct idpair
*idmap
;
7996 idmap
= kcalloc(ID_MAP_SIZE
, sizeof(struct idpair
), GFP_KERNEL
);
7997 /* If we failed to allocate the idmap, just say it's not safe */
8001 for (i
= 0; i
< MAX_BPF_REG
; i
++) {
8002 if (!regsafe(&old
->regs
[i
], &cur
->regs
[i
], idmap
))
8006 if (!stacksafe(old
, cur
, idmap
))
8009 if (!refsafe(old
, cur
))
8017 static bool states_equal(struct bpf_verifier_env
*env
,
8018 struct bpf_verifier_state
*old
,
8019 struct bpf_verifier_state
*cur
)
8023 if (old
->curframe
!= cur
->curframe
)
8026 /* Verification state from speculative execution simulation
8027 * must never prune a non-speculative execution one.
8029 if (old
->speculative
&& !cur
->speculative
)
8032 if (old
->active_spin_lock
!= cur
->active_spin_lock
)
8035 /* for states to be equal callsites have to be the same
8036 * and all frame states need to be equivalent
8038 for (i
= 0; i
<= old
->curframe
; i
++) {
8039 if (old
->frame
[i
]->callsite
!= cur
->frame
[i
]->callsite
)
8041 if (!func_states_equal(old
->frame
[i
], cur
->frame
[i
]))
8047 /* Return 0 if no propagation happened. Return negative error code if error
8048 * happened. Otherwise, return the propagated bit.
8050 static int propagate_liveness_reg(struct bpf_verifier_env
*env
,
8051 struct bpf_reg_state
*reg
,
8052 struct bpf_reg_state
*parent_reg
)
8054 u8 parent_flag
= parent_reg
->live
& REG_LIVE_READ
;
8055 u8 flag
= reg
->live
& REG_LIVE_READ
;
8058 /* When comes here, read flags of PARENT_REG or REG could be any of
8059 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
8060 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
8062 if (parent_flag
== REG_LIVE_READ64
||
8063 /* Or if there is no read flag from REG. */
8065 /* Or if the read flag from REG is the same as PARENT_REG. */
8066 parent_flag
== flag
)
8069 err
= mark_reg_read(env
, reg
, parent_reg
, flag
);
8076 /* A write screens off any subsequent reads; but write marks come from the
8077 * straight-line code between a state and its parent. When we arrive at an
8078 * equivalent state (jump target or such) we didn't arrive by the straight-line
8079 * code, so read marks in the state must propagate to the parent regardless
8080 * of the state's write marks. That's what 'parent == state->parent' comparison
8081 * in mark_reg_read() is for.
8083 static int propagate_liveness(struct bpf_verifier_env
*env
,
8084 const struct bpf_verifier_state
*vstate
,
8085 struct bpf_verifier_state
*vparent
)
8087 struct bpf_reg_state
*state_reg
, *parent_reg
;
8088 struct bpf_func_state
*state
, *parent
;
8089 int i
, frame
, err
= 0;
8091 if (vparent
->curframe
!= vstate
->curframe
) {
8092 WARN(1, "propagate_live: parent frame %d current frame %d\n",
8093 vparent
->curframe
, vstate
->curframe
);
8096 /* Propagate read liveness of registers... */
8097 BUILD_BUG_ON(BPF_REG_FP
+ 1 != MAX_BPF_REG
);
8098 for (frame
= 0; frame
<= vstate
->curframe
; frame
++) {
8099 parent
= vparent
->frame
[frame
];
8100 state
= vstate
->frame
[frame
];
8101 parent_reg
= parent
->regs
;
8102 state_reg
= state
->regs
;
8103 /* We don't need to worry about FP liveness, it's read-only */
8104 for (i
= frame
< vstate
->curframe
? BPF_REG_6
: 0; i
< BPF_REG_FP
; i
++) {
8105 err
= propagate_liveness_reg(env
, &state_reg
[i
],
8109 if (err
== REG_LIVE_READ64
)
8110 mark_insn_zext(env
, &parent_reg
[i
]);
8113 /* Propagate stack slots. */
8114 for (i
= 0; i
< state
->allocated_stack
/ BPF_REG_SIZE
&&
8115 i
< parent
->allocated_stack
/ BPF_REG_SIZE
; i
++) {
8116 parent_reg
= &parent
->stack
[i
].spilled_ptr
;
8117 state_reg
= &state
->stack
[i
].spilled_ptr
;
8118 err
= propagate_liveness_reg(env
, state_reg
,
8127 /* find precise scalars in the previous equivalent state and
8128 * propagate them into the current state
8130 static int propagate_precision(struct bpf_verifier_env
*env
,
8131 const struct bpf_verifier_state
*old
)
8133 struct bpf_reg_state
*state_reg
;
8134 struct bpf_func_state
*state
;
8137 state
= old
->frame
[old
->curframe
];
8138 state_reg
= state
->regs
;
8139 for (i
= 0; i
< BPF_REG_FP
; i
++, state_reg
++) {
8140 if (state_reg
->type
!= SCALAR_VALUE
||
8141 !state_reg
->precise
)
8143 if (env
->log
.level
& BPF_LOG_LEVEL2
)
8144 verbose(env
, "propagating r%d\n", i
);
8145 err
= mark_chain_precision(env
, i
);
8150 for (i
= 0; i
< state
->allocated_stack
/ BPF_REG_SIZE
; i
++) {
8151 if (state
->stack
[i
].slot_type
[0] != STACK_SPILL
)
8153 state_reg
= &state
->stack
[i
].spilled_ptr
;
8154 if (state_reg
->type
!= SCALAR_VALUE
||
8155 !state_reg
->precise
)
8157 if (env
->log
.level
& BPF_LOG_LEVEL2
)
8158 verbose(env
, "propagating fp%d\n",
8159 (-i
- 1) * BPF_REG_SIZE
);
8160 err
= mark_chain_precision_stack(env
, i
);
8167 static bool states_maybe_looping(struct bpf_verifier_state
*old
,
8168 struct bpf_verifier_state
*cur
)
8170 struct bpf_func_state
*fold
, *fcur
;
8171 int i
, fr
= cur
->curframe
;
8173 if (old
->curframe
!= fr
)
8176 fold
= old
->frame
[fr
];
8177 fcur
= cur
->frame
[fr
];
8178 for (i
= 0; i
< MAX_BPF_REG
; i
++)
8179 if (memcmp(&fold
->regs
[i
], &fcur
->regs
[i
],
8180 offsetof(struct bpf_reg_state
, parent
)))
8186 static int is_state_visited(struct bpf_verifier_env
*env
, int insn_idx
)
8188 struct bpf_verifier_state_list
*new_sl
;
8189 struct bpf_verifier_state_list
*sl
, **pprev
;
8190 struct bpf_verifier_state
*cur
= env
->cur_state
, *new;
8191 int i
, j
, err
, states_cnt
= 0;
8192 bool add_new_state
= env
->test_state_freq
? true : false;
8194 cur
->last_insn_idx
= env
->prev_insn_idx
;
8195 if (!env
->insn_aux_data
[insn_idx
].prune_point
)
8196 /* this 'insn_idx' instruction wasn't marked, so we will not
8197 * be doing state search here
8201 /* bpf progs typically have pruning point every 4 instructions
8202 * http://vger.kernel.org/bpfconf2019.html#session-1
8203 * Do not add new state for future pruning if the verifier hasn't seen
8204 * at least 2 jumps and at least 8 instructions.
8205 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
8206 * In tests that amounts to up to 50% reduction into total verifier
8207 * memory consumption and 20% verifier time speedup.
8209 if (env
->jmps_processed
- env
->prev_jmps_processed
>= 2 &&
8210 env
->insn_processed
- env
->prev_insn_processed
>= 8)
8211 add_new_state
= true;
8213 pprev
= explored_state(env
, insn_idx
);
8216 clean_live_states(env
, insn_idx
, cur
);
8220 if (sl
->state
.insn_idx
!= insn_idx
)
8222 if (sl
->state
.branches
) {
8223 if (states_maybe_looping(&sl
->state
, cur
) &&
8224 states_equal(env
, &sl
->state
, cur
)) {
8225 verbose_linfo(env
, insn_idx
, "; ");
8226 verbose(env
, "infinite loop detected at insn %d\n", insn_idx
);
8229 /* if the verifier is processing a loop, avoid adding new state
8230 * too often, since different loop iterations have distinct
8231 * states and may not help future pruning.
8232 * This threshold shouldn't be too low to make sure that
8233 * a loop with large bound will be rejected quickly.
8234 * The most abusive loop will be:
8236 * if r1 < 1000000 goto pc-2
8237 * 1M insn_procssed limit / 100 == 10k peak states.
8238 * This threshold shouldn't be too high either, since states
8239 * at the end of the loop are likely to be useful in pruning.
8241 if (env
->jmps_processed
- env
->prev_jmps_processed
< 20 &&
8242 env
->insn_processed
- env
->prev_insn_processed
< 100)
8243 add_new_state
= false;
8246 if (states_equal(env
, &sl
->state
, cur
)) {
8248 /* reached equivalent register/stack state,
8250 * Registers read by the continuation are read by us.
8251 * If we have any write marks in env->cur_state, they
8252 * will prevent corresponding reads in the continuation
8253 * from reaching our parent (an explored_state). Our
8254 * own state will get the read marks recorded, but
8255 * they'll be immediately forgotten as we're pruning
8256 * this state and will pop a new one.
8258 err
= propagate_liveness(env
, &sl
->state
, cur
);
8260 /* if previous state reached the exit with precision and
8261 * current state is equivalent to it (except precsion marks)
8262 * the precision needs to be propagated back in
8263 * the current state.
8265 err
= err
? : push_jmp_history(env
, cur
);
8266 err
= err
? : propagate_precision(env
, &sl
->state
);
8272 /* when new state is not going to be added do not increase miss count.
8273 * Otherwise several loop iterations will remove the state
8274 * recorded earlier. The goal of these heuristics is to have
8275 * states from some iterations of the loop (some in the beginning
8276 * and some at the end) to help pruning.
8280 /* heuristic to determine whether this state is beneficial
8281 * to keep checking from state equivalence point of view.
8282 * Higher numbers increase max_states_per_insn and verification time,
8283 * but do not meaningfully decrease insn_processed.
8285 if (sl
->miss_cnt
> sl
->hit_cnt
* 3 + 3) {
8286 /* the state is unlikely to be useful. Remove it to
8287 * speed up verification
8290 if (sl
->state
.frame
[0]->regs
[0].live
& REG_LIVE_DONE
) {
8291 u32 br
= sl
->state
.branches
;
8294 "BUG live_done but branches_to_explore %d\n",
8296 free_verifier_state(&sl
->state
, false);
8300 /* cannot free this state, since parentage chain may
8301 * walk it later. Add it for free_list instead to
8302 * be freed at the end of verification
8304 sl
->next
= env
->free_list
;
8305 env
->free_list
= sl
;
8315 if (env
->max_states_per_insn
< states_cnt
)
8316 env
->max_states_per_insn
= states_cnt
;
8318 if (!env
->allow_ptr_leaks
&& states_cnt
> BPF_COMPLEXITY_LIMIT_STATES
)
8319 return push_jmp_history(env
, cur
);
8322 return push_jmp_history(env
, cur
);
8324 /* There were no equivalent states, remember the current one.
8325 * Technically the current state is not proven to be safe yet,
8326 * but it will either reach outer most bpf_exit (which means it's safe)
8327 * or it will be rejected. When there are no loops the verifier won't be
8328 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
8329 * again on the way to bpf_exit.
8330 * When looping the sl->state.branches will be > 0 and this state
8331 * will not be considered for equivalence until branches == 0.
8333 new_sl
= kzalloc(sizeof(struct bpf_verifier_state_list
), GFP_KERNEL
);
8336 env
->total_states
++;
8338 env
->prev_jmps_processed
= env
->jmps_processed
;
8339 env
->prev_insn_processed
= env
->insn_processed
;
8341 /* add new state to the head of linked list */
8342 new = &new_sl
->state
;
8343 err
= copy_verifier_state(new, cur
);
8345 free_verifier_state(new, false);
8349 new->insn_idx
= insn_idx
;
8350 WARN_ONCE(new->branches
!= 1,
8351 "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches
, insn_idx
);
8354 cur
->first_insn_idx
= insn_idx
;
8355 clear_jmp_history(cur
);
8356 new_sl
->next
= *explored_state(env
, insn_idx
);
8357 *explored_state(env
, insn_idx
) = new_sl
;
8358 /* connect new state to parentage chain. Current frame needs all
8359 * registers connected. Only r6 - r9 of the callers are alive (pushed
8360 * to the stack implicitly by JITs) so in callers' frames connect just
8361 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
8362 * the state of the call instruction (with WRITTEN set), and r0 comes
8363 * from callee with its full parentage chain, anyway.
8365 /* clear write marks in current state: the writes we did are not writes
8366 * our child did, so they don't screen off its reads from us.
8367 * (There are no read marks in current state, because reads always mark
8368 * their parent and current state never has children yet. Only
8369 * explored_states can get read marks.)
8371 for (j
= 0; j
<= cur
->curframe
; j
++) {
8372 for (i
= j
< cur
->curframe
? BPF_REG_6
: 0; i
< BPF_REG_FP
; i
++)
8373 cur
->frame
[j
]->regs
[i
].parent
= &new->frame
[j
]->regs
[i
];
8374 for (i
= 0; i
< BPF_REG_FP
; i
++)
8375 cur
->frame
[j
]->regs
[i
].live
= REG_LIVE_NONE
;
8378 /* all stack frames are accessible from callee, clear them all */
8379 for (j
= 0; j
<= cur
->curframe
; j
++) {
8380 struct bpf_func_state
*frame
= cur
->frame
[j
];
8381 struct bpf_func_state
*newframe
= new->frame
[j
];
8383 for (i
= 0; i
< frame
->allocated_stack
/ BPF_REG_SIZE
; i
++) {
8384 frame
->stack
[i
].spilled_ptr
.live
= REG_LIVE_NONE
;
8385 frame
->stack
[i
].spilled_ptr
.parent
=
8386 &newframe
->stack
[i
].spilled_ptr
;
8392 /* Return true if it's OK to have the same insn return a different type. */
8393 static bool reg_type_mismatch_ok(enum bpf_reg_type type
)
8398 case PTR_TO_SOCKET_OR_NULL
:
8399 case PTR_TO_SOCK_COMMON
:
8400 case PTR_TO_SOCK_COMMON_OR_NULL
:
8401 case PTR_TO_TCP_SOCK
:
8402 case PTR_TO_TCP_SOCK_OR_NULL
:
8403 case PTR_TO_XDP_SOCK
:
8411 /* If an instruction was previously used with particular pointer types, then we
8412 * need to be careful to avoid cases such as the below, where it may be ok
8413 * for one branch accessing the pointer, but not ok for the other branch:
8418 * R1 = some_other_valid_ptr;
8421 * R2 = *(u32 *)(R1 + 0);
8423 static bool reg_type_mismatch(enum bpf_reg_type src
, enum bpf_reg_type prev
)
8425 return src
!= prev
&& (!reg_type_mismatch_ok(src
) ||
8426 !reg_type_mismatch_ok(prev
));
8429 static int do_check(struct bpf_verifier_env
*env
)
8431 struct bpf_verifier_state
*state
= env
->cur_state
;
8432 struct bpf_insn
*insns
= env
->prog
->insnsi
;
8433 struct bpf_reg_state
*regs
;
8434 int insn_cnt
= env
->prog
->len
;
8435 bool do_print_state
= false;
8436 int prev_insn_idx
= -1;
8439 struct bpf_insn
*insn
;
8443 env
->prev_insn_idx
= prev_insn_idx
;
8444 if (env
->insn_idx
>= insn_cnt
) {
8445 verbose(env
, "invalid insn idx %d insn_cnt %d\n",
8446 env
->insn_idx
, insn_cnt
);
8450 insn
= &insns
[env
->insn_idx
];
8451 class = BPF_CLASS(insn
->code
);
8453 if (++env
->insn_processed
> BPF_COMPLEXITY_LIMIT_INSNS
) {
8455 "BPF program is too large. Processed %d insn\n",
8456 env
->insn_processed
);
8460 err
= is_state_visited(env
, env
->insn_idx
);
8464 /* found equivalent state, can prune the search */
8465 if (env
->log
.level
& BPF_LOG_LEVEL
) {
8467 verbose(env
, "\nfrom %d to %d%s: safe\n",
8468 env
->prev_insn_idx
, env
->insn_idx
,
8469 env
->cur_state
->speculative
?
8470 " (speculative execution)" : "");
8472 verbose(env
, "%d: safe\n", env
->insn_idx
);
8474 goto process_bpf_exit
;
8477 if (signal_pending(current
))
8483 if (env
->log
.level
& BPF_LOG_LEVEL2
||
8484 (env
->log
.level
& BPF_LOG_LEVEL
&& do_print_state
)) {
8485 if (env
->log
.level
& BPF_LOG_LEVEL2
)
8486 verbose(env
, "%d:", env
->insn_idx
);
8488 verbose(env
, "\nfrom %d to %d%s:",
8489 env
->prev_insn_idx
, env
->insn_idx
,
8490 env
->cur_state
->speculative
?
8491 " (speculative execution)" : "");
8492 print_verifier_state(env
, state
->frame
[state
->curframe
]);
8493 do_print_state
= false;
8496 if (env
->log
.level
& BPF_LOG_LEVEL
) {
8497 const struct bpf_insn_cbs cbs
= {
8498 .cb_print
= verbose
,
8499 .private_data
= env
,
8502 verbose_linfo(env
, env
->insn_idx
, "; ");
8503 verbose(env
, "%d: ", env
->insn_idx
);
8504 print_bpf_insn(&cbs
, insn
, env
->allow_ptr_leaks
);
8507 if (bpf_prog_is_dev_bound(env
->prog
->aux
)) {
8508 err
= bpf_prog_offload_verify_insn(env
, env
->insn_idx
,
8509 env
->prev_insn_idx
);
8514 regs
= cur_regs(env
);
8515 env
->insn_aux_data
[env
->insn_idx
].seen
= env
->pass_cnt
;
8516 prev_insn_idx
= env
->insn_idx
;
8518 if (class == BPF_ALU
|| class == BPF_ALU64
) {
8519 err
= check_alu_op(env
, insn
);
8523 } else if (class == BPF_LDX
) {
8524 enum bpf_reg_type
*prev_src_type
, src_reg_type
;
8526 /* check for reserved fields is already done */
8528 /* check src operand */
8529 err
= check_reg_arg(env
, insn
->src_reg
, SRC_OP
);
8533 err
= check_reg_arg(env
, insn
->dst_reg
, DST_OP_NO_MARK
);
8537 src_reg_type
= regs
[insn
->src_reg
].type
;
8539 /* check that memory (src_reg + off) is readable,
8540 * the state of dst_reg will be updated by this func
8542 err
= check_mem_access(env
, env
->insn_idx
, insn
->src_reg
,
8543 insn
->off
, BPF_SIZE(insn
->code
),
8544 BPF_READ
, insn
->dst_reg
, false);
8548 prev_src_type
= &env
->insn_aux_data
[env
->insn_idx
].ptr_type
;
8550 if (*prev_src_type
== NOT_INIT
) {
8552 * dst_reg = *(u32 *)(src_reg + off)
8553 * save type to validate intersecting paths
8555 *prev_src_type
= src_reg_type
;
8557 } else if (reg_type_mismatch(src_reg_type
, *prev_src_type
)) {
8558 /* ABuser program is trying to use the same insn
8559 * dst_reg = *(u32*) (src_reg + off)
8560 * with different pointer types:
8561 * src_reg == ctx in one branch and
8562 * src_reg == stack|map in some other branch.
8565 verbose(env
, "same insn cannot be used with different pointers\n");
8569 } else if (class == BPF_STX
) {
8570 enum bpf_reg_type
*prev_dst_type
, dst_reg_type
;
8572 if (BPF_MODE(insn
->code
) == BPF_XADD
) {
8573 err
= check_xadd(env
, env
->insn_idx
, insn
);
8580 /* check src1 operand */
8581 err
= check_reg_arg(env
, insn
->src_reg
, SRC_OP
);
8584 /* check src2 operand */
8585 err
= check_reg_arg(env
, insn
->dst_reg
, SRC_OP
);
8589 dst_reg_type
= regs
[insn
->dst_reg
].type
;
8591 /* check that memory (dst_reg + off) is writeable */
8592 err
= check_mem_access(env
, env
->insn_idx
, insn
->dst_reg
,
8593 insn
->off
, BPF_SIZE(insn
->code
),
8594 BPF_WRITE
, insn
->src_reg
, false);
8598 prev_dst_type
= &env
->insn_aux_data
[env
->insn_idx
].ptr_type
;
8600 if (*prev_dst_type
== NOT_INIT
) {
8601 *prev_dst_type
= dst_reg_type
;
8602 } else if (reg_type_mismatch(dst_reg_type
, *prev_dst_type
)) {
8603 verbose(env
, "same insn cannot be used with different pointers\n");
8607 } else if (class == BPF_ST
) {
8608 if (BPF_MODE(insn
->code
) != BPF_MEM
||
8609 insn
->src_reg
!= BPF_REG_0
) {
8610 verbose(env
, "BPF_ST uses reserved fields\n");
8613 /* check src operand */
8614 err
= check_reg_arg(env
, insn
->dst_reg
, SRC_OP
);
8618 if (is_ctx_reg(env
, insn
->dst_reg
)) {
8619 verbose(env
, "BPF_ST stores into R%d %s is not allowed\n",
8621 reg_type_str
[reg_state(env
, insn
->dst_reg
)->type
]);
8625 /* check that memory (dst_reg + off) is writeable */
8626 err
= check_mem_access(env
, env
->insn_idx
, insn
->dst_reg
,
8627 insn
->off
, BPF_SIZE(insn
->code
),
8628 BPF_WRITE
, -1, false);
8632 } else if (class == BPF_JMP
|| class == BPF_JMP32
) {
8633 u8 opcode
= BPF_OP(insn
->code
);
8635 env
->jmps_processed
++;
8636 if (opcode
== BPF_CALL
) {
8637 if (BPF_SRC(insn
->code
) != BPF_K
||
8639 (insn
->src_reg
!= BPF_REG_0
&&
8640 insn
->src_reg
!= BPF_PSEUDO_CALL
) ||
8641 insn
->dst_reg
!= BPF_REG_0
||
8642 class == BPF_JMP32
) {
8643 verbose(env
, "BPF_CALL uses reserved fields\n");
8647 if (env
->cur_state
->active_spin_lock
&&
8648 (insn
->src_reg
== BPF_PSEUDO_CALL
||
8649 insn
->imm
!= BPF_FUNC_spin_unlock
)) {
8650 verbose(env
, "function calls are not allowed while holding a lock\n");
8653 if (insn
->src_reg
== BPF_PSEUDO_CALL
)
8654 err
= check_func_call(env
, insn
, &env
->insn_idx
);
8656 err
= check_helper_call(env
, insn
->imm
, env
->insn_idx
);
8660 } else if (opcode
== BPF_JA
) {
8661 if (BPF_SRC(insn
->code
) != BPF_K
||
8663 insn
->src_reg
!= BPF_REG_0
||
8664 insn
->dst_reg
!= BPF_REG_0
||
8665 class == BPF_JMP32
) {
8666 verbose(env
, "BPF_JA uses reserved fields\n");
8670 env
->insn_idx
+= insn
->off
+ 1;
8673 } else if (opcode
== BPF_EXIT
) {
8674 if (BPF_SRC(insn
->code
) != BPF_K
||
8676 insn
->src_reg
!= BPF_REG_0
||
8677 insn
->dst_reg
!= BPF_REG_0
||
8678 class == BPF_JMP32
) {
8679 verbose(env
, "BPF_EXIT uses reserved fields\n");
8683 if (env
->cur_state
->active_spin_lock
) {
8684 verbose(env
, "bpf_spin_unlock is missing\n");
8688 if (state
->curframe
) {
8689 /* exit from nested function */
8690 err
= prepare_func_exit(env
, &env
->insn_idx
);
8693 do_print_state
= true;
8697 err
= check_reference_leak(env
);
8701 err
= check_return_code(env
);
8705 update_branch_counts(env
, env
->cur_state
);
8706 err
= pop_stack(env
, &prev_insn_idx
,
8713 do_print_state
= true;
8717 err
= check_cond_jmp_op(env
, insn
, &env
->insn_idx
);
8721 } else if (class == BPF_LD
) {
8722 u8 mode
= BPF_MODE(insn
->code
);
8724 if (mode
== BPF_ABS
|| mode
== BPF_IND
) {
8725 err
= check_ld_abs(env
, insn
);
8729 } else if (mode
== BPF_IMM
) {
8730 err
= check_ld_imm(env
, insn
);
8735 env
->insn_aux_data
[env
->insn_idx
].seen
= env
->pass_cnt
;
8737 verbose(env
, "invalid BPF_LD mode\n");
8741 verbose(env
, "unknown insn class %d\n", class);
8751 static int check_map_prealloc(struct bpf_map
*map
)
8753 return (map
->map_type
!= BPF_MAP_TYPE_HASH
&&
8754 map
->map_type
!= BPF_MAP_TYPE_PERCPU_HASH
&&
8755 map
->map_type
!= BPF_MAP_TYPE_HASH_OF_MAPS
) ||
8756 !(map
->map_flags
& BPF_F_NO_PREALLOC
);
8759 static bool is_tracing_prog_type(enum bpf_prog_type type
)
8762 case BPF_PROG_TYPE_KPROBE
:
8763 case BPF_PROG_TYPE_TRACEPOINT
:
8764 case BPF_PROG_TYPE_PERF_EVENT
:
8765 case BPF_PROG_TYPE_RAW_TRACEPOINT
:
8772 static bool is_preallocated_map(struct bpf_map
*map
)
8774 if (!check_map_prealloc(map
))
8776 if (map
->inner_map_meta
&& !check_map_prealloc(map
->inner_map_meta
))
8781 static int check_map_prog_compatibility(struct bpf_verifier_env
*env
,
8782 struct bpf_map
*map
,
8783 struct bpf_prog
*prog
)
8787 * Validate that trace type programs use preallocated hash maps.
8789 * For programs attached to PERF events this is mandatory as the
8790 * perf NMI can hit any arbitrary code sequence.
8792 * All other trace types using preallocated hash maps are unsafe as
8793 * well because tracepoint or kprobes can be inside locked regions
8794 * of the memory allocator or at a place where a recursion into the
8795 * memory allocator would see inconsistent state.
8797 * On RT enabled kernels run-time allocation of all trace type
8798 * programs is strictly prohibited due to lock type constraints. On
8799 * !RT kernels it is allowed for backwards compatibility reasons for
8800 * now, but warnings are emitted so developers are made aware of
8801 * the unsafety and can fix their programs before this is enforced.
8803 if (is_tracing_prog_type(prog
->type
) && !is_preallocated_map(map
)) {
8804 if (prog
->type
== BPF_PROG_TYPE_PERF_EVENT
) {
8805 verbose(env
, "perf_event programs can only use preallocated hash map\n");
8808 if (IS_ENABLED(CONFIG_PREEMPT_RT
)) {
8809 verbose(env
, "trace type programs can only use preallocated hash map\n");
8812 WARN_ONCE(1, "trace type BPF program uses run-time allocation\n");
8813 verbose(env
, "trace type programs with run-time allocated hash maps are unsafe. Switch to preallocated hash maps.\n");
8816 if ((is_tracing_prog_type(prog
->type
) ||
8817 prog
->type
== BPF_PROG_TYPE_SOCKET_FILTER
) &&
8818 map_value_has_spin_lock(map
)) {
8819 verbose(env
, "tracing progs cannot use bpf_spin_lock yet\n");
8823 if ((bpf_prog_is_dev_bound(prog
->aux
) || bpf_map_is_dev_bound(map
)) &&
8824 !bpf_offload_prog_map_match(prog
, map
)) {
8825 verbose(env
, "offload device mismatch between prog and map\n");
8829 if (map
->map_type
== BPF_MAP_TYPE_STRUCT_OPS
) {
8830 verbose(env
, "bpf_struct_ops map cannot be used in prog\n");
8837 static bool bpf_map_is_cgroup_storage(struct bpf_map
*map
)
8839 return (map
->map_type
== BPF_MAP_TYPE_CGROUP_STORAGE
||
8840 map
->map_type
== BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE
);
8843 /* look for pseudo eBPF instructions that access map FDs and
8844 * replace them with actual map pointers
8846 static int replace_map_fd_with_map_ptr(struct bpf_verifier_env
*env
)
8848 struct bpf_insn
*insn
= env
->prog
->insnsi
;
8849 int insn_cnt
= env
->prog
->len
;
8852 err
= bpf_prog_calc_tag(env
->prog
);
8856 for (i
= 0; i
< insn_cnt
; i
++, insn
++) {
8857 if (BPF_CLASS(insn
->code
) == BPF_LDX
&&
8858 (BPF_MODE(insn
->code
) != BPF_MEM
|| insn
->imm
!= 0)) {
8859 verbose(env
, "BPF_LDX uses reserved fields\n");
8863 if (BPF_CLASS(insn
->code
) == BPF_STX
&&
8864 ((BPF_MODE(insn
->code
) != BPF_MEM
&&
8865 BPF_MODE(insn
->code
) != BPF_XADD
) || insn
->imm
!= 0)) {
8866 verbose(env
, "BPF_STX uses reserved fields\n");
8870 if (insn
[0].code
== (BPF_LD
| BPF_IMM
| BPF_DW
)) {
8871 struct bpf_insn_aux_data
*aux
;
8872 struct bpf_map
*map
;
8876 if (i
== insn_cnt
- 1 || insn
[1].code
!= 0 ||
8877 insn
[1].dst_reg
!= 0 || insn
[1].src_reg
!= 0 ||
8879 verbose(env
, "invalid bpf_ld_imm64 insn\n");
8883 if (insn
[0].src_reg
== 0)
8884 /* valid generic load 64-bit imm */
8887 /* In final convert_pseudo_ld_imm64() step, this is
8888 * converted into regular 64-bit imm load insn.
8890 if ((insn
[0].src_reg
!= BPF_PSEUDO_MAP_FD
&&
8891 insn
[0].src_reg
!= BPF_PSEUDO_MAP_VALUE
) ||
8892 (insn
[0].src_reg
== BPF_PSEUDO_MAP_FD
&&
8893 insn
[1].imm
!= 0)) {
8895 "unrecognized bpf_ld_imm64 insn\n");
8899 f
= fdget(insn
[0].imm
);
8900 map
= __bpf_map_get(f
);
8902 verbose(env
, "fd %d is not pointing to valid bpf_map\n",
8904 return PTR_ERR(map
);
8907 err
= check_map_prog_compatibility(env
, map
, env
->prog
);
8913 aux
= &env
->insn_aux_data
[i
];
8914 if (insn
->src_reg
== BPF_PSEUDO_MAP_FD
) {
8915 addr
= (unsigned long)map
;
8917 u32 off
= insn
[1].imm
;
8919 if (off
>= BPF_MAX_VAR_OFF
) {
8920 verbose(env
, "direct value offset of %u is not allowed\n", off
);
8925 if (!map
->ops
->map_direct_value_addr
) {
8926 verbose(env
, "no direct value access support for this map type\n");
8931 err
= map
->ops
->map_direct_value_addr(map
, &addr
, off
);
8933 verbose(env
, "invalid access to map value pointer, value_size=%u off=%u\n",
8934 map
->value_size
, off
);
8943 insn
[0].imm
= (u32
)addr
;
8944 insn
[1].imm
= addr
>> 32;
8946 /* check whether we recorded this map already */
8947 for (j
= 0; j
< env
->used_map_cnt
; j
++) {
8948 if (env
->used_maps
[j
] == map
) {
8955 if (env
->used_map_cnt
>= MAX_USED_MAPS
) {
8960 /* hold the map. If the program is rejected by verifier,
8961 * the map will be released by release_maps() or it
8962 * will be used by the valid program until it's unloaded
8963 * and all maps are released in free_used_maps()
8967 aux
->map_index
= env
->used_map_cnt
;
8968 env
->used_maps
[env
->used_map_cnt
++] = map
;
8970 if (bpf_map_is_cgroup_storage(map
) &&
8971 bpf_cgroup_storage_assign(env
->prog
->aux
, map
)) {
8972 verbose(env
, "only one cgroup storage of each type is allowed\n");
8984 /* Basic sanity check before we invest more work here. */
8985 if (!bpf_opcode_in_insntable(insn
->code
)) {
8986 verbose(env
, "unknown opcode %02x\n", insn
->code
);
8991 /* now all pseudo BPF_LD_IMM64 instructions load valid
8992 * 'struct bpf_map *' into a register instead of user map_fd.
8993 * These pointers will be used later by verifier to validate map access.
8998 /* drop refcnt of maps used by the rejected program */
8999 static void release_maps(struct bpf_verifier_env
*env
)
9001 __bpf_free_used_maps(env
->prog
->aux
, env
->used_maps
,
9005 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
9006 static void convert_pseudo_ld_imm64(struct bpf_verifier_env
*env
)
9008 struct bpf_insn
*insn
= env
->prog
->insnsi
;
9009 int insn_cnt
= env
->prog
->len
;
9012 for (i
= 0; i
< insn_cnt
; i
++, insn
++)
9013 if (insn
->code
== (BPF_LD
| BPF_IMM
| BPF_DW
))
9017 /* single env->prog->insni[off] instruction was replaced with the range
9018 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying
9019 * [0, off) and [off, end) to new locations, so the patched range stays zero
9021 static int adjust_insn_aux_data(struct bpf_verifier_env
*env
,
9022 struct bpf_prog
*new_prog
, u32 off
, u32 cnt
)
9024 struct bpf_insn_aux_data
*new_data
, *old_data
= env
->insn_aux_data
;
9025 struct bpf_insn
*insn
= new_prog
->insnsi
;
9029 /* aux info at OFF always needs adjustment, no matter fast path
9030 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
9031 * original insn at old prog.
9033 old_data
[off
].zext_dst
= insn_has_def32(env
, insn
+ off
+ cnt
- 1);
9037 prog_len
= new_prog
->len
;
9038 new_data
= vzalloc(array_size(prog_len
,
9039 sizeof(struct bpf_insn_aux_data
)));
9042 memcpy(new_data
, old_data
, sizeof(struct bpf_insn_aux_data
) * off
);
9043 memcpy(new_data
+ off
+ cnt
- 1, old_data
+ off
,
9044 sizeof(struct bpf_insn_aux_data
) * (prog_len
- off
- cnt
+ 1));
9045 for (i
= off
; i
< off
+ cnt
- 1; i
++) {
9046 new_data
[i
].seen
= env
->pass_cnt
;
9047 new_data
[i
].zext_dst
= insn_has_def32(env
, insn
+ i
);
9049 env
->insn_aux_data
= new_data
;
9054 static void adjust_subprog_starts(struct bpf_verifier_env
*env
, u32 off
, u32 len
)
9060 /* NOTE: fake 'exit' subprog should be updated as well. */
9061 for (i
= 0; i
<= env
->subprog_cnt
; i
++) {
9062 if (env
->subprog_info
[i
].start
<= off
)
9064 env
->subprog_info
[i
].start
+= len
- 1;
9068 static struct bpf_prog
*bpf_patch_insn_data(struct bpf_verifier_env
*env
, u32 off
,
9069 const struct bpf_insn
*patch
, u32 len
)
9071 struct bpf_prog
*new_prog
;
9073 new_prog
= bpf_patch_insn_single(env
->prog
, off
, patch
, len
);
9074 if (IS_ERR(new_prog
)) {
9075 if (PTR_ERR(new_prog
) == -ERANGE
)
9077 "insn %d cannot be patched due to 16-bit range\n",
9078 env
->insn_aux_data
[off
].orig_idx
);
9081 if (adjust_insn_aux_data(env
, new_prog
, off
, len
))
9083 adjust_subprog_starts(env
, off
, len
);
9087 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env
*env
,
9092 /* find first prog starting at or after off (first to remove) */
9093 for (i
= 0; i
< env
->subprog_cnt
; i
++)
9094 if (env
->subprog_info
[i
].start
>= off
)
9096 /* find first prog starting at or after off + cnt (first to stay) */
9097 for (j
= i
; j
< env
->subprog_cnt
; j
++)
9098 if (env
->subprog_info
[j
].start
>= off
+ cnt
)
9100 /* if j doesn't start exactly at off + cnt, we are just removing
9101 * the front of previous prog
9103 if (env
->subprog_info
[j
].start
!= off
+ cnt
)
9107 struct bpf_prog_aux
*aux
= env
->prog
->aux
;
9110 /* move fake 'exit' subprog as well */
9111 move
= env
->subprog_cnt
+ 1 - j
;
9113 memmove(env
->subprog_info
+ i
,
9114 env
->subprog_info
+ j
,
9115 sizeof(*env
->subprog_info
) * move
);
9116 env
->subprog_cnt
-= j
- i
;
9118 /* remove func_info */
9119 if (aux
->func_info
) {
9120 move
= aux
->func_info_cnt
- j
;
9122 memmove(aux
->func_info
+ i
,
9124 sizeof(*aux
->func_info
) * move
);
9125 aux
->func_info_cnt
-= j
- i
;
9126 /* func_info->insn_off is set after all code rewrites,
9127 * in adjust_btf_func() - no need to adjust
9131 /* convert i from "first prog to remove" to "first to adjust" */
9132 if (env
->subprog_info
[i
].start
== off
)
9136 /* update fake 'exit' subprog as well */
9137 for (; i
<= env
->subprog_cnt
; i
++)
9138 env
->subprog_info
[i
].start
-= cnt
;
9143 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env
*env
, u32 off
,
9146 struct bpf_prog
*prog
= env
->prog
;
9147 u32 i
, l_off
, l_cnt
, nr_linfo
;
9148 struct bpf_line_info
*linfo
;
9150 nr_linfo
= prog
->aux
->nr_linfo
;
9154 linfo
= prog
->aux
->linfo
;
9156 /* find first line info to remove, count lines to be removed */
9157 for (i
= 0; i
< nr_linfo
; i
++)
9158 if (linfo
[i
].insn_off
>= off
)
9163 for (; i
< nr_linfo
; i
++)
9164 if (linfo
[i
].insn_off
< off
+ cnt
)
9169 /* First live insn doesn't match first live linfo, it needs to "inherit"
9170 * last removed linfo. prog is already modified, so prog->len == off
9171 * means no live instructions after (tail of the program was removed).
9173 if (prog
->len
!= off
&& l_cnt
&&
9174 (i
== nr_linfo
|| linfo
[i
].insn_off
!= off
+ cnt
)) {
9176 linfo
[--i
].insn_off
= off
+ cnt
;
9179 /* remove the line info which refer to the removed instructions */
9181 memmove(linfo
+ l_off
, linfo
+ i
,
9182 sizeof(*linfo
) * (nr_linfo
- i
));
9184 prog
->aux
->nr_linfo
-= l_cnt
;
9185 nr_linfo
= prog
->aux
->nr_linfo
;
9188 /* pull all linfo[i].insn_off >= off + cnt in by cnt */
9189 for (i
= l_off
; i
< nr_linfo
; i
++)
9190 linfo
[i
].insn_off
-= cnt
;
9192 /* fix up all subprogs (incl. 'exit') which start >= off */
9193 for (i
= 0; i
<= env
->subprog_cnt
; i
++)
9194 if (env
->subprog_info
[i
].linfo_idx
> l_off
) {
9195 /* program may have started in the removed region but
9196 * may not be fully removed
9198 if (env
->subprog_info
[i
].linfo_idx
>= l_off
+ l_cnt
)
9199 env
->subprog_info
[i
].linfo_idx
-= l_cnt
;
9201 env
->subprog_info
[i
].linfo_idx
= l_off
;
9207 static int verifier_remove_insns(struct bpf_verifier_env
*env
, u32 off
, u32 cnt
)
9209 struct bpf_insn_aux_data
*aux_data
= env
->insn_aux_data
;
9210 unsigned int orig_prog_len
= env
->prog
->len
;
9213 if (bpf_prog_is_dev_bound(env
->prog
->aux
))
9214 bpf_prog_offload_remove_insns(env
, off
, cnt
);
9216 err
= bpf_remove_insns(env
->prog
, off
, cnt
);
9220 err
= adjust_subprog_starts_after_remove(env
, off
, cnt
);
9224 err
= bpf_adj_linfo_after_remove(env
, off
, cnt
);
9228 memmove(aux_data
+ off
, aux_data
+ off
+ cnt
,
9229 sizeof(*aux_data
) * (orig_prog_len
- off
- cnt
));
9234 /* The verifier does more data flow analysis than llvm and will not
9235 * explore branches that are dead at run time. Malicious programs can
9236 * have dead code too. Therefore replace all dead at-run-time code
9239 * Just nops are not optimal, e.g. if they would sit at the end of the
9240 * program and through another bug we would manage to jump there, then
9241 * we'd execute beyond program memory otherwise. Returning exception
9242 * code also wouldn't work since we can have subprogs where the dead
9243 * code could be located.
9245 static void sanitize_dead_code(struct bpf_verifier_env
*env
)
9247 struct bpf_insn_aux_data
*aux_data
= env
->insn_aux_data
;
9248 struct bpf_insn trap
= BPF_JMP_IMM(BPF_JA
, 0, 0, -1);
9249 struct bpf_insn
*insn
= env
->prog
->insnsi
;
9250 const int insn_cnt
= env
->prog
->len
;
9253 for (i
= 0; i
< insn_cnt
; i
++) {
9254 if (aux_data
[i
].seen
)
9256 memcpy(insn
+ i
, &trap
, sizeof(trap
));
9260 static bool insn_is_cond_jump(u8 code
)
9264 if (BPF_CLASS(code
) == BPF_JMP32
)
9267 if (BPF_CLASS(code
) != BPF_JMP
)
9271 return op
!= BPF_JA
&& op
!= BPF_EXIT
&& op
!= BPF_CALL
;
9274 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env
*env
)
9276 struct bpf_insn_aux_data
*aux_data
= env
->insn_aux_data
;
9277 struct bpf_insn ja
= BPF_JMP_IMM(BPF_JA
, 0, 0, 0);
9278 struct bpf_insn
*insn
= env
->prog
->insnsi
;
9279 const int insn_cnt
= env
->prog
->len
;
9282 for (i
= 0; i
< insn_cnt
; i
++, insn
++) {
9283 if (!insn_is_cond_jump(insn
->code
))
9286 if (!aux_data
[i
+ 1].seen
)
9288 else if (!aux_data
[i
+ 1 + insn
->off
].seen
)
9293 if (bpf_prog_is_dev_bound(env
->prog
->aux
))
9294 bpf_prog_offload_replace_insn(env
, i
, &ja
);
9296 memcpy(insn
, &ja
, sizeof(ja
));
9300 static int opt_remove_dead_code(struct bpf_verifier_env
*env
)
9302 struct bpf_insn_aux_data
*aux_data
= env
->insn_aux_data
;
9303 int insn_cnt
= env
->prog
->len
;
9306 for (i
= 0; i
< insn_cnt
; i
++) {
9310 while (i
+ j
< insn_cnt
&& !aux_data
[i
+ j
].seen
)
9315 err
= verifier_remove_insns(env
, i
, j
);
9318 insn_cnt
= env
->prog
->len
;
9324 static int opt_remove_nops(struct bpf_verifier_env
*env
)
9326 const struct bpf_insn ja
= BPF_JMP_IMM(BPF_JA
, 0, 0, 0);
9327 struct bpf_insn
*insn
= env
->prog
->insnsi
;
9328 int insn_cnt
= env
->prog
->len
;
9331 for (i
= 0; i
< insn_cnt
; i
++) {
9332 if (memcmp(&insn
[i
], &ja
, sizeof(ja
)))
9335 err
= verifier_remove_insns(env
, i
, 1);
9345 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env
*env
,
9346 const union bpf_attr
*attr
)
9348 struct bpf_insn
*patch
, zext_patch
[2], rnd_hi32_patch
[4];
9349 struct bpf_insn_aux_data
*aux
= env
->insn_aux_data
;
9350 int i
, patch_len
, delta
= 0, len
= env
->prog
->len
;
9351 struct bpf_insn
*insns
= env
->prog
->insnsi
;
9352 struct bpf_prog
*new_prog
;
9355 rnd_hi32
= attr
->prog_flags
& BPF_F_TEST_RND_HI32
;
9356 zext_patch
[1] = BPF_ZEXT_REG(0);
9357 rnd_hi32_patch
[1] = BPF_ALU64_IMM(BPF_MOV
, BPF_REG_AX
, 0);
9358 rnd_hi32_patch
[2] = BPF_ALU64_IMM(BPF_LSH
, BPF_REG_AX
, 32);
9359 rnd_hi32_patch
[3] = BPF_ALU64_REG(BPF_OR
, 0, BPF_REG_AX
);
9360 for (i
= 0; i
< len
; i
++) {
9361 int adj_idx
= i
+ delta
;
9362 struct bpf_insn insn
;
9364 insn
= insns
[adj_idx
];
9365 if (!aux
[adj_idx
].zext_dst
) {
9373 class = BPF_CLASS(code
);
9374 if (insn_no_def(&insn
))
9377 /* NOTE: arg "reg" (the fourth one) is only used for
9378 * BPF_STX which has been ruled out in above
9379 * check, it is safe to pass NULL here.
9381 if (is_reg64(env
, &insn
, insn
.dst_reg
, NULL
, DST_OP
)) {
9382 if (class == BPF_LD
&&
9383 BPF_MODE(code
) == BPF_IMM
)
9388 /* ctx load could be transformed into wider load. */
9389 if (class == BPF_LDX
&&
9390 aux
[adj_idx
].ptr_type
== PTR_TO_CTX
)
9393 imm_rnd
= get_random_int();
9394 rnd_hi32_patch
[0] = insn
;
9395 rnd_hi32_patch
[1].imm
= imm_rnd
;
9396 rnd_hi32_patch
[3].dst_reg
= insn
.dst_reg
;
9397 patch
= rnd_hi32_patch
;
9399 goto apply_patch_buffer
;
9402 if (!bpf_jit_needs_zext())
9405 zext_patch
[0] = insn
;
9406 zext_patch
[1].dst_reg
= insn
.dst_reg
;
9407 zext_patch
[1].src_reg
= insn
.dst_reg
;
9411 new_prog
= bpf_patch_insn_data(env
, adj_idx
, patch
, patch_len
);
9414 env
->prog
= new_prog
;
9415 insns
= new_prog
->insnsi
;
9416 aux
= env
->insn_aux_data
;
9417 delta
+= patch_len
- 1;
9423 /* convert load instructions that access fields of a context type into a
9424 * sequence of instructions that access fields of the underlying structure:
9425 * struct __sk_buff -> struct sk_buff
9426 * struct bpf_sock_ops -> struct sock
9428 static int convert_ctx_accesses(struct bpf_verifier_env
*env
)
9430 const struct bpf_verifier_ops
*ops
= env
->ops
;
9431 int i
, cnt
, size
, ctx_field_size
, delta
= 0;
9432 const int insn_cnt
= env
->prog
->len
;
9433 struct bpf_insn insn_buf
[16], *insn
;
9434 u32 target_size
, size_default
, off
;
9435 struct bpf_prog
*new_prog
;
9436 enum bpf_access_type type
;
9437 bool is_narrower_load
;
9439 if (ops
->gen_prologue
|| env
->seen_direct_write
) {
9440 if (!ops
->gen_prologue
) {
9441 verbose(env
, "bpf verifier is misconfigured\n");
9444 cnt
= ops
->gen_prologue(insn_buf
, env
->seen_direct_write
,
9446 if (cnt
>= ARRAY_SIZE(insn_buf
)) {
9447 verbose(env
, "bpf verifier is misconfigured\n");
9450 new_prog
= bpf_patch_insn_data(env
, 0, insn_buf
, cnt
);
9454 env
->prog
= new_prog
;
9459 if (bpf_prog_is_dev_bound(env
->prog
->aux
))
9462 insn
= env
->prog
->insnsi
+ delta
;
9464 for (i
= 0; i
< insn_cnt
; i
++, insn
++) {
9465 bpf_convert_ctx_access_t convert_ctx_access
;
9467 if (insn
->code
== (BPF_LDX
| BPF_MEM
| BPF_B
) ||
9468 insn
->code
== (BPF_LDX
| BPF_MEM
| BPF_H
) ||
9469 insn
->code
== (BPF_LDX
| BPF_MEM
| BPF_W
) ||
9470 insn
->code
== (BPF_LDX
| BPF_MEM
| BPF_DW
))
9472 else if (insn
->code
== (BPF_STX
| BPF_MEM
| BPF_B
) ||
9473 insn
->code
== (BPF_STX
| BPF_MEM
| BPF_H
) ||
9474 insn
->code
== (BPF_STX
| BPF_MEM
| BPF_W
) ||
9475 insn
->code
== (BPF_STX
| BPF_MEM
| BPF_DW
))
9480 if (type
== BPF_WRITE
&&
9481 env
->insn_aux_data
[i
+ delta
].sanitize_stack_off
) {
9482 struct bpf_insn patch
[] = {
9483 /* Sanitize suspicious stack slot with zero.
9484 * There are no memory dependencies for this store,
9485 * since it's only using frame pointer and immediate
9488 BPF_ST_MEM(BPF_DW
, BPF_REG_FP
,
9489 env
->insn_aux_data
[i
+ delta
].sanitize_stack_off
,
9491 /* the original STX instruction will immediately
9492 * overwrite the same stack slot with appropriate value
9497 cnt
= ARRAY_SIZE(patch
);
9498 new_prog
= bpf_patch_insn_data(env
, i
+ delta
, patch
, cnt
);
9503 env
->prog
= new_prog
;
9504 insn
= new_prog
->insnsi
+ i
+ delta
;
9508 switch (env
->insn_aux_data
[i
+ delta
].ptr_type
) {
9510 if (!ops
->convert_ctx_access
)
9512 convert_ctx_access
= ops
->convert_ctx_access
;
9515 case PTR_TO_SOCK_COMMON
:
9516 convert_ctx_access
= bpf_sock_convert_ctx_access
;
9518 case PTR_TO_TCP_SOCK
:
9519 convert_ctx_access
= bpf_tcp_sock_convert_ctx_access
;
9521 case PTR_TO_XDP_SOCK
:
9522 convert_ctx_access
= bpf_xdp_sock_convert_ctx_access
;
9525 if (type
== BPF_READ
) {
9526 insn
->code
= BPF_LDX
| BPF_PROBE_MEM
|
9527 BPF_SIZE((insn
)->code
);
9528 env
->prog
->aux
->num_exentries
++;
9529 } else if (env
->prog
->type
!= BPF_PROG_TYPE_STRUCT_OPS
) {
9530 verbose(env
, "Writes through BTF pointers are not allowed\n");
9538 ctx_field_size
= env
->insn_aux_data
[i
+ delta
].ctx_field_size
;
9539 size
= BPF_LDST_BYTES(insn
);
9541 /* If the read access is a narrower load of the field,
9542 * convert to a 4/8-byte load, to minimum program type specific
9543 * convert_ctx_access changes. If conversion is successful,
9544 * we will apply proper mask to the result.
9546 is_narrower_load
= size
< ctx_field_size
;
9547 size_default
= bpf_ctx_off_adjust_machine(ctx_field_size
);
9549 if (is_narrower_load
) {
9552 if (type
== BPF_WRITE
) {
9553 verbose(env
, "bpf verifier narrow ctx access misconfigured\n");
9558 if (ctx_field_size
== 4)
9560 else if (ctx_field_size
== 8)
9563 insn
->off
= off
& ~(size_default
- 1);
9564 insn
->code
= BPF_LDX
| BPF_MEM
| size_code
;
9568 cnt
= convert_ctx_access(type
, insn
, insn_buf
, env
->prog
,
9570 if (cnt
== 0 || cnt
>= ARRAY_SIZE(insn_buf
) ||
9571 (ctx_field_size
&& !target_size
)) {
9572 verbose(env
, "bpf verifier is misconfigured\n");
9576 if (is_narrower_load
&& size
< target_size
) {
9577 u8 shift
= bpf_ctx_narrow_access_offset(
9578 off
, size
, size_default
) * 8;
9579 if (ctx_field_size
<= 4) {
9581 insn_buf
[cnt
++] = BPF_ALU32_IMM(BPF_RSH
,
9584 insn_buf
[cnt
++] = BPF_ALU32_IMM(BPF_AND
, insn
->dst_reg
,
9585 (1 << size
* 8) - 1);
9588 insn_buf
[cnt
++] = BPF_ALU64_IMM(BPF_RSH
,
9591 insn_buf
[cnt
++] = BPF_ALU64_IMM(BPF_AND
, insn
->dst_reg
,
9592 (1ULL << size
* 8) - 1);
9596 new_prog
= bpf_patch_insn_data(env
, i
+ delta
, insn_buf
, cnt
);
9602 /* keep walking new program and skip insns we just inserted */
9603 env
->prog
= new_prog
;
9604 insn
= new_prog
->insnsi
+ i
+ delta
;
9610 static int jit_subprogs(struct bpf_verifier_env
*env
)
9612 struct bpf_prog
*prog
= env
->prog
, **func
, *tmp
;
9613 int i
, j
, subprog_start
, subprog_end
= 0, len
, subprog
;
9614 struct bpf_insn
*insn
;
9618 if (env
->subprog_cnt
<= 1)
9621 for (i
= 0, insn
= prog
->insnsi
; i
< prog
->len
; i
++, insn
++) {
9622 if (insn
->code
!= (BPF_JMP
| BPF_CALL
) ||
9623 insn
->src_reg
!= BPF_PSEUDO_CALL
)
9625 /* Upon error here we cannot fall back to interpreter but
9626 * need a hard reject of the program. Thus -EFAULT is
9627 * propagated in any case.
9629 subprog
= find_subprog(env
, i
+ insn
->imm
+ 1);
9631 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
9635 /* temporarily remember subprog id inside insn instead of
9636 * aux_data, since next loop will split up all insns into funcs
9638 insn
->off
= subprog
;
9639 /* remember original imm in case JIT fails and fallback
9640 * to interpreter will be needed
9642 env
->insn_aux_data
[i
].call_imm
= insn
->imm
;
9643 /* point imm to __bpf_call_base+1 from JITs point of view */
9647 err
= bpf_prog_alloc_jited_linfo(prog
);
9652 func
= kcalloc(env
->subprog_cnt
, sizeof(prog
), GFP_KERNEL
);
9656 for (i
= 0; i
< env
->subprog_cnt
; i
++) {
9657 subprog_start
= subprog_end
;
9658 subprog_end
= env
->subprog_info
[i
+ 1].start
;
9660 len
= subprog_end
- subprog_start
;
9661 /* BPF_PROG_RUN doesn't call subprogs directly,
9662 * hence main prog stats include the runtime of subprogs.
9663 * subprogs don't have IDs and not reachable via prog_get_next_id
9664 * func[i]->aux->stats will never be accessed and stays NULL
9666 func
[i
] = bpf_prog_alloc_no_stats(bpf_prog_size(len
), GFP_USER
);
9669 memcpy(func
[i
]->insnsi
, &prog
->insnsi
[subprog_start
],
9670 len
* sizeof(struct bpf_insn
));
9671 func
[i
]->type
= prog
->type
;
9673 if (bpf_prog_calc_tag(func
[i
]))
9675 func
[i
]->is_func
= 1;
9676 func
[i
]->aux
->func_idx
= i
;
9677 /* the btf and func_info will be freed only at prog->aux */
9678 func
[i
]->aux
->btf
= prog
->aux
->btf
;
9679 func
[i
]->aux
->func_info
= prog
->aux
->func_info
;
9681 /* Use bpf_prog_F_tag to indicate functions in stack traces.
9682 * Long term would need debug info to populate names
9684 func
[i
]->aux
->name
[0] = 'F';
9685 func
[i
]->aux
->stack_depth
= env
->subprog_info
[i
].stack_depth
;
9686 func
[i
]->jit_requested
= 1;
9687 func
[i
]->aux
->linfo
= prog
->aux
->linfo
;
9688 func
[i
]->aux
->nr_linfo
= prog
->aux
->nr_linfo
;
9689 func
[i
]->aux
->jited_linfo
= prog
->aux
->jited_linfo
;
9690 func
[i
]->aux
->linfo_idx
= env
->subprog_info
[i
].linfo_idx
;
9691 func
[i
] = bpf_int_jit_compile(func
[i
]);
9692 if (!func
[i
]->jited
) {
9698 /* at this point all bpf functions were successfully JITed
9699 * now populate all bpf_calls with correct addresses and
9700 * run last pass of JIT
9702 for (i
= 0; i
< env
->subprog_cnt
; i
++) {
9703 insn
= func
[i
]->insnsi
;
9704 for (j
= 0; j
< func
[i
]->len
; j
++, insn
++) {
9705 if (insn
->code
!= (BPF_JMP
| BPF_CALL
) ||
9706 insn
->src_reg
!= BPF_PSEUDO_CALL
)
9708 subprog
= insn
->off
;
9709 insn
->imm
= BPF_CAST_CALL(func
[subprog
]->bpf_func
) -
9713 /* we use the aux data to keep a list of the start addresses
9714 * of the JITed images for each function in the program
9716 * for some architectures, such as powerpc64, the imm field
9717 * might not be large enough to hold the offset of the start
9718 * address of the callee's JITed image from __bpf_call_base
9720 * in such cases, we can lookup the start address of a callee
9721 * by using its subprog id, available from the off field of
9722 * the call instruction, as an index for this list
9724 func
[i
]->aux
->func
= func
;
9725 func
[i
]->aux
->func_cnt
= env
->subprog_cnt
;
9727 for (i
= 0; i
< env
->subprog_cnt
; i
++) {
9728 old_bpf_func
= func
[i
]->bpf_func
;
9729 tmp
= bpf_int_jit_compile(func
[i
]);
9730 if (tmp
!= func
[i
] || func
[i
]->bpf_func
!= old_bpf_func
) {
9731 verbose(env
, "JIT doesn't support bpf-to-bpf calls\n");
9738 /* finally lock prog and jit images for all functions and
9741 for (i
= 0; i
< env
->subprog_cnt
; i
++) {
9742 bpf_prog_lock_ro(func
[i
]);
9743 bpf_prog_kallsyms_add(func
[i
]);
9746 /* Last step: make now unused interpreter insns from main
9747 * prog consistent for later dump requests, so they can
9748 * later look the same as if they were interpreted only.
9750 for (i
= 0, insn
= prog
->insnsi
; i
< prog
->len
; i
++, insn
++) {
9751 if (insn
->code
!= (BPF_JMP
| BPF_CALL
) ||
9752 insn
->src_reg
!= BPF_PSEUDO_CALL
)
9754 insn
->off
= env
->insn_aux_data
[i
].call_imm
;
9755 subprog
= find_subprog(env
, i
+ insn
->off
+ 1);
9756 insn
->imm
= subprog
;
9760 prog
->bpf_func
= func
[0]->bpf_func
;
9761 prog
->aux
->func
= func
;
9762 prog
->aux
->func_cnt
= env
->subprog_cnt
;
9763 bpf_prog_free_unused_jited_linfo(prog
);
9766 for (i
= 0; i
< env
->subprog_cnt
; i
++)
9768 bpf_jit_free(func
[i
]);
9771 /* cleanup main prog to be interpreted */
9772 prog
->jit_requested
= 0;
9773 for (i
= 0, insn
= prog
->insnsi
; i
< prog
->len
; i
++, insn
++) {
9774 if (insn
->code
!= (BPF_JMP
| BPF_CALL
) ||
9775 insn
->src_reg
!= BPF_PSEUDO_CALL
)
9778 insn
->imm
= env
->insn_aux_data
[i
].call_imm
;
9780 bpf_prog_free_jited_linfo(prog
);
9784 static int fixup_call_args(struct bpf_verifier_env
*env
)
9786 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
9787 struct bpf_prog
*prog
= env
->prog
;
9788 struct bpf_insn
*insn
= prog
->insnsi
;
9793 if (env
->prog
->jit_requested
&&
9794 !bpf_prog_is_dev_bound(env
->prog
->aux
)) {
9795 err
= jit_subprogs(env
);
9801 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
9802 for (i
= 0; i
< prog
->len
; i
++, insn
++) {
9803 if (insn
->code
!= (BPF_JMP
| BPF_CALL
) ||
9804 insn
->src_reg
!= BPF_PSEUDO_CALL
)
9806 depth
= get_callee_stack_depth(env
, insn
, i
);
9809 bpf_patch_call_args(insn
, depth
);
9816 /* fixup insn->imm field of bpf_call instructions
9817 * and inline eligible helpers as explicit sequence of BPF instructions
9819 * this function is called after eBPF program passed verification
9821 static int fixup_bpf_calls(struct bpf_verifier_env
*env
)
9823 struct bpf_prog
*prog
= env
->prog
;
9824 bool expect_blinding
= bpf_jit_blinding_enabled(prog
);
9825 struct bpf_insn
*insn
= prog
->insnsi
;
9826 const struct bpf_func_proto
*fn
;
9827 const int insn_cnt
= prog
->len
;
9828 const struct bpf_map_ops
*ops
;
9829 struct bpf_insn_aux_data
*aux
;
9830 struct bpf_insn insn_buf
[16];
9831 struct bpf_prog
*new_prog
;
9832 struct bpf_map
*map_ptr
;
9833 int i
, ret
, cnt
, delta
= 0;
9835 for (i
= 0; i
< insn_cnt
; i
++, insn
++) {
9836 if (insn
->code
== (BPF_ALU64
| BPF_MOD
| BPF_X
) ||
9837 insn
->code
== (BPF_ALU64
| BPF_DIV
| BPF_X
) ||
9838 insn
->code
== (BPF_ALU
| BPF_MOD
| BPF_X
) ||
9839 insn
->code
== (BPF_ALU
| BPF_DIV
| BPF_X
)) {
9840 bool is64
= BPF_CLASS(insn
->code
) == BPF_ALU64
;
9841 struct bpf_insn mask_and_div
[] = {
9842 BPF_MOV32_REG(insn
->src_reg
, insn
->src_reg
),
9844 BPF_JMP_IMM(BPF_JNE
, insn
->src_reg
, 0, 2),
9845 BPF_ALU32_REG(BPF_XOR
, insn
->dst_reg
, insn
->dst_reg
),
9846 BPF_JMP_IMM(BPF_JA
, 0, 0, 1),
9849 struct bpf_insn mask_and_mod
[] = {
9850 BPF_MOV32_REG(insn
->src_reg
, insn
->src_reg
),
9851 /* Rx mod 0 -> Rx */
9852 BPF_JMP_IMM(BPF_JEQ
, insn
->src_reg
, 0, 1),
9855 struct bpf_insn
*patchlet
;
9857 if (insn
->code
== (BPF_ALU64
| BPF_DIV
| BPF_X
) ||
9858 insn
->code
== (BPF_ALU
| BPF_DIV
| BPF_X
)) {
9859 patchlet
= mask_and_div
+ (is64
? 1 : 0);
9860 cnt
= ARRAY_SIZE(mask_and_div
) - (is64
? 1 : 0);
9862 patchlet
= mask_and_mod
+ (is64
? 1 : 0);
9863 cnt
= ARRAY_SIZE(mask_and_mod
) - (is64
? 1 : 0);
9866 new_prog
= bpf_patch_insn_data(env
, i
+ delta
, patchlet
, cnt
);
9871 env
->prog
= prog
= new_prog
;
9872 insn
= new_prog
->insnsi
+ i
+ delta
;
9876 if (BPF_CLASS(insn
->code
) == BPF_LD
&&
9877 (BPF_MODE(insn
->code
) == BPF_ABS
||
9878 BPF_MODE(insn
->code
) == BPF_IND
)) {
9879 cnt
= env
->ops
->gen_ld_abs(insn
, insn_buf
);
9880 if (cnt
== 0 || cnt
>= ARRAY_SIZE(insn_buf
)) {
9881 verbose(env
, "bpf verifier is misconfigured\n");
9885 new_prog
= bpf_patch_insn_data(env
, i
+ delta
, insn_buf
, cnt
);
9890 env
->prog
= prog
= new_prog
;
9891 insn
= new_prog
->insnsi
+ i
+ delta
;
9895 if (insn
->code
== (BPF_ALU64
| BPF_ADD
| BPF_X
) ||
9896 insn
->code
== (BPF_ALU64
| BPF_SUB
| BPF_X
)) {
9897 const u8 code_add
= BPF_ALU64
| BPF_ADD
| BPF_X
;
9898 const u8 code_sub
= BPF_ALU64
| BPF_SUB
| BPF_X
;
9899 struct bpf_insn insn_buf
[16];
9900 struct bpf_insn
*patch
= &insn_buf
[0];
9904 aux
= &env
->insn_aux_data
[i
+ delta
];
9905 if (!aux
->alu_state
||
9906 aux
->alu_state
== BPF_ALU_NON_POINTER
)
9909 isneg
= aux
->alu_state
& BPF_ALU_NEG_VALUE
;
9910 issrc
= (aux
->alu_state
& BPF_ALU_SANITIZE
) ==
9911 BPF_ALU_SANITIZE_SRC
;
9913 off_reg
= issrc
? insn
->src_reg
: insn
->dst_reg
;
9915 *patch
++ = BPF_ALU64_IMM(BPF_MUL
, off_reg
, -1);
9916 *patch
++ = BPF_MOV32_IMM(BPF_REG_AX
, aux
->alu_limit
- 1);
9917 *patch
++ = BPF_ALU64_REG(BPF_SUB
, BPF_REG_AX
, off_reg
);
9918 *patch
++ = BPF_ALU64_REG(BPF_OR
, BPF_REG_AX
, off_reg
);
9919 *patch
++ = BPF_ALU64_IMM(BPF_NEG
, BPF_REG_AX
, 0);
9920 *patch
++ = BPF_ALU64_IMM(BPF_ARSH
, BPF_REG_AX
, 63);
9922 *patch
++ = BPF_ALU64_REG(BPF_AND
, BPF_REG_AX
,
9924 insn
->src_reg
= BPF_REG_AX
;
9926 *patch
++ = BPF_ALU64_REG(BPF_AND
, off_reg
,
9930 insn
->code
= insn
->code
== code_add
?
9931 code_sub
: code_add
;
9934 *patch
++ = BPF_ALU64_IMM(BPF_MUL
, off_reg
, -1);
9935 cnt
= patch
- insn_buf
;
9937 new_prog
= bpf_patch_insn_data(env
, i
+ delta
, insn_buf
, cnt
);
9942 env
->prog
= prog
= new_prog
;
9943 insn
= new_prog
->insnsi
+ i
+ delta
;
9947 if (insn
->code
!= (BPF_JMP
| BPF_CALL
))
9949 if (insn
->src_reg
== BPF_PSEUDO_CALL
)
9952 if (insn
->imm
== BPF_FUNC_get_route_realm
)
9953 prog
->dst_needed
= 1;
9954 if (insn
->imm
== BPF_FUNC_get_prandom_u32
)
9955 bpf_user_rnd_init_once();
9956 if (insn
->imm
== BPF_FUNC_override_return
)
9957 prog
->kprobe_override
= 1;
9958 if (insn
->imm
== BPF_FUNC_tail_call
) {
9959 /* If we tail call into other programs, we
9960 * cannot make any assumptions since they can
9961 * be replaced dynamically during runtime in
9962 * the program array.
9964 prog
->cb_access
= 1;
9965 env
->prog
->aux
->stack_depth
= MAX_BPF_STACK
;
9966 env
->prog
->aux
->max_pkt_offset
= MAX_PACKET_OFF
;
9968 /* mark bpf_tail_call as different opcode to avoid
9969 * conditional branch in the interpeter for every normal
9970 * call and to prevent accidental JITing by JIT compiler
9971 * that doesn't support bpf_tail_call yet
9974 insn
->code
= BPF_JMP
| BPF_TAIL_CALL
;
9976 aux
= &env
->insn_aux_data
[i
+ delta
];
9977 if (env
->allow_ptr_leaks
&& !expect_blinding
&&
9978 prog
->jit_requested
&&
9979 !bpf_map_key_poisoned(aux
) &&
9980 !bpf_map_ptr_poisoned(aux
) &&
9981 !bpf_map_ptr_unpriv(aux
)) {
9982 struct bpf_jit_poke_descriptor desc
= {
9983 .reason
= BPF_POKE_REASON_TAIL_CALL
,
9984 .tail_call
.map
= BPF_MAP_PTR(aux
->map_ptr_state
),
9985 .tail_call
.key
= bpf_map_key_immediate(aux
),
9988 ret
= bpf_jit_add_poke_descriptor(prog
, &desc
);
9990 verbose(env
, "adding tail call poke descriptor failed\n");
9994 insn
->imm
= ret
+ 1;
9998 if (!bpf_map_ptr_unpriv(aux
))
10001 /* instead of changing every JIT dealing with tail_call
10002 * emit two extra insns:
10003 * if (index >= max_entries) goto out;
10004 * index &= array->index_mask;
10005 * to avoid out-of-bounds cpu speculation
10007 if (bpf_map_ptr_poisoned(aux
)) {
10008 verbose(env
, "tail_call abusing map_ptr\n");
10012 map_ptr
= BPF_MAP_PTR(aux
->map_ptr_state
);
10013 insn_buf
[0] = BPF_JMP_IMM(BPF_JGE
, BPF_REG_3
,
10014 map_ptr
->max_entries
, 2);
10015 insn_buf
[1] = BPF_ALU32_IMM(BPF_AND
, BPF_REG_3
,
10016 container_of(map_ptr
,
10019 insn_buf
[2] = *insn
;
10021 new_prog
= bpf_patch_insn_data(env
, i
+ delta
, insn_buf
, cnt
);
10026 env
->prog
= prog
= new_prog
;
10027 insn
= new_prog
->insnsi
+ i
+ delta
;
10031 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
10032 * and other inlining handlers are currently limited to 64 bit
10035 if (prog
->jit_requested
&& BITS_PER_LONG
== 64 &&
10036 (insn
->imm
== BPF_FUNC_map_lookup_elem
||
10037 insn
->imm
== BPF_FUNC_map_update_elem
||
10038 insn
->imm
== BPF_FUNC_map_delete_elem
||
10039 insn
->imm
== BPF_FUNC_map_push_elem
||
10040 insn
->imm
== BPF_FUNC_map_pop_elem
||
10041 insn
->imm
== BPF_FUNC_map_peek_elem
)) {
10042 aux
= &env
->insn_aux_data
[i
+ delta
];
10043 if (bpf_map_ptr_poisoned(aux
))
10044 goto patch_call_imm
;
10046 map_ptr
= BPF_MAP_PTR(aux
->map_ptr_state
);
10047 ops
= map_ptr
->ops
;
10048 if (insn
->imm
== BPF_FUNC_map_lookup_elem
&&
10049 ops
->map_gen_lookup
) {
10050 cnt
= ops
->map_gen_lookup(map_ptr
, insn_buf
);
10051 if (cnt
== 0 || cnt
>= ARRAY_SIZE(insn_buf
)) {
10052 verbose(env
, "bpf verifier is misconfigured\n");
10056 new_prog
= bpf_patch_insn_data(env
, i
+ delta
,
10062 env
->prog
= prog
= new_prog
;
10063 insn
= new_prog
->insnsi
+ i
+ delta
;
10067 BUILD_BUG_ON(!__same_type(ops
->map_lookup_elem
,
10068 (void *(*)(struct bpf_map
*map
, void *key
))NULL
));
10069 BUILD_BUG_ON(!__same_type(ops
->map_delete_elem
,
10070 (int (*)(struct bpf_map
*map
, void *key
))NULL
));
10071 BUILD_BUG_ON(!__same_type(ops
->map_update_elem
,
10072 (int (*)(struct bpf_map
*map
, void *key
, void *value
,
10074 BUILD_BUG_ON(!__same_type(ops
->map_push_elem
,
10075 (int (*)(struct bpf_map
*map
, void *value
,
10077 BUILD_BUG_ON(!__same_type(ops
->map_pop_elem
,
10078 (int (*)(struct bpf_map
*map
, void *value
))NULL
));
10079 BUILD_BUG_ON(!__same_type(ops
->map_peek_elem
,
10080 (int (*)(struct bpf_map
*map
, void *value
))NULL
));
10082 switch (insn
->imm
) {
10083 case BPF_FUNC_map_lookup_elem
:
10084 insn
->imm
= BPF_CAST_CALL(ops
->map_lookup_elem
) -
10087 case BPF_FUNC_map_update_elem
:
10088 insn
->imm
= BPF_CAST_CALL(ops
->map_update_elem
) -
10091 case BPF_FUNC_map_delete_elem
:
10092 insn
->imm
= BPF_CAST_CALL(ops
->map_delete_elem
) -
10095 case BPF_FUNC_map_push_elem
:
10096 insn
->imm
= BPF_CAST_CALL(ops
->map_push_elem
) -
10099 case BPF_FUNC_map_pop_elem
:
10100 insn
->imm
= BPF_CAST_CALL(ops
->map_pop_elem
) -
10103 case BPF_FUNC_map_peek_elem
:
10104 insn
->imm
= BPF_CAST_CALL(ops
->map_peek_elem
) -
10109 goto patch_call_imm
;
10112 if (prog
->jit_requested
&& BITS_PER_LONG
== 64 &&
10113 insn
->imm
== BPF_FUNC_jiffies64
) {
10114 struct bpf_insn ld_jiffies_addr
[2] = {
10115 BPF_LD_IMM64(BPF_REG_0
,
10116 (unsigned long)&jiffies
),
10119 insn_buf
[0] = ld_jiffies_addr
[0];
10120 insn_buf
[1] = ld_jiffies_addr
[1];
10121 insn_buf
[2] = BPF_LDX_MEM(BPF_DW
, BPF_REG_0
,
10125 new_prog
= bpf_patch_insn_data(env
, i
+ delta
, insn_buf
,
10131 env
->prog
= prog
= new_prog
;
10132 insn
= new_prog
->insnsi
+ i
+ delta
;
10137 fn
= env
->ops
->get_func_proto(insn
->imm
, env
->prog
);
10138 /* all functions that have prototype and verifier allowed
10139 * programs to call them, must be real in-kernel functions
10143 "kernel subsystem misconfigured func %s#%d\n",
10144 func_id_name(insn
->imm
), insn
->imm
);
10147 insn
->imm
= fn
->func
- __bpf_call_base
;
10150 /* Since poke tab is now finalized, publish aux to tracker. */
10151 for (i
= 0; i
< prog
->aux
->size_poke_tab
; i
++) {
10152 map_ptr
= prog
->aux
->poke_tab
[i
].tail_call
.map
;
10153 if (!map_ptr
->ops
->map_poke_track
||
10154 !map_ptr
->ops
->map_poke_untrack
||
10155 !map_ptr
->ops
->map_poke_run
) {
10156 verbose(env
, "bpf verifier is misconfigured\n");
10160 ret
= map_ptr
->ops
->map_poke_track(map_ptr
, prog
->aux
);
10162 verbose(env
, "tracking tail call prog failed\n");
10170 static void free_states(struct bpf_verifier_env
*env
)
10172 struct bpf_verifier_state_list
*sl
, *sln
;
10175 sl
= env
->free_list
;
10178 free_verifier_state(&sl
->state
, false);
10182 env
->free_list
= NULL
;
10184 if (!env
->explored_states
)
10187 for (i
= 0; i
< state_htab_size(env
); i
++) {
10188 sl
= env
->explored_states
[i
];
10192 free_verifier_state(&sl
->state
, false);
10196 env
->explored_states
[i
] = NULL
;
10200 /* The verifier is using insn_aux_data[] to store temporary data during
10201 * verification and to store information for passes that run after the
10202 * verification like dead code sanitization. do_check_common() for subprogram N
10203 * may analyze many other subprograms. sanitize_insn_aux_data() clears all
10204 * temporary data after do_check_common() finds that subprogram N cannot be
10205 * verified independently. pass_cnt counts the number of times
10206 * do_check_common() was run and insn->aux->seen tells the pass number
10207 * insn_aux_data was touched. These variables are compared to clear temporary
10208 * data from failed pass. For testing and experiments do_check_common() can be
10209 * run multiple times even when prior attempt to verify is unsuccessful.
10211 static void sanitize_insn_aux_data(struct bpf_verifier_env
*env
)
10213 struct bpf_insn
*insn
= env
->prog
->insnsi
;
10214 struct bpf_insn_aux_data
*aux
;
10217 for (i
= 0; i
< env
->prog
->len
; i
++) {
10218 class = BPF_CLASS(insn
[i
].code
);
10219 if (class != BPF_LDX
&& class != BPF_STX
)
10221 aux
= &env
->insn_aux_data
[i
];
10222 if (aux
->seen
!= env
->pass_cnt
)
10224 memset(aux
, 0, offsetof(typeof(*aux
), orig_idx
));
10228 static int do_check_common(struct bpf_verifier_env
*env
, int subprog
)
10230 struct bpf_verifier_state
*state
;
10231 struct bpf_reg_state
*regs
;
10234 env
->prev_linfo
= NULL
;
10237 state
= kzalloc(sizeof(struct bpf_verifier_state
), GFP_KERNEL
);
10240 state
->curframe
= 0;
10241 state
->speculative
= false;
10242 state
->branches
= 1;
10243 state
->frame
[0] = kzalloc(sizeof(struct bpf_func_state
), GFP_KERNEL
);
10244 if (!state
->frame
[0]) {
10248 env
->cur_state
= state
;
10249 init_func_state(env
, state
->frame
[0],
10250 BPF_MAIN_FUNC
/* callsite */,
10254 regs
= state
->frame
[state
->curframe
]->regs
;
10255 if (subprog
|| env
->prog
->type
== BPF_PROG_TYPE_EXT
) {
10256 ret
= btf_prepare_func_args(env
, subprog
, regs
);
10259 for (i
= BPF_REG_1
; i
<= BPF_REG_5
; i
++) {
10260 if (regs
[i
].type
== PTR_TO_CTX
)
10261 mark_reg_known_zero(env
, regs
, i
);
10262 else if (regs
[i
].type
== SCALAR_VALUE
)
10263 mark_reg_unknown(env
, regs
, i
);
10266 /* 1st arg to a function */
10267 regs
[BPF_REG_1
].type
= PTR_TO_CTX
;
10268 mark_reg_known_zero(env
, regs
, BPF_REG_1
);
10269 ret
= btf_check_func_arg_match(env
, subprog
, regs
);
10270 if (ret
== -EFAULT
)
10271 /* unlikely verifier bug. abort.
10272 * ret == 0 and ret < 0 are sadly acceptable for
10273 * main() function due to backward compatibility.
10274 * Like socket filter program may be written as:
10275 * int bpf_prog(struct pt_regs *ctx)
10276 * and never dereference that ctx in the program.
10277 * 'struct pt_regs' is a type mismatch for socket
10278 * filter that should be using 'struct __sk_buff'.
10283 ret
= do_check(env
);
10285 /* check for NULL is necessary, since cur_state can be freed inside
10286 * do_check() under memory pressure.
10288 if (env
->cur_state
) {
10289 free_verifier_state(env
->cur_state
, true);
10290 env
->cur_state
= NULL
;
10292 while (!pop_stack(env
, NULL
, NULL
));
10295 /* clean aux data in case subprog was rejected */
10296 sanitize_insn_aux_data(env
);
10300 /* Verify all global functions in a BPF program one by one based on their BTF.
10301 * All global functions must pass verification. Otherwise the whole program is rejected.
10312 * foo() will be verified first for R1=any_scalar_value. During verification it
10313 * will be assumed that bar() already verified successfully and call to bar()
10314 * from foo() will be checked for type match only. Later bar() will be verified
10315 * independently to check that it's safe for R1=any_scalar_value.
10317 static int do_check_subprogs(struct bpf_verifier_env
*env
)
10319 struct bpf_prog_aux
*aux
= env
->prog
->aux
;
10322 if (!aux
->func_info
)
10325 for (i
= 1; i
< env
->subprog_cnt
; i
++) {
10326 if (aux
->func_info_aux
[i
].linkage
!= BTF_FUNC_GLOBAL
)
10328 env
->insn_idx
= env
->subprog_info
[i
].start
;
10329 WARN_ON_ONCE(env
->insn_idx
== 0);
10330 ret
= do_check_common(env
, i
);
10333 } else if (env
->log
.level
& BPF_LOG_LEVEL
) {
10335 "Func#%d is safe for any args that match its prototype\n",
10342 static int do_check_main(struct bpf_verifier_env
*env
)
10347 ret
= do_check_common(env
, 0);
10349 env
->prog
->aux
->stack_depth
= env
->subprog_info
[0].stack_depth
;
10354 static void print_verification_stats(struct bpf_verifier_env
*env
)
10358 if (env
->log
.level
& BPF_LOG_STATS
) {
10359 verbose(env
, "verification time %lld usec\n",
10360 div_u64(env
->verification_time
, 1000));
10361 verbose(env
, "stack depth ");
10362 for (i
= 0; i
< env
->subprog_cnt
; i
++) {
10363 u32 depth
= env
->subprog_info
[i
].stack_depth
;
10365 verbose(env
, "%d", depth
);
10366 if (i
+ 1 < env
->subprog_cnt
)
10369 verbose(env
, "\n");
10371 verbose(env
, "processed %d insns (limit %d) max_states_per_insn %d "
10372 "total_states %d peak_states %d mark_read %d\n",
10373 env
->insn_processed
, BPF_COMPLEXITY_LIMIT_INSNS
,
10374 env
->max_states_per_insn
, env
->total_states
,
10375 env
->peak_states
, env
->longest_mark_read_walk
);
10378 static int check_struct_ops_btf_id(struct bpf_verifier_env
*env
)
10380 const struct btf_type
*t
, *func_proto
;
10381 const struct bpf_struct_ops
*st_ops
;
10382 const struct btf_member
*member
;
10383 struct bpf_prog
*prog
= env
->prog
;
10384 u32 btf_id
, member_idx
;
10387 btf_id
= prog
->aux
->attach_btf_id
;
10388 st_ops
= bpf_struct_ops_find(btf_id
);
10390 verbose(env
, "attach_btf_id %u is not a supported struct\n",
10396 member_idx
= prog
->expected_attach_type
;
10397 if (member_idx
>= btf_type_vlen(t
)) {
10398 verbose(env
, "attach to invalid member idx %u of struct %s\n",
10399 member_idx
, st_ops
->name
);
10403 member
= &btf_type_member(t
)[member_idx
];
10404 mname
= btf_name_by_offset(btf_vmlinux
, member
->name_off
);
10405 func_proto
= btf_type_resolve_func_ptr(btf_vmlinux
, member
->type
,
10408 verbose(env
, "attach to invalid member %s(@idx %u) of struct %s\n",
10409 mname
, member_idx
, st_ops
->name
);
10413 if (st_ops
->check_member
) {
10414 int err
= st_ops
->check_member(t
, member
);
10417 verbose(env
, "attach to unsupported member %s of struct %s\n",
10418 mname
, st_ops
->name
);
10423 prog
->aux
->attach_func_proto
= func_proto
;
10424 prog
->aux
->attach_func_name
= mname
;
10425 env
->ops
= st_ops
->verifier_ops
;
10429 #define SECURITY_PREFIX "security_"
10431 static int check_attach_modify_return(struct bpf_verifier_env
*env
)
10433 struct bpf_prog
*prog
= env
->prog
;
10434 unsigned long addr
= (unsigned long) prog
->aux
->trampoline
->func
.addr
;
10436 /* This is expected to be cleaned up in the future with the KRSI effort
10437 * introducing the LSM_HOOK macro for cleaning up lsm_hooks.h.
10439 if (within_error_injection_list(addr
) ||
10440 !strncmp(SECURITY_PREFIX
, prog
->aux
->attach_func_name
,
10441 sizeof(SECURITY_PREFIX
) - 1))
10444 verbose(env
, "fmod_ret attach_btf_id %u (%s) is not modifiable\n",
10445 prog
->aux
->attach_btf_id
, prog
->aux
->attach_func_name
);
10450 static int check_attach_btf_id(struct bpf_verifier_env
*env
)
10452 struct bpf_prog
*prog
= env
->prog
;
10453 bool prog_extension
= prog
->type
== BPF_PROG_TYPE_EXT
;
10454 struct bpf_prog
*tgt_prog
= prog
->aux
->linked_prog
;
10455 u32 btf_id
= prog
->aux
->attach_btf_id
;
10456 const char prefix
[] = "btf_trace_";
10457 int ret
= 0, subprog
= -1, i
;
10458 struct bpf_trampoline
*tr
;
10459 const struct btf_type
*t
;
10460 bool conservative
= true;
10466 if (prog
->type
== BPF_PROG_TYPE_STRUCT_OPS
)
10467 return check_struct_ops_btf_id(env
);
10469 if (prog
->type
!= BPF_PROG_TYPE_TRACING
&&
10470 prog
->type
!= BPF_PROG_TYPE_LSM
&&
10475 verbose(env
, "Tracing programs must provide btf_id\n");
10478 btf
= bpf_prog_get_target_btf(prog
);
10481 "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
10484 t
= btf_type_by_id(btf
, btf_id
);
10486 verbose(env
, "attach_btf_id %u is invalid\n", btf_id
);
10489 tname
= btf_name_by_offset(btf
, t
->name_off
);
10491 verbose(env
, "attach_btf_id %u doesn't have a name\n", btf_id
);
10495 struct bpf_prog_aux
*aux
= tgt_prog
->aux
;
10497 for (i
= 0; i
< aux
->func_info_cnt
; i
++)
10498 if (aux
->func_info
[i
].type_id
== btf_id
) {
10502 if (subprog
== -1) {
10503 verbose(env
, "Subprog %s doesn't exist\n", tname
);
10506 conservative
= aux
->func_info_aux
[subprog
].unreliable
;
10507 if (prog_extension
) {
10508 if (conservative
) {
10510 "Cannot replace static functions\n");
10513 if (!prog
->jit_requested
) {
10515 "Extension programs should be JITed\n");
10518 env
->ops
= bpf_verifier_ops
[tgt_prog
->type
];
10519 prog
->expected_attach_type
= tgt_prog
->expected_attach_type
;
10521 if (!tgt_prog
->jited
) {
10522 verbose(env
, "Can attach to only JITed progs\n");
10525 if (tgt_prog
->type
== prog
->type
) {
10526 /* Cannot fentry/fexit another fentry/fexit program.
10527 * Cannot attach program extension to another extension.
10528 * It's ok to attach fentry/fexit to extension program.
10530 verbose(env
, "Cannot recursively attach\n");
10533 if (tgt_prog
->type
== BPF_PROG_TYPE_TRACING
&&
10535 (tgt_prog
->expected_attach_type
== BPF_TRACE_FENTRY
||
10536 tgt_prog
->expected_attach_type
== BPF_TRACE_FEXIT
)) {
10537 /* Program extensions can extend all program types
10538 * except fentry/fexit. The reason is the following.
10539 * The fentry/fexit programs are used for performance
10540 * analysis, stats and can be attached to any program
10541 * type except themselves. When extension program is
10542 * replacing XDP function it is necessary to allow
10543 * performance analysis of all functions. Both original
10544 * XDP program and its program extension. Hence
10545 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
10546 * allowed. If extending of fentry/fexit was allowed it
10547 * would be possible to create long call chain
10548 * fentry->extension->fentry->extension beyond
10549 * reasonable stack size. Hence extending fentry is not
10552 verbose(env
, "Cannot extend fentry/fexit\n");
10555 key
= ((u64
)aux
->id
) << 32 | btf_id
;
10557 if (prog_extension
) {
10558 verbose(env
, "Cannot replace kernel functions\n");
10564 switch (prog
->expected_attach_type
) {
10565 case BPF_TRACE_RAW_TP
:
10568 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
10571 if (!btf_type_is_typedef(t
)) {
10572 verbose(env
, "attach_btf_id %u is not a typedef\n",
10576 if (strncmp(prefix
, tname
, sizeof(prefix
) - 1)) {
10577 verbose(env
, "attach_btf_id %u points to wrong type name %s\n",
10581 tname
+= sizeof(prefix
) - 1;
10582 t
= btf_type_by_id(btf
, t
->type
);
10583 if (!btf_type_is_ptr(t
))
10584 /* should never happen in valid vmlinux build */
10586 t
= btf_type_by_id(btf
, t
->type
);
10587 if (!btf_type_is_func_proto(t
))
10588 /* should never happen in valid vmlinux build */
10591 /* remember two read only pointers that are valid for
10592 * the life time of the kernel
10594 prog
->aux
->attach_func_name
= tname
;
10595 prog
->aux
->attach_func_proto
= t
;
10596 prog
->aux
->attach_btf_trace
= true;
10599 if (!prog_extension
)
10602 case BPF_MODIFY_RETURN
:
10604 case BPF_TRACE_FENTRY
:
10605 case BPF_TRACE_FEXIT
:
10606 prog
->aux
->attach_func_name
= tname
;
10607 if (prog
->type
== BPF_PROG_TYPE_LSM
) {
10608 ret
= bpf_lsm_verify_prog(&env
->log
, prog
);
10613 if (!btf_type_is_func(t
)) {
10614 verbose(env
, "attach_btf_id %u is not a function\n",
10618 if (prog_extension
&&
10619 btf_check_type_match(env
, prog
, btf
, t
))
10621 t
= btf_type_by_id(btf
, t
->type
);
10622 if (!btf_type_is_func_proto(t
))
10624 tr
= bpf_trampoline_lookup(key
);
10627 /* t is either vmlinux type or another program's type */
10628 prog
->aux
->attach_func_proto
= t
;
10629 mutex_lock(&tr
->mutex
);
10630 if (tr
->func
.addr
) {
10631 prog
->aux
->trampoline
= tr
;
10634 if (tgt_prog
&& conservative
) {
10635 prog
->aux
->attach_func_proto
= NULL
;
10638 ret
= btf_distill_func_proto(&env
->log
, btf
, t
,
10639 tname
, &tr
->func
.model
);
10644 addr
= (long) tgt_prog
->bpf_func
;
10646 addr
= (long) tgt_prog
->aux
->func
[subprog
]->bpf_func
;
10648 addr
= kallsyms_lookup_name(tname
);
10651 "The address of function %s cannot be found\n",
10657 tr
->func
.addr
= (void *)addr
;
10658 prog
->aux
->trampoline
= tr
;
10660 if (prog
->expected_attach_type
== BPF_MODIFY_RETURN
)
10661 ret
= check_attach_modify_return(env
);
10663 mutex_unlock(&tr
->mutex
);
10665 bpf_trampoline_put(tr
);
10670 int bpf_check(struct bpf_prog
**prog
, union bpf_attr
*attr
,
10671 union bpf_attr __user
*uattr
)
10673 u64 start_time
= ktime_get_ns();
10674 struct bpf_verifier_env
*env
;
10675 struct bpf_verifier_log
*log
;
10676 int i
, len
, ret
= -EINVAL
;
10679 /* no program is valid */
10680 if (ARRAY_SIZE(bpf_verifier_ops
) == 0)
10683 /* 'struct bpf_verifier_env' can be global, but since it's not small,
10684 * allocate/free it every time bpf_check() is called
10686 env
= kzalloc(sizeof(struct bpf_verifier_env
), GFP_KERNEL
);
10691 len
= (*prog
)->len
;
10692 env
->insn_aux_data
=
10693 vzalloc(array_size(sizeof(struct bpf_insn_aux_data
), len
));
10695 if (!env
->insn_aux_data
)
10697 for (i
= 0; i
< len
; i
++)
10698 env
->insn_aux_data
[i
].orig_idx
= i
;
10700 env
->ops
= bpf_verifier_ops
[env
->prog
->type
];
10701 is_priv
= capable(CAP_SYS_ADMIN
);
10703 if (!btf_vmlinux
&& IS_ENABLED(CONFIG_DEBUG_INFO_BTF
)) {
10704 mutex_lock(&bpf_verifier_lock
);
10706 btf_vmlinux
= btf_parse_vmlinux();
10707 mutex_unlock(&bpf_verifier_lock
);
10710 /* grab the mutex to protect few globals used by verifier */
10712 mutex_lock(&bpf_verifier_lock
);
10714 if (attr
->log_level
|| attr
->log_buf
|| attr
->log_size
) {
10715 /* user requested verbose verifier output
10716 * and supplied buffer to store the verification trace
10718 log
->level
= attr
->log_level
;
10719 log
->ubuf
= (char __user
*) (unsigned long) attr
->log_buf
;
10720 log
->len_total
= attr
->log_size
;
10723 /* log attributes have to be sane */
10724 if (log
->len_total
< 128 || log
->len_total
> UINT_MAX
>> 2 ||
10725 !log
->level
|| !log
->ubuf
|| log
->level
& ~BPF_LOG_MASK
)
10729 if (IS_ERR(btf_vmlinux
)) {
10730 /* Either gcc or pahole or kernel are broken. */
10731 verbose(env
, "in-kernel BTF is malformed\n");
10732 ret
= PTR_ERR(btf_vmlinux
);
10733 goto skip_full_check
;
10736 env
->strict_alignment
= !!(attr
->prog_flags
& BPF_F_STRICT_ALIGNMENT
);
10737 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS
))
10738 env
->strict_alignment
= true;
10739 if (attr
->prog_flags
& BPF_F_ANY_ALIGNMENT
)
10740 env
->strict_alignment
= false;
10742 env
->allow_ptr_leaks
= is_priv
;
10745 env
->test_state_freq
= attr
->prog_flags
& BPF_F_TEST_STATE_FREQ
;
10747 ret
= replace_map_fd_with_map_ptr(env
);
10749 goto skip_full_check
;
10751 if (bpf_prog_is_dev_bound(env
->prog
->aux
)) {
10752 ret
= bpf_prog_offload_verifier_prep(env
->prog
);
10754 goto skip_full_check
;
10757 env
->explored_states
= kvcalloc(state_htab_size(env
),
10758 sizeof(struct bpf_verifier_state_list
*),
10761 if (!env
->explored_states
)
10762 goto skip_full_check
;
10764 ret
= check_subprogs(env
);
10766 goto skip_full_check
;
10768 ret
= check_btf_info(env
, attr
, uattr
);
10770 goto skip_full_check
;
10772 ret
= check_attach_btf_id(env
);
10774 goto skip_full_check
;
10776 ret
= check_cfg(env
);
10778 goto skip_full_check
;
10780 ret
= do_check_subprogs(env
);
10781 ret
= ret
?: do_check_main(env
);
10783 if (ret
== 0 && bpf_prog_is_dev_bound(env
->prog
->aux
))
10784 ret
= bpf_prog_offload_finalize(env
);
10787 kvfree(env
->explored_states
);
10790 ret
= check_max_stack_depth(env
);
10792 /* instruction rewrites happen after this point */
10795 opt_hard_wire_dead_code_branches(env
);
10797 ret
= opt_remove_dead_code(env
);
10799 ret
= opt_remove_nops(env
);
10802 sanitize_dead_code(env
);
10806 /* program is valid, convert *(u32*)(ctx + off) accesses */
10807 ret
= convert_ctx_accesses(env
);
10810 ret
= fixup_bpf_calls(env
);
10812 /* do 32-bit optimization after insn patching has done so those patched
10813 * insns could be handled correctly.
10815 if (ret
== 0 && !bpf_prog_is_dev_bound(env
->prog
->aux
)) {
10816 ret
= opt_subreg_zext_lo32_rnd_hi32(env
, attr
);
10817 env
->prog
->aux
->verifier_zext
= bpf_jit_needs_zext() ? !ret
10822 ret
= fixup_call_args(env
);
10824 env
->verification_time
= ktime_get_ns() - start_time
;
10825 print_verification_stats(env
);
10827 if (log
->level
&& bpf_verifier_log_full(log
))
10829 if (log
->level
&& !log
->ubuf
) {
10831 goto err_release_maps
;
10834 if (ret
== 0 && env
->used_map_cnt
) {
10835 /* if program passed verifier, update used_maps in bpf_prog_info */
10836 env
->prog
->aux
->used_maps
= kmalloc_array(env
->used_map_cnt
,
10837 sizeof(env
->used_maps
[0]),
10840 if (!env
->prog
->aux
->used_maps
) {
10842 goto err_release_maps
;
10845 memcpy(env
->prog
->aux
->used_maps
, env
->used_maps
,
10846 sizeof(env
->used_maps
[0]) * env
->used_map_cnt
);
10847 env
->prog
->aux
->used_map_cnt
= env
->used_map_cnt
;
10849 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
10850 * bpf_ld_imm64 instructions
10852 convert_pseudo_ld_imm64(env
);
10856 adjust_btf_func(env
);
10859 if (!env
->prog
->aux
->used_maps
)
10860 /* if we didn't copy map pointers into bpf_prog_info, release
10861 * them now. Otherwise free_used_maps() will release them.
10865 /* extension progs temporarily inherit the attach_type of their targets
10866 for verification purposes, so set it back to zero before returning
10868 if (env
->prog
->type
== BPF_PROG_TYPE_EXT
)
10869 env
->prog
->expected_attach_type
= 0;
10874 mutex_unlock(&bpf_verifier_lock
);
10875 vfree(env
->insn_aux_data
);