1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com
3 * Copyright (c) 2016 Facebook
4 * Copyright (c) 2018 Covalent IO, Inc. http://covalent.io
6 #include <uapi/linux/btf.h>
7 #include <linux/kernel.h>
8 #include <linux/types.h>
9 #include <linux/slab.h>
10 #include <linux/bpf.h>
11 #include <linux/btf.h>
12 #include <linux/bpf_verifier.h>
13 #include <linux/filter.h>
14 #include <net/netlink.h>
15 #include <linux/file.h>
16 #include <linux/vmalloc.h>
17 #include <linux/stringify.h>
18 #include <linux/bsearch.h>
19 #include <linux/sort.h>
20 #include <linux/perf_event.h>
21 #include <linux/ctype.h>
22 #include <linux/error-injection.h>
23 #include <linux/bpf_lsm.h>
24 #include <linux/btf_ids.h>
28 static const struct bpf_verifier_ops
* const bpf_verifier_ops
[] = {
29 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
30 [_id] = & _name ## _verifier_ops,
31 #define BPF_MAP_TYPE(_id, _ops)
32 #define BPF_LINK_TYPE(_id, _name)
33 #include <linux/bpf_types.h>
39 /* bpf_check() is a static code analyzer that walks eBPF program
40 * instruction by instruction and updates register/stack state.
41 * All paths of conditional branches are analyzed until 'bpf_exit' insn.
43 * The first pass is depth-first-search to check that the program is a DAG.
44 * It rejects the following programs:
45 * - larger than BPF_MAXINSNS insns
46 * - if loop is present (detected via back-edge)
47 * - unreachable insns exist (shouldn't be a forest. program = one function)
48 * - out of bounds or malformed jumps
49 * The second pass is all possible path descent from the 1st insn.
50 * Since it's analyzing all pathes through the program, the length of the
51 * analysis is limited to 64k insn, which may be hit even if total number of
52 * insn is less then 4K, but there are too many branches that change stack/regs.
53 * Number of 'branches to be analyzed' is limited to 1k
55 * On entry to each instruction, each register has a type, and the instruction
56 * changes the types of the registers depending on instruction semantics.
57 * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
60 * All registers are 64-bit.
61 * R0 - return register
62 * R1-R5 argument passing registers
63 * R6-R9 callee saved registers
64 * R10 - frame pointer read-only
66 * At the start of BPF program the register R1 contains a pointer to bpf_context
67 * and has type PTR_TO_CTX.
69 * Verifier tracks arithmetic operations on pointers in case:
70 * BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
71 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
72 * 1st insn copies R10 (which has FRAME_PTR) type into R1
73 * and 2nd arithmetic instruction is pattern matched to recognize
74 * that it wants to construct a pointer to some element within stack.
75 * So after 2nd insn, the register R1 has type PTR_TO_STACK
76 * (and -20 constant is saved for further stack bounds checking).
77 * Meaning that this reg is a pointer to stack plus known immediate constant.
79 * Most of the time the registers have SCALAR_VALUE type, which
80 * means the register has some value, but it's not a valid pointer.
81 * (like pointer plus pointer becomes SCALAR_VALUE type)
83 * When verifier sees load or store instructions the type of base register
84 * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are
85 * four pointer types recognized by check_mem_access() function.
87 * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
88 * and the range of [ptr, ptr + map's value_size) is accessible.
90 * registers used to pass values to function calls are checked against
91 * function argument constraints.
93 * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
94 * It means that the register type passed to this function must be
95 * PTR_TO_STACK and it will be used inside the function as
96 * 'pointer to map element key'
98 * For example the argument constraints for bpf_map_lookup_elem():
99 * .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
100 * .arg1_type = ARG_CONST_MAP_PTR,
101 * .arg2_type = ARG_PTR_TO_MAP_KEY,
103 * ret_type says that this function returns 'pointer to map elem value or null'
104 * function expects 1st argument to be a const pointer to 'struct bpf_map' and
105 * 2nd argument should be a pointer to stack, which will be used inside
106 * the helper function as a pointer to map element key.
108 * On the kernel side the helper function looks like:
109 * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
111 * struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
112 * void *key = (void *) (unsigned long) r2;
115 * here kernel can access 'key' and 'map' pointers safely, knowing that
116 * [key, key + map->key_size) bytes are valid and were initialized on
117 * the stack of eBPF program.
120 * Corresponding eBPF program may look like:
121 * BPF_MOV64_REG(BPF_REG_2, BPF_REG_10), // after this insn R2 type is FRAME_PTR
122 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
123 * BPF_LD_MAP_FD(BPF_REG_1, map_fd), // after this insn R1 type is CONST_PTR_TO_MAP
124 * BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
125 * here verifier looks at prototype of map_lookup_elem() and sees:
126 * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
127 * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
129 * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
130 * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
131 * and were initialized prior to this call.
132 * If it's ok, then verifier allows this BPF_CALL insn and looks at
133 * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
134 * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
135 * returns ether pointer to map value or NULL.
137 * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
138 * insn, the register holding that pointer in the true branch changes state to
139 * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
140 * branch. See check_cond_jmp_op().
142 * After the call R0 is set to return type of the function and registers R1-R5
143 * are set to NOT_INIT to indicate that they are no longer readable.
145 * The following reference types represent a potential reference to a kernel
146 * resource which, after first being allocated, must be checked and freed by
148 * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET
150 * When the verifier sees a helper call return a reference type, it allocates a
151 * pointer id for the reference and stores it in the current function state.
152 * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into
153 * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type
154 * passes through a NULL-check conditional. For the branch wherein the state is
155 * changed to CONST_IMM, the verifier releases the reference.
157 * For each helper function that allocates a reference, such as
158 * bpf_sk_lookup_tcp(), there is a corresponding release function, such as
159 * bpf_sk_release(). When a reference type passes into the release function,
160 * the verifier also releases the reference. If any unchecked or unreleased
161 * reference remains at the end of the program, the verifier rejects it.
164 /* verifier_state + insn_idx are pushed to stack when branch is encountered */
165 struct bpf_verifier_stack_elem
{
166 /* verifer state is 'st'
167 * before processing instruction 'insn_idx'
168 * and after processing instruction 'prev_insn_idx'
170 struct bpf_verifier_state st
;
173 struct bpf_verifier_stack_elem
*next
;
174 /* length of verifier log at the time this state was pushed on stack */
178 #define BPF_COMPLEXITY_LIMIT_JMP_SEQ 8192
179 #define BPF_COMPLEXITY_LIMIT_STATES 64
181 #define BPF_MAP_KEY_POISON (1ULL << 63)
182 #define BPF_MAP_KEY_SEEN (1ULL << 62)
184 #define BPF_MAP_PTR_UNPRIV 1UL
185 #define BPF_MAP_PTR_POISON ((void *)((0xeB9FUL << 1) + \
186 POISON_POINTER_DELTA))
187 #define BPF_MAP_PTR(X) ((struct bpf_map *)((X) & ~BPF_MAP_PTR_UNPRIV))
189 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data
*aux
)
191 return BPF_MAP_PTR(aux
->map_ptr_state
) == BPF_MAP_PTR_POISON
;
194 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data
*aux
)
196 return aux
->map_ptr_state
& BPF_MAP_PTR_UNPRIV
;
199 static void bpf_map_ptr_store(struct bpf_insn_aux_data
*aux
,
200 const struct bpf_map
*map
, bool unpriv
)
202 BUILD_BUG_ON((unsigned long)BPF_MAP_PTR_POISON
& BPF_MAP_PTR_UNPRIV
);
203 unpriv
|= bpf_map_ptr_unpriv(aux
);
204 aux
->map_ptr_state
= (unsigned long)map
|
205 (unpriv
? BPF_MAP_PTR_UNPRIV
: 0UL);
208 static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data
*aux
)
210 return aux
->map_key_state
& BPF_MAP_KEY_POISON
;
213 static bool bpf_map_key_unseen(const struct bpf_insn_aux_data
*aux
)
215 return !(aux
->map_key_state
& BPF_MAP_KEY_SEEN
);
218 static u64
bpf_map_key_immediate(const struct bpf_insn_aux_data
*aux
)
220 return aux
->map_key_state
& ~(BPF_MAP_KEY_SEEN
| BPF_MAP_KEY_POISON
);
223 static void bpf_map_key_store(struct bpf_insn_aux_data
*aux
, u64 state
)
225 bool poisoned
= bpf_map_key_poisoned(aux
);
227 aux
->map_key_state
= state
| BPF_MAP_KEY_SEEN
|
228 (poisoned
? BPF_MAP_KEY_POISON
: 0ULL);
231 struct bpf_call_arg_meta
{
232 struct bpf_map
*map_ptr
;
243 struct btf
*btf_vmlinux
;
245 static DEFINE_MUTEX(bpf_verifier_lock
);
247 static const struct bpf_line_info
*
248 find_linfo(const struct bpf_verifier_env
*env
, u32 insn_off
)
250 const struct bpf_line_info
*linfo
;
251 const struct bpf_prog
*prog
;
255 nr_linfo
= prog
->aux
->nr_linfo
;
257 if (!nr_linfo
|| insn_off
>= prog
->len
)
260 linfo
= prog
->aux
->linfo
;
261 for (i
= 1; i
< nr_linfo
; i
++)
262 if (insn_off
< linfo
[i
].insn_off
)
265 return &linfo
[i
- 1];
268 void bpf_verifier_vlog(struct bpf_verifier_log
*log
, const char *fmt
,
273 n
= vscnprintf(log
->kbuf
, BPF_VERIFIER_TMP_LOG_SIZE
, fmt
, args
);
275 WARN_ONCE(n
>= BPF_VERIFIER_TMP_LOG_SIZE
- 1,
276 "verifier log line truncated - local buffer too short\n");
278 n
= min(log
->len_total
- log
->len_used
- 1, n
);
281 if (log
->level
== BPF_LOG_KERNEL
) {
282 pr_err("BPF:%s\n", log
->kbuf
);
285 if (!copy_to_user(log
->ubuf
+ log
->len_used
, log
->kbuf
, n
+ 1))
291 static void bpf_vlog_reset(struct bpf_verifier_log
*log
, u32 new_pos
)
295 if (!bpf_verifier_log_needed(log
))
298 log
->len_used
= new_pos
;
299 if (put_user(zero
, log
->ubuf
+ new_pos
))
303 /* log_level controls verbosity level of eBPF verifier.
304 * bpf_verifier_log_write() is used to dump the verification trace to the log,
305 * so the user can figure out what's wrong with the program
307 __printf(2, 3) void bpf_verifier_log_write(struct bpf_verifier_env
*env
,
308 const char *fmt
, ...)
312 if (!bpf_verifier_log_needed(&env
->log
))
316 bpf_verifier_vlog(&env
->log
, fmt
, args
);
319 EXPORT_SYMBOL_GPL(bpf_verifier_log_write
);
321 __printf(2, 3) static void verbose(void *private_data
, const char *fmt
, ...)
323 struct bpf_verifier_env
*env
= private_data
;
326 if (!bpf_verifier_log_needed(&env
->log
))
330 bpf_verifier_vlog(&env
->log
, fmt
, args
);
334 __printf(2, 3) void bpf_log(struct bpf_verifier_log
*log
,
335 const char *fmt
, ...)
339 if (!bpf_verifier_log_needed(log
))
343 bpf_verifier_vlog(log
, fmt
, args
);
347 static const char *ltrim(const char *s
)
355 __printf(3, 4) static void verbose_linfo(struct bpf_verifier_env
*env
,
357 const char *prefix_fmt
, ...)
359 const struct bpf_line_info
*linfo
;
361 if (!bpf_verifier_log_needed(&env
->log
))
364 linfo
= find_linfo(env
, insn_off
);
365 if (!linfo
|| linfo
== env
->prev_linfo
)
371 va_start(args
, prefix_fmt
);
372 bpf_verifier_vlog(&env
->log
, prefix_fmt
, args
);
377 ltrim(btf_name_by_offset(env
->prog
->aux
->btf
,
380 env
->prev_linfo
= linfo
;
383 static bool type_is_pkt_pointer(enum bpf_reg_type type
)
385 return type
== PTR_TO_PACKET
||
386 type
== PTR_TO_PACKET_META
;
389 static bool type_is_sk_pointer(enum bpf_reg_type type
)
391 return type
== PTR_TO_SOCKET
||
392 type
== PTR_TO_SOCK_COMMON
||
393 type
== PTR_TO_TCP_SOCK
||
394 type
== PTR_TO_XDP_SOCK
;
397 static bool reg_type_not_null(enum bpf_reg_type type
)
399 return type
== PTR_TO_SOCKET
||
400 type
== PTR_TO_TCP_SOCK
||
401 type
== PTR_TO_MAP_VALUE
||
402 type
== PTR_TO_SOCK_COMMON
;
405 static bool reg_type_may_be_null(enum bpf_reg_type type
)
407 return type
== PTR_TO_MAP_VALUE_OR_NULL
||
408 type
== PTR_TO_SOCKET_OR_NULL
||
409 type
== PTR_TO_SOCK_COMMON_OR_NULL
||
410 type
== PTR_TO_TCP_SOCK_OR_NULL
||
411 type
== PTR_TO_BTF_ID_OR_NULL
||
412 type
== PTR_TO_MEM_OR_NULL
||
413 type
== PTR_TO_RDONLY_BUF_OR_NULL
||
414 type
== PTR_TO_RDWR_BUF_OR_NULL
;
417 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state
*reg
)
419 return reg
->type
== PTR_TO_MAP_VALUE
&&
420 map_value_has_spin_lock(reg
->map_ptr
);
423 static bool reg_type_may_be_refcounted_or_null(enum bpf_reg_type type
)
425 return type
== PTR_TO_SOCKET
||
426 type
== PTR_TO_SOCKET_OR_NULL
||
427 type
== PTR_TO_TCP_SOCK
||
428 type
== PTR_TO_TCP_SOCK_OR_NULL
||
429 type
== PTR_TO_MEM
||
430 type
== PTR_TO_MEM_OR_NULL
;
433 static bool arg_type_may_be_refcounted(enum bpf_arg_type type
)
435 return type
== ARG_PTR_TO_SOCK_COMMON
;
438 static bool arg_type_may_be_null(enum bpf_arg_type type
)
440 return type
== ARG_PTR_TO_MAP_VALUE_OR_NULL
||
441 type
== ARG_PTR_TO_MEM_OR_NULL
||
442 type
== ARG_PTR_TO_CTX_OR_NULL
||
443 type
== ARG_PTR_TO_SOCKET_OR_NULL
||
444 type
== ARG_PTR_TO_ALLOC_MEM_OR_NULL
;
447 /* Determine whether the function releases some resources allocated by another
448 * function call. The first reference type argument will be assumed to be
449 * released by release_reference().
451 static bool is_release_function(enum bpf_func_id func_id
)
453 return func_id
== BPF_FUNC_sk_release
||
454 func_id
== BPF_FUNC_ringbuf_submit
||
455 func_id
== BPF_FUNC_ringbuf_discard
;
458 static bool may_be_acquire_function(enum bpf_func_id func_id
)
460 return func_id
== BPF_FUNC_sk_lookup_tcp
||
461 func_id
== BPF_FUNC_sk_lookup_udp
||
462 func_id
== BPF_FUNC_skc_lookup_tcp
||
463 func_id
== BPF_FUNC_map_lookup_elem
||
464 func_id
== BPF_FUNC_ringbuf_reserve
;
467 static bool is_acquire_function(enum bpf_func_id func_id
,
468 const struct bpf_map
*map
)
470 enum bpf_map_type map_type
= map
? map
->map_type
: BPF_MAP_TYPE_UNSPEC
;
472 if (func_id
== BPF_FUNC_sk_lookup_tcp
||
473 func_id
== BPF_FUNC_sk_lookup_udp
||
474 func_id
== BPF_FUNC_skc_lookup_tcp
||
475 func_id
== BPF_FUNC_ringbuf_reserve
)
478 if (func_id
== BPF_FUNC_map_lookup_elem
&&
479 (map_type
== BPF_MAP_TYPE_SOCKMAP
||
480 map_type
== BPF_MAP_TYPE_SOCKHASH
))
486 static bool is_ptr_cast_function(enum bpf_func_id func_id
)
488 return func_id
== BPF_FUNC_tcp_sock
||
489 func_id
== BPF_FUNC_sk_fullsock
;
492 /* string representation of 'enum bpf_reg_type' */
493 static const char * const reg_type_str
[] = {
495 [SCALAR_VALUE
] = "inv",
496 [PTR_TO_CTX
] = "ctx",
497 [CONST_PTR_TO_MAP
] = "map_ptr",
498 [PTR_TO_MAP_VALUE
] = "map_value",
499 [PTR_TO_MAP_VALUE_OR_NULL
] = "map_value_or_null",
500 [PTR_TO_STACK
] = "fp",
501 [PTR_TO_PACKET
] = "pkt",
502 [PTR_TO_PACKET_META
] = "pkt_meta",
503 [PTR_TO_PACKET_END
] = "pkt_end",
504 [PTR_TO_FLOW_KEYS
] = "flow_keys",
505 [PTR_TO_SOCKET
] = "sock",
506 [PTR_TO_SOCKET_OR_NULL
] = "sock_or_null",
507 [PTR_TO_SOCK_COMMON
] = "sock_common",
508 [PTR_TO_SOCK_COMMON_OR_NULL
] = "sock_common_or_null",
509 [PTR_TO_TCP_SOCK
] = "tcp_sock",
510 [PTR_TO_TCP_SOCK_OR_NULL
] = "tcp_sock_or_null",
511 [PTR_TO_TP_BUFFER
] = "tp_buffer",
512 [PTR_TO_XDP_SOCK
] = "xdp_sock",
513 [PTR_TO_BTF_ID
] = "ptr_",
514 [PTR_TO_BTF_ID_OR_NULL
] = "ptr_or_null_",
515 [PTR_TO_MEM
] = "mem",
516 [PTR_TO_MEM_OR_NULL
] = "mem_or_null",
517 [PTR_TO_RDONLY_BUF
] = "rdonly_buf",
518 [PTR_TO_RDONLY_BUF_OR_NULL
] = "rdonly_buf_or_null",
519 [PTR_TO_RDWR_BUF
] = "rdwr_buf",
520 [PTR_TO_RDWR_BUF_OR_NULL
] = "rdwr_buf_or_null",
523 static char slot_type_char
[] = {
524 [STACK_INVALID
] = '?',
530 static void print_liveness(struct bpf_verifier_env
*env
,
531 enum bpf_reg_liveness live
)
533 if (live
& (REG_LIVE_READ
| REG_LIVE_WRITTEN
| REG_LIVE_DONE
))
535 if (live
& REG_LIVE_READ
)
537 if (live
& REG_LIVE_WRITTEN
)
539 if (live
& REG_LIVE_DONE
)
543 static struct bpf_func_state
*func(struct bpf_verifier_env
*env
,
544 const struct bpf_reg_state
*reg
)
546 struct bpf_verifier_state
*cur
= env
->cur_state
;
548 return cur
->frame
[reg
->frameno
];
551 const char *kernel_type_name(u32 id
)
553 return btf_name_by_offset(btf_vmlinux
,
554 btf_type_by_id(btf_vmlinux
, id
)->name_off
);
557 static void print_verifier_state(struct bpf_verifier_env
*env
,
558 const struct bpf_func_state
*state
)
560 const struct bpf_reg_state
*reg
;
565 verbose(env
, " frame%d:", state
->frameno
);
566 for (i
= 0; i
< MAX_BPF_REG
; i
++) {
567 reg
= &state
->regs
[i
];
571 verbose(env
, " R%d", i
);
572 print_liveness(env
, reg
->live
);
573 verbose(env
, "=%s", reg_type_str
[t
]);
574 if (t
== SCALAR_VALUE
&& reg
->precise
)
576 if ((t
== SCALAR_VALUE
|| t
== PTR_TO_STACK
) &&
577 tnum_is_const(reg
->var_off
)) {
578 /* reg->off should be 0 for SCALAR_VALUE */
579 verbose(env
, "%lld", reg
->var_off
.value
+ reg
->off
);
581 if (t
== PTR_TO_BTF_ID
|| t
== PTR_TO_BTF_ID_OR_NULL
)
582 verbose(env
, "%s", kernel_type_name(reg
->btf_id
));
583 verbose(env
, "(id=%d", reg
->id
);
584 if (reg_type_may_be_refcounted_or_null(t
))
585 verbose(env
, ",ref_obj_id=%d", reg
->ref_obj_id
);
586 if (t
!= SCALAR_VALUE
)
587 verbose(env
, ",off=%d", reg
->off
);
588 if (type_is_pkt_pointer(t
))
589 verbose(env
, ",r=%d", reg
->range
);
590 else if (t
== CONST_PTR_TO_MAP
||
591 t
== PTR_TO_MAP_VALUE
||
592 t
== PTR_TO_MAP_VALUE_OR_NULL
)
593 verbose(env
, ",ks=%d,vs=%d",
594 reg
->map_ptr
->key_size
,
595 reg
->map_ptr
->value_size
);
596 if (tnum_is_const(reg
->var_off
)) {
597 /* Typically an immediate SCALAR_VALUE, but
598 * could be a pointer whose offset is too big
601 verbose(env
, ",imm=%llx", reg
->var_off
.value
);
603 if (reg
->smin_value
!= reg
->umin_value
&&
604 reg
->smin_value
!= S64_MIN
)
605 verbose(env
, ",smin_value=%lld",
606 (long long)reg
->smin_value
);
607 if (reg
->smax_value
!= reg
->umax_value
&&
608 reg
->smax_value
!= S64_MAX
)
609 verbose(env
, ",smax_value=%lld",
610 (long long)reg
->smax_value
);
611 if (reg
->umin_value
!= 0)
612 verbose(env
, ",umin_value=%llu",
613 (unsigned long long)reg
->umin_value
);
614 if (reg
->umax_value
!= U64_MAX
)
615 verbose(env
, ",umax_value=%llu",
616 (unsigned long long)reg
->umax_value
);
617 if (!tnum_is_unknown(reg
->var_off
)) {
620 tnum_strn(tn_buf
, sizeof(tn_buf
), reg
->var_off
);
621 verbose(env
, ",var_off=%s", tn_buf
);
623 if (reg
->s32_min_value
!= reg
->smin_value
&&
624 reg
->s32_min_value
!= S32_MIN
)
625 verbose(env
, ",s32_min_value=%d",
626 (int)(reg
->s32_min_value
));
627 if (reg
->s32_max_value
!= reg
->smax_value
&&
628 reg
->s32_max_value
!= S32_MAX
)
629 verbose(env
, ",s32_max_value=%d",
630 (int)(reg
->s32_max_value
));
631 if (reg
->u32_min_value
!= reg
->umin_value
&&
632 reg
->u32_min_value
!= U32_MIN
)
633 verbose(env
, ",u32_min_value=%d",
634 (int)(reg
->u32_min_value
));
635 if (reg
->u32_max_value
!= reg
->umax_value
&&
636 reg
->u32_max_value
!= U32_MAX
)
637 verbose(env
, ",u32_max_value=%d",
638 (int)(reg
->u32_max_value
));
643 for (i
= 0; i
< state
->allocated_stack
/ BPF_REG_SIZE
; i
++) {
644 char types_buf
[BPF_REG_SIZE
+ 1];
648 for (j
= 0; j
< BPF_REG_SIZE
; j
++) {
649 if (state
->stack
[i
].slot_type
[j
] != STACK_INVALID
)
651 types_buf
[j
] = slot_type_char
[
652 state
->stack
[i
].slot_type
[j
]];
654 types_buf
[BPF_REG_SIZE
] = 0;
657 verbose(env
, " fp%d", (-i
- 1) * BPF_REG_SIZE
);
658 print_liveness(env
, state
->stack
[i
].spilled_ptr
.live
);
659 if (state
->stack
[i
].slot_type
[0] == STACK_SPILL
) {
660 reg
= &state
->stack
[i
].spilled_ptr
;
662 verbose(env
, "=%s", reg_type_str
[t
]);
663 if (t
== SCALAR_VALUE
&& reg
->precise
)
665 if (t
== SCALAR_VALUE
&& tnum_is_const(reg
->var_off
))
666 verbose(env
, "%lld", reg
->var_off
.value
+ reg
->off
);
668 verbose(env
, "=%s", types_buf
);
671 if (state
->acquired_refs
&& state
->refs
[0].id
) {
672 verbose(env
, " refs=%d", state
->refs
[0].id
);
673 for (i
= 1; i
< state
->acquired_refs
; i
++)
674 if (state
->refs
[i
].id
)
675 verbose(env
, ",%d", state
->refs
[i
].id
);
680 #define COPY_STATE_FN(NAME, COUNT, FIELD, SIZE) \
681 static int copy_##NAME##_state(struct bpf_func_state *dst, \
682 const struct bpf_func_state *src) \
686 if (WARN_ON_ONCE(dst->COUNT < src->COUNT)) { \
687 /* internal bug, make state invalid to reject the program */ \
688 memset(dst, 0, sizeof(*dst)); \
691 memcpy(dst->FIELD, src->FIELD, \
692 sizeof(*src->FIELD) * (src->COUNT / SIZE)); \
695 /* copy_reference_state() */
696 COPY_STATE_FN(reference
, acquired_refs
, refs
, 1)
697 /* copy_stack_state() */
698 COPY_STATE_FN(stack
, allocated_stack
, stack
, BPF_REG_SIZE
)
701 #define REALLOC_STATE_FN(NAME, COUNT, FIELD, SIZE) \
702 static int realloc_##NAME##_state(struct bpf_func_state *state, int size, \
705 u32 old_size = state->COUNT; \
706 struct bpf_##NAME##_state *new_##FIELD; \
707 int slot = size / SIZE; \
709 if (size <= old_size || !size) { \
712 state->COUNT = slot * SIZE; \
713 if (!size && old_size) { \
714 kfree(state->FIELD); \
715 state->FIELD = NULL; \
719 new_##FIELD = kmalloc_array(slot, sizeof(struct bpf_##NAME##_state), \
725 memcpy(new_##FIELD, state->FIELD, \
726 sizeof(*new_##FIELD) * (old_size / SIZE)); \
727 memset(new_##FIELD + old_size / SIZE, 0, \
728 sizeof(*new_##FIELD) * (size - old_size) / SIZE); \
730 state->COUNT = slot * SIZE; \
731 kfree(state->FIELD); \
732 state->FIELD = new_##FIELD; \
735 /* realloc_reference_state() */
736 REALLOC_STATE_FN(reference
, acquired_refs
, refs
, 1)
737 /* realloc_stack_state() */
738 REALLOC_STATE_FN(stack
, allocated_stack
, stack
, BPF_REG_SIZE
)
739 #undef REALLOC_STATE_FN
741 /* do_check() starts with zero-sized stack in struct bpf_verifier_state to
742 * make it consume minimal amount of memory. check_stack_write() access from
743 * the program calls into realloc_func_state() to grow the stack size.
744 * Note there is a non-zero 'parent' pointer inside bpf_verifier_state
745 * which realloc_stack_state() copies over. It points to previous
746 * bpf_verifier_state which is never reallocated.
748 static int realloc_func_state(struct bpf_func_state
*state
, int stack_size
,
749 int refs_size
, bool copy_old
)
751 int err
= realloc_reference_state(state
, refs_size
, copy_old
);
754 return realloc_stack_state(state
, stack_size
, copy_old
);
757 /* Acquire a pointer id from the env and update the state->refs to include
758 * this new pointer reference.
759 * On success, returns a valid pointer id to associate with the register
760 * On failure, returns a negative errno.
762 static int acquire_reference_state(struct bpf_verifier_env
*env
, int insn_idx
)
764 struct bpf_func_state
*state
= cur_func(env
);
765 int new_ofs
= state
->acquired_refs
;
768 err
= realloc_reference_state(state
, state
->acquired_refs
+ 1, true);
772 state
->refs
[new_ofs
].id
= id
;
773 state
->refs
[new_ofs
].insn_idx
= insn_idx
;
778 /* release function corresponding to acquire_reference_state(). Idempotent. */
779 static int release_reference_state(struct bpf_func_state
*state
, int ptr_id
)
783 last_idx
= state
->acquired_refs
- 1;
784 for (i
= 0; i
< state
->acquired_refs
; i
++) {
785 if (state
->refs
[i
].id
== ptr_id
) {
786 if (last_idx
&& i
!= last_idx
)
787 memcpy(&state
->refs
[i
], &state
->refs
[last_idx
],
788 sizeof(*state
->refs
));
789 memset(&state
->refs
[last_idx
], 0, sizeof(*state
->refs
));
790 state
->acquired_refs
--;
797 static int transfer_reference_state(struct bpf_func_state
*dst
,
798 struct bpf_func_state
*src
)
800 int err
= realloc_reference_state(dst
, src
->acquired_refs
, false);
803 err
= copy_reference_state(dst
, src
);
809 static void free_func_state(struct bpf_func_state
*state
)
818 static void clear_jmp_history(struct bpf_verifier_state
*state
)
820 kfree(state
->jmp_history
);
821 state
->jmp_history
= NULL
;
822 state
->jmp_history_cnt
= 0;
825 static void free_verifier_state(struct bpf_verifier_state
*state
,
830 for (i
= 0; i
<= state
->curframe
; i
++) {
831 free_func_state(state
->frame
[i
]);
832 state
->frame
[i
] = NULL
;
834 clear_jmp_history(state
);
839 /* copy verifier state from src to dst growing dst stack space
840 * when necessary to accommodate larger src stack
842 static int copy_func_state(struct bpf_func_state
*dst
,
843 const struct bpf_func_state
*src
)
847 err
= realloc_func_state(dst
, src
->allocated_stack
, src
->acquired_refs
,
851 memcpy(dst
, src
, offsetof(struct bpf_func_state
, acquired_refs
));
852 err
= copy_reference_state(dst
, src
);
855 return copy_stack_state(dst
, src
);
858 static int copy_verifier_state(struct bpf_verifier_state
*dst_state
,
859 const struct bpf_verifier_state
*src
)
861 struct bpf_func_state
*dst
;
862 u32 jmp_sz
= sizeof(struct bpf_idx_pair
) * src
->jmp_history_cnt
;
865 if (dst_state
->jmp_history_cnt
< src
->jmp_history_cnt
) {
866 kfree(dst_state
->jmp_history
);
867 dst_state
->jmp_history
= kmalloc(jmp_sz
, GFP_USER
);
868 if (!dst_state
->jmp_history
)
871 memcpy(dst_state
->jmp_history
, src
->jmp_history
, jmp_sz
);
872 dst_state
->jmp_history_cnt
= src
->jmp_history_cnt
;
874 /* if dst has more stack frames then src frame, free them */
875 for (i
= src
->curframe
+ 1; i
<= dst_state
->curframe
; i
++) {
876 free_func_state(dst_state
->frame
[i
]);
877 dst_state
->frame
[i
] = NULL
;
879 dst_state
->speculative
= src
->speculative
;
880 dst_state
->curframe
= src
->curframe
;
881 dst_state
->active_spin_lock
= src
->active_spin_lock
;
882 dst_state
->branches
= src
->branches
;
883 dst_state
->parent
= src
->parent
;
884 dst_state
->first_insn_idx
= src
->first_insn_idx
;
885 dst_state
->last_insn_idx
= src
->last_insn_idx
;
886 for (i
= 0; i
<= src
->curframe
; i
++) {
887 dst
= dst_state
->frame
[i
];
889 dst
= kzalloc(sizeof(*dst
), GFP_KERNEL
);
892 dst_state
->frame
[i
] = dst
;
894 err
= copy_func_state(dst
, src
->frame
[i
]);
901 static void update_branch_counts(struct bpf_verifier_env
*env
, struct bpf_verifier_state
*st
)
904 u32 br
= --st
->branches
;
906 /* WARN_ON(br > 1) technically makes sense here,
907 * but see comment in push_stack(), hence:
909 WARN_ONCE((int)br
< 0,
910 "BUG update_branch_counts:branches_to_explore=%d\n",
918 static int pop_stack(struct bpf_verifier_env
*env
, int *prev_insn_idx
,
919 int *insn_idx
, bool pop_log
)
921 struct bpf_verifier_state
*cur
= env
->cur_state
;
922 struct bpf_verifier_stack_elem
*elem
, *head
= env
->head
;
925 if (env
->head
== NULL
)
929 err
= copy_verifier_state(cur
, &head
->st
);
934 bpf_vlog_reset(&env
->log
, head
->log_pos
);
936 *insn_idx
= head
->insn_idx
;
938 *prev_insn_idx
= head
->prev_insn_idx
;
940 free_verifier_state(&head
->st
, false);
947 static struct bpf_verifier_state
*push_stack(struct bpf_verifier_env
*env
,
948 int insn_idx
, int prev_insn_idx
,
951 struct bpf_verifier_state
*cur
= env
->cur_state
;
952 struct bpf_verifier_stack_elem
*elem
;
955 elem
= kzalloc(sizeof(struct bpf_verifier_stack_elem
), GFP_KERNEL
);
959 elem
->insn_idx
= insn_idx
;
960 elem
->prev_insn_idx
= prev_insn_idx
;
961 elem
->next
= env
->head
;
962 elem
->log_pos
= env
->log
.len_used
;
965 err
= copy_verifier_state(&elem
->st
, cur
);
968 elem
->st
.speculative
|= speculative
;
969 if (env
->stack_size
> BPF_COMPLEXITY_LIMIT_JMP_SEQ
) {
970 verbose(env
, "The sequence of %d jumps is too complex.\n",
974 if (elem
->st
.parent
) {
975 ++elem
->st
.parent
->branches
;
976 /* WARN_ON(branches > 2) technically makes sense here,
978 * 1. speculative states will bump 'branches' for non-branch
980 * 2. is_state_visited() heuristics may decide not to create
981 * a new state for a sequence of branches and all such current
982 * and cloned states will be pointing to a single parent state
983 * which might have large 'branches' count.
988 free_verifier_state(env
->cur_state
, true);
989 env
->cur_state
= NULL
;
990 /* pop all elements and return */
991 while (!pop_stack(env
, NULL
, NULL
, false));
995 #define CALLER_SAVED_REGS 6
996 static const int caller_saved
[CALLER_SAVED_REGS
] = {
997 BPF_REG_0
, BPF_REG_1
, BPF_REG_2
, BPF_REG_3
, BPF_REG_4
, BPF_REG_5
1000 static void __mark_reg_not_init(const struct bpf_verifier_env
*env
,
1001 struct bpf_reg_state
*reg
);
1003 /* Mark the unknown part of a register (variable offset or scalar value) as
1004 * known to have the value @imm.
1006 static void __mark_reg_known(struct bpf_reg_state
*reg
, u64 imm
)
1008 /* Clear id, off, and union(map_ptr, range) */
1009 memset(((u8
*)reg
) + sizeof(reg
->type
), 0,
1010 offsetof(struct bpf_reg_state
, var_off
) - sizeof(reg
->type
));
1011 reg
->var_off
= tnum_const(imm
);
1012 reg
->smin_value
= (s64
)imm
;
1013 reg
->smax_value
= (s64
)imm
;
1014 reg
->umin_value
= imm
;
1015 reg
->umax_value
= imm
;
1017 reg
->s32_min_value
= (s32
)imm
;
1018 reg
->s32_max_value
= (s32
)imm
;
1019 reg
->u32_min_value
= (u32
)imm
;
1020 reg
->u32_max_value
= (u32
)imm
;
1023 static void __mark_reg32_known(struct bpf_reg_state
*reg
, u64 imm
)
1025 reg
->var_off
= tnum_const_subreg(reg
->var_off
, imm
);
1026 reg
->s32_min_value
= (s32
)imm
;
1027 reg
->s32_max_value
= (s32
)imm
;
1028 reg
->u32_min_value
= (u32
)imm
;
1029 reg
->u32_max_value
= (u32
)imm
;
1032 /* Mark the 'variable offset' part of a register as zero. This should be
1033 * used only on registers holding a pointer type.
1035 static void __mark_reg_known_zero(struct bpf_reg_state
*reg
)
1037 __mark_reg_known(reg
, 0);
1040 static void __mark_reg_const_zero(struct bpf_reg_state
*reg
)
1042 __mark_reg_known(reg
, 0);
1043 reg
->type
= SCALAR_VALUE
;
1046 static void mark_reg_known_zero(struct bpf_verifier_env
*env
,
1047 struct bpf_reg_state
*regs
, u32 regno
)
1049 if (WARN_ON(regno
>= MAX_BPF_REG
)) {
1050 verbose(env
, "mark_reg_known_zero(regs, %u)\n", regno
);
1051 /* Something bad happened, let's kill all regs */
1052 for (regno
= 0; regno
< MAX_BPF_REG
; regno
++)
1053 __mark_reg_not_init(env
, regs
+ regno
);
1056 __mark_reg_known_zero(regs
+ regno
);
1059 static bool reg_is_pkt_pointer(const struct bpf_reg_state
*reg
)
1061 return type_is_pkt_pointer(reg
->type
);
1064 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state
*reg
)
1066 return reg_is_pkt_pointer(reg
) ||
1067 reg
->type
== PTR_TO_PACKET_END
;
1070 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
1071 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state
*reg
,
1072 enum bpf_reg_type which
)
1074 /* The register can already have a range from prior markings.
1075 * This is fine as long as it hasn't been advanced from its
1078 return reg
->type
== which
&&
1081 tnum_equals_const(reg
->var_off
, 0);
1084 /* Reset the min/max bounds of a register */
1085 static void __mark_reg_unbounded(struct bpf_reg_state
*reg
)
1087 reg
->smin_value
= S64_MIN
;
1088 reg
->smax_value
= S64_MAX
;
1089 reg
->umin_value
= 0;
1090 reg
->umax_value
= U64_MAX
;
1092 reg
->s32_min_value
= S32_MIN
;
1093 reg
->s32_max_value
= S32_MAX
;
1094 reg
->u32_min_value
= 0;
1095 reg
->u32_max_value
= U32_MAX
;
1098 static void __mark_reg64_unbounded(struct bpf_reg_state
*reg
)
1100 reg
->smin_value
= S64_MIN
;
1101 reg
->smax_value
= S64_MAX
;
1102 reg
->umin_value
= 0;
1103 reg
->umax_value
= U64_MAX
;
1106 static void __mark_reg32_unbounded(struct bpf_reg_state
*reg
)
1108 reg
->s32_min_value
= S32_MIN
;
1109 reg
->s32_max_value
= S32_MAX
;
1110 reg
->u32_min_value
= 0;
1111 reg
->u32_max_value
= U32_MAX
;
1114 static void __update_reg32_bounds(struct bpf_reg_state
*reg
)
1116 struct tnum var32_off
= tnum_subreg(reg
->var_off
);
1118 /* min signed is max(sign bit) | min(other bits) */
1119 reg
->s32_min_value
= max_t(s32
, reg
->s32_min_value
,
1120 var32_off
.value
| (var32_off
.mask
& S32_MIN
));
1121 /* max signed is min(sign bit) | max(other bits) */
1122 reg
->s32_max_value
= min_t(s32
, reg
->s32_max_value
,
1123 var32_off
.value
| (var32_off
.mask
& S32_MAX
));
1124 reg
->u32_min_value
= max_t(u32
, reg
->u32_min_value
, (u32
)var32_off
.value
);
1125 reg
->u32_max_value
= min(reg
->u32_max_value
,
1126 (u32
)(var32_off
.value
| var32_off
.mask
));
1129 static void __update_reg64_bounds(struct bpf_reg_state
*reg
)
1131 /* min signed is max(sign bit) | min(other bits) */
1132 reg
->smin_value
= max_t(s64
, reg
->smin_value
,
1133 reg
->var_off
.value
| (reg
->var_off
.mask
& S64_MIN
));
1134 /* max signed is min(sign bit) | max(other bits) */
1135 reg
->smax_value
= min_t(s64
, reg
->smax_value
,
1136 reg
->var_off
.value
| (reg
->var_off
.mask
& S64_MAX
));
1137 reg
->umin_value
= max(reg
->umin_value
, reg
->var_off
.value
);
1138 reg
->umax_value
= min(reg
->umax_value
,
1139 reg
->var_off
.value
| reg
->var_off
.mask
);
1142 static void __update_reg_bounds(struct bpf_reg_state
*reg
)
1144 __update_reg32_bounds(reg
);
1145 __update_reg64_bounds(reg
);
1148 /* Uses signed min/max values to inform unsigned, and vice-versa */
1149 static void __reg32_deduce_bounds(struct bpf_reg_state
*reg
)
1151 /* Learn sign from signed bounds.
1152 * If we cannot cross the sign boundary, then signed and unsigned bounds
1153 * are the same, so combine. This works even in the negative case, e.g.
1154 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1156 if (reg
->s32_min_value
>= 0 || reg
->s32_max_value
< 0) {
1157 reg
->s32_min_value
= reg
->u32_min_value
=
1158 max_t(u32
, reg
->s32_min_value
, reg
->u32_min_value
);
1159 reg
->s32_max_value
= reg
->u32_max_value
=
1160 min_t(u32
, reg
->s32_max_value
, reg
->u32_max_value
);
1163 /* Learn sign from unsigned bounds. Signed bounds cross the sign
1164 * boundary, so we must be careful.
1166 if ((s32
)reg
->u32_max_value
>= 0) {
1167 /* Positive. We can't learn anything from the smin, but smax
1168 * is positive, hence safe.
1170 reg
->s32_min_value
= reg
->u32_min_value
;
1171 reg
->s32_max_value
= reg
->u32_max_value
=
1172 min_t(u32
, reg
->s32_max_value
, reg
->u32_max_value
);
1173 } else if ((s32
)reg
->u32_min_value
< 0) {
1174 /* Negative. We can't learn anything from the smax, but smin
1175 * is negative, hence safe.
1177 reg
->s32_min_value
= reg
->u32_min_value
=
1178 max_t(u32
, reg
->s32_min_value
, reg
->u32_min_value
);
1179 reg
->s32_max_value
= reg
->u32_max_value
;
1183 static void __reg64_deduce_bounds(struct bpf_reg_state
*reg
)
1185 /* Learn sign from signed bounds.
1186 * If we cannot cross the sign boundary, then signed and unsigned bounds
1187 * are the same, so combine. This works even in the negative case, e.g.
1188 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1190 if (reg
->smin_value
>= 0 || reg
->smax_value
< 0) {
1191 reg
->smin_value
= reg
->umin_value
= max_t(u64
, reg
->smin_value
,
1193 reg
->smax_value
= reg
->umax_value
= min_t(u64
, reg
->smax_value
,
1197 /* Learn sign from unsigned bounds. Signed bounds cross the sign
1198 * boundary, so we must be careful.
1200 if ((s64
)reg
->umax_value
>= 0) {
1201 /* Positive. We can't learn anything from the smin, but smax
1202 * is positive, hence safe.
1204 reg
->smin_value
= reg
->umin_value
;
1205 reg
->smax_value
= reg
->umax_value
= min_t(u64
, reg
->smax_value
,
1207 } else if ((s64
)reg
->umin_value
< 0) {
1208 /* Negative. We can't learn anything from the smax, but smin
1209 * is negative, hence safe.
1211 reg
->smin_value
= reg
->umin_value
= max_t(u64
, reg
->smin_value
,
1213 reg
->smax_value
= reg
->umax_value
;
1217 static void __reg_deduce_bounds(struct bpf_reg_state
*reg
)
1219 __reg32_deduce_bounds(reg
);
1220 __reg64_deduce_bounds(reg
);
1223 /* Attempts to improve var_off based on unsigned min/max information */
1224 static void __reg_bound_offset(struct bpf_reg_state
*reg
)
1226 struct tnum var64_off
= tnum_intersect(reg
->var_off
,
1227 tnum_range(reg
->umin_value
,
1229 struct tnum var32_off
= tnum_intersect(tnum_subreg(reg
->var_off
),
1230 tnum_range(reg
->u32_min_value
,
1231 reg
->u32_max_value
));
1233 reg
->var_off
= tnum_or(tnum_clear_subreg(var64_off
), var32_off
);
1236 static void __reg_assign_32_into_64(struct bpf_reg_state
*reg
)
1238 reg
->umin_value
= reg
->u32_min_value
;
1239 reg
->umax_value
= reg
->u32_max_value
;
1240 /* Attempt to pull 32-bit signed bounds into 64-bit bounds
1241 * but must be positive otherwise set to worse case bounds
1242 * and refine later from tnum.
1244 if (reg
->s32_min_value
>= 0 && reg
->s32_max_value
>= 0)
1245 reg
->smax_value
= reg
->s32_max_value
;
1247 reg
->smax_value
= U32_MAX
;
1248 if (reg
->s32_min_value
>= 0)
1249 reg
->smin_value
= reg
->s32_min_value
;
1251 reg
->smin_value
= 0;
1254 static void __reg_combine_32_into_64(struct bpf_reg_state
*reg
)
1256 /* special case when 64-bit register has upper 32-bit register
1257 * zeroed. Typically happens after zext or <<32, >>32 sequence
1258 * allowing us to use 32-bit bounds directly,
1260 if (tnum_equals_const(tnum_clear_subreg(reg
->var_off
), 0)) {
1261 __reg_assign_32_into_64(reg
);
1263 /* Otherwise the best we can do is push lower 32bit known and
1264 * unknown bits into register (var_off set from jmp logic)
1265 * then learn as much as possible from the 64-bit tnum
1266 * known and unknown bits. The previous smin/smax bounds are
1267 * invalid here because of jmp32 compare so mark them unknown
1268 * so they do not impact tnum bounds calculation.
1270 __mark_reg64_unbounded(reg
);
1271 __update_reg_bounds(reg
);
1274 /* Intersecting with the old var_off might have improved our bounds
1275 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1276 * then new var_off is (0; 0x7f...fc) which improves our umax.
1278 __reg_deduce_bounds(reg
);
1279 __reg_bound_offset(reg
);
1280 __update_reg_bounds(reg
);
1283 static bool __reg64_bound_s32(s64 a
)
1285 if (a
> S32_MIN
&& a
< S32_MAX
)
1290 static bool __reg64_bound_u32(u64 a
)
1292 if (a
> U32_MIN
&& a
< U32_MAX
)
1297 static void __reg_combine_64_into_32(struct bpf_reg_state
*reg
)
1299 __mark_reg32_unbounded(reg
);
1301 if (__reg64_bound_s32(reg
->smin_value
))
1302 reg
->s32_min_value
= (s32
)reg
->smin_value
;
1303 if (__reg64_bound_s32(reg
->smax_value
))
1304 reg
->s32_max_value
= (s32
)reg
->smax_value
;
1305 if (__reg64_bound_u32(reg
->umin_value
))
1306 reg
->u32_min_value
= (u32
)reg
->umin_value
;
1307 if (__reg64_bound_u32(reg
->umax_value
))
1308 reg
->u32_max_value
= (u32
)reg
->umax_value
;
1310 /* Intersecting with the old var_off might have improved our bounds
1311 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1312 * then new var_off is (0; 0x7f...fc) which improves our umax.
1314 __reg_deduce_bounds(reg
);
1315 __reg_bound_offset(reg
);
1316 __update_reg_bounds(reg
);
1319 /* Mark a register as having a completely unknown (scalar) value. */
1320 static void __mark_reg_unknown(const struct bpf_verifier_env
*env
,
1321 struct bpf_reg_state
*reg
)
1324 * Clear type, id, off, and union(map_ptr, range) and
1325 * padding between 'type' and union
1327 memset(reg
, 0, offsetof(struct bpf_reg_state
, var_off
));
1328 reg
->type
= SCALAR_VALUE
;
1329 reg
->var_off
= tnum_unknown
;
1331 reg
->precise
= env
->subprog_cnt
> 1 || !env
->bpf_capable
;
1332 __mark_reg_unbounded(reg
);
1335 static void mark_reg_unknown(struct bpf_verifier_env
*env
,
1336 struct bpf_reg_state
*regs
, u32 regno
)
1338 if (WARN_ON(regno
>= MAX_BPF_REG
)) {
1339 verbose(env
, "mark_reg_unknown(regs, %u)\n", regno
);
1340 /* Something bad happened, let's kill all regs except FP */
1341 for (regno
= 0; regno
< BPF_REG_FP
; regno
++)
1342 __mark_reg_not_init(env
, regs
+ regno
);
1345 __mark_reg_unknown(env
, regs
+ regno
);
1348 static void __mark_reg_not_init(const struct bpf_verifier_env
*env
,
1349 struct bpf_reg_state
*reg
)
1351 __mark_reg_unknown(env
, reg
);
1352 reg
->type
= NOT_INIT
;
1355 static void mark_reg_not_init(struct bpf_verifier_env
*env
,
1356 struct bpf_reg_state
*regs
, u32 regno
)
1358 if (WARN_ON(regno
>= MAX_BPF_REG
)) {
1359 verbose(env
, "mark_reg_not_init(regs, %u)\n", regno
);
1360 /* Something bad happened, let's kill all regs except FP */
1361 for (regno
= 0; regno
< BPF_REG_FP
; regno
++)
1362 __mark_reg_not_init(env
, regs
+ regno
);
1365 __mark_reg_not_init(env
, regs
+ regno
);
1368 static void mark_btf_ld_reg(struct bpf_verifier_env
*env
,
1369 struct bpf_reg_state
*regs
, u32 regno
,
1370 enum bpf_reg_type reg_type
, u32 btf_id
)
1372 if (reg_type
== SCALAR_VALUE
) {
1373 mark_reg_unknown(env
, regs
, regno
);
1376 mark_reg_known_zero(env
, regs
, regno
);
1377 regs
[regno
].type
= PTR_TO_BTF_ID
;
1378 regs
[regno
].btf_id
= btf_id
;
1381 #define DEF_NOT_SUBREG (0)
1382 static void init_reg_state(struct bpf_verifier_env
*env
,
1383 struct bpf_func_state
*state
)
1385 struct bpf_reg_state
*regs
= state
->regs
;
1388 for (i
= 0; i
< MAX_BPF_REG
; i
++) {
1389 mark_reg_not_init(env
, regs
, i
);
1390 regs
[i
].live
= REG_LIVE_NONE
;
1391 regs
[i
].parent
= NULL
;
1392 regs
[i
].subreg_def
= DEF_NOT_SUBREG
;
1396 regs
[BPF_REG_FP
].type
= PTR_TO_STACK
;
1397 mark_reg_known_zero(env
, regs
, BPF_REG_FP
);
1398 regs
[BPF_REG_FP
].frameno
= state
->frameno
;
1401 #define BPF_MAIN_FUNC (-1)
1402 static void init_func_state(struct bpf_verifier_env
*env
,
1403 struct bpf_func_state
*state
,
1404 int callsite
, int frameno
, int subprogno
)
1406 state
->callsite
= callsite
;
1407 state
->frameno
= frameno
;
1408 state
->subprogno
= subprogno
;
1409 init_reg_state(env
, state
);
1413 SRC_OP
, /* register is used as source operand */
1414 DST_OP
, /* register is used as destination operand */
1415 DST_OP_NO_MARK
/* same as above, check only, don't mark */
1418 static int cmp_subprogs(const void *a
, const void *b
)
1420 return ((struct bpf_subprog_info
*)a
)->start
-
1421 ((struct bpf_subprog_info
*)b
)->start
;
1424 static int find_subprog(struct bpf_verifier_env
*env
, int off
)
1426 struct bpf_subprog_info
*p
;
1428 p
= bsearch(&off
, env
->subprog_info
, env
->subprog_cnt
,
1429 sizeof(env
->subprog_info
[0]), cmp_subprogs
);
1432 return p
- env
->subprog_info
;
1436 static int add_subprog(struct bpf_verifier_env
*env
, int off
)
1438 int insn_cnt
= env
->prog
->len
;
1441 if (off
>= insn_cnt
|| off
< 0) {
1442 verbose(env
, "call to invalid destination\n");
1445 ret
= find_subprog(env
, off
);
1448 if (env
->subprog_cnt
>= BPF_MAX_SUBPROGS
) {
1449 verbose(env
, "too many subprograms\n");
1452 env
->subprog_info
[env
->subprog_cnt
++].start
= off
;
1453 sort(env
->subprog_info
, env
->subprog_cnt
,
1454 sizeof(env
->subprog_info
[0]), cmp_subprogs
, NULL
);
1458 static int check_subprogs(struct bpf_verifier_env
*env
)
1460 int i
, ret
, subprog_start
, subprog_end
, off
, cur_subprog
= 0;
1461 struct bpf_subprog_info
*subprog
= env
->subprog_info
;
1462 struct bpf_insn
*insn
= env
->prog
->insnsi
;
1463 int insn_cnt
= env
->prog
->len
;
1465 /* Add entry function. */
1466 ret
= add_subprog(env
, 0);
1470 /* determine subprog starts. The end is one before the next starts */
1471 for (i
= 0; i
< insn_cnt
; i
++) {
1472 if (insn
[i
].code
!= (BPF_JMP
| BPF_CALL
))
1474 if (insn
[i
].src_reg
!= BPF_PSEUDO_CALL
)
1476 if (!env
->bpf_capable
) {
1478 "function calls to other bpf functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
1481 ret
= add_subprog(env
, i
+ insn
[i
].imm
+ 1);
1486 /* Add a fake 'exit' subprog which could simplify subprog iteration
1487 * logic. 'subprog_cnt' should not be increased.
1489 subprog
[env
->subprog_cnt
].start
= insn_cnt
;
1491 if (env
->log
.level
& BPF_LOG_LEVEL2
)
1492 for (i
= 0; i
< env
->subprog_cnt
; i
++)
1493 verbose(env
, "func#%d @%d\n", i
, subprog
[i
].start
);
1495 /* now check that all jumps are within the same subprog */
1496 subprog_start
= subprog
[cur_subprog
].start
;
1497 subprog_end
= subprog
[cur_subprog
+ 1].start
;
1498 for (i
= 0; i
< insn_cnt
; i
++) {
1499 u8 code
= insn
[i
].code
;
1501 if (code
== (BPF_JMP
| BPF_CALL
) &&
1502 insn
[i
].imm
== BPF_FUNC_tail_call
&&
1503 insn
[i
].src_reg
!= BPF_PSEUDO_CALL
)
1504 subprog
[cur_subprog
].has_tail_call
= true;
1505 if (BPF_CLASS(code
) == BPF_LD
&&
1506 (BPF_MODE(code
) == BPF_ABS
|| BPF_MODE(code
) == BPF_IND
))
1507 subprog
[cur_subprog
].has_ld_abs
= true;
1508 if (BPF_CLASS(code
) != BPF_JMP
&& BPF_CLASS(code
) != BPF_JMP32
)
1510 if (BPF_OP(code
) == BPF_EXIT
|| BPF_OP(code
) == BPF_CALL
)
1512 off
= i
+ insn
[i
].off
+ 1;
1513 if (off
< subprog_start
|| off
>= subprog_end
) {
1514 verbose(env
, "jump out of range from insn %d to %d\n", i
, off
);
1518 if (i
== subprog_end
- 1) {
1519 /* to avoid fall-through from one subprog into another
1520 * the last insn of the subprog should be either exit
1521 * or unconditional jump back
1523 if (code
!= (BPF_JMP
| BPF_EXIT
) &&
1524 code
!= (BPF_JMP
| BPF_JA
)) {
1525 verbose(env
, "last insn is not an exit or jmp\n");
1528 subprog_start
= subprog_end
;
1530 if (cur_subprog
< env
->subprog_cnt
)
1531 subprog_end
= subprog
[cur_subprog
+ 1].start
;
1537 /* Parentage chain of this register (or stack slot) should take care of all
1538 * issues like callee-saved registers, stack slot allocation time, etc.
1540 static int mark_reg_read(struct bpf_verifier_env
*env
,
1541 const struct bpf_reg_state
*state
,
1542 struct bpf_reg_state
*parent
, u8 flag
)
1544 bool writes
= parent
== state
->parent
; /* Observe write marks */
1548 /* if read wasn't screened by an earlier write ... */
1549 if (writes
&& state
->live
& REG_LIVE_WRITTEN
)
1551 if (parent
->live
& REG_LIVE_DONE
) {
1552 verbose(env
, "verifier BUG type %s var_off %lld off %d\n",
1553 reg_type_str
[parent
->type
],
1554 parent
->var_off
.value
, parent
->off
);
1557 /* The first condition is more likely to be true than the
1558 * second, checked it first.
1560 if ((parent
->live
& REG_LIVE_READ
) == flag
||
1561 parent
->live
& REG_LIVE_READ64
)
1562 /* The parentage chain never changes and
1563 * this parent was already marked as LIVE_READ.
1564 * There is no need to keep walking the chain again and
1565 * keep re-marking all parents as LIVE_READ.
1566 * This case happens when the same register is read
1567 * multiple times without writes into it in-between.
1568 * Also, if parent has the stronger REG_LIVE_READ64 set,
1569 * then no need to set the weak REG_LIVE_READ32.
1572 /* ... then we depend on parent's value */
1573 parent
->live
|= flag
;
1574 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
1575 if (flag
== REG_LIVE_READ64
)
1576 parent
->live
&= ~REG_LIVE_READ32
;
1578 parent
= state
->parent
;
1583 if (env
->longest_mark_read_walk
< cnt
)
1584 env
->longest_mark_read_walk
= cnt
;
1588 /* This function is supposed to be used by the following 32-bit optimization
1589 * code only. It returns TRUE if the source or destination register operates
1590 * on 64-bit, otherwise return FALSE.
1592 static bool is_reg64(struct bpf_verifier_env
*env
, struct bpf_insn
*insn
,
1593 u32 regno
, struct bpf_reg_state
*reg
, enum reg_arg_type t
)
1598 class = BPF_CLASS(code
);
1600 if (class == BPF_JMP
) {
1601 /* BPF_EXIT for "main" will reach here. Return TRUE
1606 if (op
== BPF_CALL
) {
1607 /* BPF to BPF call will reach here because of marking
1608 * caller saved clobber with DST_OP_NO_MARK for which we
1609 * don't care the register def because they are anyway
1610 * marked as NOT_INIT already.
1612 if (insn
->src_reg
== BPF_PSEUDO_CALL
)
1614 /* Helper call will reach here because of arg type
1615 * check, conservatively return TRUE.
1624 if (class == BPF_ALU64
|| class == BPF_JMP
||
1625 /* BPF_END always use BPF_ALU class. */
1626 (class == BPF_ALU
&& op
== BPF_END
&& insn
->imm
== 64))
1629 if (class == BPF_ALU
|| class == BPF_JMP32
)
1632 if (class == BPF_LDX
) {
1634 return BPF_SIZE(code
) == BPF_DW
;
1635 /* LDX source must be ptr. */
1639 if (class == BPF_STX
) {
1640 if (reg
->type
!= SCALAR_VALUE
)
1642 return BPF_SIZE(code
) == BPF_DW
;
1645 if (class == BPF_LD
) {
1646 u8 mode
= BPF_MODE(code
);
1649 if (mode
== BPF_IMM
)
1652 /* Both LD_IND and LD_ABS return 32-bit data. */
1656 /* Implicit ctx ptr. */
1657 if (regno
== BPF_REG_6
)
1660 /* Explicit source could be any width. */
1664 if (class == BPF_ST
)
1665 /* The only source register for BPF_ST is a ptr. */
1668 /* Conservatively return true at default. */
1672 /* Return TRUE if INSN doesn't have explicit value define. */
1673 static bool insn_no_def(struct bpf_insn
*insn
)
1675 u8
class = BPF_CLASS(insn
->code
);
1677 return (class == BPF_JMP
|| class == BPF_JMP32
||
1678 class == BPF_STX
|| class == BPF_ST
);
1681 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
1682 static bool insn_has_def32(struct bpf_verifier_env
*env
, struct bpf_insn
*insn
)
1684 if (insn_no_def(insn
))
1687 return !is_reg64(env
, insn
, insn
->dst_reg
, NULL
, DST_OP
);
1690 static void mark_insn_zext(struct bpf_verifier_env
*env
,
1691 struct bpf_reg_state
*reg
)
1693 s32 def_idx
= reg
->subreg_def
;
1695 if (def_idx
== DEF_NOT_SUBREG
)
1698 env
->insn_aux_data
[def_idx
- 1].zext_dst
= true;
1699 /* The dst will be zero extended, so won't be sub-register anymore. */
1700 reg
->subreg_def
= DEF_NOT_SUBREG
;
1703 static int check_reg_arg(struct bpf_verifier_env
*env
, u32 regno
,
1704 enum reg_arg_type t
)
1706 struct bpf_verifier_state
*vstate
= env
->cur_state
;
1707 struct bpf_func_state
*state
= vstate
->frame
[vstate
->curframe
];
1708 struct bpf_insn
*insn
= env
->prog
->insnsi
+ env
->insn_idx
;
1709 struct bpf_reg_state
*reg
, *regs
= state
->regs
;
1712 if (regno
>= MAX_BPF_REG
) {
1713 verbose(env
, "R%d is invalid\n", regno
);
1718 rw64
= is_reg64(env
, insn
, regno
, reg
, t
);
1720 /* check whether register used as source operand can be read */
1721 if (reg
->type
== NOT_INIT
) {
1722 verbose(env
, "R%d !read_ok\n", regno
);
1725 /* We don't need to worry about FP liveness because it's read-only */
1726 if (regno
== BPF_REG_FP
)
1730 mark_insn_zext(env
, reg
);
1732 return mark_reg_read(env
, reg
, reg
->parent
,
1733 rw64
? REG_LIVE_READ64
: REG_LIVE_READ32
);
1735 /* check whether register used as dest operand can be written to */
1736 if (regno
== BPF_REG_FP
) {
1737 verbose(env
, "frame pointer is read only\n");
1740 reg
->live
|= REG_LIVE_WRITTEN
;
1741 reg
->subreg_def
= rw64
? DEF_NOT_SUBREG
: env
->insn_idx
+ 1;
1743 mark_reg_unknown(env
, regs
, regno
);
1748 /* for any branch, call, exit record the history of jmps in the given state */
1749 static int push_jmp_history(struct bpf_verifier_env
*env
,
1750 struct bpf_verifier_state
*cur
)
1752 u32 cnt
= cur
->jmp_history_cnt
;
1753 struct bpf_idx_pair
*p
;
1756 p
= krealloc(cur
->jmp_history
, cnt
* sizeof(*p
), GFP_USER
);
1759 p
[cnt
- 1].idx
= env
->insn_idx
;
1760 p
[cnt
- 1].prev_idx
= env
->prev_insn_idx
;
1761 cur
->jmp_history
= p
;
1762 cur
->jmp_history_cnt
= cnt
;
1766 /* Backtrack one insn at a time. If idx is not at the top of recorded
1767 * history then previous instruction came from straight line execution.
1769 static int get_prev_insn_idx(struct bpf_verifier_state
*st
, int i
,
1774 if (cnt
&& st
->jmp_history
[cnt
- 1].idx
== i
) {
1775 i
= st
->jmp_history
[cnt
- 1].prev_idx
;
1783 /* For given verifier state backtrack_insn() is called from the last insn to
1784 * the first insn. Its purpose is to compute a bitmask of registers and
1785 * stack slots that needs precision in the parent verifier state.
1787 static int backtrack_insn(struct bpf_verifier_env
*env
, int idx
,
1788 u32
*reg_mask
, u64
*stack_mask
)
1790 const struct bpf_insn_cbs cbs
= {
1791 .cb_print
= verbose
,
1792 .private_data
= env
,
1794 struct bpf_insn
*insn
= env
->prog
->insnsi
+ idx
;
1795 u8
class = BPF_CLASS(insn
->code
);
1796 u8 opcode
= BPF_OP(insn
->code
);
1797 u8 mode
= BPF_MODE(insn
->code
);
1798 u32 dreg
= 1u << insn
->dst_reg
;
1799 u32 sreg
= 1u << insn
->src_reg
;
1802 if (insn
->code
== 0)
1804 if (env
->log
.level
& BPF_LOG_LEVEL
) {
1805 verbose(env
, "regs=%x stack=%llx before ", *reg_mask
, *stack_mask
);
1806 verbose(env
, "%d: ", idx
);
1807 print_bpf_insn(&cbs
, insn
, env
->allow_ptr_leaks
);
1810 if (class == BPF_ALU
|| class == BPF_ALU64
) {
1811 if (!(*reg_mask
& dreg
))
1813 if (opcode
== BPF_MOV
) {
1814 if (BPF_SRC(insn
->code
) == BPF_X
) {
1816 * dreg needs precision after this insn
1817 * sreg needs precision before this insn
1823 * dreg needs precision after this insn.
1824 * Corresponding register is already marked
1825 * as precise=true in this verifier state.
1826 * No further markings in parent are necessary
1831 if (BPF_SRC(insn
->code
) == BPF_X
) {
1833 * both dreg and sreg need precision
1838 * dreg still needs precision before this insn
1841 } else if (class == BPF_LDX
) {
1842 if (!(*reg_mask
& dreg
))
1846 /* scalars can only be spilled into stack w/o losing precision.
1847 * Load from any other memory can be zero extended.
1848 * The desire to keep that precision is already indicated
1849 * by 'precise' mark in corresponding register of this state.
1850 * No further tracking necessary.
1852 if (insn
->src_reg
!= BPF_REG_FP
)
1854 if (BPF_SIZE(insn
->code
) != BPF_DW
)
1857 /* dreg = *(u64 *)[fp - off] was a fill from the stack.
1858 * that [fp - off] slot contains scalar that needs to be
1859 * tracked with precision
1861 spi
= (-insn
->off
- 1) / BPF_REG_SIZE
;
1863 verbose(env
, "BUG spi %d\n", spi
);
1864 WARN_ONCE(1, "verifier backtracking bug");
1867 *stack_mask
|= 1ull << spi
;
1868 } else if (class == BPF_STX
|| class == BPF_ST
) {
1869 if (*reg_mask
& dreg
)
1870 /* stx & st shouldn't be using _scalar_ dst_reg
1871 * to access memory. It means backtracking
1872 * encountered a case of pointer subtraction.
1875 /* scalars can only be spilled into stack */
1876 if (insn
->dst_reg
!= BPF_REG_FP
)
1878 if (BPF_SIZE(insn
->code
) != BPF_DW
)
1880 spi
= (-insn
->off
- 1) / BPF_REG_SIZE
;
1882 verbose(env
, "BUG spi %d\n", spi
);
1883 WARN_ONCE(1, "verifier backtracking bug");
1886 if (!(*stack_mask
& (1ull << spi
)))
1888 *stack_mask
&= ~(1ull << spi
);
1889 if (class == BPF_STX
)
1891 } else if (class == BPF_JMP
|| class == BPF_JMP32
) {
1892 if (opcode
== BPF_CALL
) {
1893 if (insn
->src_reg
== BPF_PSEUDO_CALL
)
1895 /* regular helper call sets R0 */
1897 if (*reg_mask
& 0x3f) {
1898 /* if backtracing was looking for registers R1-R5
1899 * they should have been found already.
1901 verbose(env
, "BUG regs %x\n", *reg_mask
);
1902 WARN_ONCE(1, "verifier backtracking bug");
1905 } else if (opcode
== BPF_EXIT
) {
1908 } else if (class == BPF_LD
) {
1909 if (!(*reg_mask
& dreg
))
1912 /* It's ld_imm64 or ld_abs or ld_ind.
1913 * For ld_imm64 no further tracking of precision
1914 * into parent is necessary
1916 if (mode
== BPF_IND
|| mode
== BPF_ABS
)
1917 /* to be analyzed */
1923 /* the scalar precision tracking algorithm:
1924 * . at the start all registers have precise=false.
1925 * . scalar ranges are tracked as normal through alu and jmp insns.
1926 * . once precise value of the scalar register is used in:
1927 * . ptr + scalar alu
1928 * . if (scalar cond K|scalar)
1929 * . helper_call(.., scalar, ...) where ARG_CONST is expected
1930 * backtrack through the verifier states and mark all registers and
1931 * stack slots with spilled constants that these scalar regisers
1932 * should be precise.
1933 * . during state pruning two registers (or spilled stack slots)
1934 * are equivalent if both are not precise.
1936 * Note the verifier cannot simply walk register parentage chain,
1937 * since many different registers and stack slots could have been
1938 * used to compute single precise scalar.
1940 * The approach of starting with precise=true for all registers and then
1941 * backtrack to mark a register as not precise when the verifier detects
1942 * that program doesn't care about specific value (e.g., when helper
1943 * takes register as ARG_ANYTHING parameter) is not safe.
1945 * It's ok to walk single parentage chain of the verifier states.
1946 * It's possible that this backtracking will go all the way till 1st insn.
1947 * All other branches will be explored for needing precision later.
1949 * The backtracking needs to deal with cases like:
1950 * 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)
1953 * if r5 > 0x79f goto pc+7
1954 * R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
1957 * call bpf_perf_event_output#25
1958 * where .arg5_type = ARG_CONST_SIZE_OR_ZERO
1962 * call foo // uses callee's r6 inside to compute r0
1966 * to track above reg_mask/stack_mask needs to be independent for each frame.
1968 * Also if parent's curframe > frame where backtracking started,
1969 * the verifier need to mark registers in both frames, otherwise callees
1970 * may incorrectly prune callers. This is similar to
1971 * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
1973 * For now backtracking falls back into conservative marking.
1975 static void mark_all_scalars_precise(struct bpf_verifier_env
*env
,
1976 struct bpf_verifier_state
*st
)
1978 struct bpf_func_state
*func
;
1979 struct bpf_reg_state
*reg
;
1982 /* big hammer: mark all scalars precise in this path.
1983 * pop_stack may still get !precise scalars.
1985 for (; st
; st
= st
->parent
)
1986 for (i
= 0; i
<= st
->curframe
; i
++) {
1987 func
= st
->frame
[i
];
1988 for (j
= 0; j
< BPF_REG_FP
; j
++) {
1989 reg
= &func
->regs
[j
];
1990 if (reg
->type
!= SCALAR_VALUE
)
1992 reg
->precise
= true;
1994 for (j
= 0; j
< func
->allocated_stack
/ BPF_REG_SIZE
; j
++) {
1995 if (func
->stack
[j
].slot_type
[0] != STACK_SPILL
)
1997 reg
= &func
->stack
[j
].spilled_ptr
;
1998 if (reg
->type
!= SCALAR_VALUE
)
2000 reg
->precise
= true;
2005 static int __mark_chain_precision(struct bpf_verifier_env
*env
, int regno
,
2008 struct bpf_verifier_state
*st
= env
->cur_state
;
2009 int first_idx
= st
->first_insn_idx
;
2010 int last_idx
= env
->insn_idx
;
2011 struct bpf_func_state
*func
;
2012 struct bpf_reg_state
*reg
;
2013 u32 reg_mask
= regno
>= 0 ? 1u << regno
: 0;
2014 u64 stack_mask
= spi
>= 0 ? 1ull << spi
: 0;
2015 bool skip_first
= true;
2016 bool new_marks
= false;
2019 if (!env
->bpf_capable
)
2022 func
= st
->frame
[st
->curframe
];
2024 reg
= &func
->regs
[regno
];
2025 if (reg
->type
!= SCALAR_VALUE
) {
2026 WARN_ONCE(1, "backtracing misuse");
2033 reg
->precise
= true;
2037 if (func
->stack
[spi
].slot_type
[0] != STACK_SPILL
) {
2041 reg
= &func
->stack
[spi
].spilled_ptr
;
2042 if (reg
->type
!= SCALAR_VALUE
) {
2050 reg
->precise
= true;
2056 if (!reg_mask
&& !stack_mask
)
2059 DECLARE_BITMAP(mask
, 64);
2060 u32 history
= st
->jmp_history_cnt
;
2062 if (env
->log
.level
& BPF_LOG_LEVEL
)
2063 verbose(env
, "last_idx %d first_idx %d\n", last_idx
, first_idx
);
2064 for (i
= last_idx
;;) {
2069 err
= backtrack_insn(env
, i
, ®_mask
, &stack_mask
);
2071 if (err
== -ENOTSUPP
) {
2072 mark_all_scalars_precise(env
, st
);
2077 if (!reg_mask
&& !stack_mask
)
2078 /* Found assignment(s) into tracked register in this state.
2079 * Since this state is already marked, just return.
2080 * Nothing to be tracked further in the parent state.
2085 i
= get_prev_insn_idx(st
, i
, &history
);
2086 if (i
>= env
->prog
->len
) {
2087 /* This can happen if backtracking reached insn 0
2088 * and there are still reg_mask or stack_mask
2090 * It means the backtracking missed the spot where
2091 * particular register was initialized with a constant.
2093 verbose(env
, "BUG backtracking idx %d\n", i
);
2094 WARN_ONCE(1, "verifier backtracking bug");
2103 func
= st
->frame
[st
->curframe
];
2104 bitmap_from_u64(mask
, reg_mask
);
2105 for_each_set_bit(i
, mask
, 32) {
2106 reg
= &func
->regs
[i
];
2107 if (reg
->type
!= SCALAR_VALUE
) {
2108 reg_mask
&= ~(1u << i
);
2113 reg
->precise
= true;
2116 bitmap_from_u64(mask
, stack_mask
);
2117 for_each_set_bit(i
, mask
, 64) {
2118 if (i
>= func
->allocated_stack
/ BPF_REG_SIZE
) {
2119 /* the sequence of instructions:
2121 * 3: (7b) *(u64 *)(r3 -8) = r0
2122 * 4: (79) r4 = *(u64 *)(r10 -8)
2123 * doesn't contain jmps. It's backtracked
2124 * as a single block.
2125 * During backtracking insn 3 is not recognized as
2126 * stack access, so at the end of backtracking
2127 * stack slot fp-8 is still marked in stack_mask.
2128 * However the parent state may not have accessed
2129 * fp-8 and it's "unallocated" stack space.
2130 * In such case fallback to conservative.
2132 mark_all_scalars_precise(env
, st
);
2136 if (func
->stack
[i
].slot_type
[0] != STACK_SPILL
) {
2137 stack_mask
&= ~(1ull << i
);
2140 reg
= &func
->stack
[i
].spilled_ptr
;
2141 if (reg
->type
!= SCALAR_VALUE
) {
2142 stack_mask
&= ~(1ull << i
);
2147 reg
->precise
= true;
2149 if (env
->log
.level
& BPF_LOG_LEVEL
) {
2150 print_verifier_state(env
, func
);
2151 verbose(env
, "parent %s regs=%x stack=%llx marks\n",
2152 new_marks
? "didn't have" : "already had",
2153 reg_mask
, stack_mask
);
2156 if (!reg_mask
&& !stack_mask
)
2161 last_idx
= st
->last_insn_idx
;
2162 first_idx
= st
->first_insn_idx
;
2167 static int mark_chain_precision(struct bpf_verifier_env
*env
, int regno
)
2169 return __mark_chain_precision(env
, regno
, -1);
2172 static int mark_chain_precision_stack(struct bpf_verifier_env
*env
, int spi
)
2174 return __mark_chain_precision(env
, -1, spi
);
2177 static bool is_spillable_regtype(enum bpf_reg_type type
)
2180 case PTR_TO_MAP_VALUE
:
2181 case PTR_TO_MAP_VALUE_OR_NULL
:
2185 case PTR_TO_PACKET_META
:
2186 case PTR_TO_PACKET_END
:
2187 case PTR_TO_FLOW_KEYS
:
2188 case CONST_PTR_TO_MAP
:
2190 case PTR_TO_SOCKET_OR_NULL
:
2191 case PTR_TO_SOCK_COMMON
:
2192 case PTR_TO_SOCK_COMMON_OR_NULL
:
2193 case PTR_TO_TCP_SOCK
:
2194 case PTR_TO_TCP_SOCK_OR_NULL
:
2195 case PTR_TO_XDP_SOCK
:
2197 case PTR_TO_BTF_ID_OR_NULL
:
2198 case PTR_TO_RDONLY_BUF
:
2199 case PTR_TO_RDONLY_BUF_OR_NULL
:
2200 case PTR_TO_RDWR_BUF
:
2201 case PTR_TO_RDWR_BUF_OR_NULL
:
2208 /* Does this register contain a constant zero? */
2209 static bool register_is_null(struct bpf_reg_state
*reg
)
2211 return reg
->type
== SCALAR_VALUE
&& tnum_equals_const(reg
->var_off
, 0);
2214 static bool register_is_const(struct bpf_reg_state
*reg
)
2216 return reg
->type
== SCALAR_VALUE
&& tnum_is_const(reg
->var_off
);
2219 static bool __is_pointer_value(bool allow_ptr_leaks
,
2220 const struct bpf_reg_state
*reg
)
2222 if (allow_ptr_leaks
)
2225 return reg
->type
!= SCALAR_VALUE
;
2228 static void save_register_state(struct bpf_func_state
*state
,
2229 int spi
, struct bpf_reg_state
*reg
)
2233 state
->stack
[spi
].spilled_ptr
= *reg
;
2234 state
->stack
[spi
].spilled_ptr
.live
|= REG_LIVE_WRITTEN
;
2236 for (i
= 0; i
< BPF_REG_SIZE
; i
++)
2237 state
->stack
[spi
].slot_type
[i
] = STACK_SPILL
;
2240 /* check_stack_read/write functions track spill/fill of registers,
2241 * stack boundary and alignment are checked in check_mem_access()
2243 static int check_stack_write(struct bpf_verifier_env
*env
,
2244 struct bpf_func_state
*state
, /* func where register points to */
2245 int off
, int size
, int value_regno
, int insn_idx
)
2247 struct bpf_func_state
*cur
; /* state of the current function */
2248 int i
, slot
= -off
- 1, spi
= slot
/ BPF_REG_SIZE
, err
;
2249 u32 dst_reg
= env
->prog
->insnsi
[insn_idx
].dst_reg
;
2250 struct bpf_reg_state
*reg
= NULL
;
2252 err
= realloc_func_state(state
, round_up(slot
+ 1, BPF_REG_SIZE
),
2253 state
->acquired_refs
, true);
2256 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
2257 * so it's aligned access and [off, off + size) are within stack limits
2259 if (!env
->allow_ptr_leaks
&&
2260 state
->stack
[spi
].slot_type
[0] == STACK_SPILL
&&
2261 size
!= BPF_REG_SIZE
) {
2262 verbose(env
, "attempt to corrupt spilled pointer on stack\n");
2266 cur
= env
->cur_state
->frame
[env
->cur_state
->curframe
];
2267 if (value_regno
>= 0)
2268 reg
= &cur
->regs
[value_regno
];
2270 if (reg
&& size
== BPF_REG_SIZE
&& register_is_const(reg
) &&
2271 !register_is_null(reg
) && env
->bpf_capable
) {
2272 if (dst_reg
!= BPF_REG_FP
) {
2273 /* The backtracking logic can only recognize explicit
2274 * stack slot address like [fp - 8]. Other spill of
2275 * scalar via different register has to be conervative.
2276 * Backtrack from here and mark all registers as precise
2277 * that contributed into 'reg' being a constant.
2279 err
= mark_chain_precision(env
, value_regno
);
2283 save_register_state(state
, spi
, reg
);
2284 } else if (reg
&& is_spillable_regtype(reg
->type
)) {
2285 /* register containing pointer is being spilled into stack */
2286 if (size
!= BPF_REG_SIZE
) {
2287 verbose_linfo(env
, insn_idx
, "; ");
2288 verbose(env
, "invalid size of register spill\n");
2292 if (state
!= cur
&& reg
->type
== PTR_TO_STACK
) {
2293 verbose(env
, "cannot spill pointers to stack into stack frame of the caller\n");
2297 if (!env
->bypass_spec_v4
) {
2298 bool sanitize
= false;
2300 if (state
->stack
[spi
].slot_type
[0] == STACK_SPILL
&&
2301 register_is_const(&state
->stack
[spi
].spilled_ptr
))
2303 for (i
= 0; i
< BPF_REG_SIZE
; i
++)
2304 if (state
->stack
[spi
].slot_type
[i
] == STACK_MISC
) {
2309 int *poff
= &env
->insn_aux_data
[insn_idx
].sanitize_stack_off
;
2310 int soff
= (-spi
- 1) * BPF_REG_SIZE
;
2312 /* detected reuse of integer stack slot with a pointer
2313 * which means either llvm is reusing stack slot or
2314 * an attacker is trying to exploit CVE-2018-3639
2315 * (speculative store bypass)
2316 * Have to sanitize that slot with preemptive
2319 if (*poff
&& *poff
!= soff
) {
2320 /* disallow programs where single insn stores
2321 * into two different stack slots, since verifier
2322 * cannot sanitize them
2325 "insn %d cannot access two stack slots fp%d and fp%d",
2326 insn_idx
, *poff
, soff
);
2332 save_register_state(state
, spi
, reg
);
2334 u8 type
= STACK_MISC
;
2336 /* regular write of data into stack destroys any spilled ptr */
2337 state
->stack
[spi
].spilled_ptr
.type
= NOT_INIT
;
2338 /* Mark slots as STACK_MISC if they belonged to spilled ptr. */
2339 if (state
->stack
[spi
].slot_type
[0] == STACK_SPILL
)
2340 for (i
= 0; i
< BPF_REG_SIZE
; i
++)
2341 state
->stack
[spi
].slot_type
[i
] = STACK_MISC
;
2343 /* only mark the slot as written if all 8 bytes were written
2344 * otherwise read propagation may incorrectly stop too soon
2345 * when stack slots are partially written.
2346 * This heuristic means that read propagation will be
2347 * conservative, since it will add reg_live_read marks
2348 * to stack slots all the way to first state when programs
2349 * writes+reads less than 8 bytes
2351 if (size
== BPF_REG_SIZE
)
2352 state
->stack
[spi
].spilled_ptr
.live
|= REG_LIVE_WRITTEN
;
2354 /* when we zero initialize stack slots mark them as such */
2355 if (reg
&& register_is_null(reg
)) {
2356 /* backtracking doesn't work for STACK_ZERO yet. */
2357 err
= mark_chain_precision(env
, value_regno
);
2363 /* Mark slots affected by this stack write. */
2364 for (i
= 0; i
< size
; i
++)
2365 state
->stack
[spi
].slot_type
[(slot
- i
) % BPF_REG_SIZE
] =
2371 static int check_stack_read(struct bpf_verifier_env
*env
,
2372 struct bpf_func_state
*reg_state
/* func where register points to */,
2373 int off
, int size
, int value_regno
)
2375 struct bpf_verifier_state
*vstate
= env
->cur_state
;
2376 struct bpf_func_state
*state
= vstate
->frame
[vstate
->curframe
];
2377 int i
, slot
= -off
- 1, spi
= slot
/ BPF_REG_SIZE
;
2378 struct bpf_reg_state
*reg
;
2381 if (reg_state
->allocated_stack
<= slot
) {
2382 verbose(env
, "invalid read from stack off %d+0 size %d\n",
2386 stype
= reg_state
->stack
[spi
].slot_type
;
2387 reg
= ®_state
->stack
[spi
].spilled_ptr
;
2389 if (stype
[0] == STACK_SPILL
) {
2390 if (size
!= BPF_REG_SIZE
) {
2391 if (reg
->type
!= SCALAR_VALUE
) {
2392 verbose_linfo(env
, env
->insn_idx
, "; ");
2393 verbose(env
, "invalid size of register fill\n");
2396 if (value_regno
>= 0) {
2397 mark_reg_unknown(env
, state
->regs
, value_regno
);
2398 state
->regs
[value_regno
].live
|= REG_LIVE_WRITTEN
;
2400 mark_reg_read(env
, reg
, reg
->parent
, REG_LIVE_READ64
);
2403 for (i
= 1; i
< BPF_REG_SIZE
; i
++) {
2404 if (stype
[(slot
- i
) % BPF_REG_SIZE
] != STACK_SPILL
) {
2405 verbose(env
, "corrupted spill memory\n");
2410 if (value_regno
>= 0) {
2411 /* restore register state from stack */
2412 state
->regs
[value_regno
] = *reg
;
2413 /* mark reg as written since spilled pointer state likely
2414 * has its liveness marks cleared by is_state_visited()
2415 * which resets stack/reg liveness for state transitions
2417 state
->regs
[value_regno
].live
|= REG_LIVE_WRITTEN
;
2418 } else if (__is_pointer_value(env
->allow_ptr_leaks
, reg
)) {
2419 /* If value_regno==-1, the caller is asking us whether
2420 * it is acceptable to use this value as a SCALAR_VALUE
2422 * We must not allow unprivileged callers to do that
2423 * with spilled pointers.
2425 verbose(env
, "leaking pointer from stack off %d\n",
2429 mark_reg_read(env
, reg
, reg
->parent
, REG_LIVE_READ64
);
2433 for (i
= 0; i
< size
; i
++) {
2434 if (stype
[(slot
- i
) % BPF_REG_SIZE
] == STACK_MISC
)
2436 if (stype
[(slot
- i
) % BPF_REG_SIZE
] == STACK_ZERO
) {
2440 verbose(env
, "invalid read from stack off %d+%d size %d\n",
2444 mark_reg_read(env
, reg
, reg
->parent
, REG_LIVE_READ64
);
2445 if (value_regno
>= 0) {
2446 if (zeros
== size
) {
2447 /* any size read into register is zero extended,
2448 * so the whole register == const_zero
2450 __mark_reg_const_zero(&state
->regs
[value_regno
]);
2451 /* backtracking doesn't support STACK_ZERO yet,
2452 * so mark it precise here, so that later
2453 * backtracking can stop here.
2454 * Backtracking may not need this if this register
2455 * doesn't participate in pointer adjustment.
2456 * Forward propagation of precise flag is not
2457 * necessary either. This mark is only to stop
2458 * backtracking. Any register that contributed
2459 * to const 0 was marked precise before spill.
2461 state
->regs
[value_regno
].precise
= true;
2463 /* have read misc data from the stack */
2464 mark_reg_unknown(env
, state
->regs
, value_regno
);
2466 state
->regs
[value_regno
].live
|= REG_LIVE_WRITTEN
;
2472 static int check_stack_access(struct bpf_verifier_env
*env
,
2473 const struct bpf_reg_state
*reg
,
2476 /* Stack accesses must be at a fixed offset, so that we
2477 * can determine what type of data were returned. See
2478 * check_stack_read().
2480 if (!tnum_is_const(reg
->var_off
)) {
2483 tnum_strn(tn_buf
, sizeof(tn_buf
), reg
->var_off
);
2484 verbose(env
, "variable stack access var_off=%s off=%d size=%d\n",
2489 if (off
>= 0 || off
< -MAX_BPF_STACK
) {
2490 verbose(env
, "invalid stack off=%d size=%d\n", off
, size
);
2497 static int check_map_access_type(struct bpf_verifier_env
*env
, u32 regno
,
2498 int off
, int size
, enum bpf_access_type type
)
2500 struct bpf_reg_state
*regs
= cur_regs(env
);
2501 struct bpf_map
*map
= regs
[regno
].map_ptr
;
2502 u32 cap
= bpf_map_flags_to_cap(map
);
2504 if (type
== BPF_WRITE
&& !(cap
& BPF_MAP_CAN_WRITE
)) {
2505 verbose(env
, "write into map forbidden, value_size=%d off=%d size=%d\n",
2506 map
->value_size
, off
, size
);
2510 if (type
== BPF_READ
&& !(cap
& BPF_MAP_CAN_READ
)) {
2511 verbose(env
, "read from map forbidden, value_size=%d off=%d size=%d\n",
2512 map
->value_size
, off
, size
);
2519 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
2520 static int __check_mem_access(struct bpf_verifier_env
*env
, int regno
,
2521 int off
, int size
, u32 mem_size
,
2522 bool zero_size_allowed
)
2524 bool size_ok
= size
> 0 || (size
== 0 && zero_size_allowed
);
2525 struct bpf_reg_state
*reg
;
2527 if (off
>= 0 && size_ok
&& (u64
)off
+ size
<= mem_size
)
2530 reg
= &cur_regs(env
)[regno
];
2531 switch (reg
->type
) {
2532 case PTR_TO_MAP_VALUE
:
2533 verbose(env
, "invalid access to map value, value_size=%d off=%d size=%d\n",
2534 mem_size
, off
, size
);
2537 case PTR_TO_PACKET_META
:
2538 case PTR_TO_PACKET_END
:
2539 verbose(env
, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
2540 off
, size
, regno
, reg
->id
, off
, mem_size
);
2544 verbose(env
, "invalid access to memory, mem_size=%u off=%d size=%d\n",
2545 mem_size
, off
, size
);
2551 /* check read/write into a memory region with possible variable offset */
2552 static int check_mem_region_access(struct bpf_verifier_env
*env
, u32 regno
,
2553 int off
, int size
, u32 mem_size
,
2554 bool zero_size_allowed
)
2556 struct bpf_verifier_state
*vstate
= env
->cur_state
;
2557 struct bpf_func_state
*state
= vstate
->frame
[vstate
->curframe
];
2558 struct bpf_reg_state
*reg
= &state
->regs
[regno
];
2561 /* We may have adjusted the register pointing to memory region, so we
2562 * need to try adding each of min_value and max_value to off
2563 * to make sure our theoretical access will be safe.
2565 if (env
->log
.level
& BPF_LOG_LEVEL
)
2566 print_verifier_state(env
, state
);
2568 /* The minimum value is only important with signed
2569 * comparisons where we can't assume the floor of a
2570 * value is 0. If we are using signed variables for our
2571 * index'es we need to make sure that whatever we use
2572 * will have a set floor within our range.
2574 if (reg
->smin_value
< 0 &&
2575 (reg
->smin_value
== S64_MIN
||
2576 (off
+ reg
->smin_value
!= (s64
)(s32
)(off
+ reg
->smin_value
)) ||
2577 reg
->smin_value
+ off
< 0)) {
2578 verbose(env
, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
2582 err
= __check_mem_access(env
, regno
, reg
->smin_value
+ off
, size
,
2583 mem_size
, zero_size_allowed
);
2585 verbose(env
, "R%d min value is outside of the allowed memory range\n",
2590 /* If we haven't set a max value then we need to bail since we can't be
2591 * sure we won't do bad things.
2592 * If reg->umax_value + off could overflow, treat that as unbounded too.
2594 if (reg
->umax_value
>= BPF_MAX_VAR_OFF
) {
2595 verbose(env
, "R%d unbounded memory access, make sure to bounds check any such access\n",
2599 err
= __check_mem_access(env
, regno
, reg
->umax_value
+ off
, size
,
2600 mem_size
, zero_size_allowed
);
2602 verbose(env
, "R%d max value is outside of the allowed memory range\n",
2610 /* check read/write into a map element with possible variable offset */
2611 static int check_map_access(struct bpf_verifier_env
*env
, u32 regno
,
2612 int off
, int size
, bool zero_size_allowed
)
2614 struct bpf_verifier_state
*vstate
= env
->cur_state
;
2615 struct bpf_func_state
*state
= vstate
->frame
[vstate
->curframe
];
2616 struct bpf_reg_state
*reg
= &state
->regs
[regno
];
2617 struct bpf_map
*map
= reg
->map_ptr
;
2620 err
= check_mem_region_access(env
, regno
, off
, size
, map
->value_size
,
2625 if (map_value_has_spin_lock(map
)) {
2626 u32 lock
= map
->spin_lock_off
;
2628 /* if any part of struct bpf_spin_lock can be touched by
2629 * load/store reject this program.
2630 * To check that [x1, x2) overlaps with [y1, y2)
2631 * it is sufficient to check x1 < y2 && y1 < x2.
2633 if (reg
->smin_value
+ off
< lock
+ sizeof(struct bpf_spin_lock
) &&
2634 lock
< reg
->umax_value
+ off
+ size
) {
2635 verbose(env
, "bpf_spin_lock cannot be accessed directly by load/store\n");
2642 #define MAX_PACKET_OFF 0xffff
2644 static enum bpf_prog_type
resolve_prog_type(struct bpf_prog
*prog
)
2646 return prog
->aux
->linked_prog
? prog
->aux
->linked_prog
->type
2650 static bool may_access_direct_pkt_data(struct bpf_verifier_env
*env
,
2651 const struct bpf_call_arg_meta
*meta
,
2652 enum bpf_access_type t
)
2654 enum bpf_prog_type prog_type
= resolve_prog_type(env
->prog
);
2656 switch (prog_type
) {
2657 /* Program types only with direct read access go here! */
2658 case BPF_PROG_TYPE_LWT_IN
:
2659 case BPF_PROG_TYPE_LWT_OUT
:
2660 case BPF_PROG_TYPE_LWT_SEG6LOCAL
:
2661 case BPF_PROG_TYPE_SK_REUSEPORT
:
2662 case BPF_PROG_TYPE_FLOW_DISSECTOR
:
2663 case BPF_PROG_TYPE_CGROUP_SKB
:
2668 /* Program types with direct read + write access go here! */
2669 case BPF_PROG_TYPE_SCHED_CLS
:
2670 case BPF_PROG_TYPE_SCHED_ACT
:
2671 case BPF_PROG_TYPE_XDP
:
2672 case BPF_PROG_TYPE_LWT_XMIT
:
2673 case BPF_PROG_TYPE_SK_SKB
:
2674 case BPF_PROG_TYPE_SK_MSG
:
2676 return meta
->pkt_access
;
2678 env
->seen_direct_write
= true;
2681 case BPF_PROG_TYPE_CGROUP_SOCKOPT
:
2683 env
->seen_direct_write
= true;
2692 static int check_packet_access(struct bpf_verifier_env
*env
, u32 regno
, int off
,
2693 int size
, bool zero_size_allowed
)
2695 struct bpf_reg_state
*regs
= cur_regs(env
);
2696 struct bpf_reg_state
*reg
= ®s
[regno
];
2699 /* We may have added a variable offset to the packet pointer; but any
2700 * reg->range we have comes after that. We are only checking the fixed
2704 /* We don't allow negative numbers, because we aren't tracking enough
2705 * detail to prove they're safe.
2707 if (reg
->smin_value
< 0) {
2708 verbose(env
, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
2712 err
= __check_mem_access(env
, regno
, off
, size
, reg
->range
,
2715 verbose(env
, "R%d offset is outside of the packet\n", regno
);
2719 /* __check_mem_access has made sure "off + size - 1" is within u16.
2720 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
2721 * otherwise find_good_pkt_pointers would have refused to set range info
2722 * that __check_mem_access would have rejected this pkt access.
2723 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
2725 env
->prog
->aux
->max_pkt_offset
=
2726 max_t(u32
, env
->prog
->aux
->max_pkt_offset
,
2727 off
+ reg
->umax_value
+ size
- 1);
2732 /* check access to 'struct bpf_context' fields. Supports fixed offsets only */
2733 static int check_ctx_access(struct bpf_verifier_env
*env
, int insn_idx
, int off
, int size
,
2734 enum bpf_access_type t
, enum bpf_reg_type
*reg_type
,
2737 struct bpf_insn_access_aux info
= {
2738 .reg_type
= *reg_type
,
2742 if (env
->ops
->is_valid_access
&&
2743 env
->ops
->is_valid_access(off
, size
, t
, env
->prog
, &info
)) {
2744 /* A non zero info.ctx_field_size indicates that this field is a
2745 * candidate for later verifier transformation to load the whole
2746 * field and then apply a mask when accessed with a narrower
2747 * access than actual ctx access size. A zero info.ctx_field_size
2748 * will only allow for whole field access and rejects any other
2749 * type of narrower access.
2751 *reg_type
= info
.reg_type
;
2753 if (*reg_type
== PTR_TO_BTF_ID
|| *reg_type
== PTR_TO_BTF_ID_OR_NULL
)
2754 *btf_id
= info
.btf_id
;
2756 env
->insn_aux_data
[insn_idx
].ctx_field_size
= info
.ctx_field_size
;
2757 /* remember the offset of last byte accessed in ctx */
2758 if (env
->prog
->aux
->max_ctx_offset
< off
+ size
)
2759 env
->prog
->aux
->max_ctx_offset
= off
+ size
;
2763 verbose(env
, "invalid bpf_context access off=%d size=%d\n", off
, size
);
2767 static int check_flow_keys_access(struct bpf_verifier_env
*env
, int off
,
2770 if (size
< 0 || off
< 0 ||
2771 (u64
)off
+ size
> sizeof(struct bpf_flow_keys
)) {
2772 verbose(env
, "invalid access to flow keys off=%d size=%d\n",
2779 static int check_sock_access(struct bpf_verifier_env
*env
, int insn_idx
,
2780 u32 regno
, int off
, int size
,
2781 enum bpf_access_type t
)
2783 struct bpf_reg_state
*regs
= cur_regs(env
);
2784 struct bpf_reg_state
*reg
= ®s
[regno
];
2785 struct bpf_insn_access_aux info
= {};
2788 if (reg
->smin_value
< 0) {
2789 verbose(env
, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
2794 switch (reg
->type
) {
2795 case PTR_TO_SOCK_COMMON
:
2796 valid
= bpf_sock_common_is_valid_access(off
, size
, t
, &info
);
2799 valid
= bpf_sock_is_valid_access(off
, size
, t
, &info
);
2801 case PTR_TO_TCP_SOCK
:
2802 valid
= bpf_tcp_sock_is_valid_access(off
, size
, t
, &info
);
2804 case PTR_TO_XDP_SOCK
:
2805 valid
= bpf_xdp_sock_is_valid_access(off
, size
, t
, &info
);
2813 env
->insn_aux_data
[insn_idx
].ctx_field_size
=
2814 info
.ctx_field_size
;
2818 verbose(env
, "R%d invalid %s access off=%d size=%d\n",
2819 regno
, reg_type_str
[reg
->type
], off
, size
);
2824 static struct bpf_reg_state
*reg_state(struct bpf_verifier_env
*env
, int regno
)
2826 return cur_regs(env
) + regno
;
2829 static bool is_pointer_value(struct bpf_verifier_env
*env
, int regno
)
2831 return __is_pointer_value(env
->allow_ptr_leaks
, reg_state(env
, regno
));
2834 static bool is_ctx_reg(struct bpf_verifier_env
*env
, int regno
)
2836 const struct bpf_reg_state
*reg
= reg_state(env
, regno
);
2838 return reg
->type
== PTR_TO_CTX
;
2841 static bool is_sk_reg(struct bpf_verifier_env
*env
, int regno
)
2843 const struct bpf_reg_state
*reg
= reg_state(env
, regno
);
2845 return type_is_sk_pointer(reg
->type
);
2848 static bool is_pkt_reg(struct bpf_verifier_env
*env
, int regno
)
2850 const struct bpf_reg_state
*reg
= reg_state(env
, regno
);
2852 return type_is_pkt_pointer(reg
->type
);
2855 static bool is_flow_key_reg(struct bpf_verifier_env
*env
, int regno
)
2857 const struct bpf_reg_state
*reg
= reg_state(env
, regno
);
2859 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
2860 return reg
->type
== PTR_TO_FLOW_KEYS
;
2863 static int check_pkt_ptr_alignment(struct bpf_verifier_env
*env
,
2864 const struct bpf_reg_state
*reg
,
2865 int off
, int size
, bool strict
)
2867 struct tnum reg_off
;
2870 /* Byte size accesses are always allowed. */
2871 if (!strict
|| size
== 1)
2874 /* For platforms that do not have a Kconfig enabling
2875 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
2876 * NET_IP_ALIGN is universally set to '2'. And on platforms
2877 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
2878 * to this code only in strict mode where we want to emulate
2879 * the NET_IP_ALIGN==2 checking. Therefore use an
2880 * unconditional IP align value of '2'.
2884 reg_off
= tnum_add(reg
->var_off
, tnum_const(ip_align
+ reg
->off
+ off
));
2885 if (!tnum_is_aligned(reg_off
, size
)) {
2888 tnum_strn(tn_buf
, sizeof(tn_buf
), reg
->var_off
);
2890 "misaligned packet access off %d+%s+%d+%d size %d\n",
2891 ip_align
, tn_buf
, reg
->off
, off
, size
);
2898 static int check_generic_ptr_alignment(struct bpf_verifier_env
*env
,
2899 const struct bpf_reg_state
*reg
,
2900 const char *pointer_desc
,
2901 int off
, int size
, bool strict
)
2903 struct tnum reg_off
;
2905 /* Byte size accesses are always allowed. */
2906 if (!strict
|| size
== 1)
2909 reg_off
= tnum_add(reg
->var_off
, tnum_const(reg
->off
+ off
));
2910 if (!tnum_is_aligned(reg_off
, size
)) {
2913 tnum_strn(tn_buf
, sizeof(tn_buf
), reg
->var_off
);
2914 verbose(env
, "misaligned %saccess off %s+%d+%d size %d\n",
2915 pointer_desc
, tn_buf
, reg
->off
, off
, size
);
2922 static int check_ptr_alignment(struct bpf_verifier_env
*env
,
2923 const struct bpf_reg_state
*reg
, int off
,
2924 int size
, bool strict_alignment_once
)
2926 bool strict
= env
->strict_alignment
|| strict_alignment_once
;
2927 const char *pointer_desc
= "";
2929 switch (reg
->type
) {
2931 case PTR_TO_PACKET_META
:
2932 /* Special case, because of NET_IP_ALIGN. Given metadata sits
2933 * right in front, treat it the very same way.
2935 return check_pkt_ptr_alignment(env
, reg
, off
, size
, strict
);
2936 case PTR_TO_FLOW_KEYS
:
2937 pointer_desc
= "flow keys ";
2939 case PTR_TO_MAP_VALUE
:
2940 pointer_desc
= "value ";
2943 pointer_desc
= "context ";
2946 pointer_desc
= "stack ";
2947 /* The stack spill tracking logic in check_stack_write()
2948 * and check_stack_read() relies on stack accesses being
2954 pointer_desc
= "sock ";
2956 case PTR_TO_SOCK_COMMON
:
2957 pointer_desc
= "sock_common ";
2959 case PTR_TO_TCP_SOCK
:
2960 pointer_desc
= "tcp_sock ";
2962 case PTR_TO_XDP_SOCK
:
2963 pointer_desc
= "xdp_sock ";
2968 return check_generic_ptr_alignment(env
, reg
, pointer_desc
, off
, size
,
2972 static int update_stack_depth(struct bpf_verifier_env
*env
,
2973 const struct bpf_func_state
*func
,
2976 u16 stack
= env
->subprog_info
[func
->subprogno
].stack_depth
;
2981 /* update known max for given subprogram */
2982 env
->subprog_info
[func
->subprogno
].stack_depth
= -off
;
2986 /* starting from main bpf function walk all instructions of the function
2987 * and recursively walk all callees that given function can call.
2988 * Ignore jump and exit insns.
2989 * Since recursion is prevented by check_cfg() this algorithm
2990 * only needs a local stack of MAX_CALL_FRAMES to remember callsites
2992 static int check_max_stack_depth(struct bpf_verifier_env
*env
)
2994 int depth
= 0, frame
= 0, idx
= 0, i
= 0, subprog_end
;
2995 struct bpf_subprog_info
*subprog
= env
->subprog_info
;
2996 struct bpf_insn
*insn
= env
->prog
->insnsi
;
2997 bool tail_call_reachable
= false;
2998 int ret_insn
[MAX_CALL_FRAMES
];
2999 int ret_prog
[MAX_CALL_FRAMES
];
3003 /* protect against potential stack overflow that might happen when
3004 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
3005 * depth for such case down to 256 so that the worst case scenario
3006 * would result in 8k stack size (32 which is tailcall limit * 256 =
3009 * To get the idea what might happen, see an example:
3010 * func1 -> sub rsp, 128
3011 * subfunc1 -> sub rsp, 256
3012 * tailcall1 -> add rsp, 256
3013 * func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
3014 * subfunc2 -> sub rsp, 64
3015 * subfunc22 -> sub rsp, 128
3016 * tailcall2 -> add rsp, 128
3017 * func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
3019 * tailcall will unwind the current stack frame but it will not get rid
3020 * of caller's stack as shown on the example above.
3022 if (idx
&& subprog
[idx
].has_tail_call
&& depth
>= 256) {
3024 "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
3028 /* round up to 32-bytes, since this is granularity
3029 * of interpreter stack size
3031 depth
+= round_up(max_t(u32
, subprog
[idx
].stack_depth
, 1), 32);
3032 if (depth
> MAX_BPF_STACK
) {
3033 verbose(env
, "combined stack size of %d calls is %d. Too large\n",
3038 subprog_end
= subprog
[idx
+ 1].start
;
3039 for (; i
< subprog_end
; i
++) {
3040 if (insn
[i
].code
!= (BPF_JMP
| BPF_CALL
))
3042 if (insn
[i
].src_reg
!= BPF_PSEUDO_CALL
)
3044 /* remember insn and function to return to */
3045 ret_insn
[frame
] = i
+ 1;
3046 ret_prog
[frame
] = idx
;
3048 /* find the callee */
3049 i
= i
+ insn
[i
].imm
+ 1;
3050 idx
= find_subprog(env
, i
);
3052 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
3057 if (subprog
[idx
].has_tail_call
)
3058 tail_call_reachable
= true;
3061 if (frame
>= MAX_CALL_FRAMES
) {
3062 verbose(env
, "the call stack of %d frames is too deep !\n",
3068 /* if tail call got detected across bpf2bpf calls then mark each of the
3069 * currently present subprog frames as tail call reachable subprogs;
3070 * this info will be utilized by JIT so that we will be preserving the
3071 * tail call counter throughout bpf2bpf calls combined with tailcalls
3073 if (tail_call_reachable
)
3074 for (j
= 0; j
< frame
; j
++)
3075 subprog
[ret_prog
[j
]].tail_call_reachable
= true;
3077 /* end of for() loop means the last insn of the 'subprog'
3078 * was reached. Doesn't matter whether it was JA or EXIT
3082 depth
-= round_up(max_t(u32
, subprog
[idx
].stack_depth
, 1), 32);
3084 i
= ret_insn
[frame
];
3085 idx
= ret_prog
[frame
];
3089 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
3090 static int get_callee_stack_depth(struct bpf_verifier_env
*env
,
3091 const struct bpf_insn
*insn
, int idx
)
3093 int start
= idx
+ insn
->imm
+ 1, subprog
;
3095 subprog
= find_subprog(env
, start
);
3097 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
3101 return env
->subprog_info
[subprog
].stack_depth
;
3105 int check_ctx_reg(struct bpf_verifier_env
*env
,
3106 const struct bpf_reg_state
*reg
, int regno
)
3108 /* Access to ctx or passing it to a helper is only allowed in
3109 * its original, unmodified form.
3113 verbose(env
, "dereference of modified ctx ptr R%d off=%d disallowed\n",
3118 if (!tnum_is_const(reg
->var_off
) || reg
->var_off
.value
) {
3121 tnum_strn(tn_buf
, sizeof(tn_buf
), reg
->var_off
);
3122 verbose(env
, "variable ctx access var_off=%s disallowed\n", tn_buf
);
3129 static int __check_buffer_access(struct bpf_verifier_env
*env
,
3130 const char *buf_info
,
3131 const struct bpf_reg_state
*reg
,
3132 int regno
, int off
, int size
)
3136 "R%d invalid %s buffer access: off=%d, size=%d\n",
3137 regno
, buf_info
, off
, size
);
3140 if (!tnum_is_const(reg
->var_off
) || reg
->var_off
.value
) {
3143 tnum_strn(tn_buf
, sizeof(tn_buf
), reg
->var_off
);
3145 "R%d invalid variable buffer offset: off=%d, var_off=%s\n",
3146 regno
, off
, tn_buf
);
3153 static int check_tp_buffer_access(struct bpf_verifier_env
*env
,
3154 const struct bpf_reg_state
*reg
,
3155 int regno
, int off
, int size
)
3159 err
= __check_buffer_access(env
, "tracepoint", reg
, regno
, off
, size
);
3163 if (off
+ size
> env
->prog
->aux
->max_tp_access
)
3164 env
->prog
->aux
->max_tp_access
= off
+ size
;
3169 static int check_buffer_access(struct bpf_verifier_env
*env
,
3170 const struct bpf_reg_state
*reg
,
3171 int regno
, int off
, int size
,
3172 bool zero_size_allowed
,
3173 const char *buf_info
,
3178 err
= __check_buffer_access(env
, buf_info
, reg
, regno
, off
, size
);
3182 if (off
+ size
> *max_access
)
3183 *max_access
= off
+ size
;
3188 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
3189 static void zext_32_to_64(struct bpf_reg_state
*reg
)
3191 reg
->var_off
= tnum_subreg(reg
->var_off
);
3192 __reg_assign_32_into_64(reg
);
3195 /* truncate register to smaller size (in bytes)
3196 * must be called with size < BPF_REG_SIZE
3198 static void coerce_reg_to_size(struct bpf_reg_state
*reg
, int size
)
3202 /* clear high bits in bit representation */
3203 reg
->var_off
= tnum_cast(reg
->var_off
, size
);
3205 /* fix arithmetic bounds */
3206 mask
= ((u64
)1 << (size
* 8)) - 1;
3207 if ((reg
->umin_value
& ~mask
) == (reg
->umax_value
& ~mask
)) {
3208 reg
->umin_value
&= mask
;
3209 reg
->umax_value
&= mask
;
3211 reg
->umin_value
= 0;
3212 reg
->umax_value
= mask
;
3214 reg
->smin_value
= reg
->umin_value
;
3215 reg
->smax_value
= reg
->umax_value
;
3217 /* If size is smaller than 32bit register the 32bit register
3218 * values are also truncated so we push 64-bit bounds into
3219 * 32-bit bounds. Above were truncated < 32-bits already.
3223 __reg_combine_64_into_32(reg
);
3226 static bool bpf_map_is_rdonly(const struct bpf_map
*map
)
3228 return (map
->map_flags
& BPF_F_RDONLY_PROG
) && map
->frozen
;
3231 static int bpf_map_direct_read(struct bpf_map
*map
, int off
, int size
, u64
*val
)
3237 err
= map
->ops
->map_direct_value_addr(map
, &addr
, off
);
3240 ptr
= (void *)(long)addr
+ off
;
3244 *val
= (u64
)*(u8
*)ptr
;
3247 *val
= (u64
)*(u16
*)ptr
;
3250 *val
= (u64
)*(u32
*)ptr
;
3261 static int check_ptr_to_btf_access(struct bpf_verifier_env
*env
,
3262 struct bpf_reg_state
*regs
,
3263 int regno
, int off
, int size
,
3264 enum bpf_access_type atype
,
3267 struct bpf_reg_state
*reg
= regs
+ regno
;
3268 const struct btf_type
*t
= btf_type_by_id(btf_vmlinux
, reg
->btf_id
);
3269 const char *tname
= btf_name_by_offset(btf_vmlinux
, t
->name_off
);
3275 "R%d is ptr_%s invalid negative access: off=%d\n",
3279 if (!tnum_is_const(reg
->var_off
) || reg
->var_off
.value
) {
3282 tnum_strn(tn_buf
, sizeof(tn_buf
), reg
->var_off
);
3284 "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
3285 regno
, tname
, off
, tn_buf
);
3289 if (env
->ops
->btf_struct_access
) {
3290 ret
= env
->ops
->btf_struct_access(&env
->log
, t
, off
, size
,
3293 if (atype
!= BPF_READ
) {
3294 verbose(env
, "only read is supported\n");
3298 ret
= btf_struct_access(&env
->log
, t
, off
, size
, atype
,
3305 if (atype
== BPF_READ
&& value_regno
>= 0)
3306 mark_btf_ld_reg(env
, regs
, value_regno
, ret
, btf_id
);
3311 static int check_ptr_to_map_access(struct bpf_verifier_env
*env
,
3312 struct bpf_reg_state
*regs
,
3313 int regno
, int off
, int size
,
3314 enum bpf_access_type atype
,
3317 struct bpf_reg_state
*reg
= regs
+ regno
;
3318 struct bpf_map
*map
= reg
->map_ptr
;
3319 const struct btf_type
*t
;
3325 verbose(env
, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
3329 if (!map
->ops
->map_btf_id
|| !*map
->ops
->map_btf_id
) {
3330 verbose(env
, "map_ptr access not supported for map type %d\n",
3335 t
= btf_type_by_id(btf_vmlinux
, *map
->ops
->map_btf_id
);
3336 tname
= btf_name_by_offset(btf_vmlinux
, t
->name_off
);
3338 if (!env
->allow_ptr_to_map_access
) {
3340 "%s access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
3346 verbose(env
, "R%d is %s invalid negative access: off=%d\n",
3351 if (atype
!= BPF_READ
) {
3352 verbose(env
, "only read from %s is supported\n", tname
);
3356 ret
= btf_struct_access(&env
->log
, t
, off
, size
, atype
, &btf_id
);
3360 if (value_regno
>= 0)
3361 mark_btf_ld_reg(env
, regs
, value_regno
, ret
, btf_id
);
3367 /* check whether memory at (regno + off) is accessible for t = (read | write)
3368 * if t==write, value_regno is a register which value is stored into memory
3369 * if t==read, value_regno is a register which will receive the value from memory
3370 * if t==write && value_regno==-1, some unknown value is stored into memory
3371 * if t==read && value_regno==-1, don't care what we read from memory
3373 static int check_mem_access(struct bpf_verifier_env
*env
, int insn_idx
, u32 regno
,
3374 int off
, int bpf_size
, enum bpf_access_type t
,
3375 int value_regno
, bool strict_alignment_once
)
3377 struct bpf_reg_state
*regs
= cur_regs(env
);
3378 struct bpf_reg_state
*reg
= regs
+ regno
;
3379 struct bpf_func_state
*state
;
3382 size
= bpf_size_to_bytes(bpf_size
);
3386 /* alignment checks will add in reg->off themselves */
3387 err
= check_ptr_alignment(env
, reg
, off
, size
, strict_alignment_once
);
3391 /* for access checks, reg->off is just part of off */
3394 if (reg
->type
== PTR_TO_MAP_VALUE
) {
3395 if (t
== BPF_WRITE
&& value_regno
>= 0 &&
3396 is_pointer_value(env
, value_regno
)) {
3397 verbose(env
, "R%d leaks addr into map\n", value_regno
);
3400 err
= check_map_access_type(env
, regno
, off
, size
, t
);
3403 err
= check_map_access(env
, regno
, off
, size
, false);
3404 if (!err
&& t
== BPF_READ
&& value_regno
>= 0) {
3405 struct bpf_map
*map
= reg
->map_ptr
;
3407 /* if map is read-only, track its contents as scalars */
3408 if (tnum_is_const(reg
->var_off
) &&
3409 bpf_map_is_rdonly(map
) &&
3410 map
->ops
->map_direct_value_addr
) {
3411 int map_off
= off
+ reg
->var_off
.value
;
3414 err
= bpf_map_direct_read(map
, map_off
, size
,
3419 regs
[value_regno
].type
= SCALAR_VALUE
;
3420 __mark_reg_known(®s
[value_regno
], val
);
3422 mark_reg_unknown(env
, regs
, value_regno
);
3425 } else if (reg
->type
== PTR_TO_MEM
) {
3426 if (t
== BPF_WRITE
&& value_regno
>= 0 &&
3427 is_pointer_value(env
, value_regno
)) {
3428 verbose(env
, "R%d leaks addr into mem\n", value_regno
);
3431 err
= check_mem_region_access(env
, regno
, off
, size
,
3432 reg
->mem_size
, false);
3433 if (!err
&& t
== BPF_READ
&& value_regno
>= 0)
3434 mark_reg_unknown(env
, regs
, value_regno
);
3435 } else if (reg
->type
== PTR_TO_CTX
) {
3436 enum bpf_reg_type reg_type
= SCALAR_VALUE
;
3439 if (t
== BPF_WRITE
&& value_regno
>= 0 &&
3440 is_pointer_value(env
, value_regno
)) {
3441 verbose(env
, "R%d leaks addr into ctx\n", value_regno
);
3445 err
= check_ctx_reg(env
, reg
, regno
);
3449 err
= check_ctx_access(env
, insn_idx
, off
, size
, t
, ®_type
, &btf_id
);
3451 verbose_linfo(env
, insn_idx
, "; ");
3452 if (!err
&& t
== BPF_READ
&& value_regno
>= 0) {
3453 /* ctx access returns either a scalar, or a
3454 * PTR_TO_PACKET[_META,_END]. In the latter
3455 * case, we know the offset is zero.
3457 if (reg_type
== SCALAR_VALUE
) {
3458 mark_reg_unknown(env
, regs
, value_regno
);
3460 mark_reg_known_zero(env
, regs
,
3462 if (reg_type_may_be_null(reg_type
))
3463 regs
[value_regno
].id
= ++env
->id_gen
;
3464 /* A load of ctx field could have different
3465 * actual load size with the one encoded in the
3466 * insn. When the dst is PTR, it is for sure not
3469 regs
[value_regno
].subreg_def
= DEF_NOT_SUBREG
;
3470 if (reg_type
== PTR_TO_BTF_ID
||
3471 reg_type
== PTR_TO_BTF_ID_OR_NULL
)
3472 regs
[value_regno
].btf_id
= btf_id
;
3474 regs
[value_regno
].type
= reg_type
;
3477 } else if (reg
->type
== PTR_TO_STACK
) {
3478 off
+= reg
->var_off
.value
;
3479 err
= check_stack_access(env
, reg
, off
, size
);
3483 state
= func(env
, reg
);
3484 err
= update_stack_depth(env
, state
, off
);
3489 err
= check_stack_write(env
, state
, off
, size
,
3490 value_regno
, insn_idx
);
3492 err
= check_stack_read(env
, state
, off
, size
,
3494 } else if (reg_is_pkt_pointer(reg
)) {
3495 if (t
== BPF_WRITE
&& !may_access_direct_pkt_data(env
, NULL
, t
)) {
3496 verbose(env
, "cannot write into packet\n");
3499 if (t
== BPF_WRITE
&& value_regno
>= 0 &&
3500 is_pointer_value(env
, value_regno
)) {
3501 verbose(env
, "R%d leaks addr into packet\n",
3505 err
= check_packet_access(env
, regno
, off
, size
, false);
3506 if (!err
&& t
== BPF_READ
&& value_regno
>= 0)
3507 mark_reg_unknown(env
, regs
, value_regno
);
3508 } else if (reg
->type
== PTR_TO_FLOW_KEYS
) {
3509 if (t
== BPF_WRITE
&& value_regno
>= 0 &&
3510 is_pointer_value(env
, value_regno
)) {
3511 verbose(env
, "R%d leaks addr into flow keys\n",
3516 err
= check_flow_keys_access(env
, off
, size
);
3517 if (!err
&& t
== BPF_READ
&& value_regno
>= 0)
3518 mark_reg_unknown(env
, regs
, value_regno
);
3519 } else if (type_is_sk_pointer(reg
->type
)) {
3520 if (t
== BPF_WRITE
) {
3521 verbose(env
, "R%d cannot write into %s\n",
3522 regno
, reg_type_str
[reg
->type
]);
3525 err
= check_sock_access(env
, insn_idx
, regno
, off
, size
, t
);
3526 if (!err
&& value_regno
>= 0)
3527 mark_reg_unknown(env
, regs
, value_regno
);
3528 } else if (reg
->type
== PTR_TO_TP_BUFFER
) {
3529 err
= check_tp_buffer_access(env
, reg
, regno
, off
, size
);
3530 if (!err
&& t
== BPF_READ
&& value_regno
>= 0)
3531 mark_reg_unknown(env
, regs
, value_regno
);
3532 } else if (reg
->type
== PTR_TO_BTF_ID
) {
3533 err
= check_ptr_to_btf_access(env
, regs
, regno
, off
, size
, t
,
3535 } else if (reg
->type
== CONST_PTR_TO_MAP
) {
3536 err
= check_ptr_to_map_access(env
, regs
, regno
, off
, size
, t
,
3538 } else if (reg
->type
== PTR_TO_RDONLY_BUF
) {
3539 if (t
== BPF_WRITE
) {
3540 verbose(env
, "R%d cannot write into %s\n",
3541 regno
, reg_type_str
[reg
->type
]);
3544 err
= check_buffer_access(env
, reg
, regno
, off
, size
, false,
3546 &env
->prog
->aux
->max_rdonly_access
);
3547 if (!err
&& value_regno
>= 0)
3548 mark_reg_unknown(env
, regs
, value_regno
);
3549 } else if (reg
->type
== PTR_TO_RDWR_BUF
) {
3550 err
= check_buffer_access(env
, reg
, regno
, off
, size
, false,
3552 &env
->prog
->aux
->max_rdwr_access
);
3553 if (!err
&& t
== BPF_READ
&& value_regno
>= 0)
3554 mark_reg_unknown(env
, regs
, value_regno
);
3556 verbose(env
, "R%d invalid mem access '%s'\n", regno
,
3557 reg_type_str
[reg
->type
]);
3561 if (!err
&& size
< BPF_REG_SIZE
&& value_regno
>= 0 && t
== BPF_READ
&&
3562 regs
[value_regno
].type
== SCALAR_VALUE
) {
3563 /* b/h/w load zero-extends, mark upper bits as known 0 */
3564 coerce_reg_to_size(®s
[value_regno
], size
);
3569 static int check_xadd(struct bpf_verifier_env
*env
, int insn_idx
, struct bpf_insn
*insn
)
3573 if ((BPF_SIZE(insn
->code
) != BPF_W
&& BPF_SIZE(insn
->code
) != BPF_DW
) ||
3575 verbose(env
, "BPF_XADD uses reserved fields\n");
3579 /* check src1 operand */
3580 err
= check_reg_arg(env
, insn
->src_reg
, SRC_OP
);
3584 /* check src2 operand */
3585 err
= check_reg_arg(env
, insn
->dst_reg
, SRC_OP
);
3589 if (is_pointer_value(env
, insn
->src_reg
)) {
3590 verbose(env
, "R%d leaks addr into mem\n", insn
->src_reg
);
3594 if (is_ctx_reg(env
, insn
->dst_reg
) ||
3595 is_pkt_reg(env
, insn
->dst_reg
) ||
3596 is_flow_key_reg(env
, insn
->dst_reg
) ||
3597 is_sk_reg(env
, insn
->dst_reg
)) {
3598 verbose(env
, "BPF_XADD stores into R%d %s is not allowed\n",
3600 reg_type_str
[reg_state(env
, insn
->dst_reg
)->type
]);
3604 /* check whether atomic_add can read the memory */
3605 err
= check_mem_access(env
, insn_idx
, insn
->dst_reg
, insn
->off
,
3606 BPF_SIZE(insn
->code
), BPF_READ
, -1, true);
3610 /* check whether atomic_add can write into the same memory */
3611 return check_mem_access(env
, insn_idx
, insn
->dst_reg
, insn
->off
,
3612 BPF_SIZE(insn
->code
), BPF_WRITE
, -1, true);
3615 static int __check_stack_boundary(struct bpf_verifier_env
*env
, u32 regno
,
3616 int off
, int access_size
,
3617 bool zero_size_allowed
)
3619 struct bpf_reg_state
*reg
= reg_state(env
, regno
);
3621 if (off
>= 0 || off
< -MAX_BPF_STACK
|| off
+ access_size
> 0 ||
3622 access_size
< 0 || (access_size
== 0 && !zero_size_allowed
)) {
3623 if (tnum_is_const(reg
->var_off
)) {
3624 verbose(env
, "invalid stack type R%d off=%d access_size=%d\n",
3625 regno
, off
, access_size
);
3629 tnum_strn(tn_buf
, sizeof(tn_buf
), reg
->var_off
);
3630 verbose(env
, "invalid stack type R%d var_off=%s access_size=%d\n",
3631 regno
, tn_buf
, access_size
);
3638 /* when register 'regno' is passed into function that will read 'access_size'
3639 * bytes from that pointer, make sure that it's within stack boundary
3640 * and all elements of stack are initialized.
3641 * Unlike most pointer bounds-checking functions, this one doesn't take an
3642 * 'off' argument, so it has to add in reg->off itself.
3644 static int check_stack_boundary(struct bpf_verifier_env
*env
, int regno
,
3645 int access_size
, bool zero_size_allowed
,
3646 struct bpf_call_arg_meta
*meta
)
3648 struct bpf_reg_state
*reg
= reg_state(env
, regno
);
3649 struct bpf_func_state
*state
= func(env
, reg
);
3650 int err
, min_off
, max_off
, i
, j
, slot
, spi
;
3652 if (tnum_is_const(reg
->var_off
)) {
3653 min_off
= max_off
= reg
->var_off
.value
+ reg
->off
;
3654 err
= __check_stack_boundary(env
, regno
, min_off
, access_size
,
3659 /* Variable offset is prohibited for unprivileged mode for
3660 * simplicity since it requires corresponding support in
3661 * Spectre masking for stack ALU.
3662 * See also retrieve_ptr_limit().
3664 if (!env
->bypass_spec_v1
) {
3667 tnum_strn(tn_buf
, sizeof(tn_buf
), reg
->var_off
);
3668 verbose(env
, "R%d indirect variable offset stack access prohibited for !root, var_off=%s\n",
3672 /* Only initialized buffer on stack is allowed to be accessed
3673 * with variable offset. With uninitialized buffer it's hard to
3674 * guarantee that whole memory is marked as initialized on
3675 * helper return since specific bounds are unknown what may
3676 * cause uninitialized stack leaking.
3678 if (meta
&& meta
->raw_mode
)
3681 if (reg
->smax_value
>= BPF_MAX_VAR_OFF
||
3682 reg
->smax_value
<= -BPF_MAX_VAR_OFF
) {
3683 verbose(env
, "R%d unbounded indirect variable offset stack access\n",
3687 min_off
= reg
->smin_value
+ reg
->off
;
3688 max_off
= reg
->smax_value
+ reg
->off
;
3689 err
= __check_stack_boundary(env
, regno
, min_off
, access_size
,
3692 verbose(env
, "R%d min value is outside of stack bound\n",
3696 err
= __check_stack_boundary(env
, regno
, max_off
, access_size
,
3699 verbose(env
, "R%d max value is outside of stack bound\n",
3705 if (meta
&& meta
->raw_mode
) {
3706 meta
->access_size
= access_size
;
3707 meta
->regno
= regno
;
3711 for (i
= min_off
; i
< max_off
+ access_size
; i
++) {
3715 spi
= slot
/ BPF_REG_SIZE
;
3716 if (state
->allocated_stack
<= slot
)
3718 stype
= &state
->stack
[spi
].slot_type
[slot
% BPF_REG_SIZE
];
3719 if (*stype
== STACK_MISC
)
3721 if (*stype
== STACK_ZERO
) {
3722 /* helper can write anything into the stack */
3723 *stype
= STACK_MISC
;
3727 if (state
->stack
[spi
].slot_type
[0] == STACK_SPILL
&&
3728 state
->stack
[spi
].spilled_ptr
.type
== PTR_TO_BTF_ID
)
3731 if (state
->stack
[spi
].slot_type
[0] == STACK_SPILL
&&
3732 state
->stack
[spi
].spilled_ptr
.type
== SCALAR_VALUE
) {
3733 __mark_reg_unknown(env
, &state
->stack
[spi
].spilled_ptr
);
3734 for (j
= 0; j
< BPF_REG_SIZE
; j
++)
3735 state
->stack
[spi
].slot_type
[j
] = STACK_MISC
;
3740 if (tnum_is_const(reg
->var_off
)) {
3741 verbose(env
, "invalid indirect read from stack off %d+%d size %d\n",
3742 min_off
, i
- min_off
, access_size
);
3746 tnum_strn(tn_buf
, sizeof(tn_buf
), reg
->var_off
);
3747 verbose(env
, "invalid indirect read from stack var_off %s+%d size %d\n",
3748 tn_buf
, i
- min_off
, access_size
);
3752 /* reading any byte out of 8-byte 'spill_slot' will cause
3753 * the whole slot to be marked as 'read'
3755 mark_reg_read(env
, &state
->stack
[spi
].spilled_ptr
,
3756 state
->stack
[spi
].spilled_ptr
.parent
,
3759 return update_stack_depth(env
, state
, min_off
);
3762 static int check_helper_mem_access(struct bpf_verifier_env
*env
, int regno
,
3763 int access_size
, bool zero_size_allowed
,
3764 struct bpf_call_arg_meta
*meta
)
3766 struct bpf_reg_state
*regs
= cur_regs(env
), *reg
= ®s
[regno
];
3768 switch (reg
->type
) {
3770 case PTR_TO_PACKET_META
:
3771 return check_packet_access(env
, regno
, reg
->off
, access_size
,
3773 case PTR_TO_MAP_VALUE
:
3774 if (check_map_access_type(env
, regno
, reg
->off
, access_size
,
3775 meta
&& meta
->raw_mode
? BPF_WRITE
:
3778 return check_map_access(env
, regno
, reg
->off
, access_size
,
3781 return check_mem_region_access(env
, regno
, reg
->off
,
3782 access_size
, reg
->mem_size
,
3784 case PTR_TO_RDONLY_BUF
:
3785 if (meta
&& meta
->raw_mode
)
3787 return check_buffer_access(env
, reg
, regno
, reg
->off
,
3788 access_size
, zero_size_allowed
,
3790 &env
->prog
->aux
->max_rdonly_access
);
3791 case PTR_TO_RDWR_BUF
:
3792 return check_buffer_access(env
, reg
, regno
, reg
->off
,
3793 access_size
, zero_size_allowed
,
3795 &env
->prog
->aux
->max_rdwr_access
);
3797 return check_stack_boundary(env
, regno
, access_size
,
3798 zero_size_allowed
, meta
);
3799 default: /* scalar_value or invalid ptr */
3800 /* Allow zero-byte read from NULL, regardless of pointer type */
3801 if (zero_size_allowed
&& access_size
== 0 &&
3802 register_is_null(reg
))
3805 verbose(env
, "R%d type=%s expected=%s\n", regno
,
3806 reg_type_str
[reg
->type
],
3807 reg_type_str
[PTR_TO_STACK
]);
3812 /* Implementation details:
3813 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL
3814 * Two bpf_map_lookups (even with the same key) will have different reg->id.
3815 * For traditional PTR_TO_MAP_VALUE the verifier clears reg->id after
3816 * value_or_null->value transition, since the verifier only cares about
3817 * the range of access to valid map value pointer and doesn't care about actual
3818 * address of the map element.
3819 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
3820 * reg->id > 0 after value_or_null->value transition. By doing so
3821 * two bpf_map_lookups will be considered two different pointers that
3822 * point to different bpf_spin_locks.
3823 * The verifier allows taking only one bpf_spin_lock at a time to avoid
3825 * Since only one bpf_spin_lock is allowed the checks are simpler than
3826 * reg_is_refcounted() logic. The verifier needs to remember only
3827 * one spin_lock instead of array of acquired_refs.
3828 * cur_state->active_spin_lock remembers which map value element got locked
3829 * and clears it after bpf_spin_unlock.
3831 static int process_spin_lock(struct bpf_verifier_env
*env
, int regno
,
3834 struct bpf_reg_state
*regs
= cur_regs(env
), *reg
= ®s
[regno
];
3835 struct bpf_verifier_state
*cur
= env
->cur_state
;
3836 bool is_const
= tnum_is_const(reg
->var_off
);
3837 struct bpf_map
*map
= reg
->map_ptr
;
3838 u64 val
= reg
->var_off
.value
;
3842 "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
3848 "map '%s' has to have BTF in order to use bpf_spin_lock\n",
3852 if (!map_value_has_spin_lock(map
)) {
3853 if (map
->spin_lock_off
== -E2BIG
)
3855 "map '%s' has more than one 'struct bpf_spin_lock'\n",
3857 else if (map
->spin_lock_off
== -ENOENT
)
3859 "map '%s' doesn't have 'struct bpf_spin_lock'\n",
3863 "map '%s' is not a struct type or bpf_spin_lock is mangled\n",
3867 if (map
->spin_lock_off
!= val
+ reg
->off
) {
3868 verbose(env
, "off %lld doesn't point to 'struct bpf_spin_lock'\n",
3873 if (cur
->active_spin_lock
) {
3875 "Locking two bpf_spin_locks are not allowed\n");
3878 cur
->active_spin_lock
= reg
->id
;
3880 if (!cur
->active_spin_lock
) {
3881 verbose(env
, "bpf_spin_unlock without taking a lock\n");
3884 if (cur
->active_spin_lock
!= reg
->id
) {
3885 verbose(env
, "bpf_spin_unlock of different lock\n");
3888 cur
->active_spin_lock
= 0;
3893 static bool arg_type_is_mem_ptr(enum bpf_arg_type type
)
3895 return type
== ARG_PTR_TO_MEM
||
3896 type
== ARG_PTR_TO_MEM_OR_NULL
||
3897 type
== ARG_PTR_TO_UNINIT_MEM
;
3900 static bool arg_type_is_mem_size(enum bpf_arg_type type
)
3902 return type
== ARG_CONST_SIZE
||
3903 type
== ARG_CONST_SIZE_OR_ZERO
;
3906 static bool arg_type_is_alloc_size(enum bpf_arg_type type
)
3908 return type
== ARG_CONST_ALLOC_SIZE_OR_ZERO
;
3911 static bool arg_type_is_int_ptr(enum bpf_arg_type type
)
3913 return type
== ARG_PTR_TO_INT
||
3914 type
== ARG_PTR_TO_LONG
;
3917 static int int_ptr_type_to_size(enum bpf_arg_type type
)
3919 if (type
== ARG_PTR_TO_INT
)
3921 else if (type
== ARG_PTR_TO_LONG
)
3927 static int resolve_map_arg_type(struct bpf_verifier_env
*env
,
3928 const struct bpf_call_arg_meta
*meta
,
3929 enum bpf_arg_type
*arg_type
)
3931 if (!meta
->map_ptr
) {
3932 /* kernel subsystem misconfigured verifier */
3933 verbose(env
, "invalid map_ptr to access map->type\n");
3937 switch (meta
->map_ptr
->map_type
) {
3938 case BPF_MAP_TYPE_SOCKMAP
:
3939 case BPF_MAP_TYPE_SOCKHASH
:
3940 if (*arg_type
== ARG_PTR_TO_MAP_VALUE
) {
3941 *arg_type
= ARG_PTR_TO_SOCKET
;
3943 verbose(env
, "invalid arg_type for sockmap/sockhash\n");
3954 struct bpf_reg_types
{
3955 const enum bpf_reg_type types
[10];
3958 static const struct bpf_reg_types map_key_value_types
= {
3967 static const struct bpf_reg_types sock_types
= {
3976 static const struct bpf_reg_types mem_types
= {
3988 static const struct bpf_reg_types int_ptr_types
= {
3997 static const struct bpf_reg_types fullsock_types
= { .types
= { PTR_TO_SOCKET
} };
3998 static const struct bpf_reg_types scalar_types
= { .types
= { SCALAR_VALUE
} };
3999 static const struct bpf_reg_types context_types
= { .types
= { PTR_TO_CTX
} };
4000 static const struct bpf_reg_types alloc_mem_types
= { .types
= { PTR_TO_MEM
} };
4001 static const struct bpf_reg_types const_map_ptr_types
= { .types
= { CONST_PTR_TO_MAP
} };
4002 static const struct bpf_reg_types btf_ptr_types
= { .types
= { PTR_TO_BTF_ID
} };
4003 static const struct bpf_reg_types spin_lock_types
= { .types
= { PTR_TO_MAP_VALUE
} };
4005 static const struct bpf_reg_types
*compatible_reg_types
[] = {
4006 [ARG_PTR_TO_MAP_KEY
] = &map_key_value_types
,
4007 [ARG_PTR_TO_MAP_VALUE
] = &map_key_value_types
,
4008 [ARG_PTR_TO_UNINIT_MAP_VALUE
] = &map_key_value_types
,
4009 [ARG_PTR_TO_MAP_VALUE_OR_NULL
] = &map_key_value_types
,
4010 [ARG_CONST_SIZE
] = &scalar_types
,
4011 [ARG_CONST_SIZE_OR_ZERO
] = &scalar_types
,
4012 [ARG_CONST_ALLOC_SIZE_OR_ZERO
] = &scalar_types
,
4013 [ARG_CONST_MAP_PTR
] = &const_map_ptr_types
,
4014 [ARG_PTR_TO_CTX
] = &context_types
,
4015 [ARG_PTR_TO_CTX_OR_NULL
] = &context_types
,
4016 [ARG_PTR_TO_SOCK_COMMON
] = &sock_types
,
4017 [ARG_PTR_TO_SOCKET
] = &fullsock_types
,
4018 [ARG_PTR_TO_SOCKET_OR_NULL
] = &fullsock_types
,
4019 [ARG_PTR_TO_BTF_ID
] = &btf_ptr_types
,
4020 [ARG_PTR_TO_SPIN_LOCK
] = &spin_lock_types
,
4021 [ARG_PTR_TO_MEM
] = &mem_types
,
4022 [ARG_PTR_TO_MEM_OR_NULL
] = &mem_types
,
4023 [ARG_PTR_TO_UNINIT_MEM
] = &mem_types
,
4024 [ARG_PTR_TO_ALLOC_MEM
] = &alloc_mem_types
,
4025 [ARG_PTR_TO_ALLOC_MEM_OR_NULL
] = &alloc_mem_types
,
4026 [ARG_PTR_TO_INT
] = &int_ptr_types
,
4027 [ARG_PTR_TO_LONG
] = &int_ptr_types
,
4028 [__BPF_ARG_TYPE_MAX
] = NULL
,
4031 static int check_reg_type(struct bpf_verifier_env
*env
, u32 regno
,
4032 const struct bpf_reg_types
*compatible
)
4034 struct bpf_reg_state
*regs
= cur_regs(env
), *reg
= ®s
[regno
];
4035 enum bpf_reg_type expected
, type
= reg
->type
;
4038 for (i
= 0; i
< ARRAY_SIZE(compatible
->types
); i
++) {
4039 expected
= compatible
->types
[i
];
4040 if (expected
== NOT_INIT
)
4043 if (type
== expected
)
4047 verbose(env
, "R%d type=%s expected=", regno
, reg_type_str
[type
]);
4048 for (j
= 0; j
+ 1 < i
; j
++)
4049 verbose(env
, "%s, ", reg_type_str
[compatible
->types
[j
]]);
4050 verbose(env
, "%s\n", reg_type_str
[compatible
->types
[j
]]);
4054 static int check_func_arg(struct bpf_verifier_env
*env
, u32 arg
,
4055 struct bpf_call_arg_meta
*meta
,
4056 const struct bpf_func_proto
*fn
)
4058 u32 regno
= BPF_REG_1
+ arg
;
4059 struct bpf_reg_state
*regs
= cur_regs(env
), *reg
= ®s
[regno
];
4060 enum bpf_arg_type arg_type
= fn
->arg_type
[arg
];
4061 const struct bpf_reg_types
*compatible
;
4062 enum bpf_reg_type type
= reg
->type
;
4065 if (arg_type
== ARG_DONTCARE
)
4068 err
= check_reg_arg(env
, regno
, SRC_OP
);
4072 if (arg_type
== ARG_ANYTHING
) {
4073 if (is_pointer_value(env
, regno
)) {
4074 verbose(env
, "R%d leaks addr into helper function\n",
4081 if (type_is_pkt_pointer(type
) &&
4082 !may_access_direct_pkt_data(env
, meta
, BPF_READ
)) {
4083 verbose(env
, "helper access to the packet is not allowed\n");
4087 if (arg_type
== ARG_PTR_TO_MAP_VALUE
||
4088 arg_type
== ARG_PTR_TO_UNINIT_MAP_VALUE
||
4089 arg_type
== ARG_PTR_TO_MAP_VALUE_OR_NULL
) {
4090 err
= resolve_map_arg_type(env
, meta
, &arg_type
);
4095 if (register_is_null(reg
) && arg_type_may_be_null(arg_type
))
4096 /* A NULL register has a SCALAR_VALUE type, so skip
4099 goto skip_type_check
;
4101 compatible
= compatible_reg_types
[arg_type
];
4103 verbose(env
, "verifier internal error: unsupported arg type %d\n", arg_type
);
4107 err
= check_reg_type(env
, regno
, compatible
);
4111 if (type
== PTR_TO_BTF_ID
) {
4112 const u32
*btf_id
= fn
->arg_btf_id
[arg
];
4115 verbose(env
, "verifier internal error: missing BTF ID\n");
4119 if (!btf_struct_ids_match(&env
->log
, reg
->off
, reg
->btf_id
, *btf_id
)) {
4120 verbose(env
, "R%d is of type %s but %s is expected\n",
4121 regno
, kernel_type_name(reg
->btf_id
), kernel_type_name(*btf_id
));
4124 if (!tnum_is_const(reg
->var_off
) || reg
->var_off
.value
) {
4125 verbose(env
, "R%d is a pointer to in-kernel struct with non-zero offset\n",
4129 } else if (type
== PTR_TO_CTX
) {
4130 err
= check_ctx_reg(env
, reg
, regno
);
4136 if (reg
->ref_obj_id
) {
4137 if (meta
->ref_obj_id
) {
4138 verbose(env
, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
4139 regno
, reg
->ref_obj_id
,
4143 meta
->ref_obj_id
= reg
->ref_obj_id
;
4146 if (arg_type
== ARG_CONST_MAP_PTR
) {
4147 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
4148 meta
->map_ptr
= reg
->map_ptr
;
4149 } else if (arg_type
== ARG_PTR_TO_MAP_KEY
) {
4150 /* bpf_map_xxx(..., map_ptr, ..., key) call:
4151 * check that [key, key + map->key_size) are within
4152 * stack limits and initialized
4154 if (!meta
->map_ptr
) {
4155 /* in function declaration map_ptr must come before
4156 * map_key, so that it's verified and known before
4157 * we have to check map_key here. Otherwise it means
4158 * that kernel subsystem misconfigured verifier
4160 verbose(env
, "invalid map_ptr to access map->key\n");
4163 err
= check_helper_mem_access(env
, regno
,
4164 meta
->map_ptr
->key_size
, false,
4166 } else if (arg_type
== ARG_PTR_TO_MAP_VALUE
||
4167 (arg_type
== ARG_PTR_TO_MAP_VALUE_OR_NULL
&&
4168 !register_is_null(reg
)) ||
4169 arg_type
== ARG_PTR_TO_UNINIT_MAP_VALUE
) {
4170 /* bpf_map_xxx(..., map_ptr, ..., value) call:
4171 * check [value, value + map->value_size) validity
4173 if (!meta
->map_ptr
) {
4174 /* kernel subsystem misconfigured verifier */
4175 verbose(env
, "invalid map_ptr to access map->value\n");
4178 meta
->raw_mode
= (arg_type
== ARG_PTR_TO_UNINIT_MAP_VALUE
);
4179 err
= check_helper_mem_access(env
, regno
,
4180 meta
->map_ptr
->value_size
, false,
4182 } else if (arg_type
== ARG_PTR_TO_SPIN_LOCK
) {
4183 if (meta
->func_id
== BPF_FUNC_spin_lock
) {
4184 if (process_spin_lock(env
, regno
, true))
4186 } else if (meta
->func_id
== BPF_FUNC_spin_unlock
) {
4187 if (process_spin_lock(env
, regno
, false))
4190 verbose(env
, "verifier internal error\n");
4193 } else if (arg_type_is_mem_ptr(arg_type
)) {
4194 /* The access to this pointer is only checked when we hit the
4195 * next is_mem_size argument below.
4197 meta
->raw_mode
= (arg_type
== ARG_PTR_TO_UNINIT_MEM
);
4198 } else if (arg_type_is_mem_size(arg_type
)) {
4199 bool zero_size_allowed
= (arg_type
== ARG_CONST_SIZE_OR_ZERO
);
4201 /* This is used to refine r0 return value bounds for helpers
4202 * that enforce this value as an upper bound on return values.
4203 * See do_refine_retval_range() for helpers that can refine
4204 * the return value. C type of helper is u32 so we pull register
4205 * bound from umax_value however, if negative verifier errors
4206 * out. Only upper bounds can be learned because retval is an
4207 * int type and negative retvals are allowed.
4209 meta
->msize_max_value
= reg
->umax_value
;
4211 /* The register is SCALAR_VALUE; the access check
4212 * happens using its boundaries.
4214 if (!tnum_is_const(reg
->var_off
))
4215 /* For unprivileged variable accesses, disable raw
4216 * mode so that the program is required to
4217 * initialize all the memory that the helper could
4218 * just partially fill up.
4222 if (reg
->smin_value
< 0) {
4223 verbose(env
, "R%d min value is negative, either use unsigned or 'var &= const'\n",
4228 if (reg
->umin_value
== 0) {
4229 err
= check_helper_mem_access(env
, regno
- 1, 0,
4236 if (reg
->umax_value
>= BPF_MAX_VAR_SIZ
) {
4237 verbose(env
, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
4241 err
= check_helper_mem_access(env
, regno
- 1,
4243 zero_size_allowed
, meta
);
4245 err
= mark_chain_precision(env
, regno
);
4246 } else if (arg_type_is_alloc_size(arg_type
)) {
4247 if (!tnum_is_const(reg
->var_off
)) {
4248 verbose(env
, "R%d unbounded size, use 'var &= const' or 'if (var < const)'\n",
4252 meta
->mem_size
= reg
->var_off
.value
;
4253 } else if (arg_type_is_int_ptr(arg_type
)) {
4254 int size
= int_ptr_type_to_size(arg_type
);
4256 err
= check_helper_mem_access(env
, regno
, size
, false, meta
);
4259 err
= check_ptr_alignment(env
, reg
, 0, size
, true);
4265 static bool may_update_sockmap(struct bpf_verifier_env
*env
, int func_id
)
4267 enum bpf_attach_type eatype
= env
->prog
->expected_attach_type
;
4268 enum bpf_prog_type type
= resolve_prog_type(env
->prog
);
4270 if (func_id
!= BPF_FUNC_map_update_elem
)
4273 /* It's not possible to get access to a locked struct sock in these
4274 * contexts, so updating is safe.
4277 case BPF_PROG_TYPE_TRACING
:
4278 if (eatype
== BPF_TRACE_ITER
)
4281 case BPF_PROG_TYPE_SOCKET_FILTER
:
4282 case BPF_PROG_TYPE_SCHED_CLS
:
4283 case BPF_PROG_TYPE_SCHED_ACT
:
4284 case BPF_PROG_TYPE_XDP
:
4285 case BPF_PROG_TYPE_SK_REUSEPORT
:
4286 case BPF_PROG_TYPE_FLOW_DISSECTOR
:
4287 case BPF_PROG_TYPE_SK_LOOKUP
:
4293 verbose(env
, "cannot update sockmap in this context\n");
4297 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env
*env
)
4299 return env
->prog
->jit_requested
&& IS_ENABLED(CONFIG_X86_64
);
4302 static int check_map_func_compatibility(struct bpf_verifier_env
*env
,
4303 struct bpf_map
*map
, int func_id
)
4308 /* We need a two way check, first is from map perspective ... */
4309 switch (map
->map_type
) {
4310 case BPF_MAP_TYPE_PROG_ARRAY
:
4311 if (func_id
!= BPF_FUNC_tail_call
)
4314 case BPF_MAP_TYPE_PERF_EVENT_ARRAY
:
4315 if (func_id
!= BPF_FUNC_perf_event_read
&&
4316 func_id
!= BPF_FUNC_perf_event_output
&&
4317 func_id
!= BPF_FUNC_skb_output
&&
4318 func_id
!= BPF_FUNC_perf_event_read_value
&&
4319 func_id
!= BPF_FUNC_xdp_output
)
4322 case BPF_MAP_TYPE_RINGBUF
:
4323 if (func_id
!= BPF_FUNC_ringbuf_output
&&
4324 func_id
!= BPF_FUNC_ringbuf_reserve
&&
4325 func_id
!= BPF_FUNC_ringbuf_submit
&&
4326 func_id
!= BPF_FUNC_ringbuf_discard
&&
4327 func_id
!= BPF_FUNC_ringbuf_query
)
4330 case BPF_MAP_TYPE_STACK_TRACE
:
4331 if (func_id
!= BPF_FUNC_get_stackid
)
4334 case BPF_MAP_TYPE_CGROUP_ARRAY
:
4335 if (func_id
!= BPF_FUNC_skb_under_cgroup
&&
4336 func_id
!= BPF_FUNC_current_task_under_cgroup
)
4339 case BPF_MAP_TYPE_CGROUP_STORAGE
:
4340 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE
:
4341 if (func_id
!= BPF_FUNC_get_local_storage
)
4344 case BPF_MAP_TYPE_DEVMAP
:
4345 case BPF_MAP_TYPE_DEVMAP_HASH
:
4346 if (func_id
!= BPF_FUNC_redirect_map
&&
4347 func_id
!= BPF_FUNC_map_lookup_elem
)
4350 /* Restrict bpf side of cpumap and xskmap, open when use-cases
4353 case BPF_MAP_TYPE_CPUMAP
:
4354 if (func_id
!= BPF_FUNC_redirect_map
)
4357 case BPF_MAP_TYPE_XSKMAP
:
4358 if (func_id
!= BPF_FUNC_redirect_map
&&
4359 func_id
!= BPF_FUNC_map_lookup_elem
)
4362 case BPF_MAP_TYPE_ARRAY_OF_MAPS
:
4363 case BPF_MAP_TYPE_HASH_OF_MAPS
:
4364 if (func_id
!= BPF_FUNC_map_lookup_elem
)
4367 case BPF_MAP_TYPE_SOCKMAP
:
4368 if (func_id
!= BPF_FUNC_sk_redirect_map
&&
4369 func_id
!= BPF_FUNC_sock_map_update
&&
4370 func_id
!= BPF_FUNC_map_delete_elem
&&
4371 func_id
!= BPF_FUNC_msg_redirect_map
&&
4372 func_id
!= BPF_FUNC_sk_select_reuseport
&&
4373 func_id
!= BPF_FUNC_map_lookup_elem
&&
4374 !may_update_sockmap(env
, func_id
))
4377 case BPF_MAP_TYPE_SOCKHASH
:
4378 if (func_id
!= BPF_FUNC_sk_redirect_hash
&&
4379 func_id
!= BPF_FUNC_sock_hash_update
&&
4380 func_id
!= BPF_FUNC_map_delete_elem
&&
4381 func_id
!= BPF_FUNC_msg_redirect_hash
&&
4382 func_id
!= BPF_FUNC_sk_select_reuseport
&&
4383 func_id
!= BPF_FUNC_map_lookup_elem
&&
4384 !may_update_sockmap(env
, func_id
))
4387 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY
:
4388 if (func_id
!= BPF_FUNC_sk_select_reuseport
)
4391 case BPF_MAP_TYPE_QUEUE
:
4392 case BPF_MAP_TYPE_STACK
:
4393 if (func_id
!= BPF_FUNC_map_peek_elem
&&
4394 func_id
!= BPF_FUNC_map_pop_elem
&&
4395 func_id
!= BPF_FUNC_map_push_elem
)
4398 case BPF_MAP_TYPE_SK_STORAGE
:
4399 if (func_id
!= BPF_FUNC_sk_storage_get
&&
4400 func_id
!= BPF_FUNC_sk_storage_delete
)
4403 case BPF_MAP_TYPE_INODE_STORAGE
:
4404 if (func_id
!= BPF_FUNC_inode_storage_get
&&
4405 func_id
!= BPF_FUNC_inode_storage_delete
)
4412 /* ... and second from the function itself. */
4414 case BPF_FUNC_tail_call
:
4415 if (map
->map_type
!= BPF_MAP_TYPE_PROG_ARRAY
)
4417 if (env
->subprog_cnt
> 1 && !allow_tail_call_in_subprogs(env
)) {
4418 verbose(env
, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
4422 case BPF_FUNC_perf_event_read
:
4423 case BPF_FUNC_perf_event_output
:
4424 case BPF_FUNC_perf_event_read_value
:
4425 case BPF_FUNC_skb_output
:
4426 case BPF_FUNC_xdp_output
:
4427 if (map
->map_type
!= BPF_MAP_TYPE_PERF_EVENT_ARRAY
)
4430 case BPF_FUNC_get_stackid
:
4431 if (map
->map_type
!= BPF_MAP_TYPE_STACK_TRACE
)
4434 case BPF_FUNC_current_task_under_cgroup
:
4435 case BPF_FUNC_skb_under_cgroup
:
4436 if (map
->map_type
!= BPF_MAP_TYPE_CGROUP_ARRAY
)
4439 case BPF_FUNC_redirect_map
:
4440 if (map
->map_type
!= BPF_MAP_TYPE_DEVMAP
&&
4441 map
->map_type
!= BPF_MAP_TYPE_DEVMAP_HASH
&&
4442 map
->map_type
!= BPF_MAP_TYPE_CPUMAP
&&
4443 map
->map_type
!= BPF_MAP_TYPE_XSKMAP
)
4446 case BPF_FUNC_sk_redirect_map
:
4447 case BPF_FUNC_msg_redirect_map
:
4448 case BPF_FUNC_sock_map_update
:
4449 if (map
->map_type
!= BPF_MAP_TYPE_SOCKMAP
)
4452 case BPF_FUNC_sk_redirect_hash
:
4453 case BPF_FUNC_msg_redirect_hash
:
4454 case BPF_FUNC_sock_hash_update
:
4455 if (map
->map_type
!= BPF_MAP_TYPE_SOCKHASH
)
4458 case BPF_FUNC_get_local_storage
:
4459 if (map
->map_type
!= BPF_MAP_TYPE_CGROUP_STORAGE
&&
4460 map
->map_type
!= BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE
)
4463 case BPF_FUNC_sk_select_reuseport
:
4464 if (map
->map_type
!= BPF_MAP_TYPE_REUSEPORT_SOCKARRAY
&&
4465 map
->map_type
!= BPF_MAP_TYPE_SOCKMAP
&&
4466 map
->map_type
!= BPF_MAP_TYPE_SOCKHASH
)
4469 case BPF_FUNC_map_peek_elem
:
4470 case BPF_FUNC_map_pop_elem
:
4471 case BPF_FUNC_map_push_elem
:
4472 if (map
->map_type
!= BPF_MAP_TYPE_QUEUE
&&
4473 map
->map_type
!= BPF_MAP_TYPE_STACK
)
4476 case BPF_FUNC_sk_storage_get
:
4477 case BPF_FUNC_sk_storage_delete
:
4478 if (map
->map_type
!= BPF_MAP_TYPE_SK_STORAGE
)
4481 case BPF_FUNC_inode_storage_get
:
4482 case BPF_FUNC_inode_storage_delete
:
4483 if (map
->map_type
!= BPF_MAP_TYPE_INODE_STORAGE
)
4492 verbose(env
, "cannot pass map_type %d into func %s#%d\n",
4493 map
->map_type
, func_id_name(func_id
), func_id
);
4497 static bool check_raw_mode_ok(const struct bpf_func_proto
*fn
)
4501 if (fn
->arg1_type
== ARG_PTR_TO_UNINIT_MEM
)
4503 if (fn
->arg2_type
== ARG_PTR_TO_UNINIT_MEM
)
4505 if (fn
->arg3_type
== ARG_PTR_TO_UNINIT_MEM
)
4507 if (fn
->arg4_type
== ARG_PTR_TO_UNINIT_MEM
)
4509 if (fn
->arg5_type
== ARG_PTR_TO_UNINIT_MEM
)
4512 /* We only support one arg being in raw mode at the moment,
4513 * which is sufficient for the helper functions we have
4519 static bool check_args_pair_invalid(enum bpf_arg_type arg_curr
,
4520 enum bpf_arg_type arg_next
)
4522 return (arg_type_is_mem_ptr(arg_curr
) &&
4523 !arg_type_is_mem_size(arg_next
)) ||
4524 (!arg_type_is_mem_ptr(arg_curr
) &&
4525 arg_type_is_mem_size(arg_next
));
4528 static bool check_arg_pair_ok(const struct bpf_func_proto
*fn
)
4530 /* bpf_xxx(..., buf, len) call will access 'len'
4531 * bytes from memory 'buf'. Both arg types need
4532 * to be paired, so make sure there's no buggy
4533 * helper function specification.
4535 if (arg_type_is_mem_size(fn
->arg1_type
) ||
4536 arg_type_is_mem_ptr(fn
->arg5_type
) ||
4537 check_args_pair_invalid(fn
->arg1_type
, fn
->arg2_type
) ||
4538 check_args_pair_invalid(fn
->arg2_type
, fn
->arg3_type
) ||
4539 check_args_pair_invalid(fn
->arg3_type
, fn
->arg4_type
) ||
4540 check_args_pair_invalid(fn
->arg4_type
, fn
->arg5_type
))
4546 static bool check_refcount_ok(const struct bpf_func_proto
*fn
, int func_id
)
4550 if (arg_type_may_be_refcounted(fn
->arg1_type
))
4552 if (arg_type_may_be_refcounted(fn
->arg2_type
))
4554 if (arg_type_may_be_refcounted(fn
->arg3_type
))
4556 if (arg_type_may_be_refcounted(fn
->arg4_type
))
4558 if (arg_type_may_be_refcounted(fn
->arg5_type
))
4561 /* A reference acquiring function cannot acquire
4562 * another refcounted ptr.
4564 if (may_be_acquire_function(func_id
) && count
)
4567 /* We only support one arg being unreferenced at the moment,
4568 * which is sufficient for the helper functions we have right now.
4573 static bool check_btf_id_ok(const struct bpf_func_proto
*fn
)
4577 for (i
= 0; i
< ARRAY_SIZE(fn
->arg_type
); i
++)
4578 if (fn
->arg_type
[i
] == ARG_PTR_TO_BTF_ID
&& !fn
->arg_btf_id
[i
])
4584 static int check_func_proto(const struct bpf_func_proto
*fn
, int func_id
)
4586 return check_raw_mode_ok(fn
) &&
4587 check_arg_pair_ok(fn
) &&
4588 check_btf_id_ok(fn
) &&
4589 check_refcount_ok(fn
, func_id
) ? 0 : -EINVAL
;
4592 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
4593 * are now invalid, so turn them into unknown SCALAR_VALUE.
4595 static void __clear_all_pkt_pointers(struct bpf_verifier_env
*env
,
4596 struct bpf_func_state
*state
)
4598 struct bpf_reg_state
*regs
= state
->regs
, *reg
;
4601 for (i
= 0; i
< MAX_BPF_REG
; i
++)
4602 if (reg_is_pkt_pointer_any(®s
[i
]))
4603 mark_reg_unknown(env
, regs
, i
);
4605 bpf_for_each_spilled_reg(i
, state
, reg
) {
4608 if (reg_is_pkt_pointer_any(reg
))
4609 __mark_reg_unknown(env
, reg
);
4613 static void clear_all_pkt_pointers(struct bpf_verifier_env
*env
)
4615 struct bpf_verifier_state
*vstate
= env
->cur_state
;
4618 for (i
= 0; i
<= vstate
->curframe
; i
++)
4619 __clear_all_pkt_pointers(env
, vstate
->frame
[i
]);
4622 static void release_reg_references(struct bpf_verifier_env
*env
,
4623 struct bpf_func_state
*state
,
4626 struct bpf_reg_state
*regs
= state
->regs
, *reg
;
4629 for (i
= 0; i
< MAX_BPF_REG
; i
++)
4630 if (regs
[i
].ref_obj_id
== ref_obj_id
)
4631 mark_reg_unknown(env
, regs
, i
);
4633 bpf_for_each_spilled_reg(i
, state
, reg
) {
4636 if (reg
->ref_obj_id
== ref_obj_id
)
4637 __mark_reg_unknown(env
, reg
);
4641 /* The pointer with the specified id has released its reference to kernel
4642 * resources. Identify all copies of the same pointer and clear the reference.
4644 static int release_reference(struct bpf_verifier_env
*env
,
4647 struct bpf_verifier_state
*vstate
= env
->cur_state
;
4651 err
= release_reference_state(cur_func(env
), ref_obj_id
);
4655 for (i
= 0; i
<= vstate
->curframe
; i
++)
4656 release_reg_references(env
, vstate
->frame
[i
], ref_obj_id
);
4661 static void clear_caller_saved_regs(struct bpf_verifier_env
*env
,
4662 struct bpf_reg_state
*regs
)
4666 /* after the call registers r0 - r5 were scratched */
4667 for (i
= 0; i
< CALLER_SAVED_REGS
; i
++) {
4668 mark_reg_not_init(env
, regs
, caller_saved
[i
]);
4669 check_reg_arg(env
, caller_saved
[i
], DST_OP_NO_MARK
);
4673 static int check_func_call(struct bpf_verifier_env
*env
, struct bpf_insn
*insn
,
4676 struct bpf_verifier_state
*state
= env
->cur_state
;
4677 struct bpf_func_info_aux
*func_info_aux
;
4678 struct bpf_func_state
*caller
, *callee
;
4679 int i
, err
, subprog
, target_insn
;
4680 bool is_global
= false;
4682 if (state
->curframe
+ 1 >= MAX_CALL_FRAMES
) {
4683 verbose(env
, "the call stack of %d frames is too deep\n",
4684 state
->curframe
+ 2);
4688 target_insn
= *insn_idx
+ insn
->imm
;
4689 subprog
= find_subprog(env
, target_insn
+ 1);
4691 verbose(env
, "verifier bug. No program starts at insn %d\n",
4696 caller
= state
->frame
[state
->curframe
];
4697 if (state
->frame
[state
->curframe
+ 1]) {
4698 verbose(env
, "verifier bug. Frame %d already allocated\n",
4699 state
->curframe
+ 1);
4703 func_info_aux
= env
->prog
->aux
->func_info_aux
;
4705 is_global
= func_info_aux
[subprog
].linkage
== BTF_FUNC_GLOBAL
;
4706 err
= btf_check_func_arg_match(env
, subprog
, caller
->regs
);
4711 verbose(env
, "Caller passes invalid args into func#%d\n",
4715 if (env
->log
.level
& BPF_LOG_LEVEL
)
4717 "Func#%d is global and valid. Skipping.\n",
4719 clear_caller_saved_regs(env
, caller
->regs
);
4721 /* All global functions return SCALAR_VALUE */
4722 mark_reg_unknown(env
, caller
->regs
, BPF_REG_0
);
4724 /* continue with next insn after call */
4729 callee
= kzalloc(sizeof(*callee
), GFP_KERNEL
);
4732 state
->frame
[state
->curframe
+ 1] = callee
;
4734 /* callee cannot access r0, r6 - r9 for reading and has to write
4735 * into its own stack before reading from it.
4736 * callee can read/write into caller's stack
4738 init_func_state(env
, callee
,
4739 /* remember the callsite, it will be used by bpf_exit */
4740 *insn_idx
/* callsite */,
4741 state
->curframe
+ 1 /* frameno within this callchain */,
4742 subprog
/* subprog number within this prog */);
4744 /* Transfer references to the callee */
4745 err
= transfer_reference_state(callee
, caller
);
4749 /* copy r1 - r5 args that callee can access. The copy includes parent
4750 * pointers, which connects us up to the liveness chain
4752 for (i
= BPF_REG_1
; i
<= BPF_REG_5
; i
++)
4753 callee
->regs
[i
] = caller
->regs
[i
];
4755 clear_caller_saved_regs(env
, caller
->regs
);
4757 /* only increment it after check_reg_arg() finished */
4760 /* and go analyze first insn of the callee */
4761 *insn_idx
= target_insn
;
4763 if (env
->log
.level
& BPF_LOG_LEVEL
) {
4764 verbose(env
, "caller:\n");
4765 print_verifier_state(env
, caller
);
4766 verbose(env
, "callee:\n");
4767 print_verifier_state(env
, callee
);
4772 static int prepare_func_exit(struct bpf_verifier_env
*env
, int *insn_idx
)
4774 struct bpf_verifier_state
*state
= env
->cur_state
;
4775 struct bpf_func_state
*caller
, *callee
;
4776 struct bpf_reg_state
*r0
;
4779 callee
= state
->frame
[state
->curframe
];
4780 r0
= &callee
->regs
[BPF_REG_0
];
4781 if (r0
->type
== PTR_TO_STACK
) {
4782 /* technically it's ok to return caller's stack pointer
4783 * (or caller's caller's pointer) back to the caller,
4784 * since these pointers are valid. Only current stack
4785 * pointer will be invalid as soon as function exits,
4786 * but let's be conservative
4788 verbose(env
, "cannot return stack pointer to the caller\n");
4793 caller
= state
->frame
[state
->curframe
];
4794 /* return to the caller whatever r0 had in the callee */
4795 caller
->regs
[BPF_REG_0
] = *r0
;
4797 /* Transfer references to the caller */
4798 err
= transfer_reference_state(caller
, callee
);
4802 *insn_idx
= callee
->callsite
+ 1;
4803 if (env
->log
.level
& BPF_LOG_LEVEL
) {
4804 verbose(env
, "returning from callee:\n");
4805 print_verifier_state(env
, callee
);
4806 verbose(env
, "to caller at %d:\n", *insn_idx
);
4807 print_verifier_state(env
, caller
);
4809 /* clear everything in the callee */
4810 free_func_state(callee
);
4811 state
->frame
[state
->curframe
+ 1] = NULL
;
4815 static void do_refine_retval_range(struct bpf_reg_state
*regs
, int ret_type
,
4817 struct bpf_call_arg_meta
*meta
)
4819 struct bpf_reg_state
*ret_reg
= ®s
[BPF_REG_0
];
4821 if (ret_type
!= RET_INTEGER
||
4822 (func_id
!= BPF_FUNC_get_stack
&&
4823 func_id
!= BPF_FUNC_probe_read_str
&&
4824 func_id
!= BPF_FUNC_probe_read_kernel_str
&&
4825 func_id
!= BPF_FUNC_probe_read_user_str
))
4828 ret_reg
->smax_value
= meta
->msize_max_value
;
4829 ret_reg
->s32_max_value
= meta
->msize_max_value
;
4830 __reg_deduce_bounds(ret_reg
);
4831 __reg_bound_offset(ret_reg
);
4832 __update_reg_bounds(ret_reg
);
4836 record_func_map(struct bpf_verifier_env
*env
, struct bpf_call_arg_meta
*meta
,
4837 int func_id
, int insn_idx
)
4839 struct bpf_insn_aux_data
*aux
= &env
->insn_aux_data
[insn_idx
];
4840 struct bpf_map
*map
= meta
->map_ptr
;
4842 if (func_id
!= BPF_FUNC_tail_call
&&
4843 func_id
!= BPF_FUNC_map_lookup_elem
&&
4844 func_id
!= BPF_FUNC_map_update_elem
&&
4845 func_id
!= BPF_FUNC_map_delete_elem
&&
4846 func_id
!= BPF_FUNC_map_push_elem
&&
4847 func_id
!= BPF_FUNC_map_pop_elem
&&
4848 func_id
!= BPF_FUNC_map_peek_elem
)
4852 verbose(env
, "kernel subsystem misconfigured verifier\n");
4856 /* In case of read-only, some additional restrictions
4857 * need to be applied in order to prevent altering the
4858 * state of the map from program side.
4860 if ((map
->map_flags
& BPF_F_RDONLY_PROG
) &&
4861 (func_id
== BPF_FUNC_map_delete_elem
||
4862 func_id
== BPF_FUNC_map_update_elem
||
4863 func_id
== BPF_FUNC_map_push_elem
||
4864 func_id
== BPF_FUNC_map_pop_elem
)) {
4865 verbose(env
, "write into map forbidden\n");
4869 if (!BPF_MAP_PTR(aux
->map_ptr_state
))
4870 bpf_map_ptr_store(aux
, meta
->map_ptr
,
4871 !meta
->map_ptr
->bypass_spec_v1
);
4872 else if (BPF_MAP_PTR(aux
->map_ptr_state
) != meta
->map_ptr
)
4873 bpf_map_ptr_store(aux
, BPF_MAP_PTR_POISON
,
4874 !meta
->map_ptr
->bypass_spec_v1
);
4879 record_func_key(struct bpf_verifier_env
*env
, struct bpf_call_arg_meta
*meta
,
4880 int func_id
, int insn_idx
)
4882 struct bpf_insn_aux_data
*aux
= &env
->insn_aux_data
[insn_idx
];
4883 struct bpf_reg_state
*regs
= cur_regs(env
), *reg
;
4884 struct bpf_map
*map
= meta
->map_ptr
;
4889 if (func_id
!= BPF_FUNC_tail_call
)
4891 if (!map
|| map
->map_type
!= BPF_MAP_TYPE_PROG_ARRAY
) {
4892 verbose(env
, "kernel subsystem misconfigured verifier\n");
4896 range
= tnum_range(0, map
->max_entries
- 1);
4897 reg
= ®s
[BPF_REG_3
];
4899 if (!register_is_const(reg
) || !tnum_in(range
, reg
->var_off
)) {
4900 bpf_map_key_store(aux
, BPF_MAP_KEY_POISON
);
4904 err
= mark_chain_precision(env
, BPF_REG_3
);
4908 val
= reg
->var_off
.value
;
4909 if (bpf_map_key_unseen(aux
))
4910 bpf_map_key_store(aux
, val
);
4911 else if (!bpf_map_key_poisoned(aux
) &&
4912 bpf_map_key_immediate(aux
) != val
)
4913 bpf_map_key_store(aux
, BPF_MAP_KEY_POISON
);
4917 static int check_reference_leak(struct bpf_verifier_env
*env
)
4919 struct bpf_func_state
*state
= cur_func(env
);
4922 for (i
= 0; i
< state
->acquired_refs
; i
++) {
4923 verbose(env
, "Unreleased reference id=%d alloc_insn=%d\n",
4924 state
->refs
[i
].id
, state
->refs
[i
].insn_idx
);
4926 return state
->acquired_refs
? -EINVAL
: 0;
4929 static int check_helper_call(struct bpf_verifier_env
*env
, int func_id
, int insn_idx
)
4931 const struct bpf_func_proto
*fn
= NULL
;
4932 struct bpf_reg_state
*regs
;
4933 struct bpf_call_arg_meta meta
;
4937 /* find function prototype */
4938 if (func_id
< 0 || func_id
>= __BPF_FUNC_MAX_ID
) {
4939 verbose(env
, "invalid func %s#%d\n", func_id_name(func_id
),
4944 if (env
->ops
->get_func_proto
)
4945 fn
= env
->ops
->get_func_proto(func_id
, env
->prog
);
4947 verbose(env
, "unknown func %s#%d\n", func_id_name(func_id
),
4952 /* eBPF programs must be GPL compatible to use GPL-ed functions */
4953 if (!env
->prog
->gpl_compatible
&& fn
->gpl_only
) {
4954 verbose(env
, "cannot call GPL-restricted function from non-GPL compatible program\n");
4958 if (fn
->allowed
&& !fn
->allowed(env
->prog
)) {
4959 verbose(env
, "helper call is not allowed in probe\n");
4963 /* With LD_ABS/IND some JITs save/restore skb from r1. */
4964 changes_data
= bpf_helper_changes_pkt_data(fn
->func
);
4965 if (changes_data
&& fn
->arg1_type
!= ARG_PTR_TO_CTX
) {
4966 verbose(env
, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
4967 func_id_name(func_id
), func_id
);
4971 memset(&meta
, 0, sizeof(meta
));
4972 meta
.pkt_access
= fn
->pkt_access
;
4974 err
= check_func_proto(fn
, func_id
);
4976 verbose(env
, "kernel subsystem misconfigured func %s#%d\n",
4977 func_id_name(func_id
), func_id
);
4981 meta
.func_id
= func_id
;
4983 for (i
= 0; i
< 5; i
++) {
4984 err
= check_func_arg(env
, i
, &meta
, fn
);
4989 err
= record_func_map(env
, &meta
, func_id
, insn_idx
);
4993 err
= record_func_key(env
, &meta
, func_id
, insn_idx
);
4997 /* Mark slots with STACK_MISC in case of raw mode, stack offset
4998 * is inferred from register state.
5000 for (i
= 0; i
< meta
.access_size
; i
++) {
5001 err
= check_mem_access(env
, insn_idx
, meta
.regno
, i
, BPF_B
,
5002 BPF_WRITE
, -1, false);
5007 if (func_id
== BPF_FUNC_tail_call
) {
5008 err
= check_reference_leak(env
);
5010 verbose(env
, "tail_call would lead to reference leak\n");
5013 } else if (is_release_function(func_id
)) {
5014 err
= release_reference(env
, meta
.ref_obj_id
);
5016 verbose(env
, "func %s#%d reference has not been acquired before\n",
5017 func_id_name(func_id
), func_id
);
5022 regs
= cur_regs(env
);
5024 /* check that flags argument in get_local_storage(map, flags) is 0,
5025 * this is required because get_local_storage() can't return an error.
5027 if (func_id
== BPF_FUNC_get_local_storage
&&
5028 !register_is_null(®s
[BPF_REG_2
])) {
5029 verbose(env
, "get_local_storage() doesn't support non-zero flags\n");
5033 /* reset caller saved regs */
5034 for (i
= 0; i
< CALLER_SAVED_REGS
; i
++) {
5035 mark_reg_not_init(env
, regs
, caller_saved
[i
]);
5036 check_reg_arg(env
, caller_saved
[i
], DST_OP_NO_MARK
);
5039 /* helper call returns 64-bit value. */
5040 regs
[BPF_REG_0
].subreg_def
= DEF_NOT_SUBREG
;
5042 /* update return register (already marked as written above) */
5043 if (fn
->ret_type
== RET_INTEGER
) {
5044 /* sets type to SCALAR_VALUE */
5045 mark_reg_unknown(env
, regs
, BPF_REG_0
);
5046 } else if (fn
->ret_type
== RET_VOID
) {
5047 regs
[BPF_REG_0
].type
= NOT_INIT
;
5048 } else if (fn
->ret_type
== RET_PTR_TO_MAP_VALUE_OR_NULL
||
5049 fn
->ret_type
== RET_PTR_TO_MAP_VALUE
) {
5050 /* There is no offset yet applied, variable or fixed */
5051 mark_reg_known_zero(env
, regs
, BPF_REG_0
);
5052 /* remember map_ptr, so that check_map_access()
5053 * can check 'value_size' boundary of memory access
5054 * to map element returned from bpf_map_lookup_elem()
5056 if (meta
.map_ptr
== NULL
) {
5058 "kernel subsystem misconfigured verifier\n");
5061 regs
[BPF_REG_0
].map_ptr
= meta
.map_ptr
;
5062 if (fn
->ret_type
== RET_PTR_TO_MAP_VALUE
) {
5063 regs
[BPF_REG_0
].type
= PTR_TO_MAP_VALUE
;
5064 if (map_value_has_spin_lock(meta
.map_ptr
))
5065 regs
[BPF_REG_0
].id
= ++env
->id_gen
;
5067 regs
[BPF_REG_0
].type
= PTR_TO_MAP_VALUE_OR_NULL
;
5068 regs
[BPF_REG_0
].id
= ++env
->id_gen
;
5070 } else if (fn
->ret_type
== RET_PTR_TO_SOCKET_OR_NULL
) {
5071 mark_reg_known_zero(env
, regs
, BPF_REG_0
);
5072 regs
[BPF_REG_0
].type
= PTR_TO_SOCKET_OR_NULL
;
5073 regs
[BPF_REG_0
].id
= ++env
->id_gen
;
5074 } else if (fn
->ret_type
== RET_PTR_TO_SOCK_COMMON_OR_NULL
) {
5075 mark_reg_known_zero(env
, regs
, BPF_REG_0
);
5076 regs
[BPF_REG_0
].type
= PTR_TO_SOCK_COMMON_OR_NULL
;
5077 regs
[BPF_REG_0
].id
= ++env
->id_gen
;
5078 } else if (fn
->ret_type
== RET_PTR_TO_TCP_SOCK_OR_NULL
) {
5079 mark_reg_known_zero(env
, regs
, BPF_REG_0
);
5080 regs
[BPF_REG_0
].type
= PTR_TO_TCP_SOCK_OR_NULL
;
5081 regs
[BPF_REG_0
].id
= ++env
->id_gen
;
5082 } else if (fn
->ret_type
== RET_PTR_TO_ALLOC_MEM_OR_NULL
) {
5083 mark_reg_known_zero(env
, regs
, BPF_REG_0
);
5084 regs
[BPF_REG_0
].type
= PTR_TO_MEM_OR_NULL
;
5085 regs
[BPF_REG_0
].id
= ++env
->id_gen
;
5086 regs
[BPF_REG_0
].mem_size
= meta
.mem_size
;
5087 } else if (fn
->ret_type
== RET_PTR_TO_BTF_ID_OR_NULL
) {
5090 mark_reg_known_zero(env
, regs
, BPF_REG_0
);
5091 regs
[BPF_REG_0
].type
= PTR_TO_BTF_ID_OR_NULL
;
5092 ret_btf_id
= *fn
->ret_btf_id
;
5093 if (ret_btf_id
== 0) {
5094 verbose(env
, "invalid return type %d of func %s#%d\n",
5095 fn
->ret_type
, func_id_name(func_id
), func_id
);
5098 regs
[BPF_REG_0
].btf_id
= ret_btf_id
;
5100 verbose(env
, "unknown return type %d of func %s#%d\n",
5101 fn
->ret_type
, func_id_name(func_id
), func_id
);
5105 if (is_ptr_cast_function(func_id
)) {
5106 /* For release_reference() */
5107 regs
[BPF_REG_0
].ref_obj_id
= meta
.ref_obj_id
;
5108 } else if (is_acquire_function(func_id
, meta
.map_ptr
)) {
5109 int id
= acquire_reference_state(env
, insn_idx
);
5113 /* For mark_ptr_or_null_reg() */
5114 regs
[BPF_REG_0
].id
= id
;
5115 /* For release_reference() */
5116 regs
[BPF_REG_0
].ref_obj_id
= id
;
5119 do_refine_retval_range(regs
, fn
->ret_type
, func_id
, &meta
);
5121 err
= check_map_func_compatibility(env
, meta
.map_ptr
, func_id
);
5125 if ((func_id
== BPF_FUNC_get_stack
||
5126 func_id
== BPF_FUNC_get_task_stack
) &&
5127 !env
->prog
->has_callchain_buf
) {
5128 const char *err_str
;
5130 #ifdef CONFIG_PERF_EVENTS
5131 err
= get_callchain_buffers(sysctl_perf_event_max_stack
);
5132 err_str
= "cannot get callchain buffer for func %s#%d\n";
5135 err_str
= "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
5138 verbose(env
, err_str
, func_id_name(func_id
), func_id
);
5142 env
->prog
->has_callchain_buf
= true;
5145 if (func_id
== BPF_FUNC_get_stackid
|| func_id
== BPF_FUNC_get_stack
)
5146 env
->prog
->call_get_stack
= true;
5149 clear_all_pkt_pointers(env
);
5153 static bool signed_add_overflows(s64 a
, s64 b
)
5155 /* Do the add in u64, where overflow is well-defined */
5156 s64 res
= (s64
)((u64
)a
+ (u64
)b
);
5163 static bool signed_add32_overflows(s64 a
, s64 b
)
5165 /* Do the add in u32, where overflow is well-defined */
5166 s32 res
= (s32
)((u32
)a
+ (u32
)b
);
5173 static bool signed_sub_overflows(s32 a
, s32 b
)
5175 /* Do the sub in u64, where overflow is well-defined */
5176 s64 res
= (s64
)((u64
)a
- (u64
)b
);
5183 static bool signed_sub32_overflows(s32 a
, s32 b
)
5185 /* Do the sub in u64, where overflow is well-defined */
5186 s32 res
= (s32
)((u32
)a
- (u32
)b
);
5193 static bool check_reg_sane_offset(struct bpf_verifier_env
*env
,
5194 const struct bpf_reg_state
*reg
,
5195 enum bpf_reg_type type
)
5197 bool known
= tnum_is_const(reg
->var_off
);
5198 s64 val
= reg
->var_off
.value
;
5199 s64 smin
= reg
->smin_value
;
5201 if (known
&& (val
>= BPF_MAX_VAR_OFF
|| val
<= -BPF_MAX_VAR_OFF
)) {
5202 verbose(env
, "math between %s pointer and %lld is not allowed\n",
5203 reg_type_str
[type
], val
);
5207 if (reg
->off
>= BPF_MAX_VAR_OFF
|| reg
->off
<= -BPF_MAX_VAR_OFF
) {
5208 verbose(env
, "%s pointer offset %d is not allowed\n",
5209 reg_type_str
[type
], reg
->off
);
5213 if (smin
== S64_MIN
) {
5214 verbose(env
, "math between %s pointer and register with unbounded min value is not allowed\n",
5215 reg_type_str
[type
]);
5219 if (smin
>= BPF_MAX_VAR_OFF
|| smin
<= -BPF_MAX_VAR_OFF
) {
5220 verbose(env
, "value %lld makes %s pointer be out of bounds\n",
5221 smin
, reg_type_str
[type
]);
5228 static struct bpf_insn_aux_data
*cur_aux(struct bpf_verifier_env
*env
)
5230 return &env
->insn_aux_data
[env
->insn_idx
];
5233 static int retrieve_ptr_limit(const struct bpf_reg_state
*ptr_reg
,
5234 u32
*ptr_limit
, u8 opcode
, bool off_is_neg
)
5236 bool mask_to_left
= (opcode
== BPF_ADD
&& off_is_neg
) ||
5237 (opcode
== BPF_SUB
&& !off_is_neg
);
5240 switch (ptr_reg
->type
) {
5242 /* Indirect variable offset stack access is prohibited in
5243 * unprivileged mode so it's not handled here.
5245 off
= ptr_reg
->off
+ ptr_reg
->var_off
.value
;
5247 *ptr_limit
= MAX_BPF_STACK
+ off
;
5251 case PTR_TO_MAP_VALUE
:
5253 *ptr_limit
= ptr_reg
->umax_value
+ ptr_reg
->off
;
5255 off
= ptr_reg
->smin_value
+ ptr_reg
->off
;
5256 *ptr_limit
= ptr_reg
->map_ptr
->value_size
- off
;
5264 static bool can_skip_alu_sanitation(const struct bpf_verifier_env
*env
,
5265 const struct bpf_insn
*insn
)
5267 return env
->bypass_spec_v1
|| BPF_SRC(insn
->code
) == BPF_K
;
5270 static int update_alu_sanitation_state(struct bpf_insn_aux_data
*aux
,
5271 u32 alu_state
, u32 alu_limit
)
5273 /* If we arrived here from different branches with different
5274 * state or limits to sanitize, then this won't work.
5276 if (aux
->alu_state
&&
5277 (aux
->alu_state
!= alu_state
||
5278 aux
->alu_limit
!= alu_limit
))
5281 /* Corresponding fixup done in fixup_bpf_calls(). */
5282 aux
->alu_state
= alu_state
;
5283 aux
->alu_limit
= alu_limit
;
5287 static int sanitize_val_alu(struct bpf_verifier_env
*env
,
5288 struct bpf_insn
*insn
)
5290 struct bpf_insn_aux_data
*aux
= cur_aux(env
);
5292 if (can_skip_alu_sanitation(env
, insn
))
5295 return update_alu_sanitation_state(aux
, BPF_ALU_NON_POINTER
, 0);
5298 static int sanitize_ptr_alu(struct bpf_verifier_env
*env
,
5299 struct bpf_insn
*insn
,
5300 const struct bpf_reg_state
*ptr_reg
,
5301 struct bpf_reg_state
*dst_reg
,
5304 struct bpf_verifier_state
*vstate
= env
->cur_state
;
5305 struct bpf_insn_aux_data
*aux
= cur_aux(env
);
5306 bool ptr_is_dst_reg
= ptr_reg
== dst_reg
;
5307 u8 opcode
= BPF_OP(insn
->code
);
5308 u32 alu_state
, alu_limit
;
5309 struct bpf_reg_state tmp
;
5312 if (can_skip_alu_sanitation(env
, insn
))
5315 /* We already marked aux for masking from non-speculative
5316 * paths, thus we got here in the first place. We only care
5317 * to explore bad access from here.
5319 if (vstate
->speculative
)
5322 alu_state
= off_is_neg
? BPF_ALU_NEG_VALUE
: 0;
5323 alu_state
|= ptr_is_dst_reg
?
5324 BPF_ALU_SANITIZE_SRC
: BPF_ALU_SANITIZE_DST
;
5326 if (retrieve_ptr_limit(ptr_reg
, &alu_limit
, opcode
, off_is_neg
))
5328 if (update_alu_sanitation_state(aux
, alu_state
, alu_limit
))
5331 /* Simulate and find potential out-of-bounds access under
5332 * speculative execution from truncation as a result of
5333 * masking when off was not within expected range. If off
5334 * sits in dst, then we temporarily need to move ptr there
5335 * to simulate dst (== 0) +/-= ptr. Needed, for example,
5336 * for cases where we use K-based arithmetic in one direction
5337 * and truncated reg-based in the other in order to explore
5340 if (!ptr_is_dst_reg
) {
5342 *dst_reg
= *ptr_reg
;
5344 ret
= push_stack(env
, env
->insn_idx
+ 1, env
->insn_idx
, true);
5345 if (!ptr_is_dst_reg
&& ret
)
5347 return !ret
? -EFAULT
: 0;
5350 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
5351 * Caller should also handle BPF_MOV case separately.
5352 * If we return -EACCES, caller may want to try again treating pointer as a
5353 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks.
5355 static int adjust_ptr_min_max_vals(struct bpf_verifier_env
*env
,
5356 struct bpf_insn
*insn
,
5357 const struct bpf_reg_state
*ptr_reg
,
5358 const struct bpf_reg_state
*off_reg
)
5360 struct bpf_verifier_state
*vstate
= env
->cur_state
;
5361 struct bpf_func_state
*state
= vstate
->frame
[vstate
->curframe
];
5362 struct bpf_reg_state
*regs
= state
->regs
, *dst_reg
;
5363 bool known
= tnum_is_const(off_reg
->var_off
);
5364 s64 smin_val
= off_reg
->smin_value
, smax_val
= off_reg
->smax_value
,
5365 smin_ptr
= ptr_reg
->smin_value
, smax_ptr
= ptr_reg
->smax_value
;
5366 u64 umin_val
= off_reg
->umin_value
, umax_val
= off_reg
->umax_value
,
5367 umin_ptr
= ptr_reg
->umin_value
, umax_ptr
= ptr_reg
->umax_value
;
5368 u32 dst
= insn
->dst_reg
, src
= insn
->src_reg
;
5369 u8 opcode
= BPF_OP(insn
->code
);
5372 dst_reg
= ®s
[dst
];
5374 if ((known
&& (smin_val
!= smax_val
|| umin_val
!= umax_val
)) ||
5375 smin_val
> smax_val
|| umin_val
> umax_val
) {
5376 /* Taint dst register if offset had invalid bounds derived from
5377 * e.g. dead branches.
5379 __mark_reg_unknown(env
, dst_reg
);
5383 if (BPF_CLASS(insn
->code
) != BPF_ALU64
) {
5384 /* 32-bit ALU ops on pointers produce (meaningless) scalars */
5385 if (opcode
== BPF_SUB
&& env
->allow_ptr_leaks
) {
5386 __mark_reg_unknown(env
, dst_reg
);
5391 "R%d 32-bit pointer arithmetic prohibited\n",
5396 switch (ptr_reg
->type
) {
5397 case PTR_TO_MAP_VALUE_OR_NULL
:
5398 verbose(env
, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
5399 dst
, reg_type_str
[ptr_reg
->type
]);
5401 case CONST_PTR_TO_MAP
:
5402 /* smin_val represents the known value */
5403 if (known
&& smin_val
== 0 && opcode
== BPF_ADD
)
5406 case PTR_TO_PACKET_END
:
5408 case PTR_TO_SOCKET_OR_NULL
:
5409 case PTR_TO_SOCK_COMMON
:
5410 case PTR_TO_SOCK_COMMON_OR_NULL
:
5411 case PTR_TO_TCP_SOCK
:
5412 case PTR_TO_TCP_SOCK_OR_NULL
:
5413 case PTR_TO_XDP_SOCK
:
5414 verbose(env
, "R%d pointer arithmetic on %s prohibited\n",
5415 dst
, reg_type_str
[ptr_reg
->type
]);
5417 case PTR_TO_MAP_VALUE
:
5418 if (!env
->allow_ptr_leaks
&& !known
&& (smin_val
< 0) != (smax_val
< 0)) {
5419 verbose(env
, "R%d has unknown scalar with mixed signed bounds, pointer arithmetic with it prohibited for !root\n",
5420 off_reg
== dst_reg
? dst
: src
);
5428 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
5429 * The id may be overwritten later if we create a new variable offset.
5431 dst_reg
->type
= ptr_reg
->type
;
5432 dst_reg
->id
= ptr_reg
->id
;
5434 if (!check_reg_sane_offset(env
, off_reg
, ptr_reg
->type
) ||
5435 !check_reg_sane_offset(env
, ptr_reg
, ptr_reg
->type
))
5438 /* pointer types do not carry 32-bit bounds at the moment. */
5439 __mark_reg32_unbounded(dst_reg
);
5443 ret
= sanitize_ptr_alu(env
, insn
, ptr_reg
, dst_reg
, smin_val
< 0);
5445 verbose(env
, "R%d tried to add from different maps or paths\n", dst
);
5448 /* We can take a fixed offset as long as it doesn't overflow
5449 * the s32 'off' field
5451 if (known
&& (ptr_reg
->off
+ smin_val
==
5452 (s64
)(s32
)(ptr_reg
->off
+ smin_val
))) {
5453 /* pointer += K. Accumulate it into fixed offset */
5454 dst_reg
->smin_value
= smin_ptr
;
5455 dst_reg
->smax_value
= smax_ptr
;
5456 dst_reg
->umin_value
= umin_ptr
;
5457 dst_reg
->umax_value
= umax_ptr
;
5458 dst_reg
->var_off
= ptr_reg
->var_off
;
5459 dst_reg
->off
= ptr_reg
->off
+ smin_val
;
5460 dst_reg
->raw
= ptr_reg
->raw
;
5463 /* A new variable offset is created. Note that off_reg->off
5464 * == 0, since it's a scalar.
5465 * dst_reg gets the pointer type and since some positive
5466 * integer value was added to the pointer, give it a new 'id'
5467 * if it's a PTR_TO_PACKET.
5468 * this creates a new 'base' pointer, off_reg (variable) gets
5469 * added into the variable offset, and we copy the fixed offset
5472 if (signed_add_overflows(smin_ptr
, smin_val
) ||
5473 signed_add_overflows(smax_ptr
, smax_val
)) {
5474 dst_reg
->smin_value
= S64_MIN
;
5475 dst_reg
->smax_value
= S64_MAX
;
5477 dst_reg
->smin_value
= smin_ptr
+ smin_val
;
5478 dst_reg
->smax_value
= smax_ptr
+ smax_val
;
5480 if (umin_ptr
+ umin_val
< umin_ptr
||
5481 umax_ptr
+ umax_val
< umax_ptr
) {
5482 dst_reg
->umin_value
= 0;
5483 dst_reg
->umax_value
= U64_MAX
;
5485 dst_reg
->umin_value
= umin_ptr
+ umin_val
;
5486 dst_reg
->umax_value
= umax_ptr
+ umax_val
;
5488 dst_reg
->var_off
= tnum_add(ptr_reg
->var_off
, off_reg
->var_off
);
5489 dst_reg
->off
= ptr_reg
->off
;
5490 dst_reg
->raw
= ptr_reg
->raw
;
5491 if (reg_is_pkt_pointer(ptr_reg
)) {
5492 dst_reg
->id
= ++env
->id_gen
;
5493 /* something was added to pkt_ptr, set range to zero */
5498 ret
= sanitize_ptr_alu(env
, insn
, ptr_reg
, dst_reg
, smin_val
< 0);
5500 verbose(env
, "R%d tried to sub from different maps or paths\n", dst
);
5503 if (dst_reg
== off_reg
) {
5504 /* scalar -= pointer. Creates an unknown scalar */
5505 verbose(env
, "R%d tried to subtract pointer from scalar\n",
5509 /* We don't allow subtraction from FP, because (according to
5510 * test_verifier.c test "invalid fp arithmetic", JITs might not
5511 * be able to deal with it.
5513 if (ptr_reg
->type
== PTR_TO_STACK
) {
5514 verbose(env
, "R%d subtraction from stack pointer prohibited\n",
5518 if (known
&& (ptr_reg
->off
- smin_val
==
5519 (s64
)(s32
)(ptr_reg
->off
- smin_val
))) {
5520 /* pointer -= K. Subtract it from fixed offset */
5521 dst_reg
->smin_value
= smin_ptr
;
5522 dst_reg
->smax_value
= smax_ptr
;
5523 dst_reg
->umin_value
= umin_ptr
;
5524 dst_reg
->umax_value
= umax_ptr
;
5525 dst_reg
->var_off
= ptr_reg
->var_off
;
5526 dst_reg
->id
= ptr_reg
->id
;
5527 dst_reg
->off
= ptr_reg
->off
- smin_val
;
5528 dst_reg
->raw
= ptr_reg
->raw
;
5531 /* A new variable offset is created. If the subtrahend is known
5532 * nonnegative, then any reg->range we had before is still good.
5534 if (signed_sub_overflows(smin_ptr
, smax_val
) ||
5535 signed_sub_overflows(smax_ptr
, smin_val
)) {
5536 /* Overflow possible, we know nothing */
5537 dst_reg
->smin_value
= S64_MIN
;
5538 dst_reg
->smax_value
= S64_MAX
;
5540 dst_reg
->smin_value
= smin_ptr
- smax_val
;
5541 dst_reg
->smax_value
= smax_ptr
- smin_val
;
5543 if (umin_ptr
< umax_val
) {
5544 /* Overflow possible, we know nothing */
5545 dst_reg
->umin_value
= 0;
5546 dst_reg
->umax_value
= U64_MAX
;
5548 /* Cannot overflow (as long as bounds are consistent) */
5549 dst_reg
->umin_value
= umin_ptr
- umax_val
;
5550 dst_reg
->umax_value
= umax_ptr
- umin_val
;
5552 dst_reg
->var_off
= tnum_sub(ptr_reg
->var_off
, off_reg
->var_off
);
5553 dst_reg
->off
= ptr_reg
->off
;
5554 dst_reg
->raw
= ptr_reg
->raw
;
5555 if (reg_is_pkt_pointer(ptr_reg
)) {
5556 dst_reg
->id
= ++env
->id_gen
;
5557 /* something was added to pkt_ptr, set range to zero */
5565 /* bitwise ops on pointers are troublesome, prohibit. */
5566 verbose(env
, "R%d bitwise operator %s on pointer prohibited\n",
5567 dst
, bpf_alu_string
[opcode
>> 4]);
5570 /* other operators (e.g. MUL,LSH) produce non-pointer results */
5571 verbose(env
, "R%d pointer arithmetic with %s operator prohibited\n",
5572 dst
, bpf_alu_string
[opcode
>> 4]);
5576 if (!check_reg_sane_offset(env
, dst_reg
, ptr_reg
->type
))
5579 __update_reg_bounds(dst_reg
);
5580 __reg_deduce_bounds(dst_reg
);
5581 __reg_bound_offset(dst_reg
);
5583 /* For unprivileged we require that resulting offset must be in bounds
5584 * in order to be able to sanitize access later on.
5586 if (!env
->bypass_spec_v1
) {
5587 if (dst_reg
->type
== PTR_TO_MAP_VALUE
&&
5588 check_map_access(env
, dst
, dst_reg
->off
, 1, false)) {
5589 verbose(env
, "R%d pointer arithmetic of map value goes out of range, "
5590 "prohibited for !root\n", dst
);
5592 } else if (dst_reg
->type
== PTR_TO_STACK
&&
5593 check_stack_access(env
, dst_reg
, dst_reg
->off
+
5594 dst_reg
->var_off
.value
, 1)) {
5595 verbose(env
, "R%d stack pointer arithmetic goes out of range, "
5596 "prohibited for !root\n", dst
);
5604 static void scalar32_min_max_add(struct bpf_reg_state
*dst_reg
,
5605 struct bpf_reg_state
*src_reg
)
5607 s32 smin_val
= src_reg
->s32_min_value
;
5608 s32 smax_val
= src_reg
->s32_max_value
;
5609 u32 umin_val
= src_reg
->u32_min_value
;
5610 u32 umax_val
= src_reg
->u32_max_value
;
5612 if (signed_add32_overflows(dst_reg
->s32_min_value
, smin_val
) ||
5613 signed_add32_overflows(dst_reg
->s32_max_value
, smax_val
)) {
5614 dst_reg
->s32_min_value
= S32_MIN
;
5615 dst_reg
->s32_max_value
= S32_MAX
;
5617 dst_reg
->s32_min_value
+= smin_val
;
5618 dst_reg
->s32_max_value
+= smax_val
;
5620 if (dst_reg
->u32_min_value
+ umin_val
< umin_val
||
5621 dst_reg
->u32_max_value
+ umax_val
< umax_val
) {
5622 dst_reg
->u32_min_value
= 0;
5623 dst_reg
->u32_max_value
= U32_MAX
;
5625 dst_reg
->u32_min_value
+= umin_val
;
5626 dst_reg
->u32_max_value
+= umax_val
;
5630 static void scalar_min_max_add(struct bpf_reg_state
*dst_reg
,
5631 struct bpf_reg_state
*src_reg
)
5633 s64 smin_val
= src_reg
->smin_value
;
5634 s64 smax_val
= src_reg
->smax_value
;
5635 u64 umin_val
= src_reg
->umin_value
;
5636 u64 umax_val
= src_reg
->umax_value
;
5638 if (signed_add_overflows(dst_reg
->smin_value
, smin_val
) ||
5639 signed_add_overflows(dst_reg
->smax_value
, smax_val
)) {
5640 dst_reg
->smin_value
= S64_MIN
;
5641 dst_reg
->smax_value
= S64_MAX
;
5643 dst_reg
->smin_value
+= smin_val
;
5644 dst_reg
->smax_value
+= smax_val
;
5646 if (dst_reg
->umin_value
+ umin_val
< umin_val
||
5647 dst_reg
->umax_value
+ umax_val
< umax_val
) {
5648 dst_reg
->umin_value
= 0;
5649 dst_reg
->umax_value
= U64_MAX
;
5651 dst_reg
->umin_value
+= umin_val
;
5652 dst_reg
->umax_value
+= umax_val
;
5656 static void scalar32_min_max_sub(struct bpf_reg_state
*dst_reg
,
5657 struct bpf_reg_state
*src_reg
)
5659 s32 smin_val
= src_reg
->s32_min_value
;
5660 s32 smax_val
= src_reg
->s32_max_value
;
5661 u32 umin_val
= src_reg
->u32_min_value
;
5662 u32 umax_val
= src_reg
->u32_max_value
;
5664 if (signed_sub32_overflows(dst_reg
->s32_min_value
, smax_val
) ||
5665 signed_sub32_overflows(dst_reg
->s32_max_value
, smin_val
)) {
5666 /* Overflow possible, we know nothing */
5667 dst_reg
->s32_min_value
= S32_MIN
;
5668 dst_reg
->s32_max_value
= S32_MAX
;
5670 dst_reg
->s32_min_value
-= smax_val
;
5671 dst_reg
->s32_max_value
-= smin_val
;
5673 if (dst_reg
->u32_min_value
< umax_val
) {
5674 /* Overflow possible, we know nothing */
5675 dst_reg
->u32_min_value
= 0;
5676 dst_reg
->u32_max_value
= U32_MAX
;
5678 /* Cannot overflow (as long as bounds are consistent) */
5679 dst_reg
->u32_min_value
-= umax_val
;
5680 dst_reg
->u32_max_value
-= umin_val
;
5684 static void scalar_min_max_sub(struct bpf_reg_state
*dst_reg
,
5685 struct bpf_reg_state
*src_reg
)
5687 s64 smin_val
= src_reg
->smin_value
;
5688 s64 smax_val
= src_reg
->smax_value
;
5689 u64 umin_val
= src_reg
->umin_value
;
5690 u64 umax_val
= src_reg
->umax_value
;
5692 if (signed_sub_overflows(dst_reg
->smin_value
, smax_val
) ||
5693 signed_sub_overflows(dst_reg
->smax_value
, smin_val
)) {
5694 /* Overflow possible, we know nothing */
5695 dst_reg
->smin_value
= S64_MIN
;
5696 dst_reg
->smax_value
= S64_MAX
;
5698 dst_reg
->smin_value
-= smax_val
;
5699 dst_reg
->smax_value
-= smin_val
;
5701 if (dst_reg
->umin_value
< umax_val
) {
5702 /* Overflow possible, we know nothing */
5703 dst_reg
->umin_value
= 0;
5704 dst_reg
->umax_value
= U64_MAX
;
5706 /* Cannot overflow (as long as bounds are consistent) */
5707 dst_reg
->umin_value
-= umax_val
;
5708 dst_reg
->umax_value
-= umin_val
;
5712 static void scalar32_min_max_mul(struct bpf_reg_state
*dst_reg
,
5713 struct bpf_reg_state
*src_reg
)
5715 s32 smin_val
= src_reg
->s32_min_value
;
5716 u32 umin_val
= src_reg
->u32_min_value
;
5717 u32 umax_val
= src_reg
->u32_max_value
;
5719 if (smin_val
< 0 || dst_reg
->s32_min_value
< 0) {
5720 /* Ain't nobody got time to multiply that sign */
5721 __mark_reg32_unbounded(dst_reg
);
5724 /* Both values are positive, so we can work with unsigned and
5725 * copy the result to signed (unless it exceeds S32_MAX).
5727 if (umax_val
> U16_MAX
|| dst_reg
->u32_max_value
> U16_MAX
) {
5728 /* Potential overflow, we know nothing */
5729 __mark_reg32_unbounded(dst_reg
);
5732 dst_reg
->u32_min_value
*= umin_val
;
5733 dst_reg
->u32_max_value
*= umax_val
;
5734 if (dst_reg
->u32_max_value
> S32_MAX
) {
5735 /* Overflow possible, we know nothing */
5736 dst_reg
->s32_min_value
= S32_MIN
;
5737 dst_reg
->s32_max_value
= S32_MAX
;
5739 dst_reg
->s32_min_value
= dst_reg
->u32_min_value
;
5740 dst_reg
->s32_max_value
= dst_reg
->u32_max_value
;
5744 static void scalar_min_max_mul(struct bpf_reg_state
*dst_reg
,
5745 struct bpf_reg_state
*src_reg
)
5747 s64 smin_val
= src_reg
->smin_value
;
5748 u64 umin_val
= src_reg
->umin_value
;
5749 u64 umax_val
= src_reg
->umax_value
;
5751 if (smin_val
< 0 || dst_reg
->smin_value
< 0) {
5752 /* Ain't nobody got time to multiply that sign */
5753 __mark_reg64_unbounded(dst_reg
);
5756 /* Both values are positive, so we can work with unsigned and
5757 * copy the result to signed (unless it exceeds S64_MAX).
5759 if (umax_val
> U32_MAX
|| dst_reg
->umax_value
> U32_MAX
) {
5760 /* Potential overflow, we know nothing */
5761 __mark_reg64_unbounded(dst_reg
);
5764 dst_reg
->umin_value
*= umin_val
;
5765 dst_reg
->umax_value
*= umax_val
;
5766 if (dst_reg
->umax_value
> S64_MAX
) {
5767 /* Overflow possible, we know nothing */
5768 dst_reg
->smin_value
= S64_MIN
;
5769 dst_reg
->smax_value
= S64_MAX
;
5771 dst_reg
->smin_value
= dst_reg
->umin_value
;
5772 dst_reg
->smax_value
= dst_reg
->umax_value
;
5776 static void scalar32_min_max_and(struct bpf_reg_state
*dst_reg
,
5777 struct bpf_reg_state
*src_reg
)
5779 bool src_known
= tnum_subreg_is_const(src_reg
->var_off
);
5780 bool dst_known
= tnum_subreg_is_const(dst_reg
->var_off
);
5781 struct tnum var32_off
= tnum_subreg(dst_reg
->var_off
);
5782 s32 smin_val
= src_reg
->s32_min_value
;
5783 u32 umax_val
= src_reg
->u32_max_value
;
5785 /* Assuming scalar64_min_max_and will be called so its safe
5786 * to skip updating register for known 32-bit case.
5788 if (src_known
&& dst_known
)
5791 /* We get our minimum from the var_off, since that's inherently
5792 * bitwise. Our maximum is the minimum of the operands' maxima.
5794 dst_reg
->u32_min_value
= var32_off
.value
;
5795 dst_reg
->u32_max_value
= min(dst_reg
->u32_max_value
, umax_val
);
5796 if (dst_reg
->s32_min_value
< 0 || smin_val
< 0) {
5797 /* Lose signed bounds when ANDing negative numbers,
5798 * ain't nobody got time for that.
5800 dst_reg
->s32_min_value
= S32_MIN
;
5801 dst_reg
->s32_max_value
= S32_MAX
;
5803 /* ANDing two positives gives a positive, so safe to
5804 * cast result into s64.
5806 dst_reg
->s32_min_value
= dst_reg
->u32_min_value
;
5807 dst_reg
->s32_max_value
= dst_reg
->u32_max_value
;
5812 static void scalar_min_max_and(struct bpf_reg_state
*dst_reg
,
5813 struct bpf_reg_state
*src_reg
)
5815 bool src_known
= tnum_is_const(src_reg
->var_off
);
5816 bool dst_known
= tnum_is_const(dst_reg
->var_off
);
5817 s64 smin_val
= src_reg
->smin_value
;
5818 u64 umax_val
= src_reg
->umax_value
;
5820 if (src_known
&& dst_known
) {
5821 __mark_reg_known(dst_reg
, dst_reg
->var_off
.value
&
5822 src_reg
->var_off
.value
);
5826 /* We get our minimum from the var_off, since that's inherently
5827 * bitwise. Our maximum is the minimum of the operands' maxima.
5829 dst_reg
->umin_value
= dst_reg
->var_off
.value
;
5830 dst_reg
->umax_value
= min(dst_reg
->umax_value
, umax_val
);
5831 if (dst_reg
->smin_value
< 0 || smin_val
< 0) {
5832 /* Lose signed bounds when ANDing negative numbers,
5833 * ain't nobody got time for that.
5835 dst_reg
->smin_value
= S64_MIN
;
5836 dst_reg
->smax_value
= S64_MAX
;
5838 /* ANDing two positives gives a positive, so safe to
5839 * cast result into s64.
5841 dst_reg
->smin_value
= dst_reg
->umin_value
;
5842 dst_reg
->smax_value
= dst_reg
->umax_value
;
5844 /* We may learn something more from the var_off */
5845 __update_reg_bounds(dst_reg
);
5848 static void scalar32_min_max_or(struct bpf_reg_state
*dst_reg
,
5849 struct bpf_reg_state
*src_reg
)
5851 bool src_known
= tnum_subreg_is_const(src_reg
->var_off
);
5852 bool dst_known
= tnum_subreg_is_const(dst_reg
->var_off
);
5853 struct tnum var32_off
= tnum_subreg(dst_reg
->var_off
);
5854 s32 smin_val
= src_reg
->smin_value
;
5855 u32 umin_val
= src_reg
->umin_value
;
5857 /* Assuming scalar64_min_max_or will be called so it is safe
5858 * to skip updating register for known case.
5860 if (src_known
&& dst_known
)
5863 /* We get our maximum from the var_off, and our minimum is the
5864 * maximum of the operands' minima
5866 dst_reg
->u32_min_value
= max(dst_reg
->u32_min_value
, umin_val
);
5867 dst_reg
->u32_max_value
= var32_off
.value
| var32_off
.mask
;
5868 if (dst_reg
->s32_min_value
< 0 || smin_val
< 0) {
5869 /* Lose signed bounds when ORing negative numbers,
5870 * ain't nobody got time for that.
5872 dst_reg
->s32_min_value
= S32_MIN
;
5873 dst_reg
->s32_max_value
= S32_MAX
;
5875 /* ORing two positives gives a positive, so safe to
5876 * cast result into s64.
5878 dst_reg
->s32_min_value
= dst_reg
->umin_value
;
5879 dst_reg
->s32_max_value
= dst_reg
->umax_value
;
5883 static void scalar_min_max_or(struct bpf_reg_state
*dst_reg
,
5884 struct bpf_reg_state
*src_reg
)
5886 bool src_known
= tnum_is_const(src_reg
->var_off
);
5887 bool dst_known
= tnum_is_const(dst_reg
->var_off
);
5888 s64 smin_val
= src_reg
->smin_value
;
5889 u64 umin_val
= src_reg
->umin_value
;
5891 if (src_known
&& dst_known
) {
5892 __mark_reg_known(dst_reg
, dst_reg
->var_off
.value
|
5893 src_reg
->var_off
.value
);
5897 /* We get our maximum from the var_off, and our minimum is the
5898 * maximum of the operands' minima
5900 dst_reg
->umin_value
= max(dst_reg
->umin_value
, umin_val
);
5901 dst_reg
->umax_value
= dst_reg
->var_off
.value
| dst_reg
->var_off
.mask
;
5902 if (dst_reg
->smin_value
< 0 || smin_val
< 0) {
5903 /* Lose signed bounds when ORing negative numbers,
5904 * ain't nobody got time for that.
5906 dst_reg
->smin_value
= S64_MIN
;
5907 dst_reg
->smax_value
= S64_MAX
;
5909 /* ORing two positives gives a positive, so safe to
5910 * cast result into s64.
5912 dst_reg
->smin_value
= dst_reg
->umin_value
;
5913 dst_reg
->smax_value
= dst_reg
->umax_value
;
5915 /* We may learn something more from the var_off */
5916 __update_reg_bounds(dst_reg
);
5919 static void scalar32_min_max_xor(struct bpf_reg_state
*dst_reg
,
5920 struct bpf_reg_state
*src_reg
)
5922 bool src_known
= tnum_subreg_is_const(src_reg
->var_off
);
5923 bool dst_known
= tnum_subreg_is_const(dst_reg
->var_off
);
5924 struct tnum var32_off
= tnum_subreg(dst_reg
->var_off
);
5925 s32 smin_val
= src_reg
->s32_min_value
;
5927 /* Assuming scalar64_min_max_xor will be called so it is safe
5928 * to skip updating register for known case.
5930 if (src_known
&& dst_known
)
5933 /* We get both minimum and maximum from the var32_off. */
5934 dst_reg
->u32_min_value
= var32_off
.value
;
5935 dst_reg
->u32_max_value
= var32_off
.value
| var32_off
.mask
;
5937 if (dst_reg
->s32_min_value
>= 0 && smin_val
>= 0) {
5938 /* XORing two positive sign numbers gives a positive,
5939 * so safe to cast u32 result into s32.
5941 dst_reg
->s32_min_value
= dst_reg
->u32_min_value
;
5942 dst_reg
->s32_max_value
= dst_reg
->u32_max_value
;
5944 dst_reg
->s32_min_value
= S32_MIN
;
5945 dst_reg
->s32_max_value
= S32_MAX
;
5949 static void scalar_min_max_xor(struct bpf_reg_state
*dst_reg
,
5950 struct bpf_reg_state
*src_reg
)
5952 bool src_known
= tnum_is_const(src_reg
->var_off
);
5953 bool dst_known
= tnum_is_const(dst_reg
->var_off
);
5954 s64 smin_val
= src_reg
->smin_value
;
5956 if (src_known
&& dst_known
) {
5957 /* dst_reg->var_off.value has been updated earlier */
5958 __mark_reg_known(dst_reg
, dst_reg
->var_off
.value
);
5962 /* We get both minimum and maximum from the var_off. */
5963 dst_reg
->umin_value
= dst_reg
->var_off
.value
;
5964 dst_reg
->umax_value
= dst_reg
->var_off
.value
| dst_reg
->var_off
.mask
;
5966 if (dst_reg
->smin_value
>= 0 && smin_val
>= 0) {
5967 /* XORing two positive sign numbers gives a positive,
5968 * so safe to cast u64 result into s64.
5970 dst_reg
->smin_value
= dst_reg
->umin_value
;
5971 dst_reg
->smax_value
= dst_reg
->umax_value
;
5973 dst_reg
->smin_value
= S64_MIN
;
5974 dst_reg
->smax_value
= S64_MAX
;
5977 __update_reg_bounds(dst_reg
);
5980 static void __scalar32_min_max_lsh(struct bpf_reg_state
*dst_reg
,
5981 u64 umin_val
, u64 umax_val
)
5983 /* We lose all sign bit information (except what we can pick
5986 dst_reg
->s32_min_value
= S32_MIN
;
5987 dst_reg
->s32_max_value
= S32_MAX
;
5988 /* If we might shift our top bit out, then we know nothing */
5989 if (umax_val
> 31 || dst_reg
->u32_max_value
> 1ULL << (31 - umax_val
)) {
5990 dst_reg
->u32_min_value
= 0;
5991 dst_reg
->u32_max_value
= U32_MAX
;
5993 dst_reg
->u32_min_value
<<= umin_val
;
5994 dst_reg
->u32_max_value
<<= umax_val
;
5998 static void scalar32_min_max_lsh(struct bpf_reg_state
*dst_reg
,
5999 struct bpf_reg_state
*src_reg
)
6001 u32 umax_val
= src_reg
->u32_max_value
;
6002 u32 umin_val
= src_reg
->u32_min_value
;
6003 /* u32 alu operation will zext upper bits */
6004 struct tnum subreg
= tnum_subreg(dst_reg
->var_off
);
6006 __scalar32_min_max_lsh(dst_reg
, umin_val
, umax_val
);
6007 dst_reg
->var_off
= tnum_subreg(tnum_lshift(subreg
, umin_val
));
6008 /* Not required but being careful mark reg64 bounds as unknown so
6009 * that we are forced to pick them up from tnum and zext later and
6010 * if some path skips this step we are still safe.
6012 __mark_reg64_unbounded(dst_reg
);
6013 __update_reg32_bounds(dst_reg
);
6016 static void __scalar64_min_max_lsh(struct bpf_reg_state
*dst_reg
,
6017 u64 umin_val
, u64 umax_val
)
6019 /* Special case <<32 because it is a common compiler pattern to sign
6020 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
6021 * positive we know this shift will also be positive so we can track
6022 * bounds correctly. Otherwise we lose all sign bit information except
6023 * what we can pick up from var_off. Perhaps we can generalize this
6024 * later to shifts of any length.
6026 if (umin_val
== 32 && umax_val
== 32 && dst_reg
->s32_max_value
>= 0)
6027 dst_reg
->smax_value
= (s64
)dst_reg
->s32_max_value
<< 32;
6029 dst_reg
->smax_value
= S64_MAX
;
6031 if (umin_val
== 32 && umax_val
== 32 && dst_reg
->s32_min_value
>= 0)
6032 dst_reg
->smin_value
= (s64
)dst_reg
->s32_min_value
<< 32;
6034 dst_reg
->smin_value
= S64_MIN
;
6036 /* If we might shift our top bit out, then we know nothing */
6037 if (dst_reg
->umax_value
> 1ULL << (63 - umax_val
)) {
6038 dst_reg
->umin_value
= 0;
6039 dst_reg
->umax_value
= U64_MAX
;
6041 dst_reg
->umin_value
<<= umin_val
;
6042 dst_reg
->umax_value
<<= umax_val
;
6046 static void scalar_min_max_lsh(struct bpf_reg_state
*dst_reg
,
6047 struct bpf_reg_state
*src_reg
)
6049 u64 umax_val
= src_reg
->umax_value
;
6050 u64 umin_val
= src_reg
->umin_value
;
6052 /* scalar64 calc uses 32bit unshifted bounds so must be called first */
6053 __scalar64_min_max_lsh(dst_reg
, umin_val
, umax_val
);
6054 __scalar32_min_max_lsh(dst_reg
, umin_val
, umax_val
);
6056 dst_reg
->var_off
= tnum_lshift(dst_reg
->var_off
, umin_val
);
6057 /* We may learn something more from the var_off */
6058 __update_reg_bounds(dst_reg
);
6061 static void scalar32_min_max_rsh(struct bpf_reg_state
*dst_reg
,
6062 struct bpf_reg_state
*src_reg
)
6064 struct tnum subreg
= tnum_subreg(dst_reg
->var_off
);
6065 u32 umax_val
= src_reg
->u32_max_value
;
6066 u32 umin_val
= src_reg
->u32_min_value
;
6068 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
6069 * be negative, then either:
6070 * 1) src_reg might be zero, so the sign bit of the result is
6071 * unknown, so we lose our signed bounds
6072 * 2) it's known negative, thus the unsigned bounds capture the
6074 * 3) the signed bounds cross zero, so they tell us nothing
6076 * If the value in dst_reg is known nonnegative, then again the
6077 * unsigned bounts capture the signed bounds.
6078 * Thus, in all cases it suffices to blow away our signed bounds
6079 * and rely on inferring new ones from the unsigned bounds and
6080 * var_off of the result.
6082 dst_reg
->s32_min_value
= S32_MIN
;
6083 dst_reg
->s32_max_value
= S32_MAX
;
6085 dst_reg
->var_off
= tnum_rshift(subreg
, umin_val
);
6086 dst_reg
->u32_min_value
>>= umax_val
;
6087 dst_reg
->u32_max_value
>>= umin_val
;
6089 __mark_reg64_unbounded(dst_reg
);
6090 __update_reg32_bounds(dst_reg
);
6093 static void scalar_min_max_rsh(struct bpf_reg_state
*dst_reg
,
6094 struct bpf_reg_state
*src_reg
)
6096 u64 umax_val
= src_reg
->umax_value
;
6097 u64 umin_val
= src_reg
->umin_value
;
6099 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
6100 * be negative, then either:
6101 * 1) src_reg might be zero, so the sign bit of the result is
6102 * unknown, so we lose our signed bounds
6103 * 2) it's known negative, thus the unsigned bounds capture the
6105 * 3) the signed bounds cross zero, so they tell us nothing
6107 * If the value in dst_reg is known nonnegative, then again the
6108 * unsigned bounts capture the signed bounds.
6109 * Thus, in all cases it suffices to blow away our signed bounds
6110 * and rely on inferring new ones from the unsigned bounds and
6111 * var_off of the result.
6113 dst_reg
->smin_value
= S64_MIN
;
6114 dst_reg
->smax_value
= S64_MAX
;
6115 dst_reg
->var_off
= tnum_rshift(dst_reg
->var_off
, umin_val
);
6116 dst_reg
->umin_value
>>= umax_val
;
6117 dst_reg
->umax_value
>>= umin_val
;
6119 /* Its not easy to operate on alu32 bounds here because it depends
6120 * on bits being shifted in. Take easy way out and mark unbounded
6121 * so we can recalculate later from tnum.
6123 __mark_reg32_unbounded(dst_reg
);
6124 __update_reg_bounds(dst_reg
);
6127 static void scalar32_min_max_arsh(struct bpf_reg_state
*dst_reg
,
6128 struct bpf_reg_state
*src_reg
)
6130 u64 umin_val
= src_reg
->u32_min_value
;
6132 /* Upon reaching here, src_known is true and
6133 * umax_val is equal to umin_val.
6135 dst_reg
->s32_min_value
= (u32
)(((s32
)dst_reg
->s32_min_value
) >> umin_val
);
6136 dst_reg
->s32_max_value
= (u32
)(((s32
)dst_reg
->s32_max_value
) >> umin_val
);
6138 dst_reg
->var_off
= tnum_arshift(tnum_subreg(dst_reg
->var_off
), umin_val
, 32);
6140 /* blow away the dst_reg umin_value/umax_value and rely on
6141 * dst_reg var_off to refine the result.
6143 dst_reg
->u32_min_value
= 0;
6144 dst_reg
->u32_max_value
= U32_MAX
;
6146 __mark_reg64_unbounded(dst_reg
);
6147 __update_reg32_bounds(dst_reg
);
6150 static void scalar_min_max_arsh(struct bpf_reg_state
*dst_reg
,
6151 struct bpf_reg_state
*src_reg
)
6153 u64 umin_val
= src_reg
->umin_value
;
6155 /* Upon reaching here, src_known is true and umax_val is equal
6158 dst_reg
->smin_value
>>= umin_val
;
6159 dst_reg
->smax_value
>>= umin_val
;
6161 dst_reg
->var_off
= tnum_arshift(dst_reg
->var_off
, umin_val
, 64);
6163 /* blow away the dst_reg umin_value/umax_value and rely on
6164 * dst_reg var_off to refine the result.
6166 dst_reg
->umin_value
= 0;
6167 dst_reg
->umax_value
= U64_MAX
;
6169 /* Its not easy to operate on alu32 bounds here because it depends
6170 * on bits being shifted in from upper 32-bits. Take easy way out
6171 * and mark unbounded so we can recalculate later from tnum.
6173 __mark_reg32_unbounded(dst_reg
);
6174 __update_reg_bounds(dst_reg
);
6177 /* WARNING: This function does calculations on 64-bit values, but the actual
6178 * execution may occur on 32-bit values. Therefore, things like bitshifts
6179 * need extra checks in the 32-bit case.
6181 static int adjust_scalar_min_max_vals(struct bpf_verifier_env
*env
,
6182 struct bpf_insn
*insn
,
6183 struct bpf_reg_state
*dst_reg
,
6184 struct bpf_reg_state src_reg
)
6186 struct bpf_reg_state
*regs
= cur_regs(env
);
6187 u8 opcode
= BPF_OP(insn
->code
);
6189 s64 smin_val
, smax_val
;
6190 u64 umin_val
, umax_val
;
6191 s32 s32_min_val
, s32_max_val
;
6192 u32 u32_min_val
, u32_max_val
;
6193 u64 insn_bitness
= (BPF_CLASS(insn
->code
) == BPF_ALU64
) ? 64 : 32;
6194 u32 dst
= insn
->dst_reg
;
6196 bool alu32
= (BPF_CLASS(insn
->code
) != BPF_ALU64
);
6198 smin_val
= src_reg
.smin_value
;
6199 smax_val
= src_reg
.smax_value
;
6200 umin_val
= src_reg
.umin_value
;
6201 umax_val
= src_reg
.umax_value
;
6203 s32_min_val
= src_reg
.s32_min_value
;
6204 s32_max_val
= src_reg
.s32_max_value
;
6205 u32_min_val
= src_reg
.u32_min_value
;
6206 u32_max_val
= src_reg
.u32_max_value
;
6209 src_known
= tnum_subreg_is_const(src_reg
.var_off
);
6211 (s32_min_val
!= s32_max_val
|| u32_min_val
!= u32_max_val
)) ||
6212 s32_min_val
> s32_max_val
|| u32_min_val
> u32_max_val
) {
6213 /* Taint dst register if offset had invalid bounds
6214 * derived from e.g. dead branches.
6216 __mark_reg_unknown(env
, dst_reg
);
6220 src_known
= tnum_is_const(src_reg
.var_off
);
6222 (smin_val
!= smax_val
|| umin_val
!= umax_val
)) ||
6223 smin_val
> smax_val
|| umin_val
> umax_val
) {
6224 /* Taint dst register if offset had invalid bounds
6225 * derived from e.g. dead branches.
6227 __mark_reg_unknown(env
, dst_reg
);
6233 opcode
!= BPF_ADD
&& opcode
!= BPF_SUB
&& opcode
!= BPF_AND
) {
6234 __mark_reg_unknown(env
, dst_reg
);
6238 /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
6239 * There are two classes of instructions: The first class we track both
6240 * alu32 and alu64 sign/unsigned bounds independently this provides the
6241 * greatest amount of precision when alu operations are mixed with jmp32
6242 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
6243 * and BPF_OR. This is possible because these ops have fairly easy to
6244 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
6245 * See alu32 verifier tests for examples. The second class of
6246 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
6247 * with regards to tracking sign/unsigned bounds because the bits may
6248 * cross subreg boundaries in the alu64 case. When this happens we mark
6249 * the reg unbounded in the subreg bound space and use the resulting
6250 * tnum to calculate an approximation of the sign/unsigned bounds.
6254 ret
= sanitize_val_alu(env
, insn
);
6256 verbose(env
, "R%d tried to add from different pointers or scalars\n", dst
);
6259 scalar32_min_max_add(dst_reg
, &src_reg
);
6260 scalar_min_max_add(dst_reg
, &src_reg
);
6261 dst_reg
->var_off
= tnum_add(dst_reg
->var_off
, src_reg
.var_off
);
6264 ret
= sanitize_val_alu(env
, insn
);
6266 verbose(env
, "R%d tried to sub from different pointers or scalars\n", dst
);
6269 scalar32_min_max_sub(dst_reg
, &src_reg
);
6270 scalar_min_max_sub(dst_reg
, &src_reg
);
6271 dst_reg
->var_off
= tnum_sub(dst_reg
->var_off
, src_reg
.var_off
);
6274 dst_reg
->var_off
= tnum_mul(dst_reg
->var_off
, src_reg
.var_off
);
6275 scalar32_min_max_mul(dst_reg
, &src_reg
);
6276 scalar_min_max_mul(dst_reg
, &src_reg
);
6279 dst_reg
->var_off
= tnum_and(dst_reg
->var_off
, src_reg
.var_off
);
6280 scalar32_min_max_and(dst_reg
, &src_reg
);
6281 scalar_min_max_and(dst_reg
, &src_reg
);
6284 dst_reg
->var_off
= tnum_or(dst_reg
->var_off
, src_reg
.var_off
);
6285 scalar32_min_max_or(dst_reg
, &src_reg
);
6286 scalar_min_max_or(dst_reg
, &src_reg
);
6289 dst_reg
->var_off
= tnum_xor(dst_reg
->var_off
, src_reg
.var_off
);
6290 scalar32_min_max_xor(dst_reg
, &src_reg
);
6291 scalar_min_max_xor(dst_reg
, &src_reg
);
6294 if (umax_val
>= insn_bitness
) {
6295 /* Shifts greater than 31 or 63 are undefined.
6296 * This includes shifts by a negative number.
6298 mark_reg_unknown(env
, regs
, insn
->dst_reg
);
6302 scalar32_min_max_lsh(dst_reg
, &src_reg
);
6304 scalar_min_max_lsh(dst_reg
, &src_reg
);
6307 if (umax_val
>= insn_bitness
) {
6308 /* Shifts greater than 31 or 63 are undefined.
6309 * This includes shifts by a negative number.
6311 mark_reg_unknown(env
, regs
, insn
->dst_reg
);
6315 scalar32_min_max_rsh(dst_reg
, &src_reg
);
6317 scalar_min_max_rsh(dst_reg
, &src_reg
);
6320 if (umax_val
>= insn_bitness
) {
6321 /* Shifts greater than 31 or 63 are undefined.
6322 * This includes shifts by a negative number.
6324 mark_reg_unknown(env
, regs
, insn
->dst_reg
);
6328 scalar32_min_max_arsh(dst_reg
, &src_reg
);
6330 scalar_min_max_arsh(dst_reg
, &src_reg
);
6333 mark_reg_unknown(env
, regs
, insn
->dst_reg
);
6337 /* ALU32 ops are zero extended into 64bit register */
6339 zext_32_to_64(dst_reg
);
6341 __update_reg_bounds(dst_reg
);
6342 __reg_deduce_bounds(dst_reg
);
6343 __reg_bound_offset(dst_reg
);
6347 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
6350 static int adjust_reg_min_max_vals(struct bpf_verifier_env
*env
,
6351 struct bpf_insn
*insn
)
6353 struct bpf_verifier_state
*vstate
= env
->cur_state
;
6354 struct bpf_func_state
*state
= vstate
->frame
[vstate
->curframe
];
6355 struct bpf_reg_state
*regs
= state
->regs
, *dst_reg
, *src_reg
;
6356 struct bpf_reg_state
*ptr_reg
= NULL
, off_reg
= {0};
6357 u8 opcode
= BPF_OP(insn
->code
);
6360 dst_reg
= ®s
[insn
->dst_reg
];
6362 if (dst_reg
->type
!= SCALAR_VALUE
)
6364 if (BPF_SRC(insn
->code
) == BPF_X
) {
6365 src_reg
= ®s
[insn
->src_reg
];
6366 if (src_reg
->type
!= SCALAR_VALUE
) {
6367 if (dst_reg
->type
!= SCALAR_VALUE
) {
6368 /* Combining two pointers by any ALU op yields
6369 * an arbitrary scalar. Disallow all math except
6370 * pointer subtraction
6372 if (opcode
== BPF_SUB
&& env
->allow_ptr_leaks
) {
6373 mark_reg_unknown(env
, regs
, insn
->dst_reg
);
6376 verbose(env
, "R%d pointer %s pointer prohibited\n",
6378 bpf_alu_string
[opcode
>> 4]);
6381 /* scalar += pointer
6382 * This is legal, but we have to reverse our
6383 * src/dest handling in computing the range
6385 err
= mark_chain_precision(env
, insn
->dst_reg
);
6388 return adjust_ptr_min_max_vals(env
, insn
,
6391 } else if (ptr_reg
) {
6392 /* pointer += scalar */
6393 err
= mark_chain_precision(env
, insn
->src_reg
);
6396 return adjust_ptr_min_max_vals(env
, insn
,
6400 /* Pretend the src is a reg with a known value, since we only
6401 * need to be able to read from this state.
6403 off_reg
.type
= SCALAR_VALUE
;
6404 __mark_reg_known(&off_reg
, insn
->imm
);
6406 if (ptr_reg
) /* pointer += K */
6407 return adjust_ptr_min_max_vals(env
, insn
,
6411 /* Got here implies adding two SCALAR_VALUEs */
6412 if (WARN_ON_ONCE(ptr_reg
)) {
6413 print_verifier_state(env
, state
);
6414 verbose(env
, "verifier internal error: unexpected ptr_reg\n");
6417 if (WARN_ON(!src_reg
)) {
6418 print_verifier_state(env
, state
);
6419 verbose(env
, "verifier internal error: no src_reg\n");
6422 return adjust_scalar_min_max_vals(env
, insn
, dst_reg
, *src_reg
);
6425 /* check validity of 32-bit and 64-bit arithmetic operations */
6426 static int check_alu_op(struct bpf_verifier_env
*env
, struct bpf_insn
*insn
)
6428 struct bpf_reg_state
*regs
= cur_regs(env
);
6429 u8 opcode
= BPF_OP(insn
->code
);
6432 if (opcode
== BPF_END
|| opcode
== BPF_NEG
) {
6433 if (opcode
== BPF_NEG
) {
6434 if (BPF_SRC(insn
->code
) != 0 ||
6435 insn
->src_reg
!= BPF_REG_0
||
6436 insn
->off
!= 0 || insn
->imm
!= 0) {
6437 verbose(env
, "BPF_NEG uses reserved fields\n");
6441 if (insn
->src_reg
!= BPF_REG_0
|| insn
->off
!= 0 ||
6442 (insn
->imm
!= 16 && insn
->imm
!= 32 && insn
->imm
!= 64) ||
6443 BPF_CLASS(insn
->code
) == BPF_ALU64
) {
6444 verbose(env
, "BPF_END uses reserved fields\n");
6449 /* check src operand */
6450 err
= check_reg_arg(env
, insn
->dst_reg
, SRC_OP
);
6454 if (is_pointer_value(env
, insn
->dst_reg
)) {
6455 verbose(env
, "R%d pointer arithmetic prohibited\n",
6460 /* check dest operand */
6461 err
= check_reg_arg(env
, insn
->dst_reg
, DST_OP
);
6465 } else if (opcode
== BPF_MOV
) {
6467 if (BPF_SRC(insn
->code
) == BPF_X
) {
6468 if (insn
->imm
!= 0 || insn
->off
!= 0) {
6469 verbose(env
, "BPF_MOV uses reserved fields\n");
6473 /* check src operand */
6474 err
= check_reg_arg(env
, insn
->src_reg
, SRC_OP
);
6478 if (insn
->src_reg
!= BPF_REG_0
|| insn
->off
!= 0) {
6479 verbose(env
, "BPF_MOV uses reserved fields\n");
6484 /* check dest operand, mark as required later */
6485 err
= check_reg_arg(env
, insn
->dst_reg
, DST_OP_NO_MARK
);
6489 if (BPF_SRC(insn
->code
) == BPF_X
) {
6490 struct bpf_reg_state
*src_reg
= regs
+ insn
->src_reg
;
6491 struct bpf_reg_state
*dst_reg
= regs
+ insn
->dst_reg
;
6493 if (BPF_CLASS(insn
->code
) == BPF_ALU64
) {
6495 * copy register state to dest reg
6497 *dst_reg
= *src_reg
;
6498 dst_reg
->live
|= REG_LIVE_WRITTEN
;
6499 dst_reg
->subreg_def
= DEF_NOT_SUBREG
;
6502 if (is_pointer_value(env
, insn
->src_reg
)) {
6504 "R%d partial copy of pointer\n",
6507 } else if (src_reg
->type
== SCALAR_VALUE
) {
6508 *dst_reg
= *src_reg
;
6509 dst_reg
->live
|= REG_LIVE_WRITTEN
;
6510 dst_reg
->subreg_def
= env
->insn_idx
+ 1;
6512 mark_reg_unknown(env
, regs
,
6515 zext_32_to_64(dst_reg
);
6519 * remember the value we stored into this reg
6521 /* clear any state __mark_reg_known doesn't set */
6522 mark_reg_unknown(env
, regs
, insn
->dst_reg
);
6523 regs
[insn
->dst_reg
].type
= SCALAR_VALUE
;
6524 if (BPF_CLASS(insn
->code
) == BPF_ALU64
) {
6525 __mark_reg_known(regs
+ insn
->dst_reg
,
6528 __mark_reg_known(regs
+ insn
->dst_reg
,
6533 } else if (opcode
> BPF_END
) {
6534 verbose(env
, "invalid BPF_ALU opcode %x\n", opcode
);
6537 } else { /* all other ALU ops: and, sub, xor, add, ... */
6539 if (BPF_SRC(insn
->code
) == BPF_X
) {
6540 if (insn
->imm
!= 0 || insn
->off
!= 0) {
6541 verbose(env
, "BPF_ALU uses reserved fields\n");
6544 /* check src1 operand */
6545 err
= check_reg_arg(env
, insn
->src_reg
, SRC_OP
);
6549 if (insn
->src_reg
!= BPF_REG_0
|| insn
->off
!= 0) {
6550 verbose(env
, "BPF_ALU uses reserved fields\n");
6555 /* check src2 operand */
6556 err
= check_reg_arg(env
, insn
->dst_reg
, SRC_OP
);
6560 if ((opcode
== BPF_MOD
|| opcode
== BPF_DIV
) &&
6561 BPF_SRC(insn
->code
) == BPF_K
&& insn
->imm
== 0) {
6562 verbose(env
, "div by zero\n");
6566 if ((opcode
== BPF_LSH
|| opcode
== BPF_RSH
||
6567 opcode
== BPF_ARSH
) && BPF_SRC(insn
->code
) == BPF_K
) {
6568 int size
= BPF_CLASS(insn
->code
) == BPF_ALU64
? 64 : 32;
6570 if (insn
->imm
< 0 || insn
->imm
>= size
) {
6571 verbose(env
, "invalid shift %d\n", insn
->imm
);
6576 /* check dest operand */
6577 err
= check_reg_arg(env
, insn
->dst_reg
, DST_OP_NO_MARK
);
6581 return adjust_reg_min_max_vals(env
, insn
);
6587 static void __find_good_pkt_pointers(struct bpf_func_state
*state
,
6588 struct bpf_reg_state
*dst_reg
,
6589 enum bpf_reg_type type
, u16 new_range
)
6591 struct bpf_reg_state
*reg
;
6594 for (i
= 0; i
< MAX_BPF_REG
; i
++) {
6595 reg
= &state
->regs
[i
];
6596 if (reg
->type
== type
&& reg
->id
== dst_reg
->id
)
6597 /* keep the maximum range already checked */
6598 reg
->range
= max(reg
->range
, new_range
);
6601 bpf_for_each_spilled_reg(i
, state
, reg
) {
6604 if (reg
->type
== type
&& reg
->id
== dst_reg
->id
)
6605 reg
->range
= max(reg
->range
, new_range
);
6609 static void find_good_pkt_pointers(struct bpf_verifier_state
*vstate
,
6610 struct bpf_reg_state
*dst_reg
,
6611 enum bpf_reg_type type
,
6612 bool range_right_open
)
6617 if (dst_reg
->off
< 0 ||
6618 (dst_reg
->off
== 0 && range_right_open
))
6619 /* This doesn't give us any range */
6622 if (dst_reg
->umax_value
> MAX_PACKET_OFF
||
6623 dst_reg
->umax_value
+ dst_reg
->off
> MAX_PACKET_OFF
)
6624 /* Risk of overflow. For instance, ptr + (1<<63) may be less
6625 * than pkt_end, but that's because it's also less than pkt.
6629 new_range
= dst_reg
->off
;
6630 if (range_right_open
)
6633 /* Examples for register markings:
6635 * pkt_data in dst register:
6639 * if (r2 > pkt_end) goto <handle exception>
6644 * if (r2 < pkt_end) goto <access okay>
6645 * <handle exception>
6648 * r2 == dst_reg, pkt_end == src_reg
6649 * r2=pkt(id=n,off=8,r=0)
6650 * r3=pkt(id=n,off=0,r=0)
6652 * pkt_data in src register:
6656 * if (pkt_end >= r2) goto <access okay>
6657 * <handle exception>
6661 * if (pkt_end <= r2) goto <handle exception>
6665 * pkt_end == dst_reg, r2 == src_reg
6666 * r2=pkt(id=n,off=8,r=0)
6667 * r3=pkt(id=n,off=0,r=0)
6669 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
6670 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
6671 * and [r3, r3 + 8-1) respectively is safe to access depending on
6675 /* If our ids match, then we must have the same max_value. And we
6676 * don't care about the other reg's fixed offset, since if it's too big
6677 * the range won't allow anything.
6678 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
6680 for (i
= 0; i
<= vstate
->curframe
; i
++)
6681 __find_good_pkt_pointers(vstate
->frame
[i
], dst_reg
, type
,
6685 static int is_branch32_taken(struct bpf_reg_state
*reg
, u32 val
, u8 opcode
)
6687 struct tnum subreg
= tnum_subreg(reg
->var_off
);
6688 s32 sval
= (s32
)val
;
6692 if (tnum_is_const(subreg
))
6693 return !!tnum_equals_const(subreg
, val
);
6696 if (tnum_is_const(subreg
))
6697 return !tnum_equals_const(subreg
, val
);
6700 if ((~subreg
.mask
& subreg
.value
) & val
)
6702 if (!((subreg
.mask
| subreg
.value
) & val
))
6706 if (reg
->u32_min_value
> val
)
6708 else if (reg
->u32_max_value
<= val
)
6712 if (reg
->s32_min_value
> sval
)
6714 else if (reg
->s32_max_value
< sval
)
6718 if (reg
->u32_max_value
< val
)
6720 else if (reg
->u32_min_value
>= val
)
6724 if (reg
->s32_max_value
< sval
)
6726 else if (reg
->s32_min_value
>= sval
)
6730 if (reg
->u32_min_value
>= val
)
6732 else if (reg
->u32_max_value
< val
)
6736 if (reg
->s32_min_value
>= sval
)
6738 else if (reg
->s32_max_value
< sval
)
6742 if (reg
->u32_max_value
<= val
)
6744 else if (reg
->u32_min_value
> val
)
6748 if (reg
->s32_max_value
<= sval
)
6750 else if (reg
->s32_min_value
> sval
)
6759 static int is_branch64_taken(struct bpf_reg_state
*reg
, u64 val
, u8 opcode
)
6761 s64 sval
= (s64
)val
;
6765 if (tnum_is_const(reg
->var_off
))
6766 return !!tnum_equals_const(reg
->var_off
, val
);
6769 if (tnum_is_const(reg
->var_off
))
6770 return !tnum_equals_const(reg
->var_off
, val
);
6773 if ((~reg
->var_off
.mask
& reg
->var_off
.value
) & val
)
6775 if (!((reg
->var_off
.mask
| reg
->var_off
.value
) & val
))
6779 if (reg
->umin_value
> val
)
6781 else if (reg
->umax_value
<= val
)
6785 if (reg
->smin_value
> sval
)
6787 else if (reg
->smax_value
< sval
)
6791 if (reg
->umax_value
< val
)
6793 else if (reg
->umin_value
>= val
)
6797 if (reg
->smax_value
< sval
)
6799 else if (reg
->smin_value
>= sval
)
6803 if (reg
->umin_value
>= val
)
6805 else if (reg
->umax_value
< val
)
6809 if (reg
->smin_value
>= sval
)
6811 else if (reg
->smax_value
< sval
)
6815 if (reg
->umax_value
<= val
)
6817 else if (reg
->umin_value
> val
)
6821 if (reg
->smax_value
<= sval
)
6823 else if (reg
->smin_value
> sval
)
6831 /* compute branch direction of the expression "if (reg opcode val) goto target;"
6833 * 1 - branch will be taken and "goto target" will be executed
6834 * 0 - branch will not be taken and fall-through to next insn
6835 * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
6838 static int is_branch_taken(struct bpf_reg_state
*reg
, u64 val
, u8 opcode
,
6841 if (__is_pointer_value(false, reg
)) {
6842 if (!reg_type_not_null(reg
->type
))
6845 /* If pointer is valid tests against zero will fail so we can
6846 * use this to direct branch taken.
6862 return is_branch32_taken(reg
, val
, opcode
);
6863 return is_branch64_taken(reg
, val
, opcode
);
6866 /* Adjusts the register min/max values in the case that the dst_reg is the
6867 * variable register that we are working on, and src_reg is a constant or we're
6868 * simply doing a BPF_K check.
6869 * In JEQ/JNE cases we also adjust the var_off values.
6871 static void reg_set_min_max(struct bpf_reg_state
*true_reg
,
6872 struct bpf_reg_state
*false_reg
,
6874 u8 opcode
, bool is_jmp32
)
6876 struct tnum false_32off
= tnum_subreg(false_reg
->var_off
);
6877 struct tnum false_64off
= false_reg
->var_off
;
6878 struct tnum true_32off
= tnum_subreg(true_reg
->var_off
);
6879 struct tnum true_64off
= true_reg
->var_off
;
6880 s64 sval
= (s64
)val
;
6881 s32 sval32
= (s32
)val32
;
6883 /* If the dst_reg is a pointer, we can't learn anything about its
6884 * variable offset from the compare (unless src_reg were a pointer into
6885 * the same object, but we don't bother with that.
6886 * Since false_reg and true_reg have the same type by construction, we
6887 * only need to check one of them for pointerness.
6889 if (__is_pointer_value(false, false_reg
))
6896 struct bpf_reg_state
*reg
=
6897 opcode
== BPF_JEQ
? true_reg
: false_reg
;
6899 /* For BPF_JEQ, if this is false we know nothing Jon Snow, but
6900 * if it is true we know the value for sure. Likewise for
6904 __mark_reg32_known(reg
, val32
);
6906 __mark_reg_known(reg
, val
);
6911 false_32off
= tnum_and(false_32off
, tnum_const(~val32
));
6912 if (is_power_of_2(val32
))
6913 true_32off
= tnum_or(true_32off
,
6916 false_64off
= tnum_and(false_64off
, tnum_const(~val
));
6917 if (is_power_of_2(val
))
6918 true_64off
= tnum_or(true_64off
,
6926 u32 false_umax
= opcode
== BPF_JGT
? val32
: val32
- 1;
6927 u32 true_umin
= opcode
== BPF_JGT
? val32
+ 1 : val32
;
6929 false_reg
->u32_max_value
= min(false_reg
->u32_max_value
,
6931 true_reg
->u32_min_value
= max(true_reg
->u32_min_value
,
6934 u64 false_umax
= opcode
== BPF_JGT
? val
: val
- 1;
6935 u64 true_umin
= opcode
== BPF_JGT
? val
+ 1 : val
;
6937 false_reg
->umax_value
= min(false_reg
->umax_value
, false_umax
);
6938 true_reg
->umin_value
= max(true_reg
->umin_value
, true_umin
);
6946 s32 false_smax
= opcode
== BPF_JSGT
? sval32
: sval32
- 1;
6947 s32 true_smin
= opcode
== BPF_JSGT
? sval32
+ 1 : sval32
;
6949 false_reg
->s32_max_value
= min(false_reg
->s32_max_value
, false_smax
);
6950 true_reg
->s32_min_value
= max(true_reg
->s32_min_value
, true_smin
);
6952 s64 false_smax
= opcode
== BPF_JSGT
? sval
: sval
- 1;
6953 s64 true_smin
= opcode
== BPF_JSGT
? sval
+ 1 : sval
;
6955 false_reg
->smax_value
= min(false_reg
->smax_value
, false_smax
);
6956 true_reg
->smin_value
= max(true_reg
->smin_value
, true_smin
);
6964 u32 false_umin
= opcode
== BPF_JLT
? val32
: val32
+ 1;
6965 u32 true_umax
= opcode
== BPF_JLT
? val32
- 1 : val32
;
6967 false_reg
->u32_min_value
= max(false_reg
->u32_min_value
,
6969 true_reg
->u32_max_value
= min(true_reg
->u32_max_value
,
6972 u64 false_umin
= opcode
== BPF_JLT
? val
: val
+ 1;
6973 u64 true_umax
= opcode
== BPF_JLT
? val
- 1 : val
;
6975 false_reg
->umin_value
= max(false_reg
->umin_value
, false_umin
);
6976 true_reg
->umax_value
= min(true_reg
->umax_value
, true_umax
);
6984 s32 false_smin
= opcode
== BPF_JSLT
? sval32
: sval32
+ 1;
6985 s32 true_smax
= opcode
== BPF_JSLT
? sval32
- 1 : sval32
;
6987 false_reg
->s32_min_value
= max(false_reg
->s32_min_value
, false_smin
);
6988 true_reg
->s32_max_value
= min(true_reg
->s32_max_value
, true_smax
);
6990 s64 false_smin
= opcode
== BPF_JSLT
? sval
: sval
+ 1;
6991 s64 true_smax
= opcode
== BPF_JSLT
? sval
- 1 : sval
;
6993 false_reg
->smin_value
= max(false_reg
->smin_value
, false_smin
);
6994 true_reg
->smax_value
= min(true_reg
->smax_value
, true_smax
);
7003 false_reg
->var_off
= tnum_or(tnum_clear_subreg(false_64off
),
7004 tnum_subreg(false_32off
));
7005 true_reg
->var_off
= tnum_or(tnum_clear_subreg(true_64off
),
7006 tnum_subreg(true_32off
));
7007 __reg_combine_32_into_64(false_reg
);
7008 __reg_combine_32_into_64(true_reg
);
7010 false_reg
->var_off
= false_64off
;
7011 true_reg
->var_off
= true_64off
;
7012 __reg_combine_64_into_32(false_reg
);
7013 __reg_combine_64_into_32(true_reg
);
7017 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
7020 static void reg_set_min_max_inv(struct bpf_reg_state
*true_reg
,
7021 struct bpf_reg_state
*false_reg
,
7023 u8 opcode
, bool is_jmp32
)
7025 /* How can we transform "a <op> b" into "b <op> a"? */
7026 static const u8 opcode_flip
[16] = {
7027 /* these stay the same */
7028 [BPF_JEQ
>> 4] = BPF_JEQ
,
7029 [BPF_JNE
>> 4] = BPF_JNE
,
7030 [BPF_JSET
>> 4] = BPF_JSET
,
7031 /* these swap "lesser" and "greater" (L and G in the opcodes) */
7032 [BPF_JGE
>> 4] = BPF_JLE
,
7033 [BPF_JGT
>> 4] = BPF_JLT
,
7034 [BPF_JLE
>> 4] = BPF_JGE
,
7035 [BPF_JLT
>> 4] = BPF_JGT
,
7036 [BPF_JSGE
>> 4] = BPF_JSLE
,
7037 [BPF_JSGT
>> 4] = BPF_JSLT
,
7038 [BPF_JSLE
>> 4] = BPF_JSGE
,
7039 [BPF_JSLT
>> 4] = BPF_JSGT
7041 opcode
= opcode_flip
[opcode
>> 4];
7042 /* This uses zero as "not present in table"; luckily the zero opcode,
7043 * BPF_JA, can't get here.
7046 reg_set_min_max(true_reg
, false_reg
, val
, val32
, opcode
, is_jmp32
);
7049 /* Regs are known to be equal, so intersect their min/max/var_off */
7050 static void __reg_combine_min_max(struct bpf_reg_state
*src_reg
,
7051 struct bpf_reg_state
*dst_reg
)
7053 src_reg
->umin_value
= dst_reg
->umin_value
= max(src_reg
->umin_value
,
7054 dst_reg
->umin_value
);
7055 src_reg
->umax_value
= dst_reg
->umax_value
= min(src_reg
->umax_value
,
7056 dst_reg
->umax_value
);
7057 src_reg
->smin_value
= dst_reg
->smin_value
= max(src_reg
->smin_value
,
7058 dst_reg
->smin_value
);
7059 src_reg
->smax_value
= dst_reg
->smax_value
= min(src_reg
->smax_value
,
7060 dst_reg
->smax_value
);
7061 src_reg
->var_off
= dst_reg
->var_off
= tnum_intersect(src_reg
->var_off
,
7063 /* We might have learned new bounds from the var_off. */
7064 __update_reg_bounds(src_reg
);
7065 __update_reg_bounds(dst_reg
);
7066 /* We might have learned something about the sign bit. */
7067 __reg_deduce_bounds(src_reg
);
7068 __reg_deduce_bounds(dst_reg
);
7069 /* We might have learned some bits from the bounds. */
7070 __reg_bound_offset(src_reg
);
7071 __reg_bound_offset(dst_reg
);
7072 /* Intersecting with the old var_off might have improved our bounds
7073 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
7074 * then new var_off is (0; 0x7f...fc) which improves our umax.
7076 __update_reg_bounds(src_reg
);
7077 __update_reg_bounds(dst_reg
);
7080 static void reg_combine_min_max(struct bpf_reg_state
*true_src
,
7081 struct bpf_reg_state
*true_dst
,
7082 struct bpf_reg_state
*false_src
,
7083 struct bpf_reg_state
*false_dst
,
7088 __reg_combine_min_max(true_src
, true_dst
);
7091 __reg_combine_min_max(false_src
, false_dst
);
7096 static void mark_ptr_or_null_reg(struct bpf_func_state
*state
,
7097 struct bpf_reg_state
*reg
, u32 id
,
7100 if (reg_type_may_be_null(reg
->type
) && reg
->id
== id
) {
7101 /* Old offset (both fixed and variable parts) should
7102 * have been known-zero, because we don't allow pointer
7103 * arithmetic on pointers that might be NULL.
7105 if (WARN_ON_ONCE(reg
->smin_value
|| reg
->smax_value
||
7106 !tnum_equals_const(reg
->var_off
, 0) ||
7108 __mark_reg_known_zero(reg
);
7112 reg
->type
= SCALAR_VALUE
;
7113 } else if (reg
->type
== PTR_TO_MAP_VALUE_OR_NULL
) {
7114 const struct bpf_map
*map
= reg
->map_ptr
;
7116 if (map
->inner_map_meta
) {
7117 reg
->type
= CONST_PTR_TO_MAP
;
7118 reg
->map_ptr
= map
->inner_map_meta
;
7119 } else if (map
->map_type
== BPF_MAP_TYPE_XSKMAP
) {
7120 reg
->type
= PTR_TO_XDP_SOCK
;
7121 } else if (map
->map_type
== BPF_MAP_TYPE_SOCKMAP
||
7122 map
->map_type
== BPF_MAP_TYPE_SOCKHASH
) {
7123 reg
->type
= PTR_TO_SOCKET
;
7125 reg
->type
= PTR_TO_MAP_VALUE
;
7127 } else if (reg
->type
== PTR_TO_SOCKET_OR_NULL
) {
7128 reg
->type
= PTR_TO_SOCKET
;
7129 } else if (reg
->type
== PTR_TO_SOCK_COMMON_OR_NULL
) {
7130 reg
->type
= PTR_TO_SOCK_COMMON
;
7131 } else if (reg
->type
== PTR_TO_TCP_SOCK_OR_NULL
) {
7132 reg
->type
= PTR_TO_TCP_SOCK
;
7133 } else if (reg
->type
== PTR_TO_BTF_ID_OR_NULL
) {
7134 reg
->type
= PTR_TO_BTF_ID
;
7135 } else if (reg
->type
== PTR_TO_MEM_OR_NULL
) {
7136 reg
->type
= PTR_TO_MEM
;
7137 } else if (reg
->type
== PTR_TO_RDONLY_BUF_OR_NULL
) {
7138 reg
->type
= PTR_TO_RDONLY_BUF
;
7139 } else if (reg
->type
== PTR_TO_RDWR_BUF_OR_NULL
) {
7140 reg
->type
= PTR_TO_RDWR_BUF
;
7143 /* We don't need id and ref_obj_id from this point
7144 * onwards anymore, thus we should better reset it,
7145 * so that state pruning has chances to take effect.
7148 reg
->ref_obj_id
= 0;
7149 } else if (!reg_may_point_to_spin_lock(reg
)) {
7150 /* For not-NULL ptr, reg->ref_obj_id will be reset
7151 * in release_reg_references().
7153 * reg->id is still used by spin_lock ptr. Other
7154 * than spin_lock ptr type, reg->id can be reset.
7161 static void __mark_ptr_or_null_regs(struct bpf_func_state
*state
, u32 id
,
7164 struct bpf_reg_state
*reg
;
7167 for (i
= 0; i
< MAX_BPF_REG
; i
++)
7168 mark_ptr_or_null_reg(state
, &state
->regs
[i
], id
, is_null
);
7170 bpf_for_each_spilled_reg(i
, state
, reg
) {
7173 mark_ptr_or_null_reg(state
, reg
, id
, is_null
);
7177 /* The logic is similar to find_good_pkt_pointers(), both could eventually
7178 * be folded together at some point.
7180 static void mark_ptr_or_null_regs(struct bpf_verifier_state
*vstate
, u32 regno
,
7183 struct bpf_func_state
*state
= vstate
->frame
[vstate
->curframe
];
7184 struct bpf_reg_state
*regs
= state
->regs
;
7185 u32 ref_obj_id
= regs
[regno
].ref_obj_id
;
7186 u32 id
= regs
[regno
].id
;
7189 if (ref_obj_id
&& ref_obj_id
== id
&& is_null
)
7190 /* regs[regno] is in the " == NULL" branch.
7191 * No one could have freed the reference state before
7192 * doing the NULL check.
7194 WARN_ON_ONCE(release_reference_state(state
, id
));
7196 for (i
= 0; i
<= vstate
->curframe
; i
++)
7197 __mark_ptr_or_null_regs(vstate
->frame
[i
], id
, is_null
);
7200 static bool try_match_pkt_pointers(const struct bpf_insn
*insn
,
7201 struct bpf_reg_state
*dst_reg
,
7202 struct bpf_reg_state
*src_reg
,
7203 struct bpf_verifier_state
*this_branch
,
7204 struct bpf_verifier_state
*other_branch
)
7206 if (BPF_SRC(insn
->code
) != BPF_X
)
7209 /* Pointers are always 64-bit. */
7210 if (BPF_CLASS(insn
->code
) == BPF_JMP32
)
7213 switch (BPF_OP(insn
->code
)) {
7215 if ((dst_reg
->type
== PTR_TO_PACKET
&&
7216 src_reg
->type
== PTR_TO_PACKET_END
) ||
7217 (dst_reg
->type
== PTR_TO_PACKET_META
&&
7218 reg_is_init_pkt_pointer(src_reg
, PTR_TO_PACKET
))) {
7219 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
7220 find_good_pkt_pointers(this_branch
, dst_reg
,
7221 dst_reg
->type
, false);
7222 } else if ((dst_reg
->type
== PTR_TO_PACKET_END
&&
7223 src_reg
->type
== PTR_TO_PACKET
) ||
7224 (reg_is_init_pkt_pointer(dst_reg
, PTR_TO_PACKET
) &&
7225 src_reg
->type
== PTR_TO_PACKET_META
)) {
7226 /* pkt_end > pkt_data', pkt_data > pkt_meta' */
7227 find_good_pkt_pointers(other_branch
, src_reg
,
7228 src_reg
->type
, true);
7234 if ((dst_reg
->type
== PTR_TO_PACKET
&&
7235 src_reg
->type
== PTR_TO_PACKET_END
) ||
7236 (dst_reg
->type
== PTR_TO_PACKET_META
&&
7237 reg_is_init_pkt_pointer(src_reg
, PTR_TO_PACKET
))) {
7238 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
7239 find_good_pkt_pointers(other_branch
, dst_reg
,
7240 dst_reg
->type
, true);
7241 } else if ((dst_reg
->type
== PTR_TO_PACKET_END
&&
7242 src_reg
->type
== PTR_TO_PACKET
) ||
7243 (reg_is_init_pkt_pointer(dst_reg
, PTR_TO_PACKET
) &&
7244 src_reg
->type
== PTR_TO_PACKET_META
)) {
7245 /* pkt_end < pkt_data', pkt_data > pkt_meta' */
7246 find_good_pkt_pointers(this_branch
, src_reg
,
7247 src_reg
->type
, false);
7253 if ((dst_reg
->type
== PTR_TO_PACKET
&&
7254 src_reg
->type
== PTR_TO_PACKET_END
) ||
7255 (dst_reg
->type
== PTR_TO_PACKET_META
&&
7256 reg_is_init_pkt_pointer(src_reg
, PTR_TO_PACKET
))) {
7257 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
7258 find_good_pkt_pointers(this_branch
, dst_reg
,
7259 dst_reg
->type
, true);
7260 } else if ((dst_reg
->type
== PTR_TO_PACKET_END
&&
7261 src_reg
->type
== PTR_TO_PACKET
) ||
7262 (reg_is_init_pkt_pointer(dst_reg
, PTR_TO_PACKET
) &&
7263 src_reg
->type
== PTR_TO_PACKET_META
)) {
7264 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
7265 find_good_pkt_pointers(other_branch
, src_reg
,
7266 src_reg
->type
, false);
7272 if ((dst_reg
->type
== PTR_TO_PACKET
&&
7273 src_reg
->type
== PTR_TO_PACKET_END
) ||
7274 (dst_reg
->type
== PTR_TO_PACKET_META
&&
7275 reg_is_init_pkt_pointer(src_reg
, PTR_TO_PACKET
))) {
7276 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
7277 find_good_pkt_pointers(other_branch
, dst_reg
,
7278 dst_reg
->type
, false);
7279 } else if ((dst_reg
->type
== PTR_TO_PACKET_END
&&
7280 src_reg
->type
== PTR_TO_PACKET
) ||
7281 (reg_is_init_pkt_pointer(dst_reg
, PTR_TO_PACKET
) &&
7282 src_reg
->type
== PTR_TO_PACKET_META
)) {
7283 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
7284 find_good_pkt_pointers(this_branch
, src_reg
,
7285 src_reg
->type
, true);
7297 static int check_cond_jmp_op(struct bpf_verifier_env
*env
,
7298 struct bpf_insn
*insn
, int *insn_idx
)
7300 struct bpf_verifier_state
*this_branch
= env
->cur_state
;
7301 struct bpf_verifier_state
*other_branch
;
7302 struct bpf_reg_state
*regs
= this_branch
->frame
[this_branch
->curframe
]->regs
;
7303 struct bpf_reg_state
*dst_reg
, *other_branch_regs
, *src_reg
= NULL
;
7304 u8 opcode
= BPF_OP(insn
->code
);
7309 /* Only conditional jumps are expected to reach here. */
7310 if (opcode
== BPF_JA
|| opcode
> BPF_JSLE
) {
7311 verbose(env
, "invalid BPF_JMP/JMP32 opcode %x\n", opcode
);
7315 if (BPF_SRC(insn
->code
) == BPF_X
) {
7316 if (insn
->imm
!= 0) {
7317 verbose(env
, "BPF_JMP/JMP32 uses reserved fields\n");
7321 /* check src1 operand */
7322 err
= check_reg_arg(env
, insn
->src_reg
, SRC_OP
);
7326 if (is_pointer_value(env
, insn
->src_reg
)) {
7327 verbose(env
, "R%d pointer comparison prohibited\n",
7331 src_reg
= ®s
[insn
->src_reg
];
7333 if (insn
->src_reg
!= BPF_REG_0
) {
7334 verbose(env
, "BPF_JMP/JMP32 uses reserved fields\n");
7339 /* check src2 operand */
7340 err
= check_reg_arg(env
, insn
->dst_reg
, SRC_OP
);
7344 dst_reg
= ®s
[insn
->dst_reg
];
7345 is_jmp32
= BPF_CLASS(insn
->code
) == BPF_JMP32
;
7347 if (BPF_SRC(insn
->code
) == BPF_K
) {
7348 pred
= is_branch_taken(dst_reg
, insn
->imm
, opcode
, is_jmp32
);
7349 } else if (src_reg
->type
== SCALAR_VALUE
&&
7350 is_jmp32
&& tnum_is_const(tnum_subreg(src_reg
->var_off
))) {
7351 pred
= is_branch_taken(dst_reg
,
7352 tnum_subreg(src_reg
->var_off
).value
,
7355 } else if (src_reg
->type
== SCALAR_VALUE
&&
7356 !is_jmp32
&& tnum_is_const(src_reg
->var_off
)) {
7357 pred
= is_branch_taken(dst_reg
,
7358 src_reg
->var_off
.value
,
7364 /* If we get here with a dst_reg pointer type it is because
7365 * above is_branch_taken() special cased the 0 comparison.
7367 if (!__is_pointer_value(false, dst_reg
))
7368 err
= mark_chain_precision(env
, insn
->dst_reg
);
7369 if (BPF_SRC(insn
->code
) == BPF_X
&& !err
)
7370 err
= mark_chain_precision(env
, insn
->src_reg
);
7375 /* only follow the goto, ignore fall-through */
7376 *insn_idx
+= insn
->off
;
7378 } else if (pred
== 0) {
7379 /* only follow fall-through branch, since
7380 * that's where the program will go
7385 other_branch
= push_stack(env
, *insn_idx
+ insn
->off
+ 1, *insn_idx
,
7389 other_branch_regs
= other_branch
->frame
[other_branch
->curframe
]->regs
;
7391 /* detect if we are comparing against a constant value so we can adjust
7392 * our min/max values for our dst register.
7393 * this is only legit if both are scalars (or pointers to the same
7394 * object, I suppose, but we don't support that right now), because
7395 * otherwise the different base pointers mean the offsets aren't
7398 if (BPF_SRC(insn
->code
) == BPF_X
) {
7399 struct bpf_reg_state
*src_reg
= ®s
[insn
->src_reg
];
7401 if (dst_reg
->type
== SCALAR_VALUE
&&
7402 src_reg
->type
== SCALAR_VALUE
) {
7403 if (tnum_is_const(src_reg
->var_off
) ||
7405 tnum_is_const(tnum_subreg(src_reg
->var_off
))))
7406 reg_set_min_max(&other_branch_regs
[insn
->dst_reg
],
7408 src_reg
->var_off
.value
,
7409 tnum_subreg(src_reg
->var_off
).value
,
7411 else if (tnum_is_const(dst_reg
->var_off
) ||
7413 tnum_is_const(tnum_subreg(dst_reg
->var_off
))))
7414 reg_set_min_max_inv(&other_branch_regs
[insn
->src_reg
],
7416 dst_reg
->var_off
.value
,
7417 tnum_subreg(dst_reg
->var_off
).value
,
7419 else if (!is_jmp32
&&
7420 (opcode
== BPF_JEQ
|| opcode
== BPF_JNE
))
7421 /* Comparing for equality, we can combine knowledge */
7422 reg_combine_min_max(&other_branch_regs
[insn
->src_reg
],
7423 &other_branch_regs
[insn
->dst_reg
],
7424 src_reg
, dst_reg
, opcode
);
7426 } else if (dst_reg
->type
== SCALAR_VALUE
) {
7427 reg_set_min_max(&other_branch_regs
[insn
->dst_reg
],
7428 dst_reg
, insn
->imm
, (u32
)insn
->imm
,
7432 /* detect if R == 0 where R is returned from bpf_map_lookup_elem().
7433 * NOTE: these optimizations below are related with pointer comparison
7434 * which will never be JMP32.
7436 if (!is_jmp32
&& BPF_SRC(insn
->code
) == BPF_K
&&
7437 insn
->imm
== 0 && (opcode
== BPF_JEQ
|| opcode
== BPF_JNE
) &&
7438 reg_type_may_be_null(dst_reg
->type
)) {
7439 /* Mark all identical registers in each branch as either
7440 * safe or unknown depending R == 0 or R != 0 conditional.
7442 mark_ptr_or_null_regs(this_branch
, insn
->dst_reg
,
7444 mark_ptr_or_null_regs(other_branch
, insn
->dst_reg
,
7446 } else if (!try_match_pkt_pointers(insn
, dst_reg
, ®s
[insn
->src_reg
],
7447 this_branch
, other_branch
) &&
7448 is_pointer_value(env
, insn
->dst_reg
)) {
7449 verbose(env
, "R%d pointer comparison prohibited\n",
7453 if (env
->log
.level
& BPF_LOG_LEVEL
)
7454 print_verifier_state(env
, this_branch
->frame
[this_branch
->curframe
]);
7458 /* verify BPF_LD_IMM64 instruction */
7459 static int check_ld_imm(struct bpf_verifier_env
*env
, struct bpf_insn
*insn
)
7461 struct bpf_insn_aux_data
*aux
= cur_aux(env
);
7462 struct bpf_reg_state
*regs
= cur_regs(env
);
7463 struct bpf_map
*map
;
7466 if (BPF_SIZE(insn
->code
) != BPF_DW
) {
7467 verbose(env
, "invalid BPF_LD_IMM insn\n");
7470 if (insn
->off
!= 0) {
7471 verbose(env
, "BPF_LD_IMM64 uses reserved fields\n");
7475 err
= check_reg_arg(env
, insn
->dst_reg
, DST_OP
);
7479 if (insn
->src_reg
== 0) {
7480 u64 imm
= ((u64
)(insn
+ 1)->imm
<< 32) | (u32
)insn
->imm
;
7482 regs
[insn
->dst_reg
].type
= SCALAR_VALUE
;
7483 __mark_reg_known(®s
[insn
->dst_reg
], imm
);
7487 map
= env
->used_maps
[aux
->map_index
];
7488 mark_reg_known_zero(env
, regs
, insn
->dst_reg
);
7489 regs
[insn
->dst_reg
].map_ptr
= map
;
7491 if (insn
->src_reg
== BPF_PSEUDO_MAP_VALUE
) {
7492 regs
[insn
->dst_reg
].type
= PTR_TO_MAP_VALUE
;
7493 regs
[insn
->dst_reg
].off
= aux
->map_off
;
7494 if (map_value_has_spin_lock(map
))
7495 regs
[insn
->dst_reg
].id
= ++env
->id_gen
;
7496 } else if (insn
->src_reg
== BPF_PSEUDO_MAP_FD
) {
7497 regs
[insn
->dst_reg
].type
= CONST_PTR_TO_MAP
;
7499 verbose(env
, "bpf verifier is misconfigured\n");
7506 static bool may_access_skb(enum bpf_prog_type type
)
7509 case BPF_PROG_TYPE_SOCKET_FILTER
:
7510 case BPF_PROG_TYPE_SCHED_CLS
:
7511 case BPF_PROG_TYPE_SCHED_ACT
:
7518 /* verify safety of LD_ABS|LD_IND instructions:
7519 * - they can only appear in the programs where ctx == skb
7520 * - since they are wrappers of function calls, they scratch R1-R5 registers,
7521 * preserve R6-R9, and store return value into R0
7524 * ctx == skb == R6 == CTX
7527 * SRC == any register
7528 * IMM == 32-bit immediate
7531 * R0 - 8/16/32-bit skb data converted to cpu endianness
7533 static int check_ld_abs(struct bpf_verifier_env
*env
, struct bpf_insn
*insn
)
7535 struct bpf_reg_state
*regs
= cur_regs(env
);
7536 static const int ctx_reg
= BPF_REG_6
;
7537 u8 mode
= BPF_MODE(insn
->code
);
7540 if (!may_access_skb(resolve_prog_type(env
->prog
))) {
7541 verbose(env
, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
7545 if (!env
->ops
->gen_ld_abs
) {
7546 verbose(env
, "bpf verifier is misconfigured\n");
7550 if (insn
->dst_reg
!= BPF_REG_0
|| insn
->off
!= 0 ||
7551 BPF_SIZE(insn
->code
) == BPF_DW
||
7552 (mode
== BPF_ABS
&& insn
->src_reg
!= BPF_REG_0
)) {
7553 verbose(env
, "BPF_LD_[ABS|IND] uses reserved fields\n");
7557 /* check whether implicit source operand (register R6) is readable */
7558 err
= check_reg_arg(env
, ctx_reg
, SRC_OP
);
7562 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
7563 * gen_ld_abs() may terminate the program at runtime, leading to
7566 err
= check_reference_leak(env
);
7568 verbose(env
, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
7572 if (env
->cur_state
->active_spin_lock
) {
7573 verbose(env
, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
7577 if (regs
[ctx_reg
].type
!= PTR_TO_CTX
) {
7579 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
7583 if (mode
== BPF_IND
) {
7584 /* check explicit source operand */
7585 err
= check_reg_arg(env
, insn
->src_reg
, SRC_OP
);
7590 err
= check_ctx_reg(env
, ®s
[ctx_reg
], ctx_reg
);
7594 /* reset caller saved regs to unreadable */
7595 for (i
= 0; i
< CALLER_SAVED_REGS
; i
++) {
7596 mark_reg_not_init(env
, regs
, caller_saved
[i
]);
7597 check_reg_arg(env
, caller_saved
[i
], DST_OP_NO_MARK
);
7600 /* mark destination R0 register as readable, since it contains
7601 * the value fetched from the packet.
7602 * Already marked as written above.
7604 mark_reg_unknown(env
, regs
, BPF_REG_0
);
7605 /* ld_abs load up to 32-bit skb data. */
7606 regs
[BPF_REG_0
].subreg_def
= env
->insn_idx
+ 1;
7610 static int check_return_code(struct bpf_verifier_env
*env
)
7612 struct tnum enforce_attach_type_range
= tnum_unknown
;
7613 const struct bpf_prog
*prog
= env
->prog
;
7614 struct bpf_reg_state
*reg
;
7615 struct tnum range
= tnum_range(0, 1);
7616 enum bpf_prog_type prog_type
= resolve_prog_type(env
->prog
);
7619 /* LSM and struct_ops func-ptr's return type could be "void" */
7620 if ((prog_type
== BPF_PROG_TYPE_STRUCT_OPS
||
7621 prog_type
== BPF_PROG_TYPE_LSM
) &&
7622 !prog
->aux
->attach_func_proto
->type
)
7625 /* eBPF calling convetion is such that R0 is used
7626 * to return the value from eBPF program.
7627 * Make sure that it's readable at this time
7628 * of bpf_exit, which means that program wrote
7629 * something into it earlier
7631 err
= check_reg_arg(env
, BPF_REG_0
, SRC_OP
);
7635 if (is_pointer_value(env
, BPF_REG_0
)) {
7636 verbose(env
, "R0 leaks addr as return value\n");
7640 switch (prog_type
) {
7641 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR
:
7642 if (env
->prog
->expected_attach_type
== BPF_CGROUP_UDP4_RECVMSG
||
7643 env
->prog
->expected_attach_type
== BPF_CGROUP_UDP6_RECVMSG
||
7644 env
->prog
->expected_attach_type
== BPF_CGROUP_INET4_GETPEERNAME
||
7645 env
->prog
->expected_attach_type
== BPF_CGROUP_INET6_GETPEERNAME
||
7646 env
->prog
->expected_attach_type
== BPF_CGROUP_INET4_GETSOCKNAME
||
7647 env
->prog
->expected_attach_type
== BPF_CGROUP_INET6_GETSOCKNAME
)
7648 range
= tnum_range(1, 1);
7650 case BPF_PROG_TYPE_CGROUP_SKB
:
7651 if (env
->prog
->expected_attach_type
== BPF_CGROUP_INET_EGRESS
) {
7652 range
= tnum_range(0, 3);
7653 enforce_attach_type_range
= tnum_range(2, 3);
7656 case BPF_PROG_TYPE_CGROUP_SOCK
:
7657 case BPF_PROG_TYPE_SOCK_OPS
:
7658 case BPF_PROG_TYPE_CGROUP_DEVICE
:
7659 case BPF_PROG_TYPE_CGROUP_SYSCTL
:
7660 case BPF_PROG_TYPE_CGROUP_SOCKOPT
:
7662 case BPF_PROG_TYPE_RAW_TRACEPOINT
:
7663 if (!env
->prog
->aux
->attach_btf_id
)
7665 range
= tnum_const(0);
7667 case BPF_PROG_TYPE_TRACING
:
7668 switch (env
->prog
->expected_attach_type
) {
7669 case BPF_TRACE_FENTRY
:
7670 case BPF_TRACE_FEXIT
:
7671 range
= tnum_const(0);
7673 case BPF_TRACE_RAW_TP
:
7674 case BPF_MODIFY_RETURN
:
7676 case BPF_TRACE_ITER
:
7682 case BPF_PROG_TYPE_SK_LOOKUP
:
7683 range
= tnum_range(SK_DROP
, SK_PASS
);
7685 case BPF_PROG_TYPE_EXT
:
7686 /* freplace program can return anything as its return value
7687 * depends on the to-be-replaced kernel func or bpf program.
7693 reg
= cur_regs(env
) + BPF_REG_0
;
7694 if (reg
->type
!= SCALAR_VALUE
) {
7695 verbose(env
, "At program exit the register R0 is not a known value (%s)\n",
7696 reg_type_str
[reg
->type
]);
7700 if (!tnum_in(range
, reg
->var_off
)) {
7703 verbose(env
, "At program exit the register R0 ");
7704 if (!tnum_is_unknown(reg
->var_off
)) {
7705 tnum_strn(tn_buf
, sizeof(tn_buf
), reg
->var_off
);
7706 verbose(env
, "has value %s", tn_buf
);
7708 verbose(env
, "has unknown scalar value");
7710 tnum_strn(tn_buf
, sizeof(tn_buf
), range
);
7711 verbose(env
, " should have been in %s\n", tn_buf
);
7715 if (!tnum_is_unknown(enforce_attach_type_range
) &&
7716 tnum_in(enforce_attach_type_range
, reg
->var_off
))
7717 env
->prog
->enforce_expected_attach_type
= 1;
7721 /* non-recursive DFS pseudo code
7722 * 1 procedure DFS-iterative(G,v):
7723 * 2 label v as discovered
7724 * 3 let S be a stack
7726 * 5 while S is not empty
7728 * 7 if t is what we're looking for:
7730 * 9 for all edges e in G.adjacentEdges(t) do
7731 * 10 if edge e is already labelled
7732 * 11 continue with the next edge
7733 * 12 w <- G.adjacentVertex(t,e)
7734 * 13 if vertex w is not discovered and not explored
7735 * 14 label e as tree-edge
7736 * 15 label w as discovered
7739 * 18 else if vertex w is discovered
7740 * 19 label e as back-edge
7742 * 21 // vertex w is explored
7743 * 22 label e as forward- or cross-edge
7744 * 23 label t as explored
7749 * 0x11 - discovered and fall-through edge labelled
7750 * 0x12 - discovered and fall-through and branch edges labelled
7761 static u32
state_htab_size(struct bpf_verifier_env
*env
)
7763 return env
->prog
->len
;
7766 static struct bpf_verifier_state_list
**explored_state(
7767 struct bpf_verifier_env
*env
,
7770 struct bpf_verifier_state
*cur
= env
->cur_state
;
7771 struct bpf_func_state
*state
= cur
->frame
[cur
->curframe
];
7773 return &env
->explored_states
[(idx
^ state
->callsite
) % state_htab_size(env
)];
7776 static void init_explored_state(struct bpf_verifier_env
*env
, int idx
)
7778 env
->insn_aux_data
[idx
].prune_point
= true;
7781 /* t, w, e - match pseudo-code above:
7782 * t - index of current instruction
7783 * w - next instruction
7786 static int push_insn(int t
, int w
, int e
, struct bpf_verifier_env
*env
,
7789 int *insn_stack
= env
->cfg
.insn_stack
;
7790 int *insn_state
= env
->cfg
.insn_state
;
7792 if (e
== FALLTHROUGH
&& insn_state
[t
] >= (DISCOVERED
| FALLTHROUGH
))
7795 if (e
== BRANCH
&& insn_state
[t
] >= (DISCOVERED
| BRANCH
))
7798 if (w
< 0 || w
>= env
->prog
->len
) {
7799 verbose_linfo(env
, t
, "%d: ", t
);
7800 verbose(env
, "jump out of range from insn %d to %d\n", t
, w
);
7805 /* mark branch target for state pruning */
7806 init_explored_state(env
, w
);
7808 if (insn_state
[w
] == 0) {
7810 insn_state
[t
] = DISCOVERED
| e
;
7811 insn_state
[w
] = DISCOVERED
;
7812 if (env
->cfg
.cur_stack
>= env
->prog
->len
)
7814 insn_stack
[env
->cfg
.cur_stack
++] = w
;
7816 } else if ((insn_state
[w
] & 0xF0) == DISCOVERED
) {
7817 if (loop_ok
&& env
->bpf_capable
)
7819 verbose_linfo(env
, t
, "%d: ", t
);
7820 verbose_linfo(env
, w
, "%d: ", w
);
7821 verbose(env
, "back-edge from insn %d to %d\n", t
, w
);
7823 } else if (insn_state
[w
] == EXPLORED
) {
7824 /* forward- or cross-edge */
7825 insn_state
[t
] = DISCOVERED
| e
;
7827 verbose(env
, "insn state internal bug\n");
7833 /* non-recursive depth-first-search to detect loops in BPF program
7834 * loop == back-edge in directed graph
7836 static int check_cfg(struct bpf_verifier_env
*env
)
7838 struct bpf_insn
*insns
= env
->prog
->insnsi
;
7839 int insn_cnt
= env
->prog
->len
;
7840 int *insn_stack
, *insn_state
;
7844 insn_state
= env
->cfg
.insn_state
= kvcalloc(insn_cnt
, sizeof(int), GFP_KERNEL
);
7848 insn_stack
= env
->cfg
.insn_stack
= kvcalloc(insn_cnt
, sizeof(int), GFP_KERNEL
);
7854 insn_state
[0] = DISCOVERED
; /* mark 1st insn as discovered */
7855 insn_stack
[0] = 0; /* 0 is the first instruction */
7856 env
->cfg
.cur_stack
= 1;
7859 if (env
->cfg
.cur_stack
== 0)
7861 t
= insn_stack
[env
->cfg
.cur_stack
- 1];
7863 if (BPF_CLASS(insns
[t
].code
) == BPF_JMP
||
7864 BPF_CLASS(insns
[t
].code
) == BPF_JMP32
) {
7865 u8 opcode
= BPF_OP(insns
[t
].code
);
7867 if (opcode
== BPF_EXIT
) {
7869 } else if (opcode
== BPF_CALL
) {
7870 ret
= push_insn(t
, t
+ 1, FALLTHROUGH
, env
, false);
7875 if (t
+ 1 < insn_cnt
)
7876 init_explored_state(env
, t
+ 1);
7877 if (insns
[t
].src_reg
== BPF_PSEUDO_CALL
) {
7878 init_explored_state(env
, t
);
7879 ret
= push_insn(t
, t
+ insns
[t
].imm
+ 1, BRANCH
,
7886 } else if (opcode
== BPF_JA
) {
7887 if (BPF_SRC(insns
[t
].code
) != BPF_K
) {
7891 /* unconditional jump with single edge */
7892 ret
= push_insn(t
, t
+ insns
[t
].off
+ 1,
7893 FALLTHROUGH
, env
, true);
7898 /* unconditional jmp is not a good pruning point,
7899 * but it's marked, since backtracking needs
7900 * to record jmp history in is_state_visited().
7902 init_explored_state(env
, t
+ insns
[t
].off
+ 1);
7903 /* tell verifier to check for equivalent states
7904 * after every call and jump
7906 if (t
+ 1 < insn_cnt
)
7907 init_explored_state(env
, t
+ 1);
7909 /* conditional jump with two edges */
7910 init_explored_state(env
, t
);
7911 ret
= push_insn(t
, t
+ 1, FALLTHROUGH
, env
, true);
7917 ret
= push_insn(t
, t
+ insns
[t
].off
+ 1, BRANCH
, env
, true);
7924 /* all other non-branch instructions with single
7927 ret
= push_insn(t
, t
+ 1, FALLTHROUGH
, env
, false);
7935 insn_state
[t
] = EXPLORED
;
7936 if (env
->cfg
.cur_stack
-- <= 0) {
7937 verbose(env
, "pop stack internal bug\n");
7944 for (i
= 0; i
< insn_cnt
; i
++) {
7945 if (insn_state
[i
] != EXPLORED
) {
7946 verbose(env
, "unreachable insn %d\n", i
);
7951 ret
= 0; /* cfg looks good */
7956 env
->cfg
.insn_state
= env
->cfg
.insn_stack
= NULL
;
7960 static int check_abnormal_return(struct bpf_verifier_env
*env
)
7964 for (i
= 1; i
< env
->subprog_cnt
; i
++) {
7965 if (env
->subprog_info
[i
].has_ld_abs
) {
7966 verbose(env
, "LD_ABS is not allowed in subprogs without BTF\n");
7969 if (env
->subprog_info
[i
].has_tail_call
) {
7970 verbose(env
, "tail_call is not allowed in subprogs without BTF\n");
7977 /* The minimum supported BTF func info size */
7978 #define MIN_BPF_FUNCINFO_SIZE 8
7979 #define MAX_FUNCINFO_REC_SIZE 252
7981 static int check_btf_func(struct bpf_verifier_env
*env
,
7982 const union bpf_attr
*attr
,
7983 union bpf_attr __user
*uattr
)
7985 const struct btf_type
*type
, *func_proto
, *ret_type
;
7986 u32 i
, nfuncs
, urec_size
, min_size
;
7987 u32 krec_size
= sizeof(struct bpf_func_info
);
7988 struct bpf_func_info
*krecord
;
7989 struct bpf_func_info_aux
*info_aux
= NULL
;
7990 struct bpf_prog
*prog
;
7991 const struct btf
*btf
;
7992 void __user
*urecord
;
7993 u32 prev_offset
= 0;
7997 nfuncs
= attr
->func_info_cnt
;
7999 if (check_abnormal_return(env
))
8004 if (nfuncs
!= env
->subprog_cnt
) {
8005 verbose(env
, "number of funcs in func_info doesn't match number of subprogs\n");
8009 urec_size
= attr
->func_info_rec_size
;
8010 if (urec_size
< MIN_BPF_FUNCINFO_SIZE
||
8011 urec_size
> MAX_FUNCINFO_REC_SIZE
||
8012 urec_size
% sizeof(u32
)) {
8013 verbose(env
, "invalid func info rec size %u\n", urec_size
);
8018 btf
= prog
->aux
->btf
;
8020 urecord
= u64_to_user_ptr(attr
->func_info
);
8021 min_size
= min_t(u32
, krec_size
, urec_size
);
8023 krecord
= kvcalloc(nfuncs
, krec_size
, GFP_KERNEL
| __GFP_NOWARN
);
8026 info_aux
= kcalloc(nfuncs
, sizeof(*info_aux
), GFP_KERNEL
| __GFP_NOWARN
);
8030 for (i
= 0; i
< nfuncs
; i
++) {
8031 ret
= bpf_check_uarg_tail_zero(urecord
, krec_size
, urec_size
);
8033 if (ret
== -E2BIG
) {
8034 verbose(env
, "nonzero tailing record in func info");
8035 /* set the size kernel expects so loader can zero
8036 * out the rest of the record.
8038 if (put_user(min_size
, &uattr
->func_info_rec_size
))
8044 if (copy_from_user(&krecord
[i
], urecord
, min_size
)) {
8049 /* check insn_off */
8052 if (krecord
[i
].insn_off
) {
8054 "nonzero insn_off %u for the first func info record",
8055 krecord
[i
].insn_off
);
8058 } else if (krecord
[i
].insn_off
<= prev_offset
) {
8060 "same or smaller insn offset (%u) than previous func info record (%u)",
8061 krecord
[i
].insn_off
, prev_offset
);
8065 if (env
->subprog_info
[i
].start
!= krecord
[i
].insn_off
) {
8066 verbose(env
, "func_info BTF section doesn't match subprog layout in BPF program\n");
8071 type
= btf_type_by_id(btf
, krecord
[i
].type_id
);
8072 if (!type
|| !btf_type_is_func(type
)) {
8073 verbose(env
, "invalid type id %d in func info",
8074 krecord
[i
].type_id
);
8077 info_aux
[i
].linkage
= BTF_INFO_VLEN(type
->info
);
8079 func_proto
= btf_type_by_id(btf
, type
->type
);
8080 if (unlikely(!func_proto
|| !btf_type_is_func_proto(func_proto
)))
8081 /* btf_func_check() already verified it during BTF load */
8083 ret_type
= btf_type_skip_modifiers(btf
, func_proto
->type
, NULL
);
8085 btf_type_is_small_int(ret_type
) || btf_type_is_enum(ret_type
);
8086 if (i
&& !scalar_return
&& env
->subprog_info
[i
].has_ld_abs
) {
8087 verbose(env
, "LD_ABS is only allowed in functions that return 'int'.\n");
8090 if (i
&& !scalar_return
&& env
->subprog_info
[i
].has_tail_call
) {
8091 verbose(env
, "tail_call is only allowed in functions that return 'int'.\n");
8095 prev_offset
= krecord
[i
].insn_off
;
8096 urecord
+= urec_size
;
8099 prog
->aux
->func_info
= krecord
;
8100 prog
->aux
->func_info_cnt
= nfuncs
;
8101 prog
->aux
->func_info_aux
= info_aux
;
8110 static void adjust_btf_func(struct bpf_verifier_env
*env
)
8112 struct bpf_prog_aux
*aux
= env
->prog
->aux
;
8115 if (!aux
->func_info
)
8118 for (i
= 0; i
< env
->subprog_cnt
; i
++)
8119 aux
->func_info
[i
].insn_off
= env
->subprog_info
[i
].start
;
8122 #define MIN_BPF_LINEINFO_SIZE (offsetof(struct bpf_line_info, line_col) + \
8123 sizeof(((struct bpf_line_info *)(0))->line_col))
8124 #define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE
8126 static int check_btf_line(struct bpf_verifier_env
*env
,
8127 const union bpf_attr
*attr
,
8128 union bpf_attr __user
*uattr
)
8130 u32 i
, s
, nr_linfo
, ncopy
, expected_size
, rec_size
, prev_offset
= 0;
8131 struct bpf_subprog_info
*sub
;
8132 struct bpf_line_info
*linfo
;
8133 struct bpf_prog
*prog
;
8134 const struct btf
*btf
;
8135 void __user
*ulinfo
;
8138 nr_linfo
= attr
->line_info_cnt
;
8142 rec_size
= attr
->line_info_rec_size
;
8143 if (rec_size
< MIN_BPF_LINEINFO_SIZE
||
8144 rec_size
> MAX_LINEINFO_REC_SIZE
||
8145 rec_size
& (sizeof(u32
) - 1))
8148 /* Need to zero it in case the userspace may
8149 * pass in a smaller bpf_line_info object.
8151 linfo
= kvcalloc(nr_linfo
, sizeof(struct bpf_line_info
),
8152 GFP_KERNEL
| __GFP_NOWARN
);
8157 btf
= prog
->aux
->btf
;
8160 sub
= env
->subprog_info
;
8161 ulinfo
= u64_to_user_ptr(attr
->line_info
);
8162 expected_size
= sizeof(struct bpf_line_info
);
8163 ncopy
= min_t(u32
, expected_size
, rec_size
);
8164 for (i
= 0; i
< nr_linfo
; i
++) {
8165 err
= bpf_check_uarg_tail_zero(ulinfo
, expected_size
, rec_size
);
8167 if (err
== -E2BIG
) {
8168 verbose(env
, "nonzero tailing record in line_info");
8169 if (put_user(expected_size
,
8170 &uattr
->line_info_rec_size
))
8176 if (copy_from_user(&linfo
[i
], ulinfo
, ncopy
)) {
8182 * Check insn_off to ensure
8183 * 1) strictly increasing AND
8184 * 2) bounded by prog->len
8186 * The linfo[0].insn_off == 0 check logically falls into
8187 * the later "missing bpf_line_info for func..." case
8188 * because the first linfo[0].insn_off must be the
8189 * first sub also and the first sub must have
8190 * subprog_info[0].start == 0.
8192 if ((i
&& linfo
[i
].insn_off
<= prev_offset
) ||
8193 linfo
[i
].insn_off
>= prog
->len
) {
8194 verbose(env
, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
8195 i
, linfo
[i
].insn_off
, prev_offset
,
8201 if (!prog
->insnsi
[linfo
[i
].insn_off
].code
) {
8203 "Invalid insn code at line_info[%u].insn_off\n",
8209 if (!btf_name_by_offset(btf
, linfo
[i
].line_off
) ||
8210 !btf_name_by_offset(btf
, linfo
[i
].file_name_off
)) {
8211 verbose(env
, "Invalid line_info[%u].line_off or .file_name_off\n", i
);
8216 if (s
!= env
->subprog_cnt
) {
8217 if (linfo
[i
].insn_off
== sub
[s
].start
) {
8218 sub
[s
].linfo_idx
= i
;
8220 } else if (sub
[s
].start
< linfo
[i
].insn_off
) {
8221 verbose(env
, "missing bpf_line_info for func#%u\n", s
);
8227 prev_offset
= linfo
[i
].insn_off
;
8231 if (s
!= env
->subprog_cnt
) {
8232 verbose(env
, "missing bpf_line_info for %u funcs starting from func#%u\n",
8233 env
->subprog_cnt
- s
, s
);
8238 prog
->aux
->linfo
= linfo
;
8239 prog
->aux
->nr_linfo
= nr_linfo
;
8248 static int check_btf_info(struct bpf_verifier_env
*env
,
8249 const union bpf_attr
*attr
,
8250 union bpf_attr __user
*uattr
)
8255 if (!attr
->func_info_cnt
&& !attr
->line_info_cnt
) {
8256 if (check_abnormal_return(env
))
8261 btf
= btf_get_by_fd(attr
->prog_btf_fd
);
8263 return PTR_ERR(btf
);
8264 env
->prog
->aux
->btf
= btf
;
8266 err
= check_btf_func(env
, attr
, uattr
);
8270 err
= check_btf_line(env
, attr
, uattr
);
8277 /* check %cur's range satisfies %old's */
8278 static bool range_within(struct bpf_reg_state
*old
,
8279 struct bpf_reg_state
*cur
)
8281 return old
->umin_value
<= cur
->umin_value
&&
8282 old
->umax_value
>= cur
->umax_value
&&
8283 old
->smin_value
<= cur
->smin_value
&&
8284 old
->smax_value
>= cur
->smax_value
;
8287 /* Maximum number of register states that can exist at once */
8288 #define ID_MAP_SIZE (MAX_BPF_REG + MAX_BPF_STACK / BPF_REG_SIZE)
8294 /* If in the old state two registers had the same id, then they need to have
8295 * the same id in the new state as well. But that id could be different from
8296 * the old state, so we need to track the mapping from old to new ids.
8297 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
8298 * regs with old id 5 must also have new id 9 for the new state to be safe. But
8299 * regs with a different old id could still have new id 9, we don't care about
8301 * So we look through our idmap to see if this old id has been seen before. If
8302 * so, we require the new id to match; otherwise, we add the id pair to the map.
8304 static bool check_ids(u32 old_id
, u32 cur_id
, struct idpair
*idmap
)
8308 for (i
= 0; i
< ID_MAP_SIZE
; i
++) {
8309 if (!idmap
[i
].old
) {
8310 /* Reached an empty slot; haven't seen this id before */
8311 idmap
[i
].old
= old_id
;
8312 idmap
[i
].cur
= cur_id
;
8315 if (idmap
[i
].old
== old_id
)
8316 return idmap
[i
].cur
== cur_id
;
8318 /* We ran out of idmap slots, which should be impossible */
8323 static void clean_func_state(struct bpf_verifier_env
*env
,
8324 struct bpf_func_state
*st
)
8326 enum bpf_reg_liveness live
;
8329 for (i
= 0; i
< BPF_REG_FP
; i
++) {
8330 live
= st
->regs
[i
].live
;
8331 /* liveness must not touch this register anymore */
8332 st
->regs
[i
].live
|= REG_LIVE_DONE
;
8333 if (!(live
& REG_LIVE_READ
))
8334 /* since the register is unused, clear its state
8335 * to make further comparison simpler
8337 __mark_reg_not_init(env
, &st
->regs
[i
]);
8340 for (i
= 0; i
< st
->allocated_stack
/ BPF_REG_SIZE
; i
++) {
8341 live
= st
->stack
[i
].spilled_ptr
.live
;
8342 /* liveness must not touch this stack slot anymore */
8343 st
->stack
[i
].spilled_ptr
.live
|= REG_LIVE_DONE
;
8344 if (!(live
& REG_LIVE_READ
)) {
8345 __mark_reg_not_init(env
, &st
->stack
[i
].spilled_ptr
);
8346 for (j
= 0; j
< BPF_REG_SIZE
; j
++)
8347 st
->stack
[i
].slot_type
[j
] = STACK_INVALID
;
8352 static void clean_verifier_state(struct bpf_verifier_env
*env
,
8353 struct bpf_verifier_state
*st
)
8357 if (st
->frame
[0]->regs
[0].live
& REG_LIVE_DONE
)
8358 /* all regs in this state in all frames were already marked */
8361 for (i
= 0; i
<= st
->curframe
; i
++)
8362 clean_func_state(env
, st
->frame
[i
]);
8365 /* the parentage chains form a tree.
8366 * the verifier states are added to state lists at given insn and
8367 * pushed into state stack for future exploration.
8368 * when the verifier reaches bpf_exit insn some of the verifer states
8369 * stored in the state lists have their final liveness state already,
8370 * but a lot of states will get revised from liveness point of view when
8371 * the verifier explores other branches.
8374 * 2: if r1 == 100 goto pc+1
8377 * when the verifier reaches exit insn the register r0 in the state list of
8378 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
8379 * of insn 2 and goes exploring further. At the insn 4 it will walk the
8380 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
8382 * Since the verifier pushes the branch states as it sees them while exploring
8383 * the program the condition of walking the branch instruction for the second
8384 * time means that all states below this branch were already explored and
8385 * their final liveness markes are already propagated.
8386 * Hence when the verifier completes the search of state list in is_state_visited()
8387 * we can call this clean_live_states() function to mark all liveness states
8388 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
8390 * This function also clears the registers and stack for states that !READ
8391 * to simplify state merging.
8393 * Important note here that walking the same branch instruction in the callee
8394 * doesn't meant that the states are DONE. The verifier has to compare
8397 static void clean_live_states(struct bpf_verifier_env
*env
, int insn
,
8398 struct bpf_verifier_state
*cur
)
8400 struct bpf_verifier_state_list
*sl
;
8403 sl
= *explored_state(env
, insn
);
8405 if (sl
->state
.branches
)
8407 if (sl
->state
.insn_idx
!= insn
||
8408 sl
->state
.curframe
!= cur
->curframe
)
8410 for (i
= 0; i
<= cur
->curframe
; i
++)
8411 if (sl
->state
.frame
[i
]->callsite
!= cur
->frame
[i
]->callsite
)
8413 clean_verifier_state(env
, &sl
->state
);
8419 /* Returns true if (rold safe implies rcur safe) */
8420 static bool regsafe(struct bpf_reg_state
*rold
, struct bpf_reg_state
*rcur
,
8421 struct idpair
*idmap
)
8425 if (!(rold
->live
& REG_LIVE_READ
))
8426 /* explored state didn't use this */
8429 equal
= memcmp(rold
, rcur
, offsetof(struct bpf_reg_state
, parent
)) == 0;
8431 if (rold
->type
== PTR_TO_STACK
)
8432 /* two stack pointers are equal only if they're pointing to
8433 * the same stack frame, since fp-8 in foo != fp-8 in bar
8435 return equal
&& rold
->frameno
== rcur
->frameno
;
8440 if (rold
->type
== NOT_INIT
)
8441 /* explored state can't have used this */
8443 if (rcur
->type
== NOT_INIT
)
8445 switch (rold
->type
) {
8447 if (rcur
->type
== SCALAR_VALUE
) {
8448 if (!rold
->precise
&& !rcur
->precise
)
8450 /* new val must satisfy old val knowledge */
8451 return range_within(rold
, rcur
) &&
8452 tnum_in(rold
->var_off
, rcur
->var_off
);
8454 /* We're trying to use a pointer in place of a scalar.
8455 * Even if the scalar was unbounded, this could lead to
8456 * pointer leaks because scalars are allowed to leak
8457 * while pointers are not. We could make this safe in
8458 * special cases if root is calling us, but it's
8459 * probably not worth the hassle.
8463 case PTR_TO_MAP_VALUE
:
8464 /* If the new min/max/var_off satisfy the old ones and
8465 * everything else matches, we are OK.
8466 * 'id' is not compared, since it's only used for maps with
8467 * bpf_spin_lock inside map element and in such cases if
8468 * the rest of the prog is valid for one map element then
8469 * it's valid for all map elements regardless of the key
8470 * used in bpf_map_lookup()
8472 return memcmp(rold
, rcur
, offsetof(struct bpf_reg_state
, id
)) == 0 &&
8473 range_within(rold
, rcur
) &&
8474 tnum_in(rold
->var_off
, rcur
->var_off
);
8475 case PTR_TO_MAP_VALUE_OR_NULL
:
8476 /* a PTR_TO_MAP_VALUE could be safe to use as a
8477 * PTR_TO_MAP_VALUE_OR_NULL into the same map.
8478 * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
8479 * checked, doing so could have affected others with the same
8480 * id, and we can't check for that because we lost the id when
8481 * we converted to a PTR_TO_MAP_VALUE.
8483 if (rcur
->type
!= PTR_TO_MAP_VALUE_OR_NULL
)
8485 if (memcmp(rold
, rcur
, offsetof(struct bpf_reg_state
, id
)))
8487 /* Check our ids match any regs they're supposed to */
8488 return check_ids(rold
->id
, rcur
->id
, idmap
);
8489 case PTR_TO_PACKET_META
:
8491 if (rcur
->type
!= rold
->type
)
8493 /* We must have at least as much range as the old ptr
8494 * did, so that any accesses which were safe before are
8495 * still safe. This is true even if old range < old off,
8496 * since someone could have accessed through (ptr - k), or
8497 * even done ptr -= k in a register, to get a safe access.
8499 if (rold
->range
> rcur
->range
)
8501 /* If the offsets don't match, we can't trust our alignment;
8502 * nor can we be sure that we won't fall out of range.
8504 if (rold
->off
!= rcur
->off
)
8506 /* id relations must be preserved */
8507 if (rold
->id
&& !check_ids(rold
->id
, rcur
->id
, idmap
))
8509 /* new val must satisfy old val knowledge */
8510 return range_within(rold
, rcur
) &&
8511 tnum_in(rold
->var_off
, rcur
->var_off
);
8513 case CONST_PTR_TO_MAP
:
8514 case PTR_TO_PACKET_END
:
8515 case PTR_TO_FLOW_KEYS
:
8517 case PTR_TO_SOCKET_OR_NULL
:
8518 case PTR_TO_SOCK_COMMON
:
8519 case PTR_TO_SOCK_COMMON_OR_NULL
:
8520 case PTR_TO_TCP_SOCK
:
8521 case PTR_TO_TCP_SOCK_OR_NULL
:
8522 case PTR_TO_XDP_SOCK
:
8523 /* Only valid matches are exact, which memcmp() above
8524 * would have accepted
8527 /* Don't know what's going on, just say it's not safe */
8531 /* Shouldn't get here; if we do, say it's not safe */
8536 static bool stacksafe(struct bpf_func_state
*old
,
8537 struct bpf_func_state
*cur
,
8538 struct idpair
*idmap
)
8542 /* walk slots of the explored stack and ignore any additional
8543 * slots in the current stack, since explored(safe) state
8546 for (i
= 0; i
< old
->allocated_stack
; i
++) {
8547 spi
= i
/ BPF_REG_SIZE
;
8549 if (!(old
->stack
[spi
].spilled_ptr
.live
& REG_LIVE_READ
)) {
8550 i
+= BPF_REG_SIZE
- 1;
8551 /* explored state didn't use this */
8555 if (old
->stack
[spi
].slot_type
[i
% BPF_REG_SIZE
] == STACK_INVALID
)
8558 /* explored stack has more populated slots than current stack
8559 * and these slots were used
8561 if (i
>= cur
->allocated_stack
)
8564 /* if old state was safe with misc data in the stack
8565 * it will be safe with zero-initialized stack.
8566 * The opposite is not true
8568 if (old
->stack
[spi
].slot_type
[i
% BPF_REG_SIZE
] == STACK_MISC
&&
8569 cur
->stack
[spi
].slot_type
[i
% BPF_REG_SIZE
] == STACK_ZERO
)
8571 if (old
->stack
[spi
].slot_type
[i
% BPF_REG_SIZE
] !=
8572 cur
->stack
[spi
].slot_type
[i
% BPF_REG_SIZE
])
8573 /* Ex: old explored (safe) state has STACK_SPILL in
8574 * this stack slot, but current has STACK_MISC ->
8575 * this verifier states are not equivalent,
8576 * return false to continue verification of this path
8579 if (i
% BPF_REG_SIZE
)
8581 if (old
->stack
[spi
].slot_type
[0] != STACK_SPILL
)
8583 if (!regsafe(&old
->stack
[spi
].spilled_ptr
,
8584 &cur
->stack
[spi
].spilled_ptr
,
8586 /* when explored and current stack slot are both storing
8587 * spilled registers, check that stored pointers types
8588 * are the same as well.
8589 * Ex: explored safe path could have stored
8590 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
8591 * but current path has stored:
8592 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
8593 * such verifier states are not equivalent.
8594 * return false to continue verification of this path
8601 static bool refsafe(struct bpf_func_state
*old
, struct bpf_func_state
*cur
)
8603 if (old
->acquired_refs
!= cur
->acquired_refs
)
8605 return !memcmp(old
->refs
, cur
->refs
,
8606 sizeof(*old
->refs
) * old
->acquired_refs
);
8609 /* compare two verifier states
8611 * all states stored in state_list are known to be valid, since
8612 * verifier reached 'bpf_exit' instruction through them
8614 * this function is called when verifier exploring different branches of
8615 * execution popped from the state stack. If it sees an old state that has
8616 * more strict register state and more strict stack state then this execution
8617 * branch doesn't need to be explored further, since verifier already
8618 * concluded that more strict state leads to valid finish.
8620 * Therefore two states are equivalent if register state is more conservative
8621 * and explored stack state is more conservative than the current one.
8624 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
8625 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
8627 * In other words if current stack state (one being explored) has more
8628 * valid slots than old one that already passed validation, it means
8629 * the verifier can stop exploring and conclude that current state is valid too
8631 * Similarly with registers. If explored state has register type as invalid
8632 * whereas register type in current state is meaningful, it means that
8633 * the current state will reach 'bpf_exit' instruction safely
8635 static bool func_states_equal(struct bpf_func_state
*old
,
8636 struct bpf_func_state
*cur
)
8638 struct idpair
*idmap
;
8642 idmap
= kcalloc(ID_MAP_SIZE
, sizeof(struct idpair
), GFP_KERNEL
);
8643 /* If we failed to allocate the idmap, just say it's not safe */
8647 for (i
= 0; i
< MAX_BPF_REG
; i
++) {
8648 if (!regsafe(&old
->regs
[i
], &cur
->regs
[i
], idmap
))
8652 if (!stacksafe(old
, cur
, idmap
))
8655 if (!refsafe(old
, cur
))
8663 static bool states_equal(struct bpf_verifier_env
*env
,
8664 struct bpf_verifier_state
*old
,
8665 struct bpf_verifier_state
*cur
)
8669 if (old
->curframe
!= cur
->curframe
)
8672 /* Verification state from speculative execution simulation
8673 * must never prune a non-speculative execution one.
8675 if (old
->speculative
&& !cur
->speculative
)
8678 if (old
->active_spin_lock
!= cur
->active_spin_lock
)
8681 /* for states to be equal callsites have to be the same
8682 * and all frame states need to be equivalent
8684 for (i
= 0; i
<= old
->curframe
; i
++) {
8685 if (old
->frame
[i
]->callsite
!= cur
->frame
[i
]->callsite
)
8687 if (!func_states_equal(old
->frame
[i
], cur
->frame
[i
]))
8693 /* Return 0 if no propagation happened. Return negative error code if error
8694 * happened. Otherwise, return the propagated bit.
8696 static int propagate_liveness_reg(struct bpf_verifier_env
*env
,
8697 struct bpf_reg_state
*reg
,
8698 struct bpf_reg_state
*parent_reg
)
8700 u8 parent_flag
= parent_reg
->live
& REG_LIVE_READ
;
8701 u8 flag
= reg
->live
& REG_LIVE_READ
;
8704 /* When comes here, read flags of PARENT_REG or REG could be any of
8705 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
8706 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
8708 if (parent_flag
== REG_LIVE_READ64
||
8709 /* Or if there is no read flag from REG. */
8711 /* Or if the read flag from REG is the same as PARENT_REG. */
8712 parent_flag
== flag
)
8715 err
= mark_reg_read(env
, reg
, parent_reg
, flag
);
8722 /* A write screens off any subsequent reads; but write marks come from the
8723 * straight-line code between a state and its parent. When we arrive at an
8724 * equivalent state (jump target or such) we didn't arrive by the straight-line
8725 * code, so read marks in the state must propagate to the parent regardless
8726 * of the state's write marks. That's what 'parent == state->parent' comparison
8727 * in mark_reg_read() is for.
8729 static int propagate_liveness(struct bpf_verifier_env
*env
,
8730 const struct bpf_verifier_state
*vstate
,
8731 struct bpf_verifier_state
*vparent
)
8733 struct bpf_reg_state
*state_reg
, *parent_reg
;
8734 struct bpf_func_state
*state
, *parent
;
8735 int i
, frame
, err
= 0;
8737 if (vparent
->curframe
!= vstate
->curframe
) {
8738 WARN(1, "propagate_live: parent frame %d current frame %d\n",
8739 vparent
->curframe
, vstate
->curframe
);
8742 /* Propagate read liveness of registers... */
8743 BUILD_BUG_ON(BPF_REG_FP
+ 1 != MAX_BPF_REG
);
8744 for (frame
= 0; frame
<= vstate
->curframe
; frame
++) {
8745 parent
= vparent
->frame
[frame
];
8746 state
= vstate
->frame
[frame
];
8747 parent_reg
= parent
->regs
;
8748 state_reg
= state
->regs
;
8749 /* We don't need to worry about FP liveness, it's read-only */
8750 for (i
= frame
< vstate
->curframe
? BPF_REG_6
: 0; i
< BPF_REG_FP
; i
++) {
8751 err
= propagate_liveness_reg(env
, &state_reg
[i
],
8755 if (err
== REG_LIVE_READ64
)
8756 mark_insn_zext(env
, &parent_reg
[i
]);
8759 /* Propagate stack slots. */
8760 for (i
= 0; i
< state
->allocated_stack
/ BPF_REG_SIZE
&&
8761 i
< parent
->allocated_stack
/ BPF_REG_SIZE
; i
++) {
8762 parent_reg
= &parent
->stack
[i
].spilled_ptr
;
8763 state_reg
= &state
->stack
[i
].spilled_ptr
;
8764 err
= propagate_liveness_reg(env
, state_reg
,
8773 /* find precise scalars in the previous equivalent state and
8774 * propagate them into the current state
8776 static int propagate_precision(struct bpf_verifier_env
*env
,
8777 const struct bpf_verifier_state
*old
)
8779 struct bpf_reg_state
*state_reg
;
8780 struct bpf_func_state
*state
;
8783 state
= old
->frame
[old
->curframe
];
8784 state_reg
= state
->regs
;
8785 for (i
= 0; i
< BPF_REG_FP
; i
++, state_reg
++) {
8786 if (state_reg
->type
!= SCALAR_VALUE
||
8787 !state_reg
->precise
)
8789 if (env
->log
.level
& BPF_LOG_LEVEL2
)
8790 verbose(env
, "propagating r%d\n", i
);
8791 err
= mark_chain_precision(env
, i
);
8796 for (i
= 0; i
< state
->allocated_stack
/ BPF_REG_SIZE
; i
++) {
8797 if (state
->stack
[i
].slot_type
[0] != STACK_SPILL
)
8799 state_reg
= &state
->stack
[i
].spilled_ptr
;
8800 if (state_reg
->type
!= SCALAR_VALUE
||
8801 !state_reg
->precise
)
8803 if (env
->log
.level
& BPF_LOG_LEVEL2
)
8804 verbose(env
, "propagating fp%d\n",
8805 (-i
- 1) * BPF_REG_SIZE
);
8806 err
= mark_chain_precision_stack(env
, i
);
8813 static bool states_maybe_looping(struct bpf_verifier_state
*old
,
8814 struct bpf_verifier_state
*cur
)
8816 struct bpf_func_state
*fold
, *fcur
;
8817 int i
, fr
= cur
->curframe
;
8819 if (old
->curframe
!= fr
)
8822 fold
= old
->frame
[fr
];
8823 fcur
= cur
->frame
[fr
];
8824 for (i
= 0; i
< MAX_BPF_REG
; i
++)
8825 if (memcmp(&fold
->regs
[i
], &fcur
->regs
[i
],
8826 offsetof(struct bpf_reg_state
, parent
)))
8832 static int is_state_visited(struct bpf_verifier_env
*env
, int insn_idx
)
8834 struct bpf_verifier_state_list
*new_sl
;
8835 struct bpf_verifier_state_list
*sl
, **pprev
;
8836 struct bpf_verifier_state
*cur
= env
->cur_state
, *new;
8837 int i
, j
, err
, states_cnt
= 0;
8838 bool add_new_state
= env
->test_state_freq
? true : false;
8840 cur
->last_insn_idx
= env
->prev_insn_idx
;
8841 if (!env
->insn_aux_data
[insn_idx
].prune_point
)
8842 /* this 'insn_idx' instruction wasn't marked, so we will not
8843 * be doing state search here
8847 /* bpf progs typically have pruning point every 4 instructions
8848 * http://vger.kernel.org/bpfconf2019.html#session-1
8849 * Do not add new state for future pruning if the verifier hasn't seen
8850 * at least 2 jumps and at least 8 instructions.
8851 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
8852 * In tests that amounts to up to 50% reduction into total verifier
8853 * memory consumption and 20% verifier time speedup.
8855 if (env
->jmps_processed
- env
->prev_jmps_processed
>= 2 &&
8856 env
->insn_processed
- env
->prev_insn_processed
>= 8)
8857 add_new_state
= true;
8859 pprev
= explored_state(env
, insn_idx
);
8862 clean_live_states(env
, insn_idx
, cur
);
8866 if (sl
->state
.insn_idx
!= insn_idx
)
8868 if (sl
->state
.branches
) {
8869 if (states_maybe_looping(&sl
->state
, cur
) &&
8870 states_equal(env
, &sl
->state
, cur
)) {
8871 verbose_linfo(env
, insn_idx
, "; ");
8872 verbose(env
, "infinite loop detected at insn %d\n", insn_idx
);
8875 /* if the verifier is processing a loop, avoid adding new state
8876 * too often, since different loop iterations have distinct
8877 * states and may not help future pruning.
8878 * This threshold shouldn't be too low to make sure that
8879 * a loop with large bound will be rejected quickly.
8880 * The most abusive loop will be:
8882 * if r1 < 1000000 goto pc-2
8883 * 1M insn_procssed limit / 100 == 10k peak states.
8884 * This threshold shouldn't be too high either, since states
8885 * at the end of the loop are likely to be useful in pruning.
8887 if (env
->jmps_processed
- env
->prev_jmps_processed
< 20 &&
8888 env
->insn_processed
- env
->prev_insn_processed
< 100)
8889 add_new_state
= false;
8892 if (states_equal(env
, &sl
->state
, cur
)) {
8894 /* reached equivalent register/stack state,
8896 * Registers read by the continuation are read by us.
8897 * If we have any write marks in env->cur_state, they
8898 * will prevent corresponding reads in the continuation
8899 * from reaching our parent (an explored_state). Our
8900 * own state will get the read marks recorded, but
8901 * they'll be immediately forgotten as we're pruning
8902 * this state and will pop a new one.
8904 err
= propagate_liveness(env
, &sl
->state
, cur
);
8906 /* if previous state reached the exit with precision and
8907 * current state is equivalent to it (except precsion marks)
8908 * the precision needs to be propagated back in
8909 * the current state.
8911 err
= err
? : push_jmp_history(env
, cur
);
8912 err
= err
? : propagate_precision(env
, &sl
->state
);
8918 /* when new state is not going to be added do not increase miss count.
8919 * Otherwise several loop iterations will remove the state
8920 * recorded earlier. The goal of these heuristics is to have
8921 * states from some iterations of the loop (some in the beginning
8922 * and some at the end) to help pruning.
8926 /* heuristic to determine whether this state is beneficial
8927 * to keep checking from state equivalence point of view.
8928 * Higher numbers increase max_states_per_insn and verification time,
8929 * but do not meaningfully decrease insn_processed.
8931 if (sl
->miss_cnt
> sl
->hit_cnt
* 3 + 3) {
8932 /* the state is unlikely to be useful. Remove it to
8933 * speed up verification
8936 if (sl
->state
.frame
[0]->regs
[0].live
& REG_LIVE_DONE
) {
8937 u32 br
= sl
->state
.branches
;
8940 "BUG live_done but branches_to_explore %d\n",
8942 free_verifier_state(&sl
->state
, false);
8946 /* cannot free this state, since parentage chain may
8947 * walk it later. Add it for free_list instead to
8948 * be freed at the end of verification
8950 sl
->next
= env
->free_list
;
8951 env
->free_list
= sl
;
8961 if (env
->max_states_per_insn
< states_cnt
)
8962 env
->max_states_per_insn
= states_cnt
;
8964 if (!env
->bpf_capable
&& states_cnt
> BPF_COMPLEXITY_LIMIT_STATES
)
8965 return push_jmp_history(env
, cur
);
8968 return push_jmp_history(env
, cur
);
8970 /* There were no equivalent states, remember the current one.
8971 * Technically the current state is not proven to be safe yet,
8972 * but it will either reach outer most bpf_exit (which means it's safe)
8973 * or it will be rejected. When there are no loops the verifier won't be
8974 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
8975 * again on the way to bpf_exit.
8976 * When looping the sl->state.branches will be > 0 and this state
8977 * will not be considered for equivalence until branches == 0.
8979 new_sl
= kzalloc(sizeof(struct bpf_verifier_state_list
), GFP_KERNEL
);
8982 env
->total_states
++;
8984 env
->prev_jmps_processed
= env
->jmps_processed
;
8985 env
->prev_insn_processed
= env
->insn_processed
;
8987 /* add new state to the head of linked list */
8988 new = &new_sl
->state
;
8989 err
= copy_verifier_state(new, cur
);
8991 free_verifier_state(new, false);
8995 new->insn_idx
= insn_idx
;
8996 WARN_ONCE(new->branches
!= 1,
8997 "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches
, insn_idx
);
9000 cur
->first_insn_idx
= insn_idx
;
9001 clear_jmp_history(cur
);
9002 new_sl
->next
= *explored_state(env
, insn_idx
);
9003 *explored_state(env
, insn_idx
) = new_sl
;
9004 /* connect new state to parentage chain. Current frame needs all
9005 * registers connected. Only r6 - r9 of the callers are alive (pushed
9006 * to the stack implicitly by JITs) so in callers' frames connect just
9007 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
9008 * the state of the call instruction (with WRITTEN set), and r0 comes
9009 * from callee with its full parentage chain, anyway.
9011 /* clear write marks in current state: the writes we did are not writes
9012 * our child did, so they don't screen off its reads from us.
9013 * (There are no read marks in current state, because reads always mark
9014 * their parent and current state never has children yet. Only
9015 * explored_states can get read marks.)
9017 for (j
= 0; j
<= cur
->curframe
; j
++) {
9018 for (i
= j
< cur
->curframe
? BPF_REG_6
: 0; i
< BPF_REG_FP
; i
++)
9019 cur
->frame
[j
]->regs
[i
].parent
= &new->frame
[j
]->regs
[i
];
9020 for (i
= 0; i
< BPF_REG_FP
; i
++)
9021 cur
->frame
[j
]->regs
[i
].live
= REG_LIVE_NONE
;
9024 /* all stack frames are accessible from callee, clear them all */
9025 for (j
= 0; j
<= cur
->curframe
; j
++) {
9026 struct bpf_func_state
*frame
= cur
->frame
[j
];
9027 struct bpf_func_state
*newframe
= new->frame
[j
];
9029 for (i
= 0; i
< frame
->allocated_stack
/ BPF_REG_SIZE
; i
++) {
9030 frame
->stack
[i
].spilled_ptr
.live
= REG_LIVE_NONE
;
9031 frame
->stack
[i
].spilled_ptr
.parent
=
9032 &newframe
->stack
[i
].spilled_ptr
;
9038 /* Return true if it's OK to have the same insn return a different type. */
9039 static bool reg_type_mismatch_ok(enum bpf_reg_type type
)
9044 case PTR_TO_SOCKET_OR_NULL
:
9045 case PTR_TO_SOCK_COMMON
:
9046 case PTR_TO_SOCK_COMMON_OR_NULL
:
9047 case PTR_TO_TCP_SOCK
:
9048 case PTR_TO_TCP_SOCK_OR_NULL
:
9049 case PTR_TO_XDP_SOCK
:
9051 case PTR_TO_BTF_ID_OR_NULL
:
9058 /* If an instruction was previously used with particular pointer types, then we
9059 * need to be careful to avoid cases such as the below, where it may be ok
9060 * for one branch accessing the pointer, but not ok for the other branch:
9065 * R1 = some_other_valid_ptr;
9068 * R2 = *(u32 *)(R1 + 0);
9070 static bool reg_type_mismatch(enum bpf_reg_type src
, enum bpf_reg_type prev
)
9072 return src
!= prev
&& (!reg_type_mismatch_ok(src
) ||
9073 !reg_type_mismatch_ok(prev
));
9076 static int do_check(struct bpf_verifier_env
*env
)
9078 bool pop_log
= !(env
->log
.level
& BPF_LOG_LEVEL2
);
9079 struct bpf_verifier_state
*state
= env
->cur_state
;
9080 struct bpf_insn
*insns
= env
->prog
->insnsi
;
9081 struct bpf_reg_state
*regs
;
9082 int insn_cnt
= env
->prog
->len
;
9083 bool do_print_state
= false;
9084 int prev_insn_idx
= -1;
9087 struct bpf_insn
*insn
;
9091 env
->prev_insn_idx
= prev_insn_idx
;
9092 if (env
->insn_idx
>= insn_cnt
) {
9093 verbose(env
, "invalid insn idx %d insn_cnt %d\n",
9094 env
->insn_idx
, insn_cnt
);
9098 insn
= &insns
[env
->insn_idx
];
9099 class = BPF_CLASS(insn
->code
);
9101 if (++env
->insn_processed
> BPF_COMPLEXITY_LIMIT_INSNS
) {
9103 "BPF program is too large. Processed %d insn\n",
9104 env
->insn_processed
);
9108 err
= is_state_visited(env
, env
->insn_idx
);
9112 /* found equivalent state, can prune the search */
9113 if (env
->log
.level
& BPF_LOG_LEVEL
) {
9115 verbose(env
, "\nfrom %d to %d%s: safe\n",
9116 env
->prev_insn_idx
, env
->insn_idx
,
9117 env
->cur_state
->speculative
?
9118 " (speculative execution)" : "");
9120 verbose(env
, "%d: safe\n", env
->insn_idx
);
9122 goto process_bpf_exit
;
9125 if (signal_pending(current
))
9131 if (env
->log
.level
& BPF_LOG_LEVEL2
||
9132 (env
->log
.level
& BPF_LOG_LEVEL
&& do_print_state
)) {
9133 if (env
->log
.level
& BPF_LOG_LEVEL2
)
9134 verbose(env
, "%d:", env
->insn_idx
);
9136 verbose(env
, "\nfrom %d to %d%s:",
9137 env
->prev_insn_idx
, env
->insn_idx
,
9138 env
->cur_state
->speculative
?
9139 " (speculative execution)" : "");
9140 print_verifier_state(env
, state
->frame
[state
->curframe
]);
9141 do_print_state
= false;
9144 if (env
->log
.level
& BPF_LOG_LEVEL
) {
9145 const struct bpf_insn_cbs cbs
= {
9146 .cb_print
= verbose
,
9147 .private_data
= env
,
9150 verbose_linfo(env
, env
->insn_idx
, "; ");
9151 verbose(env
, "%d: ", env
->insn_idx
);
9152 print_bpf_insn(&cbs
, insn
, env
->allow_ptr_leaks
);
9155 if (bpf_prog_is_dev_bound(env
->prog
->aux
)) {
9156 err
= bpf_prog_offload_verify_insn(env
, env
->insn_idx
,
9157 env
->prev_insn_idx
);
9162 regs
= cur_regs(env
);
9163 env
->insn_aux_data
[env
->insn_idx
].seen
= env
->pass_cnt
;
9164 prev_insn_idx
= env
->insn_idx
;
9166 if (class == BPF_ALU
|| class == BPF_ALU64
) {
9167 err
= check_alu_op(env
, insn
);
9171 } else if (class == BPF_LDX
) {
9172 enum bpf_reg_type
*prev_src_type
, src_reg_type
;
9174 /* check for reserved fields is already done */
9176 /* check src operand */
9177 err
= check_reg_arg(env
, insn
->src_reg
, SRC_OP
);
9181 err
= check_reg_arg(env
, insn
->dst_reg
, DST_OP_NO_MARK
);
9185 src_reg_type
= regs
[insn
->src_reg
].type
;
9187 /* check that memory (src_reg + off) is readable,
9188 * the state of dst_reg will be updated by this func
9190 err
= check_mem_access(env
, env
->insn_idx
, insn
->src_reg
,
9191 insn
->off
, BPF_SIZE(insn
->code
),
9192 BPF_READ
, insn
->dst_reg
, false);
9196 prev_src_type
= &env
->insn_aux_data
[env
->insn_idx
].ptr_type
;
9198 if (*prev_src_type
== NOT_INIT
) {
9200 * dst_reg = *(u32 *)(src_reg + off)
9201 * save type to validate intersecting paths
9203 *prev_src_type
= src_reg_type
;
9205 } else if (reg_type_mismatch(src_reg_type
, *prev_src_type
)) {
9206 /* ABuser program is trying to use the same insn
9207 * dst_reg = *(u32*) (src_reg + off)
9208 * with different pointer types:
9209 * src_reg == ctx in one branch and
9210 * src_reg == stack|map in some other branch.
9213 verbose(env
, "same insn cannot be used with different pointers\n");
9217 } else if (class == BPF_STX
) {
9218 enum bpf_reg_type
*prev_dst_type
, dst_reg_type
;
9220 if (BPF_MODE(insn
->code
) == BPF_XADD
) {
9221 err
= check_xadd(env
, env
->insn_idx
, insn
);
9228 /* check src1 operand */
9229 err
= check_reg_arg(env
, insn
->src_reg
, SRC_OP
);
9232 /* check src2 operand */
9233 err
= check_reg_arg(env
, insn
->dst_reg
, SRC_OP
);
9237 dst_reg_type
= regs
[insn
->dst_reg
].type
;
9239 /* check that memory (dst_reg + off) is writeable */
9240 err
= check_mem_access(env
, env
->insn_idx
, insn
->dst_reg
,
9241 insn
->off
, BPF_SIZE(insn
->code
),
9242 BPF_WRITE
, insn
->src_reg
, false);
9246 prev_dst_type
= &env
->insn_aux_data
[env
->insn_idx
].ptr_type
;
9248 if (*prev_dst_type
== NOT_INIT
) {
9249 *prev_dst_type
= dst_reg_type
;
9250 } else if (reg_type_mismatch(dst_reg_type
, *prev_dst_type
)) {
9251 verbose(env
, "same insn cannot be used with different pointers\n");
9255 } else if (class == BPF_ST
) {
9256 if (BPF_MODE(insn
->code
) != BPF_MEM
||
9257 insn
->src_reg
!= BPF_REG_0
) {
9258 verbose(env
, "BPF_ST uses reserved fields\n");
9261 /* check src operand */
9262 err
= check_reg_arg(env
, insn
->dst_reg
, SRC_OP
);
9266 if (is_ctx_reg(env
, insn
->dst_reg
)) {
9267 verbose(env
, "BPF_ST stores into R%d %s is not allowed\n",
9269 reg_type_str
[reg_state(env
, insn
->dst_reg
)->type
]);
9273 /* check that memory (dst_reg + off) is writeable */
9274 err
= check_mem_access(env
, env
->insn_idx
, insn
->dst_reg
,
9275 insn
->off
, BPF_SIZE(insn
->code
),
9276 BPF_WRITE
, -1, false);
9280 } else if (class == BPF_JMP
|| class == BPF_JMP32
) {
9281 u8 opcode
= BPF_OP(insn
->code
);
9283 env
->jmps_processed
++;
9284 if (opcode
== BPF_CALL
) {
9285 if (BPF_SRC(insn
->code
) != BPF_K
||
9287 (insn
->src_reg
!= BPF_REG_0
&&
9288 insn
->src_reg
!= BPF_PSEUDO_CALL
) ||
9289 insn
->dst_reg
!= BPF_REG_0
||
9290 class == BPF_JMP32
) {
9291 verbose(env
, "BPF_CALL uses reserved fields\n");
9295 if (env
->cur_state
->active_spin_lock
&&
9296 (insn
->src_reg
== BPF_PSEUDO_CALL
||
9297 insn
->imm
!= BPF_FUNC_spin_unlock
)) {
9298 verbose(env
, "function calls are not allowed while holding a lock\n");
9301 if (insn
->src_reg
== BPF_PSEUDO_CALL
)
9302 err
= check_func_call(env
, insn
, &env
->insn_idx
);
9304 err
= check_helper_call(env
, insn
->imm
, env
->insn_idx
);
9308 } else if (opcode
== BPF_JA
) {
9309 if (BPF_SRC(insn
->code
) != BPF_K
||
9311 insn
->src_reg
!= BPF_REG_0
||
9312 insn
->dst_reg
!= BPF_REG_0
||
9313 class == BPF_JMP32
) {
9314 verbose(env
, "BPF_JA uses reserved fields\n");
9318 env
->insn_idx
+= insn
->off
+ 1;
9321 } else if (opcode
== BPF_EXIT
) {
9322 if (BPF_SRC(insn
->code
) != BPF_K
||
9324 insn
->src_reg
!= BPF_REG_0
||
9325 insn
->dst_reg
!= BPF_REG_0
||
9326 class == BPF_JMP32
) {
9327 verbose(env
, "BPF_EXIT uses reserved fields\n");
9331 if (env
->cur_state
->active_spin_lock
) {
9332 verbose(env
, "bpf_spin_unlock is missing\n");
9336 if (state
->curframe
) {
9337 /* exit from nested function */
9338 err
= prepare_func_exit(env
, &env
->insn_idx
);
9341 do_print_state
= true;
9345 err
= check_reference_leak(env
);
9349 err
= check_return_code(env
);
9353 update_branch_counts(env
, env
->cur_state
);
9354 err
= pop_stack(env
, &prev_insn_idx
,
9355 &env
->insn_idx
, pop_log
);
9361 do_print_state
= true;
9365 err
= check_cond_jmp_op(env
, insn
, &env
->insn_idx
);
9369 } else if (class == BPF_LD
) {
9370 u8 mode
= BPF_MODE(insn
->code
);
9372 if (mode
== BPF_ABS
|| mode
== BPF_IND
) {
9373 err
= check_ld_abs(env
, insn
);
9377 } else if (mode
== BPF_IMM
) {
9378 err
= check_ld_imm(env
, insn
);
9383 env
->insn_aux_data
[env
->insn_idx
].seen
= env
->pass_cnt
;
9385 verbose(env
, "invalid BPF_LD mode\n");
9389 verbose(env
, "unknown insn class %d\n", class);
9399 static int check_map_prealloc(struct bpf_map
*map
)
9401 return (map
->map_type
!= BPF_MAP_TYPE_HASH
&&
9402 map
->map_type
!= BPF_MAP_TYPE_PERCPU_HASH
&&
9403 map
->map_type
!= BPF_MAP_TYPE_HASH_OF_MAPS
) ||
9404 !(map
->map_flags
& BPF_F_NO_PREALLOC
);
9407 static bool is_tracing_prog_type(enum bpf_prog_type type
)
9410 case BPF_PROG_TYPE_KPROBE
:
9411 case BPF_PROG_TYPE_TRACEPOINT
:
9412 case BPF_PROG_TYPE_PERF_EVENT
:
9413 case BPF_PROG_TYPE_RAW_TRACEPOINT
:
9420 static bool is_preallocated_map(struct bpf_map
*map
)
9422 if (!check_map_prealloc(map
))
9424 if (map
->inner_map_meta
&& !check_map_prealloc(map
->inner_map_meta
))
9429 static int check_map_prog_compatibility(struct bpf_verifier_env
*env
,
9430 struct bpf_map
*map
,
9431 struct bpf_prog
*prog
)
9434 enum bpf_prog_type prog_type
= resolve_prog_type(prog
);
9436 * Validate that trace type programs use preallocated hash maps.
9438 * For programs attached to PERF events this is mandatory as the
9439 * perf NMI can hit any arbitrary code sequence.
9441 * All other trace types using preallocated hash maps are unsafe as
9442 * well because tracepoint or kprobes can be inside locked regions
9443 * of the memory allocator or at a place where a recursion into the
9444 * memory allocator would see inconsistent state.
9446 * On RT enabled kernels run-time allocation of all trace type
9447 * programs is strictly prohibited due to lock type constraints. On
9448 * !RT kernels it is allowed for backwards compatibility reasons for
9449 * now, but warnings are emitted so developers are made aware of
9450 * the unsafety and can fix their programs before this is enforced.
9452 if (is_tracing_prog_type(prog_type
) && !is_preallocated_map(map
)) {
9453 if (prog_type
== BPF_PROG_TYPE_PERF_EVENT
) {
9454 verbose(env
, "perf_event programs can only use preallocated hash map\n");
9457 if (IS_ENABLED(CONFIG_PREEMPT_RT
)) {
9458 verbose(env
, "trace type programs can only use preallocated hash map\n");
9461 WARN_ONCE(1, "trace type BPF program uses run-time allocation\n");
9462 verbose(env
, "trace type programs with run-time allocated hash maps are unsafe. Switch to preallocated hash maps.\n");
9465 if ((is_tracing_prog_type(prog_type
) ||
9466 prog_type
== BPF_PROG_TYPE_SOCKET_FILTER
) &&
9467 map_value_has_spin_lock(map
)) {
9468 verbose(env
, "tracing progs cannot use bpf_spin_lock yet\n");
9472 if ((bpf_prog_is_dev_bound(prog
->aux
) || bpf_map_is_dev_bound(map
)) &&
9473 !bpf_offload_prog_map_match(prog
, map
)) {
9474 verbose(env
, "offload device mismatch between prog and map\n");
9478 if (map
->map_type
== BPF_MAP_TYPE_STRUCT_OPS
) {
9479 verbose(env
, "bpf_struct_ops map cannot be used in prog\n");
9483 if (prog
->aux
->sleepable
)
9484 switch (map
->map_type
) {
9485 case BPF_MAP_TYPE_HASH
:
9486 case BPF_MAP_TYPE_LRU_HASH
:
9487 case BPF_MAP_TYPE_ARRAY
:
9488 if (!is_preallocated_map(map
)) {
9490 "Sleepable programs can only use preallocated hash maps\n");
9496 "Sleepable programs can only use array and hash maps\n");
9503 static bool bpf_map_is_cgroup_storage(struct bpf_map
*map
)
9505 return (map
->map_type
== BPF_MAP_TYPE_CGROUP_STORAGE
||
9506 map
->map_type
== BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE
);
9509 /* look for pseudo eBPF instructions that access map FDs and
9510 * replace them with actual map pointers
9512 static int replace_map_fd_with_map_ptr(struct bpf_verifier_env
*env
)
9514 struct bpf_insn
*insn
= env
->prog
->insnsi
;
9515 int insn_cnt
= env
->prog
->len
;
9518 err
= bpf_prog_calc_tag(env
->prog
);
9522 for (i
= 0; i
< insn_cnt
; i
++, insn
++) {
9523 if (BPF_CLASS(insn
->code
) == BPF_LDX
&&
9524 (BPF_MODE(insn
->code
) != BPF_MEM
|| insn
->imm
!= 0)) {
9525 verbose(env
, "BPF_LDX uses reserved fields\n");
9529 if (BPF_CLASS(insn
->code
) == BPF_STX
&&
9530 ((BPF_MODE(insn
->code
) != BPF_MEM
&&
9531 BPF_MODE(insn
->code
) != BPF_XADD
) || insn
->imm
!= 0)) {
9532 verbose(env
, "BPF_STX uses reserved fields\n");
9536 if (insn
[0].code
== (BPF_LD
| BPF_IMM
| BPF_DW
)) {
9537 struct bpf_insn_aux_data
*aux
;
9538 struct bpf_map
*map
;
9542 if (i
== insn_cnt
- 1 || insn
[1].code
!= 0 ||
9543 insn
[1].dst_reg
!= 0 || insn
[1].src_reg
!= 0 ||
9545 verbose(env
, "invalid bpf_ld_imm64 insn\n");
9549 if (insn
[0].src_reg
== 0)
9550 /* valid generic load 64-bit imm */
9553 /* In final convert_pseudo_ld_imm64() step, this is
9554 * converted into regular 64-bit imm load insn.
9556 if ((insn
[0].src_reg
!= BPF_PSEUDO_MAP_FD
&&
9557 insn
[0].src_reg
!= BPF_PSEUDO_MAP_VALUE
) ||
9558 (insn
[0].src_reg
== BPF_PSEUDO_MAP_FD
&&
9559 insn
[1].imm
!= 0)) {
9561 "unrecognized bpf_ld_imm64 insn\n");
9565 f
= fdget(insn
[0].imm
);
9566 map
= __bpf_map_get(f
);
9568 verbose(env
, "fd %d is not pointing to valid bpf_map\n",
9570 return PTR_ERR(map
);
9573 err
= check_map_prog_compatibility(env
, map
, env
->prog
);
9579 aux
= &env
->insn_aux_data
[i
];
9580 if (insn
->src_reg
== BPF_PSEUDO_MAP_FD
) {
9581 addr
= (unsigned long)map
;
9583 u32 off
= insn
[1].imm
;
9585 if (off
>= BPF_MAX_VAR_OFF
) {
9586 verbose(env
, "direct value offset of %u is not allowed\n", off
);
9591 if (!map
->ops
->map_direct_value_addr
) {
9592 verbose(env
, "no direct value access support for this map type\n");
9597 err
= map
->ops
->map_direct_value_addr(map
, &addr
, off
);
9599 verbose(env
, "invalid access to map value pointer, value_size=%u off=%u\n",
9600 map
->value_size
, off
);
9609 insn
[0].imm
= (u32
)addr
;
9610 insn
[1].imm
= addr
>> 32;
9612 /* check whether we recorded this map already */
9613 for (j
= 0; j
< env
->used_map_cnt
; j
++) {
9614 if (env
->used_maps
[j
] == map
) {
9621 if (env
->used_map_cnt
>= MAX_USED_MAPS
) {
9626 /* hold the map. If the program is rejected by verifier,
9627 * the map will be released by release_maps() or it
9628 * will be used by the valid program until it's unloaded
9629 * and all maps are released in free_used_maps()
9633 aux
->map_index
= env
->used_map_cnt
;
9634 env
->used_maps
[env
->used_map_cnt
++] = map
;
9636 if (bpf_map_is_cgroup_storage(map
) &&
9637 bpf_cgroup_storage_assign(env
->prog
->aux
, map
)) {
9638 verbose(env
, "only one cgroup storage of each type is allowed\n");
9650 /* Basic sanity check before we invest more work here. */
9651 if (!bpf_opcode_in_insntable(insn
->code
)) {
9652 verbose(env
, "unknown opcode %02x\n", insn
->code
);
9657 /* now all pseudo BPF_LD_IMM64 instructions load valid
9658 * 'struct bpf_map *' into a register instead of user map_fd.
9659 * These pointers will be used later by verifier to validate map access.
9664 /* drop refcnt of maps used by the rejected program */
9665 static void release_maps(struct bpf_verifier_env
*env
)
9667 __bpf_free_used_maps(env
->prog
->aux
, env
->used_maps
,
9671 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
9672 static void convert_pseudo_ld_imm64(struct bpf_verifier_env
*env
)
9674 struct bpf_insn
*insn
= env
->prog
->insnsi
;
9675 int insn_cnt
= env
->prog
->len
;
9678 for (i
= 0; i
< insn_cnt
; i
++, insn
++)
9679 if (insn
->code
== (BPF_LD
| BPF_IMM
| BPF_DW
))
9683 /* single env->prog->insni[off] instruction was replaced with the range
9684 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying
9685 * [0, off) and [off, end) to new locations, so the patched range stays zero
9687 static int adjust_insn_aux_data(struct bpf_verifier_env
*env
,
9688 struct bpf_prog
*new_prog
, u32 off
, u32 cnt
)
9690 struct bpf_insn_aux_data
*new_data
, *old_data
= env
->insn_aux_data
;
9691 struct bpf_insn
*insn
= new_prog
->insnsi
;
9695 /* aux info at OFF always needs adjustment, no matter fast path
9696 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
9697 * original insn at old prog.
9699 old_data
[off
].zext_dst
= insn_has_def32(env
, insn
+ off
+ cnt
- 1);
9703 prog_len
= new_prog
->len
;
9704 new_data
= vzalloc(array_size(prog_len
,
9705 sizeof(struct bpf_insn_aux_data
)));
9708 memcpy(new_data
, old_data
, sizeof(struct bpf_insn_aux_data
) * off
);
9709 memcpy(new_data
+ off
+ cnt
- 1, old_data
+ off
,
9710 sizeof(struct bpf_insn_aux_data
) * (prog_len
- off
- cnt
+ 1));
9711 for (i
= off
; i
< off
+ cnt
- 1; i
++) {
9712 new_data
[i
].seen
= env
->pass_cnt
;
9713 new_data
[i
].zext_dst
= insn_has_def32(env
, insn
+ i
);
9715 env
->insn_aux_data
= new_data
;
9720 static void adjust_subprog_starts(struct bpf_verifier_env
*env
, u32 off
, u32 len
)
9726 /* NOTE: fake 'exit' subprog should be updated as well. */
9727 for (i
= 0; i
<= env
->subprog_cnt
; i
++) {
9728 if (env
->subprog_info
[i
].start
<= off
)
9730 env
->subprog_info
[i
].start
+= len
- 1;
9734 static void adjust_poke_descs(struct bpf_prog
*prog
, u32 len
)
9736 struct bpf_jit_poke_descriptor
*tab
= prog
->aux
->poke_tab
;
9737 int i
, sz
= prog
->aux
->size_poke_tab
;
9738 struct bpf_jit_poke_descriptor
*desc
;
9740 for (i
= 0; i
< sz
; i
++) {
9742 desc
->insn_idx
+= len
- 1;
9746 static struct bpf_prog
*bpf_patch_insn_data(struct bpf_verifier_env
*env
, u32 off
,
9747 const struct bpf_insn
*patch
, u32 len
)
9749 struct bpf_prog
*new_prog
;
9751 new_prog
= bpf_patch_insn_single(env
->prog
, off
, patch
, len
);
9752 if (IS_ERR(new_prog
)) {
9753 if (PTR_ERR(new_prog
) == -ERANGE
)
9755 "insn %d cannot be patched due to 16-bit range\n",
9756 env
->insn_aux_data
[off
].orig_idx
);
9759 if (adjust_insn_aux_data(env
, new_prog
, off
, len
))
9761 adjust_subprog_starts(env
, off
, len
);
9762 adjust_poke_descs(new_prog
, len
);
9766 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env
*env
,
9771 /* find first prog starting at or after off (first to remove) */
9772 for (i
= 0; i
< env
->subprog_cnt
; i
++)
9773 if (env
->subprog_info
[i
].start
>= off
)
9775 /* find first prog starting at or after off + cnt (first to stay) */
9776 for (j
= i
; j
< env
->subprog_cnt
; j
++)
9777 if (env
->subprog_info
[j
].start
>= off
+ cnt
)
9779 /* if j doesn't start exactly at off + cnt, we are just removing
9780 * the front of previous prog
9782 if (env
->subprog_info
[j
].start
!= off
+ cnt
)
9786 struct bpf_prog_aux
*aux
= env
->prog
->aux
;
9789 /* move fake 'exit' subprog as well */
9790 move
= env
->subprog_cnt
+ 1 - j
;
9792 memmove(env
->subprog_info
+ i
,
9793 env
->subprog_info
+ j
,
9794 sizeof(*env
->subprog_info
) * move
);
9795 env
->subprog_cnt
-= j
- i
;
9797 /* remove func_info */
9798 if (aux
->func_info
) {
9799 move
= aux
->func_info_cnt
- j
;
9801 memmove(aux
->func_info
+ i
,
9803 sizeof(*aux
->func_info
) * move
);
9804 aux
->func_info_cnt
-= j
- i
;
9805 /* func_info->insn_off is set after all code rewrites,
9806 * in adjust_btf_func() - no need to adjust
9810 /* convert i from "first prog to remove" to "first to adjust" */
9811 if (env
->subprog_info
[i
].start
== off
)
9815 /* update fake 'exit' subprog as well */
9816 for (; i
<= env
->subprog_cnt
; i
++)
9817 env
->subprog_info
[i
].start
-= cnt
;
9822 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env
*env
, u32 off
,
9825 struct bpf_prog
*prog
= env
->prog
;
9826 u32 i
, l_off
, l_cnt
, nr_linfo
;
9827 struct bpf_line_info
*linfo
;
9829 nr_linfo
= prog
->aux
->nr_linfo
;
9833 linfo
= prog
->aux
->linfo
;
9835 /* find first line info to remove, count lines to be removed */
9836 for (i
= 0; i
< nr_linfo
; i
++)
9837 if (linfo
[i
].insn_off
>= off
)
9842 for (; i
< nr_linfo
; i
++)
9843 if (linfo
[i
].insn_off
< off
+ cnt
)
9848 /* First live insn doesn't match first live linfo, it needs to "inherit"
9849 * last removed linfo. prog is already modified, so prog->len == off
9850 * means no live instructions after (tail of the program was removed).
9852 if (prog
->len
!= off
&& l_cnt
&&
9853 (i
== nr_linfo
|| linfo
[i
].insn_off
!= off
+ cnt
)) {
9855 linfo
[--i
].insn_off
= off
+ cnt
;
9858 /* remove the line info which refer to the removed instructions */
9860 memmove(linfo
+ l_off
, linfo
+ i
,
9861 sizeof(*linfo
) * (nr_linfo
- i
));
9863 prog
->aux
->nr_linfo
-= l_cnt
;
9864 nr_linfo
= prog
->aux
->nr_linfo
;
9867 /* pull all linfo[i].insn_off >= off + cnt in by cnt */
9868 for (i
= l_off
; i
< nr_linfo
; i
++)
9869 linfo
[i
].insn_off
-= cnt
;
9871 /* fix up all subprogs (incl. 'exit') which start >= off */
9872 for (i
= 0; i
<= env
->subprog_cnt
; i
++)
9873 if (env
->subprog_info
[i
].linfo_idx
> l_off
) {
9874 /* program may have started in the removed region but
9875 * may not be fully removed
9877 if (env
->subprog_info
[i
].linfo_idx
>= l_off
+ l_cnt
)
9878 env
->subprog_info
[i
].linfo_idx
-= l_cnt
;
9880 env
->subprog_info
[i
].linfo_idx
= l_off
;
9886 static int verifier_remove_insns(struct bpf_verifier_env
*env
, u32 off
, u32 cnt
)
9888 struct bpf_insn_aux_data
*aux_data
= env
->insn_aux_data
;
9889 unsigned int orig_prog_len
= env
->prog
->len
;
9892 if (bpf_prog_is_dev_bound(env
->prog
->aux
))
9893 bpf_prog_offload_remove_insns(env
, off
, cnt
);
9895 err
= bpf_remove_insns(env
->prog
, off
, cnt
);
9899 err
= adjust_subprog_starts_after_remove(env
, off
, cnt
);
9903 err
= bpf_adj_linfo_after_remove(env
, off
, cnt
);
9907 memmove(aux_data
+ off
, aux_data
+ off
+ cnt
,
9908 sizeof(*aux_data
) * (orig_prog_len
- off
- cnt
));
9913 /* The verifier does more data flow analysis than llvm and will not
9914 * explore branches that are dead at run time. Malicious programs can
9915 * have dead code too. Therefore replace all dead at-run-time code
9918 * Just nops are not optimal, e.g. if they would sit at the end of the
9919 * program and through another bug we would manage to jump there, then
9920 * we'd execute beyond program memory otherwise. Returning exception
9921 * code also wouldn't work since we can have subprogs where the dead
9922 * code could be located.
9924 static void sanitize_dead_code(struct bpf_verifier_env
*env
)
9926 struct bpf_insn_aux_data
*aux_data
= env
->insn_aux_data
;
9927 struct bpf_insn trap
= BPF_JMP_IMM(BPF_JA
, 0, 0, -1);
9928 struct bpf_insn
*insn
= env
->prog
->insnsi
;
9929 const int insn_cnt
= env
->prog
->len
;
9932 for (i
= 0; i
< insn_cnt
; i
++) {
9933 if (aux_data
[i
].seen
)
9935 memcpy(insn
+ i
, &trap
, sizeof(trap
));
9939 static bool insn_is_cond_jump(u8 code
)
9943 if (BPF_CLASS(code
) == BPF_JMP32
)
9946 if (BPF_CLASS(code
) != BPF_JMP
)
9950 return op
!= BPF_JA
&& op
!= BPF_EXIT
&& op
!= BPF_CALL
;
9953 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env
*env
)
9955 struct bpf_insn_aux_data
*aux_data
= env
->insn_aux_data
;
9956 struct bpf_insn ja
= BPF_JMP_IMM(BPF_JA
, 0, 0, 0);
9957 struct bpf_insn
*insn
= env
->prog
->insnsi
;
9958 const int insn_cnt
= env
->prog
->len
;
9961 for (i
= 0; i
< insn_cnt
; i
++, insn
++) {
9962 if (!insn_is_cond_jump(insn
->code
))
9965 if (!aux_data
[i
+ 1].seen
)
9967 else if (!aux_data
[i
+ 1 + insn
->off
].seen
)
9972 if (bpf_prog_is_dev_bound(env
->prog
->aux
))
9973 bpf_prog_offload_replace_insn(env
, i
, &ja
);
9975 memcpy(insn
, &ja
, sizeof(ja
));
9979 static int opt_remove_dead_code(struct bpf_verifier_env
*env
)
9981 struct bpf_insn_aux_data
*aux_data
= env
->insn_aux_data
;
9982 int insn_cnt
= env
->prog
->len
;
9985 for (i
= 0; i
< insn_cnt
; i
++) {
9989 while (i
+ j
< insn_cnt
&& !aux_data
[i
+ j
].seen
)
9994 err
= verifier_remove_insns(env
, i
, j
);
9997 insn_cnt
= env
->prog
->len
;
10003 static int opt_remove_nops(struct bpf_verifier_env
*env
)
10005 const struct bpf_insn ja
= BPF_JMP_IMM(BPF_JA
, 0, 0, 0);
10006 struct bpf_insn
*insn
= env
->prog
->insnsi
;
10007 int insn_cnt
= env
->prog
->len
;
10010 for (i
= 0; i
< insn_cnt
; i
++) {
10011 if (memcmp(&insn
[i
], &ja
, sizeof(ja
)))
10014 err
= verifier_remove_insns(env
, i
, 1);
10024 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env
*env
,
10025 const union bpf_attr
*attr
)
10027 struct bpf_insn
*patch
, zext_patch
[2], rnd_hi32_patch
[4];
10028 struct bpf_insn_aux_data
*aux
= env
->insn_aux_data
;
10029 int i
, patch_len
, delta
= 0, len
= env
->prog
->len
;
10030 struct bpf_insn
*insns
= env
->prog
->insnsi
;
10031 struct bpf_prog
*new_prog
;
10034 rnd_hi32
= attr
->prog_flags
& BPF_F_TEST_RND_HI32
;
10035 zext_patch
[1] = BPF_ZEXT_REG(0);
10036 rnd_hi32_patch
[1] = BPF_ALU64_IMM(BPF_MOV
, BPF_REG_AX
, 0);
10037 rnd_hi32_patch
[2] = BPF_ALU64_IMM(BPF_LSH
, BPF_REG_AX
, 32);
10038 rnd_hi32_patch
[3] = BPF_ALU64_REG(BPF_OR
, 0, BPF_REG_AX
);
10039 for (i
= 0; i
< len
; i
++) {
10040 int adj_idx
= i
+ delta
;
10041 struct bpf_insn insn
;
10043 insn
= insns
[adj_idx
];
10044 if (!aux
[adj_idx
].zext_dst
) {
10052 class = BPF_CLASS(code
);
10053 if (insn_no_def(&insn
))
10056 /* NOTE: arg "reg" (the fourth one) is only used for
10057 * BPF_STX which has been ruled out in above
10058 * check, it is safe to pass NULL here.
10060 if (is_reg64(env
, &insn
, insn
.dst_reg
, NULL
, DST_OP
)) {
10061 if (class == BPF_LD
&&
10062 BPF_MODE(code
) == BPF_IMM
)
10067 /* ctx load could be transformed into wider load. */
10068 if (class == BPF_LDX
&&
10069 aux
[adj_idx
].ptr_type
== PTR_TO_CTX
)
10072 imm_rnd
= get_random_int();
10073 rnd_hi32_patch
[0] = insn
;
10074 rnd_hi32_patch
[1].imm
= imm_rnd
;
10075 rnd_hi32_patch
[3].dst_reg
= insn
.dst_reg
;
10076 patch
= rnd_hi32_patch
;
10078 goto apply_patch_buffer
;
10081 if (!bpf_jit_needs_zext())
10084 zext_patch
[0] = insn
;
10085 zext_patch
[1].dst_reg
= insn
.dst_reg
;
10086 zext_patch
[1].src_reg
= insn
.dst_reg
;
10087 patch
= zext_patch
;
10089 apply_patch_buffer
:
10090 new_prog
= bpf_patch_insn_data(env
, adj_idx
, patch
, patch_len
);
10093 env
->prog
= new_prog
;
10094 insns
= new_prog
->insnsi
;
10095 aux
= env
->insn_aux_data
;
10096 delta
+= patch_len
- 1;
10102 /* convert load instructions that access fields of a context type into a
10103 * sequence of instructions that access fields of the underlying structure:
10104 * struct __sk_buff -> struct sk_buff
10105 * struct bpf_sock_ops -> struct sock
10107 static int convert_ctx_accesses(struct bpf_verifier_env
*env
)
10109 const struct bpf_verifier_ops
*ops
= env
->ops
;
10110 int i
, cnt
, size
, ctx_field_size
, delta
= 0;
10111 const int insn_cnt
= env
->prog
->len
;
10112 struct bpf_insn insn_buf
[16], *insn
;
10113 u32 target_size
, size_default
, off
;
10114 struct bpf_prog
*new_prog
;
10115 enum bpf_access_type type
;
10116 bool is_narrower_load
;
10118 if (ops
->gen_prologue
|| env
->seen_direct_write
) {
10119 if (!ops
->gen_prologue
) {
10120 verbose(env
, "bpf verifier is misconfigured\n");
10123 cnt
= ops
->gen_prologue(insn_buf
, env
->seen_direct_write
,
10125 if (cnt
>= ARRAY_SIZE(insn_buf
)) {
10126 verbose(env
, "bpf verifier is misconfigured\n");
10129 new_prog
= bpf_patch_insn_data(env
, 0, insn_buf
, cnt
);
10133 env
->prog
= new_prog
;
10138 if (bpf_prog_is_dev_bound(env
->prog
->aux
))
10141 insn
= env
->prog
->insnsi
+ delta
;
10143 for (i
= 0; i
< insn_cnt
; i
++, insn
++) {
10144 bpf_convert_ctx_access_t convert_ctx_access
;
10146 if (insn
->code
== (BPF_LDX
| BPF_MEM
| BPF_B
) ||
10147 insn
->code
== (BPF_LDX
| BPF_MEM
| BPF_H
) ||
10148 insn
->code
== (BPF_LDX
| BPF_MEM
| BPF_W
) ||
10149 insn
->code
== (BPF_LDX
| BPF_MEM
| BPF_DW
))
10151 else if (insn
->code
== (BPF_STX
| BPF_MEM
| BPF_B
) ||
10152 insn
->code
== (BPF_STX
| BPF_MEM
| BPF_H
) ||
10153 insn
->code
== (BPF_STX
| BPF_MEM
| BPF_W
) ||
10154 insn
->code
== (BPF_STX
| BPF_MEM
| BPF_DW
))
10159 if (type
== BPF_WRITE
&&
10160 env
->insn_aux_data
[i
+ delta
].sanitize_stack_off
) {
10161 struct bpf_insn patch
[] = {
10162 /* Sanitize suspicious stack slot with zero.
10163 * There are no memory dependencies for this store,
10164 * since it's only using frame pointer and immediate
10167 BPF_ST_MEM(BPF_DW
, BPF_REG_FP
,
10168 env
->insn_aux_data
[i
+ delta
].sanitize_stack_off
,
10170 /* the original STX instruction will immediately
10171 * overwrite the same stack slot with appropriate value
10176 cnt
= ARRAY_SIZE(patch
);
10177 new_prog
= bpf_patch_insn_data(env
, i
+ delta
, patch
, cnt
);
10182 env
->prog
= new_prog
;
10183 insn
= new_prog
->insnsi
+ i
+ delta
;
10187 switch (env
->insn_aux_data
[i
+ delta
].ptr_type
) {
10189 if (!ops
->convert_ctx_access
)
10191 convert_ctx_access
= ops
->convert_ctx_access
;
10193 case PTR_TO_SOCKET
:
10194 case PTR_TO_SOCK_COMMON
:
10195 convert_ctx_access
= bpf_sock_convert_ctx_access
;
10197 case PTR_TO_TCP_SOCK
:
10198 convert_ctx_access
= bpf_tcp_sock_convert_ctx_access
;
10200 case PTR_TO_XDP_SOCK
:
10201 convert_ctx_access
= bpf_xdp_sock_convert_ctx_access
;
10203 case PTR_TO_BTF_ID
:
10204 if (type
== BPF_READ
) {
10205 insn
->code
= BPF_LDX
| BPF_PROBE_MEM
|
10206 BPF_SIZE((insn
)->code
);
10207 env
->prog
->aux
->num_exentries
++;
10208 } else if (resolve_prog_type(env
->prog
) != BPF_PROG_TYPE_STRUCT_OPS
) {
10209 verbose(env
, "Writes through BTF pointers are not allowed\n");
10217 ctx_field_size
= env
->insn_aux_data
[i
+ delta
].ctx_field_size
;
10218 size
= BPF_LDST_BYTES(insn
);
10220 /* If the read access is a narrower load of the field,
10221 * convert to a 4/8-byte load, to minimum program type specific
10222 * convert_ctx_access changes. If conversion is successful,
10223 * we will apply proper mask to the result.
10225 is_narrower_load
= size
< ctx_field_size
;
10226 size_default
= bpf_ctx_off_adjust_machine(ctx_field_size
);
10228 if (is_narrower_load
) {
10231 if (type
== BPF_WRITE
) {
10232 verbose(env
, "bpf verifier narrow ctx access misconfigured\n");
10237 if (ctx_field_size
== 4)
10239 else if (ctx_field_size
== 8)
10240 size_code
= BPF_DW
;
10242 insn
->off
= off
& ~(size_default
- 1);
10243 insn
->code
= BPF_LDX
| BPF_MEM
| size_code
;
10247 cnt
= convert_ctx_access(type
, insn
, insn_buf
, env
->prog
,
10249 if (cnt
== 0 || cnt
>= ARRAY_SIZE(insn_buf
) ||
10250 (ctx_field_size
&& !target_size
)) {
10251 verbose(env
, "bpf verifier is misconfigured\n");
10255 if (is_narrower_load
&& size
< target_size
) {
10256 u8 shift
= bpf_ctx_narrow_access_offset(
10257 off
, size
, size_default
) * 8;
10258 if (ctx_field_size
<= 4) {
10260 insn_buf
[cnt
++] = BPF_ALU32_IMM(BPF_RSH
,
10263 insn_buf
[cnt
++] = BPF_ALU32_IMM(BPF_AND
, insn
->dst_reg
,
10264 (1 << size
* 8) - 1);
10267 insn_buf
[cnt
++] = BPF_ALU64_IMM(BPF_RSH
,
10270 insn_buf
[cnt
++] = BPF_ALU64_IMM(BPF_AND
, insn
->dst_reg
,
10271 (1ULL << size
* 8) - 1);
10275 new_prog
= bpf_patch_insn_data(env
, i
+ delta
, insn_buf
, cnt
);
10281 /* keep walking new program and skip insns we just inserted */
10282 env
->prog
= new_prog
;
10283 insn
= new_prog
->insnsi
+ i
+ delta
;
10289 static int jit_subprogs(struct bpf_verifier_env
*env
)
10291 struct bpf_prog
*prog
= env
->prog
, **func
, *tmp
;
10292 int i
, j
, subprog_start
, subprog_end
= 0, len
, subprog
;
10293 struct bpf_map
*map_ptr
;
10294 struct bpf_insn
*insn
;
10295 void *old_bpf_func
;
10296 int err
, num_exentries
;
10298 if (env
->subprog_cnt
<= 1)
10301 for (i
= 0, insn
= prog
->insnsi
; i
< prog
->len
; i
++, insn
++) {
10302 if (insn
->code
!= (BPF_JMP
| BPF_CALL
) ||
10303 insn
->src_reg
!= BPF_PSEUDO_CALL
)
10305 /* Upon error here we cannot fall back to interpreter but
10306 * need a hard reject of the program. Thus -EFAULT is
10307 * propagated in any case.
10309 subprog
= find_subprog(env
, i
+ insn
->imm
+ 1);
10311 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
10312 i
+ insn
->imm
+ 1);
10315 /* temporarily remember subprog id inside insn instead of
10316 * aux_data, since next loop will split up all insns into funcs
10318 insn
->off
= subprog
;
10319 /* remember original imm in case JIT fails and fallback
10320 * to interpreter will be needed
10322 env
->insn_aux_data
[i
].call_imm
= insn
->imm
;
10323 /* point imm to __bpf_call_base+1 from JITs point of view */
10327 err
= bpf_prog_alloc_jited_linfo(prog
);
10329 goto out_undo_insn
;
10332 func
= kcalloc(env
->subprog_cnt
, sizeof(prog
), GFP_KERNEL
);
10334 goto out_undo_insn
;
10336 for (i
= 0; i
< env
->subprog_cnt
; i
++) {
10337 subprog_start
= subprog_end
;
10338 subprog_end
= env
->subprog_info
[i
+ 1].start
;
10340 len
= subprog_end
- subprog_start
;
10341 /* BPF_PROG_RUN doesn't call subprogs directly,
10342 * hence main prog stats include the runtime of subprogs.
10343 * subprogs don't have IDs and not reachable via prog_get_next_id
10344 * func[i]->aux->stats will never be accessed and stays NULL
10346 func
[i
] = bpf_prog_alloc_no_stats(bpf_prog_size(len
), GFP_USER
);
10349 memcpy(func
[i
]->insnsi
, &prog
->insnsi
[subprog_start
],
10350 len
* sizeof(struct bpf_insn
));
10351 func
[i
]->type
= prog
->type
;
10352 func
[i
]->len
= len
;
10353 if (bpf_prog_calc_tag(func
[i
]))
10355 func
[i
]->is_func
= 1;
10356 func
[i
]->aux
->func_idx
= i
;
10357 /* the btf and func_info will be freed only at prog->aux */
10358 func
[i
]->aux
->btf
= prog
->aux
->btf
;
10359 func
[i
]->aux
->func_info
= prog
->aux
->func_info
;
10361 for (j
= 0; j
< prog
->aux
->size_poke_tab
; j
++) {
10362 u32 insn_idx
= prog
->aux
->poke_tab
[j
].insn_idx
;
10365 if (!(insn_idx
>= subprog_start
&&
10366 insn_idx
<= subprog_end
))
10369 ret
= bpf_jit_add_poke_descriptor(func
[i
],
10370 &prog
->aux
->poke_tab
[j
]);
10372 verbose(env
, "adding tail call poke descriptor failed\n");
10376 func
[i
]->insnsi
[insn_idx
- subprog_start
].imm
= ret
+ 1;
10378 map_ptr
= func
[i
]->aux
->poke_tab
[ret
].tail_call
.map
;
10379 ret
= map_ptr
->ops
->map_poke_track(map_ptr
, func
[i
]->aux
);
10381 verbose(env
, "tracking tail call prog failed\n");
10386 /* Use bpf_prog_F_tag to indicate functions in stack traces.
10387 * Long term would need debug info to populate names
10389 func
[i
]->aux
->name
[0] = 'F';
10390 func
[i
]->aux
->stack_depth
= env
->subprog_info
[i
].stack_depth
;
10391 func
[i
]->jit_requested
= 1;
10392 func
[i
]->aux
->linfo
= prog
->aux
->linfo
;
10393 func
[i
]->aux
->nr_linfo
= prog
->aux
->nr_linfo
;
10394 func
[i
]->aux
->jited_linfo
= prog
->aux
->jited_linfo
;
10395 func
[i
]->aux
->linfo_idx
= env
->subprog_info
[i
].linfo_idx
;
10397 insn
= func
[i
]->insnsi
;
10398 for (j
= 0; j
< func
[i
]->len
; j
++, insn
++) {
10399 if (BPF_CLASS(insn
->code
) == BPF_LDX
&&
10400 BPF_MODE(insn
->code
) == BPF_PROBE_MEM
)
10403 func
[i
]->aux
->num_exentries
= num_exentries
;
10404 func
[i
]->aux
->tail_call_reachable
= env
->subprog_info
[i
].tail_call_reachable
;
10405 func
[i
] = bpf_int_jit_compile(func
[i
]);
10406 if (!func
[i
]->jited
) {
10413 /* Untrack main program's aux structs so that during map_poke_run()
10414 * we will not stumble upon the unfilled poke descriptors; each
10415 * of the main program's poke descs got distributed across subprogs
10416 * and got tracked onto map, so we are sure that none of them will
10417 * be missed after the operation below
10419 for (i
= 0; i
< prog
->aux
->size_poke_tab
; i
++) {
10420 map_ptr
= prog
->aux
->poke_tab
[i
].tail_call
.map
;
10422 map_ptr
->ops
->map_poke_untrack(map_ptr
, prog
->aux
);
10425 /* at this point all bpf functions were successfully JITed
10426 * now populate all bpf_calls with correct addresses and
10427 * run last pass of JIT
10429 for (i
= 0; i
< env
->subprog_cnt
; i
++) {
10430 insn
= func
[i
]->insnsi
;
10431 for (j
= 0; j
< func
[i
]->len
; j
++, insn
++) {
10432 if (insn
->code
!= (BPF_JMP
| BPF_CALL
) ||
10433 insn
->src_reg
!= BPF_PSEUDO_CALL
)
10435 subprog
= insn
->off
;
10436 insn
->imm
= BPF_CAST_CALL(func
[subprog
]->bpf_func
) -
10440 /* we use the aux data to keep a list of the start addresses
10441 * of the JITed images for each function in the program
10443 * for some architectures, such as powerpc64, the imm field
10444 * might not be large enough to hold the offset of the start
10445 * address of the callee's JITed image from __bpf_call_base
10447 * in such cases, we can lookup the start address of a callee
10448 * by using its subprog id, available from the off field of
10449 * the call instruction, as an index for this list
10451 func
[i
]->aux
->func
= func
;
10452 func
[i
]->aux
->func_cnt
= env
->subprog_cnt
;
10454 for (i
= 0; i
< env
->subprog_cnt
; i
++) {
10455 old_bpf_func
= func
[i
]->bpf_func
;
10456 tmp
= bpf_int_jit_compile(func
[i
]);
10457 if (tmp
!= func
[i
] || func
[i
]->bpf_func
!= old_bpf_func
) {
10458 verbose(env
, "JIT doesn't support bpf-to-bpf calls\n");
10465 /* finally lock prog and jit images for all functions and
10466 * populate kallsysm
10468 for (i
= 0; i
< env
->subprog_cnt
; i
++) {
10469 bpf_prog_lock_ro(func
[i
]);
10470 bpf_prog_kallsyms_add(func
[i
]);
10473 /* Last step: make now unused interpreter insns from main
10474 * prog consistent for later dump requests, so they can
10475 * later look the same as if they were interpreted only.
10477 for (i
= 0, insn
= prog
->insnsi
; i
< prog
->len
; i
++, insn
++) {
10478 if (insn
->code
!= (BPF_JMP
| BPF_CALL
) ||
10479 insn
->src_reg
!= BPF_PSEUDO_CALL
)
10481 insn
->off
= env
->insn_aux_data
[i
].call_imm
;
10482 subprog
= find_subprog(env
, i
+ insn
->off
+ 1);
10483 insn
->imm
= subprog
;
10487 prog
->bpf_func
= func
[0]->bpf_func
;
10488 prog
->aux
->func
= func
;
10489 prog
->aux
->func_cnt
= env
->subprog_cnt
;
10490 bpf_prog_free_unused_jited_linfo(prog
);
10493 for (i
= 0; i
< env
->subprog_cnt
; i
++) {
10497 for (j
= 0; j
< func
[i
]->aux
->size_poke_tab
; j
++) {
10498 map_ptr
= func
[i
]->aux
->poke_tab
[j
].tail_call
.map
;
10499 map_ptr
->ops
->map_poke_untrack(map_ptr
, func
[i
]->aux
);
10501 bpf_jit_free(func
[i
]);
10505 /* cleanup main prog to be interpreted */
10506 prog
->jit_requested
= 0;
10507 for (i
= 0, insn
= prog
->insnsi
; i
< prog
->len
; i
++, insn
++) {
10508 if (insn
->code
!= (BPF_JMP
| BPF_CALL
) ||
10509 insn
->src_reg
!= BPF_PSEUDO_CALL
)
10512 insn
->imm
= env
->insn_aux_data
[i
].call_imm
;
10514 bpf_prog_free_jited_linfo(prog
);
10518 static int fixup_call_args(struct bpf_verifier_env
*env
)
10520 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
10521 struct bpf_prog
*prog
= env
->prog
;
10522 struct bpf_insn
*insn
= prog
->insnsi
;
10527 if (env
->prog
->jit_requested
&&
10528 !bpf_prog_is_dev_bound(env
->prog
->aux
)) {
10529 err
= jit_subprogs(env
);
10532 if (err
== -EFAULT
)
10535 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
10536 if (env
->subprog_cnt
> 1 && env
->prog
->aux
->tail_call_reachable
) {
10537 /* When JIT fails the progs with bpf2bpf calls and tail_calls
10538 * have to be rejected, since interpreter doesn't support them yet.
10540 verbose(env
, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
10543 for (i
= 0; i
< prog
->len
; i
++, insn
++) {
10544 if (insn
->code
!= (BPF_JMP
| BPF_CALL
) ||
10545 insn
->src_reg
!= BPF_PSEUDO_CALL
)
10547 depth
= get_callee_stack_depth(env
, insn
, i
);
10550 bpf_patch_call_args(insn
, depth
);
10557 /* fixup insn->imm field of bpf_call instructions
10558 * and inline eligible helpers as explicit sequence of BPF instructions
10560 * this function is called after eBPF program passed verification
10562 static int fixup_bpf_calls(struct bpf_verifier_env
*env
)
10564 struct bpf_prog
*prog
= env
->prog
;
10565 bool expect_blinding
= bpf_jit_blinding_enabled(prog
);
10566 struct bpf_insn
*insn
= prog
->insnsi
;
10567 const struct bpf_func_proto
*fn
;
10568 const int insn_cnt
= prog
->len
;
10569 const struct bpf_map_ops
*ops
;
10570 struct bpf_insn_aux_data
*aux
;
10571 struct bpf_insn insn_buf
[16];
10572 struct bpf_prog
*new_prog
;
10573 struct bpf_map
*map_ptr
;
10574 int i
, ret
, cnt
, delta
= 0;
10576 for (i
= 0; i
< insn_cnt
; i
++, insn
++) {
10577 if (insn
->code
== (BPF_ALU64
| BPF_MOD
| BPF_X
) ||
10578 insn
->code
== (BPF_ALU64
| BPF_DIV
| BPF_X
) ||
10579 insn
->code
== (BPF_ALU
| BPF_MOD
| BPF_X
) ||
10580 insn
->code
== (BPF_ALU
| BPF_DIV
| BPF_X
)) {
10581 bool is64
= BPF_CLASS(insn
->code
) == BPF_ALU64
;
10582 struct bpf_insn mask_and_div
[] = {
10583 BPF_MOV32_REG(insn
->src_reg
, insn
->src_reg
),
10584 /* Rx div 0 -> 0 */
10585 BPF_JMP_IMM(BPF_JNE
, insn
->src_reg
, 0, 2),
10586 BPF_ALU32_REG(BPF_XOR
, insn
->dst_reg
, insn
->dst_reg
),
10587 BPF_JMP_IMM(BPF_JA
, 0, 0, 1),
10590 struct bpf_insn mask_and_mod
[] = {
10591 BPF_MOV32_REG(insn
->src_reg
, insn
->src_reg
),
10592 /* Rx mod 0 -> Rx */
10593 BPF_JMP_IMM(BPF_JEQ
, insn
->src_reg
, 0, 1),
10596 struct bpf_insn
*patchlet
;
10598 if (insn
->code
== (BPF_ALU64
| BPF_DIV
| BPF_X
) ||
10599 insn
->code
== (BPF_ALU
| BPF_DIV
| BPF_X
)) {
10600 patchlet
= mask_and_div
+ (is64
? 1 : 0);
10601 cnt
= ARRAY_SIZE(mask_and_div
) - (is64
? 1 : 0);
10603 patchlet
= mask_and_mod
+ (is64
? 1 : 0);
10604 cnt
= ARRAY_SIZE(mask_and_mod
) - (is64
? 1 : 0);
10607 new_prog
= bpf_patch_insn_data(env
, i
+ delta
, patchlet
, cnt
);
10612 env
->prog
= prog
= new_prog
;
10613 insn
= new_prog
->insnsi
+ i
+ delta
;
10617 if (BPF_CLASS(insn
->code
) == BPF_LD
&&
10618 (BPF_MODE(insn
->code
) == BPF_ABS
||
10619 BPF_MODE(insn
->code
) == BPF_IND
)) {
10620 cnt
= env
->ops
->gen_ld_abs(insn
, insn_buf
);
10621 if (cnt
== 0 || cnt
>= ARRAY_SIZE(insn_buf
)) {
10622 verbose(env
, "bpf verifier is misconfigured\n");
10626 new_prog
= bpf_patch_insn_data(env
, i
+ delta
, insn_buf
, cnt
);
10631 env
->prog
= prog
= new_prog
;
10632 insn
= new_prog
->insnsi
+ i
+ delta
;
10636 if (insn
->code
== (BPF_ALU64
| BPF_ADD
| BPF_X
) ||
10637 insn
->code
== (BPF_ALU64
| BPF_SUB
| BPF_X
)) {
10638 const u8 code_add
= BPF_ALU64
| BPF_ADD
| BPF_X
;
10639 const u8 code_sub
= BPF_ALU64
| BPF_SUB
| BPF_X
;
10640 struct bpf_insn insn_buf
[16];
10641 struct bpf_insn
*patch
= &insn_buf
[0];
10645 aux
= &env
->insn_aux_data
[i
+ delta
];
10646 if (!aux
->alu_state
||
10647 aux
->alu_state
== BPF_ALU_NON_POINTER
)
10650 isneg
= aux
->alu_state
& BPF_ALU_NEG_VALUE
;
10651 issrc
= (aux
->alu_state
& BPF_ALU_SANITIZE
) ==
10652 BPF_ALU_SANITIZE_SRC
;
10654 off_reg
= issrc
? insn
->src_reg
: insn
->dst_reg
;
10656 *patch
++ = BPF_ALU64_IMM(BPF_MUL
, off_reg
, -1);
10657 *patch
++ = BPF_MOV32_IMM(BPF_REG_AX
, aux
->alu_limit
- 1);
10658 *patch
++ = BPF_ALU64_REG(BPF_SUB
, BPF_REG_AX
, off_reg
);
10659 *patch
++ = BPF_ALU64_REG(BPF_OR
, BPF_REG_AX
, off_reg
);
10660 *patch
++ = BPF_ALU64_IMM(BPF_NEG
, BPF_REG_AX
, 0);
10661 *patch
++ = BPF_ALU64_IMM(BPF_ARSH
, BPF_REG_AX
, 63);
10663 *patch
++ = BPF_ALU64_REG(BPF_AND
, BPF_REG_AX
,
10665 insn
->src_reg
= BPF_REG_AX
;
10667 *patch
++ = BPF_ALU64_REG(BPF_AND
, off_reg
,
10671 insn
->code
= insn
->code
== code_add
?
10672 code_sub
: code_add
;
10674 if (issrc
&& isneg
)
10675 *patch
++ = BPF_ALU64_IMM(BPF_MUL
, off_reg
, -1);
10676 cnt
= patch
- insn_buf
;
10678 new_prog
= bpf_patch_insn_data(env
, i
+ delta
, insn_buf
, cnt
);
10683 env
->prog
= prog
= new_prog
;
10684 insn
= new_prog
->insnsi
+ i
+ delta
;
10688 if (insn
->code
!= (BPF_JMP
| BPF_CALL
))
10690 if (insn
->src_reg
== BPF_PSEUDO_CALL
)
10693 if (insn
->imm
== BPF_FUNC_get_route_realm
)
10694 prog
->dst_needed
= 1;
10695 if (insn
->imm
== BPF_FUNC_get_prandom_u32
)
10696 bpf_user_rnd_init_once();
10697 if (insn
->imm
== BPF_FUNC_override_return
)
10698 prog
->kprobe_override
= 1;
10699 if (insn
->imm
== BPF_FUNC_tail_call
) {
10700 /* If we tail call into other programs, we
10701 * cannot make any assumptions since they can
10702 * be replaced dynamically during runtime in
10703 * the program array.
10705 prog
->cb_access
= 1;
10706 if (!allow_tail_call_in_subprogs(env
))
10707 prog
->aux
->stack_depth
= MAX_BPF_STACK
;
10708 prog
->aux
->max_pkt_offset
= MAX_PACKET_OFF
;
10710 /* mark bpf_tail_call as different opcode to avoid
10711 * conditional branch in the interpeter for every normal
10712 * call and to prevent accidental JITing by JIT compiler
10713 * that doesn't support bpf_tail_call yet
10716 insn
->code
= BPF_JMP
| BPF_TAIL_CALL
;
10718 aux
= &env
->insn_aux_data
[i
+ delta
];
10719 if (env
->bpf_capable
&& !expect_blinding
&&
10720 prog
->jit_requested
&&
10721 !bpf_map_key_poisoned(aux
) &&
10722 !bpf_map_ptr_poisoned(aux
) &&
10723 !bpf_map_ptr_unpriv(aux
)) {
10724 struct bpf_jit_poke_descriptor desc
= {
10725 .reason
= BPF_POKE_REASON_TAIL_CALL
,
10726 .tail_call
.map
= BPF_MAP_PTR(aux
->map_ptr_state
),
10727 .tail_call
.key
= bpf_map_key_immediate(aux
),
10728 .insn_idx
= i
+ delta
,
10731 ret
= bpf_jit_add_poke_descriptor(prog
, &desc
);
10733 verbose(env
, "adding tail call poke descriptor failed\n");
10737 insn
->imm
= ret
+ 1;
10741 if (!bpf_map_ptr_unpriv(aux
))
10744 /* instead of changing every JIT dealing with tail_call
10745 * emit two extra insns:
10746 * if (index >= max_entries) goto out;
10747 * index &= array->index_mask;
10748 * to avoid out-of-bounds cpu speculation
10750 if (bpf_map_ptr_poisoned(aux
)) {
10751 verbose(env
, "tail_call abusing map_ptr\n");
10755 map_ptr
= BPF_MAP_PTR(aux
->map_ptr_state
);
10756 insn_buf
[0] = BPF_JMP_IMM(BPF_JGE
, BPF_REG_3
,
10757 map_ptr
->max_entries
, 2);
10758 insn_buf
[1] = BPF_ALU32_IMM(BPF_AND
, BPF_REG_3
,
10759 container_of(map_ptr
,
10762 insn_buf
[2] = *insn
;
10764 new_prog
= bpf_patch_insn_data(env
, i
+ delta
, insn_buf
, cnt
);
10769 env
->prog
= prog
= new_prog
;
10770 insn
= new_prog
->insnsi
+ i
+ delta
;
10774 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
10775 * and other inlining handlers are currently limited to 64 bit
10778 if (prog
->jit_requested
&& BITS_PER_LONG
== 64 &&
10779 (insn
->imm
== BPF_FUNC_map_lookup_elem
||
10780 insn
->imm
== BPF_FUNC_map_update_elem
||
10781 insn
->imm
== BPF_FUNC_map_delete_elem
||
10782 insn
->imm
== BPF_FUNC_map_push_elem
||
10783 insn
->imm
== BPF_FUNC_map_pop_elem
||
10784 insn
->imm
== BPF_FUNC_map_peek_elem
)) {
10785 aux
= &env
->insn_aux_data
[i
+ delta
];
10786 if (bpf_map_ptr_poisoned(aux
))
10787 goto patch_call_imm
;
10789 map_ptr
= BPF_MAP_PTR(aux
->map_ptr_state
);
10790 ops
= map_ptr
->ops
;
10791 if (insn
->imm
== BPF_FUNC_map_lookup_elem
&&
10792 ops
->map_gen_lookup
) {
10793 cnt
= ops
->map_gen_lookup(map_ptr
, insn_buf
);
10794 if (cnt
== 0 || cnt
>= ARRAY_SIZE(insn_buf
)) {
10795 verbose(env
, "bpf verifier is misconfigured\n");
10799 new_prog
= bpf_patch_insn_data(env
, i
+ delta
,
10805 env
->prog
= prog
= new_prog
;
10806 insn
= new_prog
->insnsi
+ i
+ delta
;
10810 BUILD_BUG_ON(!__same_type(ops
->map_lookup_elem
,
10811 (void *(*)(struct bpf_map
*map
, void *key
))NULL
));
10812 BUILD_BUG_ON(!__same_type(ops
->map_delete_elem
,
10813 (int (*)(struct bpf_map
*map
, void *key
))NULL
));
10814 BUILD_BUG_ON(!__same_type(ops
->map_update_elem
,
10815 (int (*)(struct bpf_map
*map
, void *key
, void *value
,
10817 BUILD_BUG_ON(!__same_type(ops
->map_push_elem
,
10818 (int (*)(struct bpf_map
*map
, void *value
,
10820 BUILD_BUG_ON(!__same_type(ops
->map_pop_elem
,
10821 (int (*)(struct bpf_map
*map
, void *value
))NULL
));
10822 BUILD_BUG_ON(!__same_type(ops
->map_peek_elem
,
10823 (int (*)(struct bpf_map
*map
, void *value
))NULL
));
10825 switch (insn
->imm
) {
10826 case BPF_FUNC_map_lookup_elem
:
10827 insn
->imm
= BPF_CAST_CALL(ops
->map_lookup_elem
) -
10830 case BPF_FUNC_map_update_elem
:
10831 insn
->imm
= BPF_CAST_CALL(ops
->map_update_elem
) -
10834 case BPF_FUNC_map_delete_elem
:
10835 insn
->imm
= BPF_CAST_CALL(ops
->map_delete_elem
) -
10838 case BPF_FUNC_map_push_elem
:
10839 insn
->imm
= BPF_CAST_CALL(ops
->map_push_elem
) -
10842 case BPF_FUNC_map_pop_elem
:
10843 insn
->imm
= BPF_CAST_CALL(ops
->map_pop_elem
) -
10846 case BPF_FUNC_map_peek_elem
:
10847 insn
->imm
= BPF_CAST_CALL(ops
->map_peek_elem
) -
10852 goto patch_call_imm
;
10855 if (prog
->jit_requested
&& BITS_PER_LONG
== 64 &&
10856 insn
->imm
== BPF_FUNC_jiffies64
) {
10857 struct bpf_insn ld_jiffies_addr
[2] = {
10858 BPF_LD_IMM64(BPF_REG_0
,
10859 (unsigned long)&jiffies
),
10862 insn_buf
[0] = ld_jiffies_addr
[0];
10863 insn_buf
[1] = ld_jiffies_addr
[1];
10864 insn_buf
[2] = BPF_LDX_MEM(BPF_DW
, BPF_REG_0
,
10868 new_prog
= bpf_patch_insn_data(env
, i
+ delta
, insn_buf
,
10874 env
->prog
= prog
= new_prog
;
10875 insn
= new_prog
->insnsi
+ i
+ delta
;
10880 fn
= env
->ops
->get_func_proto(insn
->imm
, env
->prog
);
10881 /* all functions that have prototype and verifier allowed
10882 * programs to call them, must be real in-kernel functions
10886 "kernel subsystem misconfigured func %s#%d\n",
10887 func_id_name(insn
->imm
), insn
->imm
);
10890 insn
->imm
= fn
->func
- __bpf_call_base
;
10893 /* Since poke tab is now finalized, publish aux to tracker. */
10894 for (i
= 0; i
< prog
->aux
->size_poke_tab
; i
++) {
10895 map_ptr
= prog
->aux
->poke_tab
[i
].tail_call
.map
;
10896 if (!map_ptr
->ops
->map_poke_track
||
10897 !map_ptr
->ops
->map_poke_untrack
||
10898 !map_ptr
->ops
->map_poke_run
) {
10899 verbose(env
, "bpf verifier is misconfigured\n");
10903 ret
= map_ptr
->ops
->map_poke_track(map_ptr
, prog
->aux
);
10905 verbose(env
, "tracking tail call prog failed\n");
10913 static void free_states(struct bpf_verifier_env
*env
)
10915 struct bpf_verifier_state_list
*sl
, *sln
;
10918 sl
= env
->free_list
;
10921 free_verifier_state(&sl
->state
, false);
10925 env
->free_list
= NULL
;
10927 if (!env
->explored_states
)
10930 for (i
= 0; i
< state_htab_size(env
); i
++) {
10931 sl
= env
->explored_states
[i
];
10935 free_verifier_state(&sl
->state
, false);
10939 env
->explored_states
[i
] = NULL
;
10943 /* The verifier is using insn_aux_data[] to store temporary data during
10944 * verification and to store information for passes that run after the
10945 * verification like dead code sanitization. do_check_common() for subprogram N
10946 * may analyze many other subprograms. sanitize_insn_aux_data() clears all
10947 * temporary data after do_check_common() finds that subprogram N cannot be
10948 * verified independently. pass_cnt counts the number of times
10949 * do_check_common() was run and insn->aux->seen tells the pass number
10950 * insn_aux_data was touched. These variables are compared to clear temporary
10951 * data from failed pass. For testing and experiments do_check_common() can be
10952 * run multiple times even when prior attempt to verify is unsuccessful.
10954 static void sanitize_insn_aux_data(struct bpf_verifier_env
*env
)
10956 struct bpf_insn
*insn
= env
->prog
->insnsi
;
10957 struct bpf_insn_aux_data
*aux
;
10960 for (i
= 0; i
< env
->prog
->len
; i
++) {
10961 class = BPF_CLASS(insn
[i
].code
);
10962 if (class != BPF_LDX
&& class != BPF_STX
)
10964 aux
= &env
->insn_aux_data
[i
];
10965 if (aux
->seen
!= env
->pass_cnt
)
10967 memset(aux
, 0, offsetof(typeof(*aux
), orig_idx
));
10971 static int do_check_common(struct bpf_verifier_env
*env
, int subprog
)
10973 bool pop_log
= !(env
->log
.level
& BPF_LOG_LEVEL2
);
10974 struct bpf_verifier_state
*state
;
10975 struct bpf_reg_state
*regs
;
10978 env
->prev_linfo
= NULL
;
10981 state
= kzalloc(sizeof(struct bpf_verifier_state
), GFP_KERNEL
);
10984 state
->curframe
= 0;
10985 state
->speculative
= false;
10986 state
->branches
= 1;
10987 state
->frame
[0] = kzalloc(sizeof(struct bpf_func_state
), GFP_KERNEL
);
10988 if (!state
->frame
[0]) {
10992 env
->cur_state
= state
;
10993 init_func_state(env
, state
->frame
[0],
10994 BPF_MAIN_FUNC
/* callsite */,
10998 regs
= state
->frame
[state
->curframe
]->regs
;
10999 if (subprog
|| env
->prog
->type
== BPF_PROG_TYPE_EXT
) {
11000 ret
= btf_prepare_func_args(env
, subprog
, regs
);
11003 for (i
= BPF_REG_1
; i
<= BPF_REG_5
; i
++) {
11004 if (regs
[i
].type
== PTR_TO_CTX
)
11005 mark_reg_known_zero(env
, regs
, i
);
11006 else if (regs
[i
].type
== SCALAR_VALUE
)
11007 mark_reg_unknown(env
, regs
, i
);
11010 /* 1st arg to a function */
11011 regs
[BPF_REG_1
].type
= PTR_TO_CTX
;
11012 mark_reg_known_zero(env
, regs
, BPF_REG_1
);
11013 ret
= btf_check_func_arg_match(env
, subprog
, regs
);
11014 if (ret
== -EFAULT
)
11015 /* unlikely verifier bug. abort.
11016 * ret == 0 and ret < 0 are sadly acceptable for
11017 * main() function due to backward compatibility.
11018 * Like socket filter program may be written as:
11019 * int bpf_prog(struct pt_regs *ctx)
11020 * and never dereference that ctx in the program.
11021 * 'struct pt_regs' is a type mismatch for socket
11022 * filter that should be using 'struct __sk_buff'.
11027 ret
= do_check(env
);
11029 /* check for NULL is necessary, since cur_state can be freed inside
11030 * do_check() under memory pressure.
11032 if (env
->cur_state
) {
11033 free_verifier_state(env
->cur_state
, true);
11034 env
->cur_state
= NULL
;
11036 while (!pop_stack(env
, NULL
, NULL
, false));
11037 if (!ret
&& pop_log
)
11038 bpf_vlog_reset(&env
->log
, 0);
11041 /* clean aux data in case subprog was rejected */
11042 sanitize_insn_aux_data(env
);
11046 /* Verify all global functions in a BPF program one by one based on their BTF.
11047 * All global functions must pass verification. Otherwise the whole program is rejected.
11058 * foo() will be verified first for R1=any_scalar_value. During verification it
11059 * will be assumed that bar() already verified successfully and call to bar()
11060 * from foo() will be checked for type match only. Later bar() will be verified
11061 * independently to check that it's safe for R1=any_scalar_value.
11063 static int do_check_subprogs(struct bpf_verifier_env
*env
)
11065 struct bpf_prog_aux
*aux
= env
->prog
->aux
;
11068 if (!aux
->func_info
)
11071 for (i
= 1; i
< env
->subprog_cnt
; i
++) {
11072 if (aux
->func_info_aux
[i
].linkage
!= BTF_FUNC_GLOBAL
)
11074 env
->insn_idx
= env
->subprog_info
[i
].start
;
11075 WARN_ON_ONCE(env
->insn_idx
== 0);
11076 ret
= do_check_common(env
, i
);
11079 } else if (env
->log
.level
& BPF_LOG_LEVEL
) {
11081 "Func#%d is safe for any args that match its prototype\n",
11088 static int do_check_main(struct bpf_verifier_env
*env
)
11093 ret
= do_check_common(env
, 0);
11095 env
->prog
->aux
->stack_depth
= env
->subprog_info
[0].stack_depth
;
11100 static void print_verification_stats(struct bpf_verifier_env
*env
)
11104 if (env
->log
.level
& BPF_LOG_STATS
) {
11105 verbose(env
, "verification time %lld usec\n",
11106 div_u64(env
->verification_time
, 1000));
11107 verbose(env
, "stack depth ");
11108 for (i
= 0; i
< env
->subprog_cnt
; i
++) {
11109 u32 depth
= env
->subprog_info
[i
].stack_depth
;
11111 verbose(env
, "%d", depth
);
11112 if (i
+ 1 < env
->subprog_cnt
)
11115 verbose(env
, "\n");
11117 verbose(env
, "processed %d insns (limit %d) max_states_per_insn %d "
11118 "total_states %d peak_states %d mark_read %d\n",
11119 env
->insn_processed
, BPF_COMPLEXITY_LIMIT_INSNS
,
11120 env
->max_states_per_insn
, env
->total_states
,
11121 env
->peak_states
, env
->longest_mark_read_walk
);
11124 static int check_struct_ops_btf_id(struct bpf_verifier_env
*env
)
11126 const struct btf_type
*t
, *func_proto
;
11127 const struct bpf_struct_ops
*st_ops
;
11128 const struct btf_member
*member
;
11129 struct bpf_prog
*prog
= env
->prog
;
11130 u32 btf_id
, member_idx
;
11133 btf_id
= prog
->aux
->attach_btf_id
;
11134 st_ops
= bpf_struct_ops_find(btf_id
);
11136 verbose(env
, "attach_btf_id %u is not a supported struct\n",
11142 member_idx
= prog
->expected_attach_type
;
11143 if (member_idx
>= btf_type_vlen(t
)) {
11144 verbose(env
, "attach to invalid member idx %u of struct %s\n",
11145 member_idx
, st_ops
->name
);
11149 member
= &btf_type_member(t
)[member_idx
];
11150 mname
= btf_name_by_offset(btf_vmlinux
, member
->name_off
);
11151 func_proto
= btf_type_resolve_func_ptr(btf_vmlinux
, member
->type
,
11154 verbose(env
, "attach to invalid member %s(@idx %u) of struct %s\n",
11155 mname
, member_idx
, st_ops
->name
);
11159 if (st_ops
->check_member
) {
11160 int err
= st_ops
->check_member(t
, member
);
11163 verbose(env
, "attach to unsupported member %s of struct %s\n",
11164 mname
, st_ops
->name
);
11169 prog
->aux
->attach_func_proto
= func_proto
;
11170 prog
->aux
->attach_func_name
= mname
;
11171 env
->ops
= st_ops
->verifier_ops
;
11175 #define SECURITY_PREFIX "security_"
11177 static int check_attach_modify_return(struct bpf_prog
*prog
, unsigned long addr
)
11179 if (within_error_injection_list(addr
) ||
11180 !strncmp(SECURITY_PREFIX
, prog
->aux
->attach_func_name
,
11181 sizeof(SECURITY_PREFIX
) - 1))
11187 /* non exhaustive list of sleepable bpf_lsm_*() functions */
11188 BTF_SET_START(btf_sleepable_lsm_hooks
)
11189 #ifdef CONFIG_BPF_LSM
11190 BTF_ID(func
, bpf_lsm_bprm_committed_creds
)
11194 BTF_SET_END(btf_sleepable_lsm_hooks
)
11196 static int check_sleepable_lsm_hook(u32 btf_id
)
11198 return btf_id_set_contains(&btf_sleepable_lsm_hooks
, btf_id
);
11201 /* list of non-sleepable functions that are otherwise on
11202 * ALLOW_ERROR_INJECTION list
11204 BTF_SET_START(btf_non_sleepable_error_inject
)
11205 /* Three functions below can be called from sleepable and non-sleepable context.
11206 * Assume non-sleepable from bpf safety point of view.
11208 BTF_ID(func
, __add_to_page_cache_locked
)
11209 BTF_ID(func
, should_fail_alloc_page
)
11210 BTF_ID(func
, should_failslab
)
11211 BTF_SET_END(btf_non_sleepable_error_inject
)
11213 static int check_non_sleepable_error_inject(u32 btf_id
)
11215 return btf_id_set_contains(&btf_non_sleepable_error_inject
, btf_id
);
11218 static int check_attach_btf_id(struct bpf_verifier_env
*env
)
11220 struct bpf_prog
*prog
= env
->prog
;
11221 bool prog_extension
= prog
->type
== BPF_PROG_TYPE_EXT
;
11222 struct bpf_prog
*tgt_prog
= prog
->aux
->linked_prog
;
11223 u32 btf_id
= prog
->aux
->attach_btf_id
;
11224 const char prefix
[] = "btf_trace_";
11225 struct btf_func_model fmodel
;
11226 int ret
= 0, subprog
= -1, i
;
11227 struct bpf_trampoline
*tr
;
11228 const struct btf_type
*t
;
11229 bool conservative
= true;
11235 if (prog
->aux
->sleepable
&& prog
->type
!= BPF_PROG_TYPE_TRACING
&&
11236 prog
->type
!= BPF_PROG_TYPE_LSM
) {
11237 verbose(env
, "Only fentry/fexit/fmod_ret and lsm programs can be sleepable\n");
11241 if (prog
->type
== BPF_PROG_TYPE_STRUCT_OPS
)
11242 return check_struct_ops_btf_id(env
);
11244 if (prog
->type
!= BPF_PROG_TYPE_TRACING
&&
11245 prog
->type
!= BPF_PROG_TYPE_LSM
&&
11250 verbose(env
, "Tracing programs must provide btf_id\n");
11253 btf
= bpf_prog_get_target_btf(prog
);
11256 "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
11259 t
= btf_type_by_id(btf
, btf_id
);
11261 verbose(env
, "attach_btf_id %u is invalid\n", btf_id
);
11264 tname
= btf_name_by_offset(btf
, t
->name_off
);
11266 verbose(env
, "attach_btf_id %u doesn't have a name\n", btf_id
);
11270 struct bpf_prog_aux
*aux
= tgt_prog
->aux
;
11272 for (i
= 0; i
< aux
->func_info_cnt
; i
++)
11273 if (aux
->func_info
[i
].type_id
== btf_id
) {
11277 if (subprog
== -1) {
11278 verbose(env
, "Subprog %s doesn't exist\n", tname
);
11281 conservative
= aux
->func_info_aux
[subprog
].unreliable
;
11282 if (prog_extension
) {
11283 if (conservative
) {
11285 "Cannot replace static functions\n");
11288 if (!prog
->jit_requested
) {
11290 "Extension programs should be JITed\n");
11293 env
->ops
= bpf_verifier_ops
[tgt_prog
->type
];
11294 prog
->expected_attach_type
= tgt_prog
->expected_attach_type
;
11296 if (!tgt_prog
->jited
) {
11297 verbose(env
, "Can attach to only JITed progs\n");
11300 if (tgt_prog
->type
== prog
->type
) {
11301 /* Cannot fentry/fexit another fentry/fexit program.
11302 * Cannot attach program extension to another extension.
11303 * It's ok to attach fentry/fexit to extension program.
11305 verbose(env
, "Cannot recursively attach\n");
11308 if (tgt_prog
->type
== BPF_PROG_TYPE_TRACING
&&
11310 (tgt_prog
->expected_attach_type
== BPF_TRACE_FENTRY
||
11311 tgt_prog
->expected_attach_type
== BPF_TRACE_FEXIT
)) {
11312 /* Program extensions can extend all program types
11313 * except fentry/fexit. The reason is the following.
11314 * The fentry/fexit programs are used for performance
11315 * analysis, stats and can be attached to any program
11316 * type except themselves. When extension program is
11317 * replacing XDP function it is necessary to allow
11318 * performance analysis of all functions. Both original
11319 * XDP program and its program extension. Hence
11320 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
11321 * allowed. If extending of fentry/fexit was allowed it
11322 * would be possible to create long call chain
11323 * fentry->extension->fentry->extension beyond
11324 * reasonable stack size. Hence extending fentry is not
11327 verbose(env
, "Cannot extend fentry/fexit\n");
11330 key
= ((u64
)aux
->id
) << 32 | btf_id
;
11332 if (prog_extension
) {
11333 verbose(env
, "Cannot replace kernel functions\n");
11339 switch (prog
->expected_attach_type
) {
11340 case BPF_TRACE_RAW_TP
:
11343 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
11346 if (!btf_type_is_typedef(t
)) {
11347 verbose(env
, "attach_btf_id %u is not a typedef\n",
11351 if (strncmp(prefix
, tname
, sizeof(prefix
) - 1)) {
11352 verbose(env
, "attach_btf_id %u points to wrong type name %s\n",
11356 tname
+= sizeof(prefix
) - 1;
11357 t
= btf_type_by_id(btf
, t
->type
);
11358 if (!btf_type_is_ptr(t
))
11359 /* should never happen in valid vmlinux build */
11361 t
= btf_type_by_id(btf
, t
->type
);
11362 if (!btf_type_is_func_proto(t
))
11363 /* should never happen in valid vmlinux build */
11366 /* remember two read only pointers that are valid for
11367 * the life time of the kernel
11369 prog
->aux
->attach_func_name
= tname
;
11370 prog
->aux
->attach_func_proto
= t
;
11371 prog
->aux
->attach_btf_trace
= true;
11373 case BPF_TRACE_ITER
:
11374 if (!btf_type_is_func(t
)) {
11375 verbose(env
, "attach_btf_id %u is not a function\n",
11379 t
= btf_type_by_id(btf
, t
->type
);
11380 if (!btf_type_is_func_proto(t
))
11382 prog
->aux
->attach_func_name
= tname
;
11383 prog
->aux
->attach_func_proto
= t
;
11384 if (!bpf_iter_prog_supported(prog
))
11386 ret
= btf_distill_func_proto(&env
->log
, btf
, t
,
11390 if (!prog_extension
)
11393 case BPF_MODIFY_RETURN
:
11395 case BPF_TRACE_FENTRY
:
11396 case BPF_TRACE_FEXIT
:
11397 prog
->aux
->attach_func_name
= tname
;
11398 if (prog
->type
== BPF_PROG_TYPE_LSM
) {
11399 ret
= bpf_lsm_verify_prog(&env
->log
, prog
);
11404 if (!btf_type_is_func(t
)) {
11405 verbose(env
, "attach_btf_id %u is not a function\n",
11409 if (prog_extension
&&
11410 btf_check_type_match(env
, prog
, btf
, t
))
11412 t
= btf_type_by_id(btf
, t
->type
);
11413 if (!btf_type_is_func_proto(t
))
11415 tr
= bpf_trampoline_lookup(key
);
11418 /* t is either vmlinux type or another program's type */
11419 prog
->aux
->attach_func_proto
= t
;
11420 mutex_lock(&tr
->mutex
);
11421 if (tr
->func
.addr
) {
11422 prog
->aux
->trampoline
= tr
;
11425 if (tgt_prog
&& conservative
) {
11426 prog
->aux
->attach_func_proto
= NULL
;
11429 ret
= btf_distill_func_proto(&env
->log
, btf
, t
,
11430 tname
, &tr
->func
.model
);
11435 addr
= (long) tgt_prog
->bpf_func
;
11437 addr
= (long) tgt_prog
->aux
->func
[subprog
]->bpf_func
;
11439 addr
= kallsyms_lookup_name(tname
);
11442 "The address of function %s cannot be found\n",
11449 if (prog
->aux
->sleepable
) {
11451 switch (prog
->type
) {
11452 case BPF_PROG_TYPE_TRACING
:
11453 /* fentry/fexit/fmod_ret progs can be sleepable only if they are
11454 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
11456 if (!check_non_sleepable_error_inject(btf_id
) &&
11457 within_error_injection_list(addr
))
11460 case BPF_PROG_TYPE_LSM
:
11461 /* LSM progs check that they are attached to bpf_lsm_*() funcs.
11462 * Only some of them are sleepable.
11464 if (check_sleepable_lsm_hook(btf_id
))
11471 verbose(env
, "%s is not sleepable\n",
11472 prog
->aux
->attach_func_name
);
11473 } else if (prog
->expected_attach_type
== BPF_MODIFY_RETURN
) {
11474 ret
= check_attach_modify_return(prog
, addr
);
11476 verbose(env
, "%s() is not modifiable\n",
11477 prog
->aux
->attach_func_name
);
11481 tr
->func
.addr
= (void *)addr
;
11482 prog
->aux
->trampoline
= tr
;
11484 mutex_unlock(&tr
->mutex
);
11486 bpf_trampoline_put(tr
);
11491 int bpf_check(struct bpf_prog
**prog
, union bpf_attr
*attr
,
11492 union bpf_attr __user
*uattr
)
11494 u64 start_time
= ktime_get_ns();
11495 struct bpf_verifier_env
*env
;
11496 struct bpf_verifier_log
*log
;
11497 int i
, len
, ret
= -EINVAL
;
11500 /* no program is valid */
11501 if (ARRAY_SIZE(bpf_verifier_ops
) == 0)
11504 /* 'struct bpf_verifier_env' can be global, but since it's not small,
11505 * allocate/free it every time bpf_check() is called
11507 env
= kzalloc(sizeof(struct bpf_verifier_env
), GFP_KERNEL
);
11512 len
= (*prog
)->len
;
11513 env
->insn_aux_data
=
11514 vzalloc(array_size(sizeof(struct bpf_insn_aux_data
), len
));
11516 if (!env
->insn_aux_data
)
11518 for (i
= 0; i
< len
; i
++)
11519 env
->insn_aux_data
[i
].orig_idx
= i
;
11521 env
->ops
= bpf_verifier_ops
[env
->prog
->type
];
11522 is_priv
= bpf_capable();
11524 if (!btf_vmlinux
&& IS_ENABLED(CONFIG_DEBUG_INFO_BTF
)) {
11525 mutex_lock(&bpf_verifier_lock
);
11527 btf_vmlinux
= btf_parse_vmlinux();
11528 mutex_unlock(&bpf_verifier_lock
);
11531 /* grab the mutex to protect few globals used by verifier */
11533 mutex_lock(&bpf_verifier_lock
);
11535 if (attr
->log_level
|| attr
->log_buf
|| attr
->log_size
) {
11536 /* user requested verbose verifier output
11537 * and supplied buffer to store the verification trace
11539 log
->level
= attr
->log_level
;
11540 log
->ubuf
= (char __user
*) (unsigned long) attr
->log_buf
;
11541 log
->len_total
= attr
->log_size
;
11544 /* log attributes have to be sane */
11545 if (log
->len_total
< 128 || log
->len_total
> UINT_MAX
>> 2 ||
11546 !log
->level
|| !log
->ubuf
|| log
->level
& ~BPF_LOG_MASK
)
11550 if (IS_ERR(btf_vmlinux
)) {
11551 /* Either gcc or pahole or kernel are broken. */
11552 verbose(env
, "in-kernel BTF is malformed\n");
11553 ret
= PTR_ERR(btf_vmlinux
);
11554 goto skip_full_check
;
11557 env
->strict_alignment
= !!(attr
->prog_flags
& BPF_F_STRICT_ALIGNMENT
);
11558 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS
))
11559 env
->strict_alignment
= true;
11560 if (attr
->prog_flags
& BPF_F_ANY_ALIGNMENT
)
11561 env
->strict_alignment
= false;
11563 env
->allow_ptr_leaks
= bpf_allow_ptr_leaks();
11564 env
->allow_ptr_to_map_access
= bpf_allow_ptr_to_map_access();
11565 env
->bypass_spec_v1
= bpf_bypass_spec_v1();
11566 env
->bypass_spec_v4
= bpf_bypass_spec_v4();
11567 env
->bpf_capable
= bpf_capable();
11570 env
->test_state_freq
= attr
->prog_flags
& BPF_F_TEST_STATE_FREQ
;
11572 ret
= replace_map_fd_with_map_ptr(env
);
11574 goto skip_full_check
;
11576 if (bpf_prog_is_dev_bound(env
->prog
->aux
)) {
11577 ret
= bpf_prog_offload_verifier_prep(env
->prog
);
11579 goto skip_full_check
;
11582 env
->explored_states
= kvcalloc(state_htab_size(env
),
11583 sizeof(struct bpf_verifier_state_list
*),
11586 if (!env
->explored_states
)
11587 goto skip_full_check
;
11589 ret
= check_subprogs(env
);
11591 goto skip_full_check
;
11593 ret
= check_btf_info(env
, attr
, uattr
);
11595 goto skip_full_check
;
11597 ret
= check_attach_btf_id(env
);
11599 goto skip_full_check
;
11601 ret
= check_cfg(env
);
11603 goto skip_full_check
;
11605 ret
= do_check_subprogs(env
);
11606 ret
= ret
?: do_check_main(env
);
11608 if (ret
== 0 && bpf_prog_is_dev_bound(env
->prog
->aux
))
11609 ret
= bpf_prog_offload_finalize(env
);
11612 kvfree(env
->explored_states
);
11615 ret
= check_max_stack_depth(env
);
11617 /* instruction rewrites happen after this point */
11620 opt_hard_wire_dead_code_branches(env
);
11622 ret
= opt_remove_dead_code(env
);
11624 ret
= opt_remove_nops(env
);
11627 sanitize_dead_code(env
);
11631 /* program is valid, convert *(u32*)(ctx + off) accesses */
11632 ret
= convert_ctx_accesses(env
);
11635 ret
= fixup_bpf_calls(env
);
11637 /* do 32-bit optimization after insn patching has done so those patched
11638 * insns could be handled correctly.
11640 if (ret
== 0 && !bpf_prog_is_dev_bound(env
->prog
->aux
)) {
11641 ret
= opt_subreg_zext_lo32_rnd_hi32(env
, attr
);
11642 env
->prog
->aux
->verifier_zext
= bpf_jit_needs_zext() ? !ret
11647 ret
= fixup_call_args(env
);
11649 env
->verification_time
= ktime_get_ns() - start_time
;
11650 print_verification_stats(env
);
11652 if (log
->level
&& bpf_verifier_log_full(log
))
11654 if (log
->level
&& !log
->ubuf
) {
11656 goto err_release_maps
;
11659 if (ret
== 0 && env
->used_map_cnt
) {
11660 /* if program passed verifier, update used_maps in bpf_prog_info */
11661 env
->prog
->aux
->used_maps
= kmalloc_array(env
->used_map_cnt
,
11662 sizeof(env
->used_maps
[0]),
11665 if (!env
->prog
->aux
->used_maps
) {
11667 goto err_release_maps
;
11670 memcpy(env
->prog
->aux
->used_maps
, env
->used_maps
,
11671 sizeof(env
->used_maps
[0]) * env
->used_map_cnt
);
11672 env
->prog
->aux
->used_map_cnt
= env
->used_map_cnt
;
11674 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
11675 * bpf_ld_imm64 instructions
11677 convert_pseudo_ld_imm64(env
);
11681 adjust_btf_func(env
);
11684 if (!env
->prog
->aux
->used_maps
)
11685 /* if we didn't copy map pointers into bpf_prog_info, release
11686 * them now. Otherwise free_used_maps() will release them.
11690 /* extension progs temporarily inherit the attach_type of their targets
11691 for verification purposes, so set it back to zero before returning
11693 if (env
->prog
->type
== BPF_PROG_TYPE_EXT
)
11694 env
->prog
->expected_attach_type
= 0;
11699 mutex_unlock(&bpf_verifier_lock
);
11700 vfree(env
->insn_aux_data
);