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
;
247 struct btf
*btf_vmlinux
;
249 static DEFINE_MUTEX(bpf_verifier_lock
);
251 static const struct bpf_line_info
*
252 find_linfo(const struct bpf_verifier_env
*env
, u32 insn_off
)
254 const struct bpf_line_info
*linfo
;
255 const struct bpf_prog
*prog
;
259 nr_linfo
= prog
->aux
->nr_linfo
;
261 if (!nr_linfo
|| insn_off
>= prog
->len
)
264 linfo
= prog
->aux
->linfo
;
265 for (i
= 1; i
< nr_linfo
; i
++)
266 if (insn_off
< linfo
[i
].insn_off
)
269 return &linfo
[i
- 1];
272 void bpf_verifier_vlog(struct bpf_verifier_log
*log
, const char *fmt
,
277 n
= vscnprintf(log
->kbuf
, BPF_VERIFIER_TMP_LOG_SIZE
, fmt
, args
);
279 WARN_ONCE(n
>= BPF_VERIFIER_TMP_LOG_SIZE
- 1,
280 "verifier log line truncated - local buffer too short\n");
282 n
= min(log
->len_total
- log
->len_used
- 1, n
);
285 if (log
->level
== BPF_LOG_KERNEL
) {
286 pr_err("BPF:%s\n", log
->kbuf
);
289 if (!copy_to_user(log
->ubuf
+ log
->len_used
, log
->kbuf
, n
+ 1))
295 static void bpf_vlog_reset(struct bpf_verifier_log
*log
, u32 new_pos
)
299 if (!bpf_verifier_log_needed(log
))
302 log
->len_used
= new_pos
;
303 if (put_user(zero
, log
->ubuf
+ new_pos
))
307 /* log_level controls verbosity level of eBPF verifier.
308 * bpf_verifier_log_write() is used to dump the verification trace to the log,
309 * so the user can figure out what's wrong with the program
311 __printf(2, 3) void bpf_verifier_log_write(struct bpf_verifier_env
*env
,
312 const char *fmt
, ...)
316 if (!bpf_verifier_log_needed(&env
->log
))
320 bpf_verifier_vlog(&env
->log
, fmt
, args
);
323 EXPORT_SYMBOL_GPL(bpf_verifier_log_write
);
325 __printf(2, 3) static void verbose(void *private_data
, const char *fmt
, ...)
327 struct bpf_verifier_env
*env
= private_data
;
330 if (!bpf_verifier_log_needed(&env
->log
))
334 bpf_verifier_vlog(&env
->log
, fmt
, args
);
338 __printf(2, 3) void bpf_log(struct bpf_verifier_log
*log
,
339 const char *fmt
, ...)
343 if (!bpf_verifier_log_needed(log
))
347 bpf_verifier_vlog(log
, fmt
, args
);
351 static const char *ltrim(const char *s
)
359 __printf(3, 4) static void verbose_linfo(struct bpf_verifier_env
*env
,
361 const char *prefix_fmt
, ...)
363 const struct bpf_line_info
*linfo
;
365 if (!bpf_verifier_log_needed(&env
->log
))
368 linfo
= find_linfo(env
, insn_off
);
369 if (!linfo
|| linfo
== env
->prev_linfo
)
375 va_start(args
, prefix_fmt
);
376 bpf_verifier_vlog(&env
->log
, prefix_fmt
, args
);
381 ltrim(btf_name_by_offset(env
->prog
->aux
->btf
,
384 env
->prev_linfo
= linfo
;
387 static bool type_is_pkt_pointer(enum bpf_reg_type type
)
389 return type
== PTR_TO_PACKET
||
390 type
== PTR_TO_PACKET_META
;
393 static bool type_is_sk_pointer(enum bpf_reg_type type
)
395 return type
== PTR_TO_SOCKET
||
396 type
== PTR_TO_SOCK_COMMON
||
397 type
== PTR_TO_TCP_SOCK
||
398 type
== PTR_TO_XDP_SOCK
;
401 static bool reg_type_not_null(enum bpf_reg_type type
)
403 return type
== PTR_TO_SOCKET
||
404 type
== PTR_TO_TCP_SOCK
||
405 type
== PTR_TO_MAP_VALUE
||
406 type
== PTR_TO_SOCK_COMMON
;
409 static bool reg_type_may_be_null(enum bpf_reg_type type
)
411 return type
== PTR_TO_MAP_VALUE_OR_NULL
||
412 type
== PTR_TO_SOCKET_OR_NULL
||
413 type
== PTR_TO_SOCK_COMMON_OR_NULL
||
414 type
== PTR_TO_TCP_SOCK_OR_NULL
||
415 type
== PTR_TO_BTF_ID_OR_NULL
||
416 type
== PTR_TO_MEM_OR_NULL
||
417 type
== PTR_TO_RDONLY_BUF_OR_NULL
||
418 type
== PTR_TO_RDWR_BUF_OR_NULL
;
421 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state
*reg
)
423 return reg
->type
== PTR_TO_MAP_VALUE
&&
424 map_value_has_spin_lock(reg
->map_ptr
);
427 static bool reg_type_may_be_refcounted_or_null(enum bpf_reg_type type
)
429 return type
== PTR_TO_SOCKET
||
430 type
== PTR_TO_SOCKET_OR_NULL
||
431 type
== PTR_TO_TCP_SOCK
||
432 type
== PTR_TO_TCP_SOCK_OR_NULL
||
433 type
== PTR_TO_MEM
||
434 type
== PTR_TO_MEM_OR_NULL
;
437 static bool arg_type_may_be_refcounted(enum bpf_arg_type type
)
439 return type
== ARG_PTR_TO_SOCK_COMMON
;
442 static bool arg_type_may_be_null(enum bpf_arg_type type
)
444 return type
== ARG_PTR_TO_MAP_VALUE_OR_NULL
||
445 type
== ARG_PTR_TO_MEM_OR_NULL
||
446 type
== ARG_PTR_TO_CTX_OR_NULL
||
447 type
== ARG_PTR_TO_SOCKET_OR_NULL
||
448 type
== ARG_PTR_TO_ALLOC_MEM_OR_NULL
;
451 /* Determine whether the function releases some resources allocated by another
452 * function call. The first reference type argument will be assumed to be
453 * released by release_reference().
455 static bool is_release_function(enum bpf_func_id func_id
)
457 return func_id
== BPF_FUNC_sk_release
||
458 func_id
== BPF_FUNC_ringbuf_submit
||
459 func_id
== BPF_FUNC_ringbuf_discard
;
462 static bool may_be_acquire_function(enum bpf_func_id func_id
)
464 return func_id
== BPF_FUNC_sk_lookup_tcp
||
465 func_id
== BPF_FUNC_sk_lookup_udp
||
466 func_id
== BPF_FUNC_skc_lookup_tcp
||
467 func_id
== BPF_FUNC_map_lookup_elem
||
468 func_id
== BPF_FUNC_ringbuf_reserve
;
471 static bool is_acquire_function(enum bpf_func_id func_id
,
472 const struct bpf_map
*map
)
474 enum bpf_map_type map_type
= map
? map
->map_type
: BPF_MAP_TYPE_UNSPEC
;
476 if (func_id
== BPF_FUNC_sk_lookup_tcp
||
477 func_id
== BPF_FUNC_sk_lookup_udp
||
478 func_id
== BPF_FUNC_skc_lookup_tcp
||
479 func_id
== BPF_FUNC_ringbuf_reserve
)
482 if (func_id
== BPF_FUNC_map_lookup_elem
&&
483 (map_type
== BPF_MAP_TYPE_SOCKMAP
||
484 map_type
== BPF_MAP_TYPE_SOCKHASH
))
490 static bool is_ptr_cast_function(enum bpf_func_id func_id
)
492 return func_id
== BPF_FUNC_tcp_sock
||
493 func_id
== BPF_FUNC_sk_fullsock
||
494 func_id
== BPF_FUNC_skc_to_tcp_sock
||
495 func_id
== BPF_FUNC_skc_to_tcp6_sock
||
496 func_id
== BPF_FUNC_skc_to_udp6_sock
||
497 func_id
== BPF_FUNC_skc_to_tcp_timewait_sock
||
498 func_id
== BPF_FUNC_skc_to_tcp_request_sock
;
501 /* string representation of 'enum bpf_reg_type' */
502 static const char * const reg_type_str
[] = {
504 [SCALAR_VALUE
] = "inv",
505 [PTR_TO_CTX
] = "ctx",
506 [CONST_PTR_TO_MAP
] = "map_ptr",
507 [PTR_TO_MAP_VALUE
] = "map_value",
508 [PTR_TO_MAP_VALUE_OR_NULL
] = "map_value_or_null",
509 [PTR_TO_STACK
] = "fp",
510 [PTR_TO_PACKET
] = "pkt",
511 [PTR_TO_PACKET_META
] = "pkt_meta",
512 [PTR_TO_PACKET_END
] = "pkt_end",
513 [PTR_TO_FLOW_KEYS
] = "flow_keys",
514 [PTR_TO_SOCKET
] = "sock",
515 [PTR_TO_SOCKET_OR_NULL
] = "sock_or_null",
516 [PTR_TO_SOCK_COMMON
] = "sock_common",
517 [PTR_TO_SOCK_COMMON_OR_NULL
] = "sock_common_or_null",
518 [PTR_TO_TCP_SOCK
] = "tcp_sock",
519 [PTR_TO_TCP_SOCK_OR_NULL
] = "tcp_sock_or_null",
520 [PTR_TO_TP_BUFFER
] = "tp_buffer",
521 [PTR_TO_XDP_SOCK
] = "xdp_sock",
522 [PTR_TO_BTF_ID
] = "ptr_",
523 [PTR_TO_BTF_ID_OR_NULL
] = "ptr_or_null_",
524 [PTR_TO_PERCPU_BTF_ID
] = "percpu_ptr_",
525 [PTR_TO_MEM
] = "mem",
526 [PTR_TO_MEM_OR_NULL
] = "mem_or_null",
527 [PTR_TO_RDONLY_BUF
] = "rdonly_buf",
528 [PTR_TO_RDONLY_BUF_OR_NULL
] = "rdonly_buf_or_null",
529 [PTR_TO_RDWR_BUF
] = "rdwr_buf",
530 [PTR_TO_RDWR_BUF_OR_NULL
] = "rdwr_buf_or_null",
533 static char slot_type_char
[] = {
534 [STACK_INVALID
] = '?',
540 static void print_liveness(struct bpf_verifier_env
*env
,
541 enum bpf_reg_liveness live
)
543 if (live
& (REG_LIVE_READ
| REG_LIVE_WRITTEN
| REG_LIVE_DONE
))
545 if (live
& REG_LIVE_READ
)
547 if (live
& REG_LIVE_WRITTEN
)
549 if (live
& REG_LIVE_DONE
)
553 static struct bpf_func_state
*func(struct bpf_verifier_env
*env
,
554 const struct bpf_reg_state
*reg
)
556 struct bpf_verifier_state
*cur
= env
->cur_state
;
558 return cur
->frame
[reg
->frameno
];
561 static const char *kernel_type_name(const struct btf
* btf
, u32 id
)
563 return btf_name_by_offset(btf
, btf_type_by_id(btf
, id
)->name_off
);
566 static void print_verifier_state(struct bpf_verifier_env
*env
,
567 const struct bpf_func_state
*state
)
569 const struct bpf_reg_state
*reg
;
574 verbose(env
, " frame%d:", state
->frameno
);
575 for (i
= 0; i
< MAX_BPF_REG
; i
++) {
576 reg
= &state
->regs
[i
];
580 verbose(env
, " R%d", i
);
581 print_liveness(env
, reg
->live
);
582 verbose(env
, "=%s", reg_type_str
[t
]);
583 if (t
== SCALAR_VALUE
&& reg
->precise
)
585 if ((t
== SCALAR_VALUE
|| t
== PTR_TO_STACK
) &&
586 tnum_is_const(reg
->var_off
)) {
587 /* reg->off should be 0 for SCALAR_VALUE */
588 verbose(env
, "%lld", reg
->var_off
.value
+ reg
->off
);
590 if (t
== PTR_TO_BTF_ID
||
591 t
== PTR_TO_BTF_ID_OR_NULL
||
592 t
== PTR_TO_PERCPU_BTF_ID
)
593 verbose(env
, "%s", kernel_type_name(reg
->btf
, reg
->btf_id
));
594 verbose(env
, "(id=%d", reg
->id
);
595 if (reg_type_may_be_refcounted_or_null(t
))
596 verbose(env
, ",ref_obj_id=%d", reg
->ref_obj_id
);
597 if (t
!= SCALAR_VALUE
)
598 verbose(env
, ",off=%d", reg
->off
);
599 if (type_is_pkt_pointer(t
))
600 verbose(env
, ",r=%d", reg
->range
);
601 else if (t
== CONST_PTR_TO_MAP
||
602 t
== PTR_TO_MAP_VALUE
||
603 t
== PTR_TO_MAP_VALUE_OR_NULL
)
604 verbose(env
, ",ks=%d,vs=%d",
605 reg
->map_ptr
->key_size
,
606 reg
->map_ptr
->value_size
);
607 if (tnum_is_const(reg
->var_off
)) {
608 /* Typically an immediate SCALAR_VALUE, but
609 * could be a pointer whose offset is too big
612 verbose(env
, ",imm=%llx", reg
->var_off
.value
);
614 if (reg
->smin_value
!= reg
->umin_value
&&
615 reg
->smin_value
!= S64_MIN
)
616 verbose(env
, ",smin_value=%lld",
617 (long long)reg
->smin_value
);
618 if (reg
->smax_value
!= reg
->umax_value
&&
619 reg
->smax_value
!= S64_MAX
)
620 verbose(env
, ",smax_value=%lld",
621 (long long)reg
->smax_value
);
622 if (reg
->umin_value
!= 0)
623 verbose(env
, ",umin_value=%llu",
624 (unsigned long long)reg
->umin_value
);
625 if (reg
->umax_value
!= U64_MAX
)
626 verbose(env
, ",umax_value=%llu",
627 (unsigned long long)reg
->umax_value
);
628 if (!tnum_is_unknown(reg
->var_off
)) {
631 tnum_strn(tn_buf
, sizeof(tn_buf
), reg
->var_off
);
632 verbose(env
, ",var_off=%s", tn_buf
);
634 if (reg
->s32_min_value
!= reg
->smin_value
&&
635 reg
->s32_min_value
!= S32_MIN
)
636 verbose(env
, ",s32_min_value=%d",
637 (int)(reg
->s32_min_value
));
638 if (reg
->s32_max_value
!= reg
->smax_value
&&
639 reg
->s32_max_value
!= S32_MAX
)
640 verbose(env
, ",s32_max_value=%d",
641 (int)(reg
->s32_max_value
));
642 if (reg
->u32_min_value
!= reg
->umin_value
&&
643 reg
->u32_min_value
!= U32_MIN
)
644 verbose(env
, ",u32_min_value=%d",
645 (int)(reg
->u32_min_value
));
646 if (reg
->u32_max_value
!= reg
->umax_value
&&
647 reg
->u32_max_value
!= U32_MAX
)
648 verbose(env
, ",u32_max_value=%d",
649 (int)(reg
->u32_max_value
));
654 for (i
= 0; i
< state
->allocated_stack
/ BPF_REG_SIZE
; i
++) {
655 char types_buf
[BPF_REG_SIZE
+ 1];
659 for (j
= 0; j
< BPF_REG_SIZE
; j
++) {
660 if (state
->stack
[i
].slot_type
[j
] != STACK_INVALID
)
662 types_buf
[j
] = slot_type_char
[
663 state
->stack
[i
].slot_type
[j
]];
665 types_buf
[BPF_REG_SIZE
] = 0;
668 verbose(env
, " fp%d", (-i
- 1) * BPF_REG_SIZE
);
669 print_liveness(env
, state
->stack
[i
].spilled_ptr
.live
);
670 if (state
->stack
[i
].slot_type
[0] == STACK_SPILL
) {
671 reg
= &state
->stack
[i
].spilled_ptr
;
673 verbose(env
, "=%s", reg_type_str
[t
]);
674 if (t
== SCALAR_VALUE
&& reg
->precise
)
676 if (t
== SCALAR_VALUE
&& tnum_is_const(reg
->var_off
))
677 verbose(env
, "%lld", reg
->var_off
.value
+ reg
->off
);
679 verbose(env
, "=%s", types_buf
);
682 if (state
->acquired_refs
&& state
->refs
[0].id
) {
683 verbose(env
, " refs=%d", state
->refs
[0].id
);
684 for (i
= 1; i
< state
->acquired_refs
; i
++)
685 if (state
->refs
[i
].id
)
686 verbose(env
, ",%d", state
->refs
[i
].id
);
691 #define COPY_STATE_FN(NAME, COUNT, FIELD, SIZE) \
692 static int copy_##NAME##_state(struct bpf_func_state *dst, \
693 const struct bpf_func_state *src) \
697 if (WARN_ON_ONCE(dst->COUNT < src->COUNT)) { \
698 /* internal bug, make state invalid to reject the program */ \
699 memset(dst, 0, sizeof(*dst)); \
702 memcpy(dst->FIELD, src->FIELD, \
703 sizeof(*src->FIELD) * (src->COUNT / SIZE)); \
706 /* copy_reference_state() */
707 COPY_STATE_FN(reference
, acquired_refs
, refs
, 1)
708 /* copy_stack_state() */
709 COPY_STATE_FN(stack
, allocated_stack
, stack
, BPF_REG_SIZE
)
712 #define REALLOC_STATE_FN(NAME, COUNT, FIELD, SIZE) \
713 static int realloc_##NAME##_state(struct bpf_func_state *state, int size, \
716 u32 old_size = state->COUNT; \
717 struct bpf_##NAME##_state *new_##FIELD; \
718 int slot = size / SIZE; \
720 if (size <= old_size || !size) { \
723 state->COUNT = slot * SIZE; \
724 if (!size && old_size) { \
725 kfree(state->FIELD); \
726 state->FIELD = NULL; \
730 new_##FIELD = kmalloc_array(slot, sizeof(struct bpf_##NAME##_state), \
736 memcpy(new_##FIELD, state->FIELD, \
737 sizeof(*new_##FIELD) * (old_size / SIZE)); \
738 memset(new_##FIELD + old_size / SIZE, 0, \
739 sizeof(*new_##FIELD) * (size - old_size) / SIZE); \
741 state->COUNT = slot * SIZE; \
742 kfree(state->FIELD); \
743 state->FIELD = new_##FIELD; \
746 /* realloc_reference_state() */
747 REALLOC_STATE_FN(reference
, acquired_refs
, refs
, 1)
748 /* realloc_stack_state() */
749 REALLOC_STATE_FN(stack
, allocated_stack
, stack
, BPF_REG_SIZE
)
750 #undef REALLOC_STATE_FN
752 /* do_check() starts with zero-sized stack in struct bpf_verifier_state to
753 * make it consume minimal amount of memory. check_stack_write() access from
754 * the program calls into realloc_func_state() to grow the stack size.
755 * Note there is a non-zero 'parent' pointer inside bpf_verifier_state
756 * which realloc_stack_state() copies over. It points to previous
757 * bpf_verifier_state which is never reallocated.
759 static int realloc_func_state(struct bpf_func_state
*state
, int stack_size
,
760 int refs_size
, bool copy_old
)
762 int err
= realloc_reference_state(state
, refs_size
, copy_old
);
765 return realloc_stack_state(state
, stack_size
, copy_old
);
768 /* Acquire a pointer id from the env and update the state->refs to include
769 * this new pointer reference.
770 * On success, returns a valid pointer id to associate with the register
771 * On failure, returns a negative errno.
773 static int acquire_reference_state(struct bpf_verifier_env
*env
, int insn_idx
)
775 struct bpf_func_state
*state
= cur_func(env
);
776 int new_ofs
= state
->acquired_refs
;
779 err
= realloc_reference_state(state
, state
->acquired_refs
+ 1, true);
783 state
->refs
[new_ofs
].id
= id
;
784 state
->refs
[new_ofs
].insn_idx
= insn_idx
;
789 /* release function corresponding to acquire_reference_state(). Idempotent. */
790 static int release_reference_state(struct bpf_func_state
*state
, int ptr_id
)
794 last_idx
= state
->acquired_refs
- 1;
795 for (i
= 0; i
< state
->acquired_refs
; i
++) {
796 if (state
->refs
[i
].id
== ptr_id
) {
797 if (last_idx
&& i
!= last_idx
)
798 memcpy(&state
->refs
[i
], &state
->refs
[last_idx
],
799 sizeof(*state
->refs
));
800 memset(&state
->refs
[last_idx
], 0, sizeof(*state
->refs
));
801 state
->acquired_refs
--;
808 static int transfer_reference_state(struct bpf_func_state
*dst
,
809 struct bpf_func_state
*src
)
811 int err
= realloc_reference_state(dst
, src
->acquired_refs
, false);
814 err
= copy_reference_state(dst
, src
);
820 static void free_func_state(struct bpf_func_state
*state
)
829 static void clear_jmp_history(struct bpf_verifier_state
*state
)
831 kfree(state
->jmp_history
);
832 state
->jmp_history
= NULL
;
833 state
->jmp_history_cnt
= 0;
836 static void free_verifier_state(struct bpf_verifier_state
*state
,
841 for (i
= 0; i
<= state
->curframe
; i
++) {
842 free_func_state(state
->frame
[i
]);
843 state
->frame
[i
] = NULL
;
845 clear_jmp_history(state
);
850 /* copy verifier state from src to dst growing dst stack space
851 * when necessary to accommodate larger src stack
853 static int copy_func_state(struct bpf_func_state
*dst
,
854 const struct bpf_func_state
*src
)
858 err
= realloc_func_state(dst
, src
->allocated_stack
, src
->acquired_refs
,
862 memcpy(dst
, src
, offsetof(struct bpf_func_state
, acquired_refs
));
863 err
= copy_reference_state(dst
, src
);
866 return copy_stack_state(dst
, src
);
869 static int copy_verifier_state(struct bpf_verifier_state
*dst_state
,
870 const struct bpf_verifier_state
*src
)
872 struct bpf_func_state
*dst
;
873 u32 jmp_sz
= sizeof(struct bpf_idx_pair
) * src
->jmp_history_cnt
;
876 if (dst_state
->jmp_history_cnt
< src
->jmp_history_cnt
) {
877 kfree(dst_state
->jmp_history
);
878 dst_state
->jmp_history
= kmalloc(jmp_sz
, GFP_USER
);
879 if (!dst_state
->jmp_history
)
882 memcpy(dst_state
->jmp_history
, src
->jmp_history
, jmp_sz
);
883 dst_state
->jmp_history_cnt
= src
->jmp_history_cnt
;
885 /* if dst has more stack frames then src frame, free them */
886 for (i
= src
->curframe
+ 1; i
<= dst_state
->curframe
; i
++) {
887 free_func_state(dst_state
->frame
[i
]);
888 dst_state
->frame
[i
] = NULL
;
890 dst_state
->speculative
= src
->speculative
;
891 dst_state
->curframe
= src
->curframe
;
892 dst_state
->active_spin_lock
= src
->active_spin_lock
;
893 dst_state
->branches
= src
->branches
;
894 dst_state
->parent
= src
->parent
;
895 dst_state
->first_insn_idx
= src
->first_insn_idx
;
896 dst_state
->last_insn_idx
= src
->last_insn_idx
;
897 for (i
= 0; i
<= src
->curframe
; i
++) {
898 dst
= dst_state
->frame
[i
];
900 dst
= kzalloc(sizeof(*dst
), GFP_KERNEL
);
903 dst_state
->frame
[i
] = dst
;
905 err
= copy_func_state(dst
, src
->frame
[i
]);
912 static void update_branch_counts(struct bpf_verifier_env
*env
, struct bpf_verifier_state
*st
)
915 u32 br
= --st
->branches
;
917 /* WARN_ON(br > 1) technically makes sense here,
918 * but see comment in push_stack(), hence:
920 WARN_ONCE((int)br
< 0,
921 "BUG update_branch_counts:branches_to_explore=%d\n",
929 static int pop_stack(struct bpf_verifier_env
*env
, int *prev_insn_idx
,
930 int *insn_idx
, bool pop_log
)
932 struct bpf_verifier_state
*cur
= env
->cur_state
;
933 struct bpf_verifier_stack_elem
*elem
, *head
= env
->head
;
936 if (env
->head
== NULL
)
940 err
= copy_verifier_state(cur
, &head
->st
);
945 bpf_vlog_reset(&env
->log
, head
->log_pos
);
947 *insn_idx
= head
->insn_idx
;
949 *prev_insn_idx
= head
->prev_insn_idx
;
951 free_verifier_state(&head
->st
, false);
958 static struct bpf_verifier_state
*push_stack(struct bpf_verifier_env
*env
,
959 int insn_idx
, int prev_insn_idx
,
962 struct bpf_verifier_state
*cur
= env
->cur_state
;
963 struct bpf_verifier_stack_elem
*elem
;
966 elem
= kzalloc(sizeof(struct bpf_verifier_stack_elem
), GFP_KERNEL
);
970 elem
->insn_idx
= insn_idx
;
971 elem
->prev_insn_idx
= prev_insn_idx
;
972 elem
->next
= env
->head
;
973 elem
->log_pos
= env
->log
.len_used
;
976 err
= copy_verifier_state(&elem
->st
, cur
);
979 elem
->st
.speculative
|= speculative
;
980 if (env
->stack_size
> BPF_COMPLEXITY_LIMIT_JMP_SEQ
) {
981 verbose(env
, "The sequence of %d jumps is too complex.\n",
985 if (elem
->st
.parent
) {
986 ++elem
->st
.parent
->branches
;
987 /* WARN_ON(branches > 2) technically makes sense here,
989 * 1. speculative states will bump 'branches' for non-branch
991 * 2. is_state_visited() heuristics may decide not to create
992 * a new state for a sequence of branches and all such current
993 * and cloned states will be pointing to a single parent state
994 * which might have large 'branches' count.
999 free_verifier_state(env
->cur_state
, true);
1000 env
->cur_state
= NULL
;
1001 /* pop all elements and return */
1002 while (!pop_stack(env
, NULL
, NULL
, false));
1006 #define CALLER_SAVED_REGS 6
1007 static const int caller_saved
[CALLER_SAVED_REGS
] = {
1008 BPF_REG_0
, BPF_REG_1
, BPF_REG_2
, BPF_REG_3
, BPF_REG_4
, BPF_REG_5
1011 static void __mark_reg_not_init(const struct bpf_verifier_env
*env
,
1012 struct bpf_reg_state
*reg
);
1014 /* This helper doesn't clear reg->id */
1015 static void ___mark_reg_known(struct bpf_reg_state
*reg
, u64 imm
)
1017 reg
->var_off
= tnum_const(imm
);
1018 reg
->smin_value
= (s64
)imm
;
1019 reg
->smax_value
= (s64
)imm
;
1020 reg
->umin_value
= imm
;
1021 reg
->umax_value
= imm
;
1023 reg
->s32_min_value
= (s32
)imm
;
1024 reg
->s32_max_value
= (s32
)imm
;
1025 reg
->u32_min_value
= (u32
)imm
;
1026 reg
->u32_max_value
= (u32
)imm
;
1029 /* Mark the unknown part of a register (variable offset or scalar value) as
1030 * known to have the value @imm.
1032 static void __mark_reg_known(struct bpf_reg_state
*reg
, u64 imm
)
1034 /* Clear id, off, and union(map_ptr, range) */
1035 memset(((u8
*)reg
) + sizeof(reg
->type
), 0,
1036 offsetof(struct bpf_reg_state
, var_off
) - sizeof(reg
->type
));
1037 ___mark_reg_known(reg
, imm
);
1040 static void __mark_reg32_known(struct bpf_reg_state
*reg
, u64 imm
)
1042 reg
->var_off
= tnum_const_subreg(reg
->var_off
, imm
);
1043 reg
->s32_min_value
= (s32
)imm
;
1044 reg
->s32_max_value
= (s32
)imm
;
1045 reg
->u32_min_value
= (u32
)imm
;
1046 reg
->u32_max_value
= (u32
)imm
;
1049 /* Mark the 'variable offset' part of a register as zero. This should be
1050 * used only on registers holding a pointer type.
1052 static void __mark_reg_known_zero(struct bpf_reg_state
*reg
)
1054 __mark_reg_known(reg
, 0);
1057 static void __mark_reg_const_zero(struct bpf_reg_state
*reg
)
1059 __mark_reg_known(reg
, 0);
1060 reg
->type
= SCALAR_VALUE
;
1063 static void mark_reg_known_zero(struct bpf_verifier_env
*env
,
1064 struct bpf_reg_state
*regs
, u32 regno
)
1066 if (WARN_ON(regno
>= MAX_BPF_REG
)) {
1067 verbose(env
, "mark_reg_known_zero(regs, %u)\n", regno
);
1068 /* Something bad happened, let's kill all regs */
1069 for (regno
= 0; regno
< MAX_BPF_REG
; regno
++)
1070 __mark_reg_not_init(env
, regs
+ regno
);
1073 __mark_reg_known_zero(regs
+ regno
);
1076 static bool reg_is_pkt_pointer(const struct bpf_reg_state
*reg
)
1078 return type_is_pkt_pointer(reg
->type
);
1081 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state
*reg
)
1083 return reg_is_pkt_pointer(reg
) ||
1084 reg
->type
== PTR_TO_PACKET_END
;
1087 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
1088 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state
*reg
,
1089 enum bpf_reg_type which
)
1091 /* The register can already have a range from prior markings.
1092 * This is fine as long as it hasn't been advanced from its
1095 return reg
->type
== which
&&
1098 tnum_equals_const(reg
->var_off
, 0);
1101 /* Reset the min/max bounds of a register */
1102 static void __mark_reg_unbounded(struct bpf_reg_state
*reg
)
1104 reg
->smin_value
= S64_MIN
;
1105 reg
->smax_value
= S64_MAX
;
1106 reg
->umin_value
= 0;
1107 reg
->umax_value
= U64_MAX
;
1109 reg
->s32_min_value
= S32_MIN
;
1110 reg
->s32_max_value
= S32_MAX
;
1111 reg
->u32_min_value
= 0;
1112 reg
->u32_max_value
= U32_MAX
;
1115 static void __mark_reg64_unbounded(struct bpf_reg_state
*reg
)
1117 reg
->smin_value
= S64_MIN
;
1118 reg
->smax_value
= S64_MAX
;
1119 reg
->umin_value
= 0;
1120 reg
->umax_value
= U64_MAX
;
1123 static void __mark_reg32_unbounded(struct bpf_reg_state
*reg
)
1125 reg
->s32_min_value
= S32_MIN
;
1126 reg
->s32_max_value
= S32_MAX
;
1127 reg
->u32_min_value
= 0;
1128 reg
->u32_max_value
= U32_MAX
;
1131 static void __update_reg32_bounds(struct bpf_reg_state
*reg
)
1133 struct tnum var32_off
= tnum_subreg(reg
->var_off
);
1135 /* min signed is max(sign bit) | min(other bits) */
1136 reg
->s32_min_value
= max_t(s32
, reg
->s32_min_value
,
1137 var32_off
.value
| (var32_off
.mask
& S32_MIN
));
1138 /* max signed is min(sign bit) | max(other bits) */
1139 reg
->s32_max_value
= min_t(s32
, reg
->s32_max_value
,
1140 var32_off
.value
| (var32_off
.mask
& S32_MAX
));
1141 reg
->u32_min_value
= max_t(u32
, reg
->u32_min_value
, (u32
)var32_off
.value
);
1142 reg
->u32_max_value
= min(reg
->u32_max_value
,
1143 (u32
)(var32_off
.value
| var32_off
.mask
));
1146 static void __update_reg64_bounds(struct bpf_reg_state
*reg
)
1148 /* min signed is max(sign bit) | min(other bits) */
1149 reg
->smin_value
= max_t(s64
, reg
->smin_value
,
1150 reg
->var_off
.value
| (reg
->var_off
.mask
& S64_MIN
));
1151 /* max signed is min(sign bit) | max(other bits) */
1152 reg
->smax_value
= min_t(s64
, reg
->smax_value
,
1153 reg
->var_off
.value
| (reg
->var_off
.mask
& S64_MAX
));
1154 reg
->umin_value
= max(reg
->umin_value
, reg
->var_off
.value
);
1155 reg
->umax_value
= min(reg
->umax_value
,
1156 reg
->var_off
.value
| reg
->var_off
.mask
);
1159 static void __update_reg_bounds(struct bpf_reg_state
*reg
)
1161 __update_reg32_bounds(reg
);
1162 __update_reg64_bounds(reg
);
1165 /* Uses signed min/max values to inform unsigned, and vice-versa */
1166 static void __reg32_deduce_bounds(struct bpf_reg_state
*reg
)
1168 /* Learn sign from signed bounds.
1169 * If we cannot cross the sign boundary, then signed and unsigned bounds
1170 * are the same, so combine. This works even in the negative case, e.g.
1171 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1173 if (reg
->s32_min_value
>= 0 || reg
->s32_max_value
< 0) {
1174 reg
->s32_min_value
= reg
->u32_min_value
=
1175 max_t(u32
, reg
->s32_min_value
, reg
->u32_min_value
);
1176 reg
->s32_max_value
= reg
->u32_max_value
=
1177 min_t(u32
, reg
->s32_max_value
, reg
->u32_max_value
);
1180 /* Learn sign from unsigned bounds. Signed bounds cross the sign
1181 * boundary, so we must be careful.
1183 if ((s32
)reg
->u32_max_value
>= 0) {
1184 /* Positive. We can't learn anything from the smin, but smax
1185 * is positive, hence safe.
1187 reg
->s32_min_value
= reg
->u32_min_value
;
1188 reg
->s32_max_value
= reg
->u32_max_value
=
1189 min_t(u32
, reg
->s32_max_value
, reg
->u32_max_value
);
1190 } else if ((s32
)reg
->u32_min_value
< 0) {
1191 /* Negative. We can't learn anything from the smax, but smin
1192 * is negative, hence safe.
1194 reg
->s32_min_value
= reg
->u32_min_value
=
1195 max_t(u32
, reg
->s32_min_value
, reg
->u32_min_value
);
1196 reg
->s32_max_value
= reg
->u32_max_value
;
1200 static void __reg64_deduce_bounds(struct bpf_reg_state
*reg
)
1202 /* Learn sign from signed bounds.
1203 * If we cannot cross the sign boundary, then signed and unsigned bounds
1204 * are the same, so combine. This works even in the negative case, e.g.
1205 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1207 if (reg
->smin_value
>= 0 || reg
->smax_value
< 0) {
1208 reg
->smin_value
= reg
->umin_value
= max_t(u64
, reg
->smin_value
,
1210 reg
->smax_value
= reg
->umax_value
= min_t(u64
, reg
->smax_value
,
1214 /* Learn sign from unsigned bounds. Signed bounds cross the sign
1215 * boundary, so we must be careful.
1217 if ((s64
)reg
->umax_value
>= 0) {
1218 /* Positive. We can't learn anything from the smin, but smax
1219 * is positive, hence safe.
1221 reg
->smin_value
= reg
->umin_value
;
1222 reg
->smax_value
= reg
->umax_value
= min_t(u64
, reg
->smax_value
,
1224 } else if ((s64
)reg
->umin_value
< 0) {
1225 /* Negative. We can't learn anything from the smax, but smin
1226 * is negative, hence safe.
1228 reg
->smin_value
= reg
->umin_value
= max_t(u64
, reg
->smin_value
,
1230 reg
->smax_value
= reg
->umax_value
;
1234 static void __reg_deduce_bounds(struct bpf_reg_state
*reg
)
1236 __reg32_deduce_bounds(reg
);
1237 __reg64_deduce_bounds(reg
);
1240 /* Attempts to improve var_off based on unsigned min/max information */
1241 static void __reg_bound_offset(struct bpf_reg_state
*reg
)
1243 struct tnum var64_off
= tnum_intersect(reg
->var_off
,
1244 tnum_range(reg
->umin_value
,
1246 struct tnum var32_off
= tnum_intersect(tnum_subreg(reg
->var_off
),
1247 tnum_range(reg
->u32_min_value
,
1248 reg
->u32_max_value
));
1250 reg
->var_off
= tnum_or(tnum_clear_subreg(var64_off
), var32_off
);
1253 static void __reg_assign_32_into_64(struct bpf_reg_state
*reg
)
1255 reg
->umin_value
= reg
->u32_min_value
;
1256 reg
->umax_value
= reg
->u32_max_value
;
1257 /* Attempt to pull 32-bit signed bounds into 64-bit bounds
1258 * but must be positive otherwise set to worse case bounds
1259 * and refine later from tnum.
1261 if (reg
->s32_min_value
>= 0 && reg
->s32_max_value
>= 0)
1262 reg
->smax_value
= reg
->s32_max_value
;
1264 reg
->smax_value
= U32_MAX
;
1265 if (reg
->s32_min_value
>= 0)
1266 reg
->smin_value
= reg
->s32_min_value
;
1268 reg
->smin_value
= 0;
1271 static void __reg_combine_32_into_64(struct bpf_reg_state
*reg
)
1273 /* special case when 64-bit register has upper 32-bit register
1274 * zeroed. Typically happens after zext or <<32, >>32 sequence
1275 * allowing us to use 32-bit bounds directly,
1277 if (tnum_equals_const(tnum_clear_subreg(reg
->var_off
), 0)) {
1278 __reg_assign_32_into_64(reg
);
1280 /* Otherwise the best we can do is push lower 32bit known and
1281 * unknown bits into register (var_off set from jmp logic)
1282 * then learn as much as possible from the 64-bit tnum
1283 * known and unknown bits. The previous smin/smax bounds are
1284 * invalid here because of jmp32 compare so mark them unknown
1285 * so they do not impact tnum bounds calculation.
1287 __mark_reg64_unbounded(reg
);
1288 __update_reg_bounds(reg
);
1291 /* Intersecting with the old var_off might have improved our bounds
1292 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1293 * then new var_off is (0; 0x7f...fc) which improves our umax.
1295 __reg_deduce_bounds(reg
);
1296 __reg_bound_offset(reg
);
1297 __update_reg_bounds(reg
);
1300 static bool __reg64_bound_s32(s64 a
)
1302 return a
> S32_MIN
&& a
< S32_MAX
;
1305 static bool __reg64_bound_u32(u64 a
)
1307 if (a
> U32_MIN
&& a
< U32_MAX
)
1312 static void __reg_combine_64_into_32(struct bpf_reg_state
*reg
)
1314 __mark_reg32_unbounded(reg
);
1316 if (__reg64_bound_s32(reg
->smin_value
) && __reg64_bound_s32(reg
->smax_value
)) {
1317 reg
->s32_min_value
= (s32
)reg
->smin_value
;
1318 reg
->s32_max_value
= (s32
)reg
->smax_value
;
1320 if (__reg64_bound_u32(reg
->umin_value
))
1321 reg
->u32_min_value
= (u32
)reg
->umin_value
;
1322 if (__reg64_bound_u32(reg
->umax_value
))
1323 reg
->u32_max_value
= (u32
)reg
->umax_value
;
1325 /* Intersecting with the old var_off might have improved our bounds
1326 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1327 * then new var_off is (0; 0x7f...fc) which improves our umax.
1329 __reg_deduce_bounds(reg
);
1330 __reg_bound_offset(reg
);
1331 __update_reg_bounds(reg
);
1334 /* Mark a register as having a completely unknown (scalar) value. */
1335 static void __mark_reg_unknown(const struct bpf_verifier_env
*env
,
1336 struct bpf_reg_state
*reg
)
1339 * Clear type, id, off, and union(map_ptr, range) and
1340 * padding between 'type' and union
1342 memset(reg
, 0, offsetof(struct bpf_reg_state
, var_off
));
1343 reg
->type
= SCALAR_VALUE
;
1344 reg
->var_off
= tnum_unknown
;
1346 reg
->precise
= env
->subprog_cnt
> 1 || !env
->bpf_capable
;
1347 __mark_reg_unbounded(reg
);
1350 static void mark_reg_unknown(struct bpf_verifier_env
*env
,
1351 struct bpf_reg_state
*regs
, u32 regno
)
1353 if (WARN_ON(regno
>= MAX_BPF_REG
)) {
1354 verbose(env
, "mark_reg_unknown(regs, %u)\n", regno
);
1355 /* Something bad happened, let's kill all regs except FP */
1356 for (regno
= 0; regno
< BPF_REG_FP
; regno
++)
1357 __mark_reg_not_init(env
, regs
+ regno
);
1360 __mark_reg_unknown(env
, regs
+ regno
);
1363 static void __mark_reg_not_init(const struct bpf_verifier_env
*env
,
1364 struct bpf_reg_state
*reg
)
1366 __mark_reg_unknown(env
, reg
);
1367 reg
->type
= NOT_INIT
;
1370 static void mark_reg_not_init(struct bpf_verifier_env
*env
,
1371 struct bpf_reg_state
*regs
, u32 regno
)
1373 if (WARN_ON(regno
>= MAX_BPF_REG
)) {
1374 verbose(env
, "mark_reg_not_init(regs, %u)\n", regno
);
1375 /* Something bad happened, let's kill all regs except FP */
1376 for (regno
= 0; regno
< BPF_REG_FP
; regno
++)
1377 __mark_reg_not_init(env
, regs
+ regno
);
1380 __mark_reg_not_init(env
, regs
+ regno
);
1383 static void mark_btf_ld_reg(struct bpf_verifier_env
*env
,
1384 struct bpf_reg_state
*regs
, u32 regno
,
1385 enum bpf_reg_type reg_type
,
1386 struct btf
*btf
, u32 btf_id
)
1388 if (reg_type
== SCALAR_VALUE
) {
1389 mark_reg_unknown(env
, regs
, regno
);
1392 mark_reg_known_zero(env
, regs
, regno
);
1393 regs
[regno
].type
= PTR_TO_BTF_ID
;
1394 regs
[regno
].btf
= btf
;
1395 regs
[regno
].btf_id
= btf_id
;
1398 #define DEF_NOT_SUBREG (0)
1399 static void init_reg_state(struct bpf_verifier_env
*env
,
1400 struct bpf_func_state
*state
)
1402 struct bpf_reg_state
*regs
= state
->regs
;
1405 for (i
= 0; i
< MAX_BPF_REG
; i
++) {
1406 mark_reg_not_init(env
, regs
, i
);
1407 regs
[i
].live
= REG_LIVE_NONE
;
1408 regs
[i
].parent
= NULL
;
1409 regs
[i
].subreg_def
= DEF_NOT_SUBREG
;
1413 regs
[BPF_REG_FP
].type
= PTR_TO_STACK
;
1414 mark_reg_known_zero(env
, regs
, BPF_REG_FP
);
1415 regs
[BPF_REG_FP
].frameno
= state
->frameno
;
1418 #define BPF_MAIN_FUNC (-1)
1419 static void init_func_state(struct bpf_verifier_env
*env
,
1420 struct bpf_func_state
*state
,
1421 int callsite
, int frameno
, int subprogno
)
1423 state
->callsite
= callsite
;
1424 state
->frameno
= frameno
;
1425 state
->subprogno
= subprogno
;
1426 init_reg_state(env
, state
);
1430 SRC_OP
, /* register is used as source operand */
1431 DST_OP
, /* register is used as destination operand */
1432 DST_OP_NO_MARK
/* same as above, check only, don't mark */
1435 static int cmp_subprogs(const void *a
, const void *b
)
1437 return ((struct bpf_subprog_info
*)a
)->start
-
1438 ((struct bpf_subprog_info
*)b
)->start
;
1441 static int find_subprog(struct bpf_verifier_env
*env
, int off
)
1443 struct bpf_subprog_info
*p
;
1445 p
= bsearch(&off
, env
->subprog_info
, env
->subprog_cnt
,
1446 sizeof(env
->subprog_info
[0]), cmp_subprogs
);
1449 return p
- env
->subprog_info
;
1453 static int add_subprog(struct bpf_verifier_env
*env
, int off
)
1455 int insn_cnt
= env
->prog
->len
;
1458 if (off
>= insn_cnt
|| off
< 0) {
1459 verbose(env
, "call to invalid destination\n");
1462 ret
= find_subprog(env
, off
);
1465 if (env
->subprog_cnt
>= BPF_MAX_SUBPROGS
) {
1466 verbose(env
, "too many subprograms\n");
1469 env
->subprog_info
[env
->subprog_cnt
++].start
= off
;
1470 sort(env
->subprog_info
, env
->subprog_cnt
,
1471 sizeof(env
->subprog_info
[0]), cmp_subprogs
, NULL
);
1475 static int check_subprogs(struct bpf_verifier_env
*env
)
1477 int i
, ret
, subprog_start
, subprog_end
, off
, cur_subprog
= 0;
1478 struct bpf_subprog_info
*subprog
= env
->subprog_info
;
1479 struct bpf_insn
*insn
= env
->prog
->insnsi
;
1480 int insn_cnt
= env
->prog
->len
;
1482 /* Add entry function. */
1483 ret
= add_subprog(env
, 0);
1487 /* determine subprog starts. The end is one before the next starts */
1488 for (i
= 0; i
< insn_cnt
; i
++) {
1489 if (insn
[i
].code
!= (BPF_JMP
| BPF_CALL
))
1491 if (insn
[i
].src_reg
!= BPF_PSEUDO_CALL
)
1493 if (!env
->bpf_capable
) {
1495 "function calls to other bpf functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
1498 ret
= add_subprog(env
, i
+ insn
[i
].imm
+ 1);
1503 /* Add a fake 'exit' subprog which could simplify subprog iteration
1504 * logic. 'subprog_cnt' should not be increased.
1506 subprog
[env
->subprog_cnt
].start
= insn_cnt
;
1508 if (env
->log
.level
& BPF_LOG_LEVEL2
)
1509 for (i
= 0; i
< env
->subprog_cnt
; i
++)
1510 verbose(env
, "func#%d @%d\n", i
, subprog
[i
].start
);
1512 /* now check that all jumps are within the same subprog */
1513 subprog_start
= subprog
[cur_subprog
].start
;
1514 subprog_end
= subprog
[cur_subprog
+ 1].start
;
1515 for (i
= 0; i
< insn_cnt
; i
++) {
1516 u8 code
= insn
[i
].code
;
1518 if (code
== (BPF_JMP
| BPF_CALL
) &&
1519 insn
[i
].imm
== BPF_FUNC_tail_call
&&
1520 insn
[i
].src_reg
!= BPF_PSEUDO_CALL
)
1521 subprog
[cur_subprog
].has_tail_call
= true;
1522 if (BPF_CLASS(code
) == BPF_LD
&&
1523 (BPF_MODE(code
) == BPF_ABS
|| BPF_MODE(code
) == BPF_IND
))
1524 subprog
[cur_subprog
].has_ld_abs
= true;
1525 if (BPF_CLASS(code
) != BPF_JMP
&& BPF_CLASS(code
) != BPF_JMP32
)
1527 if (BPF_OP(code
) == BPF_EXIT
|| BPF_OP(code
) == BPF_CALL
)
1529 off
= i
+ insn
[i
].off
+ 1;
1530 if (off
< subprog_start
|| off
>= subprog_end
) {
1531 verbose(env
, "jump out of range from insn %d to %d\n", i
, off
);
1535 if (i
== subprog_end
- 1) {
1536 /* to avoid fall-through from one subprog into another
1537 * the last insn of the subprog should be either exit
1538 * or unconditional jump back
1540 if (code
!= (BPF_JMP
| BPF_EXIT
) &&
1541 code
!= (BPF_JMP
| BPF_JA
)) {
1542 verbose(env
, "last insn is not an exit or jmp\n");
1545 subprog_start
= subprog_end
;
1547 if (cur_subprog
< env
->subprog_cnt
)
1548 subprog_end
= subprog
[cur_subprog
+ 1].start
;
1554 /* Parentage chain of this register (or stack slot) should take care of all
1555 * issues like callee-saved registers, stack slot allocation time, etc.
1557 static int mark_reg_read(struct bpf_verifier_env
*env
,
1558 const struct bpf_reg_state
*state
,
1559 struct bpf_reg_state
*parent
, u8 flag
)
1561 bool writes
= parent
== state
->parent
; /* Observe write marks */
1565 /* if read wasn't screened by an earlier write ... */
1566 if (writes
&& state
->live
& REG_LIVE_WRITTEN
)
1568 if (parent
->live
& REG_LIVE_DONE
) {
1569 verbose(env
, "verifier BUG type %s var_off %lld off %d\n",
1570 reg_type_str
[parent
->type
],
1571 parent
->var_off
.value
, parent
->off
);
1574 /* The first condition is more likely to be true than the
1575 * second, checked it first.
1577 if ((parent
->live
& REG_LIVE_READ
) == flag
||
1578 parent
->live
& REG_LIVE_READ64
)
1579 /* The parentage chain never changes and
1580 * this parent was already marked as LIVE_READ.
1581 * There is no need to keep walking the chain again and
1582 * keep re-marking all parents as LIVE_READ.
1583 * This case happens when the same register is read
1584 * multiple times without writes into it in-between.
1585 * Also, if parent has the stronger REG_LIVE_READ64 set,
1586 * then no need to set the weak REG_LIVE_READ32.
1589 /* ... then we depend on parent's value */
1590 parent
->live
|= flag
;
1591 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
1592 if (flag
== REG_LIVE_READ64
)
1593 parent
->live
&= ~REG_LIVE_READ32
;
1595 parent
= state
->parent
;
1600 if (env
->longest_mark_read_walk
< cnt
)
1601 env
->longest_mark_read_walk
= cnt
;
1605 /* This function is supposed to be used by the following 32-bit optimization
1606 * code only. It returns TRUE if the source or destination register operates
1607 * on 64-bit, otherwise return FALSE.
1609 static bool is_reg64(struct bpf_verifier_env
*env
, struct bpf_insn
*insn
,
1610 u32 regno
, struct bpf_reg_state
*reg
, enum reg_arg_type t
)
1615 class = BPF_CLASS(code
);
1617 if (class == BPF_JMP
) {
1618 /* BPF_EXIT for "main" will reach here. Return TRUE
1623 if (op
== BPF_CALL
) {
1624 /* BPF to BPF call will reach here because of marking
1625 * caller saved clobber with DST_OP_NO_MARK for which we
1626 * don't care the register def because they are anyway
1627 * marked as NOT_INIT already.
1629 if (insn
->src_reg
== BPF_PSEUDO_CALL
)
1631 /* Helper call will reach here because of arg type
1632 * check, conservatively return TRUE.
1641 if (class == BPF_ALU64
|| class == BPF_JMP
||
1642 /* BPF_END always use BPF_ALU class. */
1643 (class == BPF_ALU
&& op
== BPF_END
&& insn
->imm
== 64))
1646 if (class == BPF_ALU
|| class == BPF_JMP32
)
1649 if (class == BPF_LDX
) {
1651 return BPF_SIZE(code
) == BPF_DW
;
1652 /* LDX source must be ptr. */
1656 if (class == BPF_STX
) {
1657 if (reg
->type
!= SCALAR_VALUE
)
1659 return BPF_SIZE(code
) == BPF_DW
;
1662 if (class == BPF_LD
) {
1663 u8 mode
= BPF_MODE(code
);
1666 if (mode
== BPF_IMM
)
1669 /* Both LD_IND and LD_ABS return 32-bit data. */
1673 /* Implicit ctx ptr. */
1674 if (regno
== BPF_REG_6
)
1677 /* Explicit source could be any width. */
1681 if (class == BPF_ST
)
1682 /* The only source register for BPF_ST is a ptr. */
1685 /* Conservatively return true at default. */
1689 /* Return TRUE if INSN doesn't have explicit value define. */
1690 static bool insn_no_def(struct bpf_insn
*insn
)
1692 u8
class = BPF_CLASS(insn
->code
);
1694 return (class == BPF_JMP
|| class == BPF_JMP32
||
1695 class == BPF_STX
|| class == BPF_ST
);
1698 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
1699 static bool insn_has_def32(struct bpf_verifier_env
*env
, struct bpf_insn
*insn
)
1701 if (insn_no_def(insn
))
1704 return !is_reg64(env
, insn
, insn
->dst_reg
, NULL
, DST_OP
);
1707 static void mark_insn_zext(struct bpf_verifier_env
*env
,
1708 struct bpf_reg_state
*reg
)
1710 s32 def_idx
= reg
->subreg_def
;
1712 if (def_idx
== DEF_NOT_SUBREG
)
1715 env
->insn_aux_data
[def_idx
- 1].zext_dst
= true;
1716 /* The dst will be zero extended, so won't be sub-register anymore. */
1717 reg
->subreg_def
= DEF_NOT_SUBREG
;
1720 static int check_reg_arg(struct bpf_verifier_env
*env
, u32 regno
,
1721 enum reg_arg_type t
)
1723 struct bpf_verifier_state
*vstate
= env
->cur_state
;
1724 struct bpf_func_state
*state
= vstate
->frame
[vstate
->curframe
];
1725 struct bpf_insn
*insn
= env
->prog
->insnsi
+ env
->insn_idx
;
1726 struct bpf_reg_state
*reg
, *regs
= state
->regs
;
1729 if (regno
>= MAX_BPF_REG
) {
1730 verbose(env
, "R%d is invalid\n", regno
);
1735 rw64
= is_reg64(env
, insn
, regno
, reg
, t
);
1737 /* check whether register used as source operand can be read */
1738 if (reg
->type
== NOT_INIT
) {
1739 verbose(env
, "R%d !read_ok\n", regno
);
1742 /* We don't need to worry about FP liveness because it's read-only */
1743 if (regno
== BPF_REG_FP
)
1747 mark_insn_zext(env
, reg
);
1749 return mark_reg_read(env
, reg
, reg
->parent
,
1750 rw64
? REG_LIVE_READ64
: REG_LIVE_READ32
);
1752 /* check whether register used as dest operand can be written to */
1753 if (regno
== BPF_REG_FP
) {
1754 verbose(env
, "frame pointer is read only\n");
1757 reg
->live
|= REG_LIVE_WRITTEN
;
1758 reg
->subreg_def
= rw64
? DEF_NOT_SUBREG
: env
->insn_idx
+ 1;
1760 mark_reg_unknown(env
, regs
, regno
);
1765 /* for any branch, call, exit record the history of jmps in the given state */
1766 static int push_jmp_history(struct bpf_verifier_env
*env
,
1767 struct bpf_verifier_state
*cur
)
1769 u32 cnt
= cur
->jmp_history_cnt
;
1770 struct bpf_idx_pair
*p
;
1773 p
= krealloc(cur
->jmp_history
, cnt
* sizeof(*p
), GFP_USER
);
1776 p
[cnt
- 1].idx
= env
->insn_idx
;
1777 p
[cnt
- 1].prev_idx
= env
->prev_insn_idx
;
1778 cur
->jmp_history
= p
;
1779 cur
->jmp_history_cnt
= cnt
;
1783 /* Backtrack one insn at a time. If idx is not at the top of recorded
1784 * history then previous instruction came from straight line execution.
1786 static int get_prev_insn_idx(struct bpf_verifier_state
*st
, int i
,
1791 if (cnt
&& st
->jmp_history
[cnt
- 1].idx
== i
) {
1792 i
= st
->jmp_history
[cnt
- 1].prev_idx
;
1800 /* For given verifier state backtrack_insn() is called from the last insn to
1801 * the first insn. Its purpose is to compute a bitmask of registers and
1802 * stack slots that needs precision in the parent verifier state.
1804 static int backtrack_insn(struct bpf_verifier_env
*env
, int idx
,
1805 u32
*reg_mask
, u64
*stack_mask
)
1807 const struct bpf_insn_cbs cbs
= {
1808 .cb_print
= verbose
,
1809 .private_data
= env
,
1811 struct bpf_insn
*insn
= env
->prog
->insnsi
+ idx
;
1812 u8
class = BPF_CLASS(insn
->code
);
1813 u8 opcode
= BPF_OP(insn
->code
);
1814 u8 mode
= BPF_MODE(insn
->code
);
1815 u32 dreg
= 1u << insn
->dst_reg
;
1816 u32 sreg
= 1u << insn
->src_reg
;
1819 if (insn
->code
== 0)
1821 if (env
->log
.level
& BPF_LOG_LEVEL
) {
1822 verbose(env
, "regs=%x stack=%llx before ", *reg_mask
, *stack_mask
);
1823 verbose(env
, "%d: ", idx
);
1824 print_bpf_insn(&cbs
, insn
, env
->allow_ptr_leaks
);
1827 if (class == BPF_ALU
|| class == BPF_ALU64
) {
1828 if (!(*reg_mask
& dreg
))
1830 if (opcode
== BPF_MOV
) {
1831 if (BPF_SRC(insn
->code
) == BPF_X
) {
1833 * dreg needs precision after this insn
1834 * sreg needs precision before this insn
1840 * dreg needs precision after this insn.
1841 * Corresponding register is already marked
1842 * as precise=true in this verifier state.
1843 * No further markings in parent are necessary
1848 if (BPF_SRC(insn
->code
) == BPF_X
) {
1850 * both dreg and sreg need precision
1855 * dreg still needs precision before this insn
1858 } else if (class == BPF_LDX
) {
1859 if (!(*reg_mask
& dreg
))
1863 /* scalars can only be spilled into stack w/o losing precision.
1864 * Load from any other memory can be zero extended.
1865 * The desire to keep that precision is already indicated
1866 * by 'precise' mark in corresponding register of this state.
1867 * No further tracking necessary.
1869 if (insn
->src_reg
!= BPF_REG_FP
)
1871 if (BPF_SIZE(insn
->code
) != BPF_DW
)
1874 /* dreg = *(u64 *)[fp - off] was a fill from the stack.
1875 * that [fp - off] slot contains scalar that needs to be
1876 * tracked with precision
1878 spi
= (-insn
->off
- 1) / BPF_REG_SIZE
;
1880 verbose(env
, "BUG spi %d\n", spi
);
1881 WARN_ONCE(1, "verifier backtracking bug");
1884 *stack_mask
|= 1ull << spi
;
1885 } else if (class == BPF_STX
|| class == BPF_ST
) {
1886 if (*reg_mask
& dreg
)
1887 /* stx & st shouldn't be using _scalar_ dst_reg
1888 * to access memory. It means backtracking
1889 * encountered a case of pointer subtraction.
1892 /* scalars can only be spilled into stack */
1893 if (insn
->dst_reg
!= BPF_REG_FP
)
1895 if (BPF_SIZE(insn
->code
) != BPF_DW
)
1897 spi
= (-insn
->off
- 1) / BPF_REG_SIZE
;
1899 verbose(env
, "BUG spi %d\n", spi
);
1900 WARN_ONCE(1, "verifier backtracking bug");
1903 if (!(*stack_mask
& (1ull << spi
)))
1905 *stack_mask
&= ~(1ull << spi
);
1906 if (class == BPF_STX
)
1908 } else if (class == BPF_JMP
|| class == BPF_JMP32
) {
1909 if (opcode
== BPF_CALL
) {
1910 if (insn
->src_reg
== BPF_PSEUDO_CALL
)
1912 /* regular helper call sets R0 */
1914 if (*reg_mask
& 0x3f) {
1915 /* if backtracing was looking for registers R1-R5
1916 * they should have been found already.
1918 verbose(env
, "BUG regs %x\n", *reg_mask
);
1919 WARN_ONCE(1, "verifier backtracking bug");
1922 } else if (opcode
== BPF_EXIT
) {
1925 } else if (class == BPF_LD
) {
1926 if (!(*reg_mask
& dreg
))
1929 /* It's ld_imm64 or ld_abs or ld_ind.
1930 * For ld_imm64 no further tracking of precision
1931 * into parent is necessary
1933 if (mode
== BPF_IND
|| mode
== BPF_ABS
)
1934 /* to be analyzed */
1940 /* the scalar precision tracking algorithm:
1941 * . at the start all registers have precise=false.
1942 * . scalar ranges are tracked as normal through alu and jmp insns.
1943 * . once precise value of the scalar register is used in:
1944 * . ptr + scalar alu
1945 * . if (scalar cond K|scalar)
1946 * . helper_call(.., scalar, ...) where ARG_CONST is expected
1947 * backtrack through the verifier states and mark all registers and
1948 * stack slots with spilled constants that these scalar regisers
1949 * should be precise.
1950 * . during state pruning two registers (or spilled stack slots)
1951 * are equivalent if both are not precise.
1953 * Note the verifier cannot simply walk register parentage chain,
1954 * since many different registers and stack slots could have been
1955 * used to compute single precise scalar.
1957 * The approach of starting with precise=true for all registers and then
1958 * backtrack to mark a register as not precise when the verifier detects
1959 * that program doesn't care about specific value (e.g., when helper
1960 * takes register as ARG_ANYTHING parameter) is not safe.
1962 * It's ok to walk single parentage chain of the verifier states.
1963 * It's possible that this backtracking will go all the way till 1st insn.
1964 * All other branches will be explored for needing precision later.
1966 * The backtracking needs to deal with cases like:
1967 * 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)
1970 * if r5 > 0x79f goto pc+7
1971 * R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
1974 * call bpf_perf_event_output#25
1975 * where .arg5_type = ARG_CONST_SIZE_OR_ZERO
1979 * call foo // uses callee's r6 inside to compute r0
1983 * to track above reg_mask/stack_mask needs to be independent for each frame.
1985 * Also if parent's curframe > frame where backtracking started,
1986 * the verifier need to mark registers in both frames, otherwise callees
1987 * may incorrectly prune callers. This is similar to
1988 * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
1990 * For now backtracking falls back into conservative marking.
1992 static void mark_all_scalars_precise(struct bpf_verifier_env
*env
,
1993 struct bpf_verifier_state
*st
)
1995 struct bpf_func_state
*func
;
1996 struct bpf_reg_state
*reg
;
1999 /* big hammer: mark all scalars precise in this path.
2000 * pop_stack may still get !precise scalars.
2002 for (; st
; st
= st
->parent
)
2003 for (i
= 0; i
<= st
->curframe
; i
++) {
2004 func
= st
->frame
[i
];
2005 for (j
= 0; j
< BPF_REG_FP
; j
++) {
2006 reg
= &func
->regs
[j
];
2007 if (reg
->type
!= SCALAR_VALUE
)
2009 reg
->precise
= true;
2011 for (j
= 0; j
< func
->allocated_stack
/ BPF_REG_SIZE
; j
++) {
2012 if (func
->stack
[j
].slot_type
[0] != STACK_SPILL
)
2014 reg
= &func
->stack
[j
].spilled_ptr
;
2015 if (reg
->type
!= SCALAR_VALUE
)
2017 reg
->precise
= true;
2022 static int __mark_chain_precision(struct bpf_verifier_env
*env
, int regno
,
2025 struct bpf_verifier_state
*st
= env
->cur_state
;
2026 int first_idx
= st
->first_insn_idx
;
2027 int last_idx
= env
->insn_idx
;
2028 struct bpf_func_state
*func
;
2029 struct bpf_reg_state
*reg
;
2030 u32 reg_mask
= regno
>= 0 ? 1u << regno
: 0;
2031 u64 stack_mask
= spi
>= 0 ? 1ull << spi
: 0;
2032 bool skip_first
= true;
2033 bool new_marks
= false;
2036 if (!env
->bpf_capable
)
2039 func
= st
->frame
[st
->curframe
];
2041 reg
= &func
->regs
[regno
];
2042 if (reg
->type
!= SCALAR_VALUE
) {
2043 WARN_ONCE(1, "backtracing misuse");
2050 reg
->precise
= true;
2054 if (func
->stack
[spi
].slot_type
[0] != STACK_SPILL
) {
2058 reg
= &func
->stack
[spi
].spilled_ptr
;
2059 if (reg
->type
!= SCALAR_VALUE
) {
2067 reg
->precise
= true;
2073 if (!reg_mask
&& !stack_mask
)
2076 DECLARE_BITMAP(mask
, 64);
2077 u32 history
= st
->jmp_history_cnt
;
2079 if (env
->log
.level
& BPF_LOG_LEVEL
)
2080 verbose(env
, "last_idx %d first_idx %d\n", last_idx
, first_idx
);
2081 for (i
= last_idx
;;) {
2086 err
= backtrack_insn(env
, i
, ®_mask
, &stack_mask
);
2088 if (err
== -ENOTSUPP
) {
2089 mark_all_scalars_precise(env
, st
);
2094 if (!reg_mask
&& !stack_mask
)
2095 /* Found assignment(s) into tracked register in this state.
2096 * Since this state is already marked, just return.
2097 * Nothing to be tracked further in the parent state.
2102 i
= get_prev_insn_idx(st
, i
, &history
);
2103 if (i
>= env
->prog
->len
) {
2104 /* This can happen if backtracking reached insn 0
2105 * and there are still reg_mask or stack_mask
2107 * It means the backtracking missed the spot where
2108 * particular register was initialized with a constant.
2110 verbose(env
, "BUG backtracking idx %d\n", i
);
2111 WARN_ONCE(1, "verifier backtracking bug");
2120 func
= st
->frame
[st
->curframe
];
2121 bitmap_from_u64(mask
, reg_mask
);
2122 for_each_set_bit(i
, mask
, 32) {
2123 reg
= &func
->regs
[i
];
2124 if (reg
->type
!= SCALAR_VALUE
) {
2125 reg_mask
&= ~(1u << i
);
2130 reg
->precise
= true;
2133 bitmap_from_u64(mask
, stack_mask
);
2134 for_each_set_bit(i
, mask
, 64) {
2135 if (i
>= func
->allocated_stack
/ BPF_REG_SIZE
) {
2136 /* the sequence of instructions:
2138 * 3: (7b) *(u64 *)(r3 -8) = r0
2139 * 4: (79) r4 = *(u64 *)(r10 -8)
2140 * doesn't contain jmps. It's backtracked
2141 * as a single block.
2142 * During backtracking insn 3 is not recognized as
2143 * stack access, so at the end of backtracking
2144 * stack slot fp-8 is still marked in stack_mask.
2145 * However the parent state may not have accessed
2146 * fp-8 and it's "unallocated" stack space.
2147 * In such case fallback to conservative.
2149 mark_all_scalars_precise(env
, st
);
2153 if (func
->stack
[i
].slot_type
[0] != STACK_SPILL
) {
2154 stack_mask
&= ~(1ull << i
);
2157 reg
= &func
->stack
[i
].spilled_ptr
;
2158 if (reg
->type
!= SCALAR_VALUE
) {
2159 stack_mask
&= ~(1ull << i
);
2164 reg
->precise
= true;
2166 if (env
->log
.level
& BPF_LOG_LEVEL
) {
2167 print_verifier_state(env
, func
);
2168 verbose(env
, "parent %s regs=%x stack=%llx marks\n",
2169 new_marks
? "didn't have" : "already had",
2170 reg_mask
, stack_mask
);
2173 if (!reg_mask
&& !stack_mask
)
2178 last_idx
= st
->last_insn_idx
;
2179 first_idx
= st
->first_insn_idx
;
2184 static int mark_chain_precision(struct bpf_verifier_env
*env
, int regno
)
2186 return __mark_chain_precision(env
, regno
, -1);
2189 static int mark_chain_precision_stack(struct bpf_verifier_env
*env
, int spi
)
2191 return __mark_chain_precision(env
, -1, spi
);
2194 static bool is_spillable_regtype(enum bpf_reg_type type
)
2197 case PTR_TO_MAP_VALUE
:
2198 case PTR_TO_MAP_VALUE_OR_NULL
:
2202 case PTR_TO_PACKET_META
:
2203 case PTR_TO_PACKET_END
:
2204 case PTR_TO_FLOW_KEYS
:
2205 case CONST_PTR_TO_MAP
:
2207 case PTR_TO_SOCKET_OR_NULL
:
2208 case PTR_TO_SOCK_COMMON
:
2209 case PTR_TO_SOCK_COMMON_OR_NULL
:
2210 case PTR_TO_TCP_SOCK
:
2211 case PTR_TO_TCP_SOCK_OR_NULL
:
2212 case PTR_TO_XDP_SOCK
:
2214 case PTR_TO_BTF_ID_OR_NULL
:
2215 case PTR_TO_RDONLY_BUF
:
2216 case PTR_TO_RDONLY_BUF_OR_NULL
:
2217 case PTR_TO_RDWR_BUF
:
2218 case PTR_TO_RDWR_BUF_OR_NULL
:
2219 case PTR_TO_PERCPU_BTF_ID
:
2221 case PTR_TO_MEM_OR_NULL
:
2228 /* Does this register contain a constant zero? */
2229 static bool register_is_null(struct bpf_reg_state
*reg
)
2231 return reg
->type
== SCALAR_VALUE
&& tnum_equals_const(reg
->var_off
, 0);
2234 static bool register_is_const(struct bpf_reg_state
*reg
)
2236 return reg
->type
== SCALAR_VALUE
&& tnum_is_const(reg
->var_off
);
2239 static bool __is_scalar_unbounded(struct bpf_reg_state
*reg
)
2241 return tnum_is_unknown(reg
->var_off
) &&
2242 reg
->smin_value
== S64_MIN
&& reg
->smax_value
== S64_MAX
&&
2243 reg
->umin_value
== 0 && reg
->umax_value
== U64_MAX
&&
2244 reg
->s32_min_value
== S32_MIN
&& reg
->s32_max_value
== S32_MAX
&&
2245 reg
->u32_min_value
== 0 && reg
->u32_max_value
== U32_MAX
;
2248 static bool register_is_bounded(struct bpf_reg_state
*reg
)
2250 return reg
->type
== SCALAR_VALUE
&& !__is_scalar_unbounded(reg
);
2253 static bool __is_pointer_value(bool allow_ptr_leaks
,
2254 const struct bpf_reg_state
*reg
)
2256 if (allow_ptr_leaks
)
2259 return reg
->type
!= SCALAR_VALUE
;
2262 static void save_register_state(struct bpf_func_state
*state
,
2263 int spi
, struct bpf_reg_state
*reg
)
2267 state
->stack
[spi
].spilled_ptr
= *reg
;
2268 state
->stack
[spi
].spilled_ptr
.live
|= REG_LIVE_WRITTEN
;
2270 for (i
= 0; i
< BPF_REG_SIZE
; i
++)
2271 state
->stack
[spi
].slot_type
[i
] = STACK_SPILL
;
2274 /* check_stack_read/write functions track spill/fill of registers,
2275 * stack boundary and alignment are checked in check_mem_access()
2277 static int check_stack_write(struct bpf_verifier_env
*env
,
2278 struct bpf_func_state
*state
, /* func where register points to */
2279 int off
, int size
, int value_regno
, int insn_idx
)
2281 struct bpf_func_state
*cur
; /* state of the current function */
2282 int i
, slot
= -off
- 1, spi
= slot
/ BPF_REG_SIZE
, err
;
2283 u32 dst_reg
= env
->prog
->insnsi
[insn_idx
].dst_reg
;
2284 struct bpf_reg_state
*reg
= NULL
;
2286 err
= realloc_func_state(state
, round_up(slot
+ 1, BPF_REG_SIZE
),
2287 state
->acquired_refs
, true);
2290 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
2291 * so it's aligned access and [off, off + size) are within stack limits
2293 if (!env
->allow_ptr_leaks
&&
2294 state
->stack
[spi
].slot_type
[0] == STACK_SPILL
&&
2295 size
!= BPF_REG_SIZE
) {
2296 verbose(env
, "attempt to corrupt spilled pointer on stack\n");
2300 cur
= env
->cur_state
->frame
[env
->cur_state
->curframe
];
2301 if (value_regno
>= 0)
2302 reg
= &cur
->regs
[value_regno
];
2304 if (reg
&& size
== BPF_REG_SIZE
&& register_is_bounded(reg
) &&
2305 !register_is_null(reg
) && env
->bpf_capable
) {
2306 if (dst_reg
!= BPF_REG_FP
) {
2307 /* The backtracking logic can only recognize explicit
2308 * stack slot address like [fp - 8]. Other spill of
2309 * scalar via different register has to be conervative.
2310 * Backtrack from here and mark all registers as precise
2311 * that contributed into 'reg' being a constant.
2313 err
= mark_chain_precision(env
, value_regno
);
2317 save_register_state(state
, spi
, reg
);
2318 } else if (reg
&& is_spillable_regtype(reg
->type
)) {
2319 /* register containing pointer is being spilled into stack */
2320 if (size
!= BPF_REG_SIZE
) {
2321 verbose_linfo(env
, insn_idx
, "; ");
2322 verbose(env
, "invalid size of register spill\n");
2326 if (state
!= cur
&& reg
->type
== PTR_TO_STACK
) {
2327 verbose(env
, "cannot spill pointers to stack into stack frame of the caller\n");
2331 if (!env
->bypass_spec_v4
) {
2332 bool sanitize
= false;
2334 if (state
->stack
[spi
].slot_type
[0] == STACK_SPILL
&&
2335 register_is_const(&state
->stack
[spi
].spilled_ptr
))
2337 for (i
= 0; i
< BPF_REG_SIZE
; i
++)
2338 if (state
->stack
[spi
].slot_type
[i
] == STACK_MISC
) {
2343 int *poff
= &env
->insn_aux_data
[insn_idx
].sanitize_stack_off
;
2344 int soff
= (-spi
- 1) * BPF_REG_SIZE
;
2346 /* detected reuse of integer stack slot with a pointer
2347 * which means either llvm is reusing stack slot or
2348 * an attacker is trying to exploit CVE-2018-3639
2349 * (speculative store bypass)
2350 * Have to sanitize that slot with preemptive
2353 if (*poff
&& *poff
!= soff
) {
2354 /* disallow programs where single insn stores
2355 * into two different stack slots, since verifier
2356 * cannot sanitize them
2359 "insn %d cannot access two stack slots fp%d and fp%d",
2360 insn_idx
, *poff
, soff
);
2366 save_register_state(state
, spi
, reg
);
2368 u8 type
= STACK_MISC
;
2370 /* regular write of data into stack destroys any spilled ptr */
2371 state
->stack
[spi
].spilled_ptr
.type
= NOT_INIT
;
2372 /* Mark slots as STACK_MISC if they belonged to spilled ptr. */
2373 if (state
->stack
[spi
].slot_type
[0] == STACK_SPILL
)
2374 for (i
= 0; i
< BPF_REG_SIZE
; i
++)
2375 state
->stack
[spi
].slot_type
[i
] = STACK_MISC
;
2377 /* only mark the slot as written if all 8 bytes were written
2378 * otherwise read propagation may incorrectly stop too soon
2379 * when stack slots are partially written.
2380 * This heuristic means that read propagation will be
2381 * conservative, since it will add reg_live_read marks
2382 * to stack slots all the way to first state when programs
2383 * writes+reads less than 8 bytes
2385 if (size
== BPF_REG_SIZE
)
2386 state
->stack
[spi
].spilled_ptr
.live
|= REG_LIVE_WRITTEN
;
2388 /* when we zero initialize stack slots mark them as such */
2389 if (reg
&& register_is_null(reg
)) {
2390 /* backtracking doesn't work for STACK_ZERO yet. */
2391 err
= mark_chain_precision(env
, value_regno
);
2397 /* Mark slots affected by this stack write. */
2398 for (i
= 0; i
< size
; i
++)
2399 state
->stack
[spi
].slot_type
[(slot
- i
) % BPF_REG_SIZE
] =
2405 static int check_stack_read(struct bpf_verifier_env
*env
,
2406 struct bpf_func_state
*reg_state
/* func where register points to */,
2407 int off
, int size
, int value_regno
)
2409 struct bpf_verifier_state
*vstate
= env
->cur_state
;
2410 struct bpf_func_state
*state
= vstate
->frame
[vstate
->curframe
];
2411 int i
, slot
= -off
- 1, spi
= slot
/ BPF_REG_SIZE
;
2412 struct bpf_reg_state
*reg
;
2415 if (reg_state
->allocated_stack
<= slot
) {
2416 verbose(env
, "invalid read from stack off %d+0 size %d\n",
2420 stype
= reg_state
->stack
[spi
].slot_type
;
2421 reg
= ®_state
->stack
[spi
].spilled_ptr
;
2423 if (stype
[0] == STACK_SPILL
) {
2424 if (size
!= BPF_REG_SIZE
) {
2425 if (reg
->type
!= SCALAR_VALUE
) {
2426 verbose_linfo(env
, env
->insn_idx
, "; ");
2427 verbose(env
, "invalid size of register fill\n");
2430 if (value_regno
>= 0) {
2431 mark_reg_unknown(env
, state
->regs
, value_regno
);
2432 state
->regs
[value_regno
].live
|= REG_LIVE_WRITTEN
;
2434 mark_reg_read(env
, reg
, reg
->parent
, REG_LIVE_READ64
);
2437 for (i
= 1; i
< BPF_REG_SIZE
; i
++) {
2438 if (stype
[(slot
- i
) % BPF_REG_SIZE
] != STACK_SPILL
) {
2439 verbose(env
, "corrupted spill memory\n");
2444 if (value_regno
>= 0) {
2445 /* restore register state from stack */
2446 state
->regs
[value_regno
] = *reg
;
2447 /* mark reg as written since spilled pointer state likely
2448 * has its liveness marks cleared by is_state_visited()
2449 * which resets stack/reg liveness for state transitions
2451 state
->regs
[value_regno
].live
|= REG_LIVE_WRITTEN
;
2452 } else if (__is_pointer_value(env
->allow_ptr_leaks
, reg
)) {
2453 /* If value_regno==-1, the caller is asking us whether
2454 * it is acceptable to use this value as a SCALAR_VALUE
2456 * We must not allow unprivileged callers to do that
2457 * with spilled pointers.
2459 verbose(env
, "leaking pointer from stack off %d\n",
2463 mark_reg_read(env
, reg
, reg
->parent
, REG_LIVE_READ64
);
2467 for (i
= 0; i
< size
; i
++) {
2468 if (stype
[(slot
- i
) % BPF_REG_SIZE
] == STACK_MISC
)
2470 if (stype
[(slot
- i
) % BPF_REG_SIZE
] == STACK_ZERO
) {
2474 verbose(env
, "invalid read from stack off %d+%d size %d\n",
2478 mark_reg_read(env
, reg
, reg
->parent
, REG_LIVE_READ64
);
2479 if (value_regno
>= 0) {
2480 if (zeros
== size
) {
2481 /* any size read into register is zero extended,
2482 * so the whole register == const_zero
2484 __mark_reg_const_zero(&state
->regs
[value_regno
]);
2485 /* backtracking doesn't support STACK_ZERO yet,
2486 * so mark it precise here, so that later
2487 * backtracking can stop here.
2488 * Backtracking may not need this if this register
2489 * doesn't participate in pointer adjustment.
2490 * Forward propagation of precise flag is not
2491 * necessary either. This mark is only to stop
2492 * backtracking. Any register that contributed
2493 * to const 0 was marked precise before spill.
2495 state
->regs
[value_regno
].precise
= true;
2497 /* have read misc data from the stack */
2498 mark_reg_unknown(env
, state
->regs
, value_regno
);
2500 state
->regs
[value_regno
].live
|= REG_LIVE_WRITTEN
;
2506 static int check_stack_access(struct bpf_verifier_env
*env
,
2507 const struct bpf_reg_state
*reg
,
2510 /* Stack accesses must be at a fixed offset, so that we
2511 * can determine what type of data were returned. See
2512 * check_stack_read().
2514 if (!tnum_is_const(reg
->var_off
)) {
2517 tnum_strn(tn_buf
, sizeof(tn_buf
), reg
->var_off
);
2518 verbose(env
, "variable stack access var_off=%s off=%d size=%d\n",
2523 if (off
>= 0 || off
< -MAX_BPF_STACK
) {
2524 verbose(env
, "invalid stack off=%d size=%d\n", off
, size
);
2531 static int check_map_access_type(struct bpf_verifier_env
*env
, u32 regno
,
2532 int off
, int size
, enum bpf_access_type type
)
2534 struct bpf_reg_state
*regs
= cur_regs(env
);
2535 struct bpf_map
*map
= regs
[regno
].map_ptr
;
2536 u32 cap
= bpf_map_flags_to_cap(map
);
2538 if (type
== BPF_WRITE
&& !(cap
& BPF_MAP_CAN_WRITE
)) {
2539 verbose(env
, "write into map forbidden, value_size=%d off=%d size=%d\n",
2540 map
->value_size
, off
, size
);
2544 if (type
== BPF_READ
&& !(cap
& BPF_MAP_CAN_READ
)) {
2545 verbose(env
, "read from map forbidden, value_size=%d off=%d size=%d\n",
2546 map
->value_size
, off
, size
);
2553 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
2554 static int __check_mem_access(struct bpf_verifier_env
*env
, int regno
,
2555 int off
, int size
, u32 mem_size
,
2556 bool zero_size_allowed
)
2558 bool size_ok
= size
> 0 || (size
== 0 && zero_size_allowed
);
2559 struct bpf_reg_state
*reg
;
2561 if (off
>= 0 && size_ok
&& (u64
)off
+ size
<= mem_size
)
2564 reg
= &cur_regs(env
)[regno
];
2565 switch (reg
->type
) {
2566 case PTR_TO_MAP_VALUE
:
2567 verbose(env
, "invalid access to map value, value_size=%d off=%d size=%d\n",
2568 mem_size
, off
, size
);
2571 case PTR_TO_PACKET_META
:
2572 case PTR_TO_PACKET_END
:
2573 verbose(env
, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
2574 off
, size
, regno
, reg
->id
, off
, mem_size
);
2578 verbose(env
, "invalid access to memory, mem_size=%u off=%d size=%d\n",
2579 mem_size
, off
, size
);
2585 /* check read/write into a memory region with possible variable offset */
2586 static int check_mem_region_access(struct bpf_verifier_env
*env
, u32 regno
,
2587 int off
, int size
, u32 mem_size
,
2588 bool zero_size_allowed
)
2590 struct bpf_verifier_state
*vstate
= env
->cur_state
;
2591 struct bpf_func_state
*state
= vstate
->frame
[vstate
->curframe
];
2592 struct bpf_reg_state
*reg
= &state
->regs
[regno
];
2595 /* We may have adjusted the register pointing to memory region, so we
2596 * need to try adding each of min_value and max_value to off
2597 * to make sure our theoretical access will be safe.
2599 if (env
->log
.level
& BPF_LOG_LEVEL
)
2600 print_verifier_state(env
, state
);
2602 /* The minimum value is only important with signed
2603 * comparisons where we can't assume the floor of a
2604 * value is 0. If we are using signed variables for our
2605 * index'es we need to make sure that whatever we use
2606 * will have a set floor within our range.
2608 if (reg
->smin_value
< 0 &&
2609 (reg
->smin_value
== S64_MIN
||
2610 (off
+ reg
->smin_value
!= (s64
)(s32
)(off
+ reg
->smin_value
)) ||
2611 reg
->smin_value
+ off
< 0)) {
2612 verbose(env
, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
2616 err
= __check_mem_access(env
, regno
, reg
->smin_value
+ off
, size
,
2617 mem_size
, zero_size_allowed
);
2619 verbose(env
, "R%d min value is outside of the allowed memory range\n",
2624 /* If we haven't set a max value then we need to bail since we can't be
2625 * sure we won't do bad things.
2626 * If reg->umax_value + off could overflow, treat that as unbounded too.
2628 if (reg
->umax_value
>= BPF_MAX_VAR_OFF
) {
2629 verbose(env
, "R%d unbounded memory access, make sure to bounds check any such access\n",
2633 err
= __check_mem_access(env
, regno
, reg
->umax_value
+ off
, size
,
2634 mem_size
, zero_size_allowed
);
2636 verbose(env
, "R%d max value is outside of the allowed memory range\n",
2644 /* check read/write into a map element with possible variable offset */
2645 static int check_map_access(struct bpf_verifier_env
*env
, u32 regno
,
2646 int off
, int size
, bool zero_size_allowed
)
2648 struct bpf_verifier_state
*vstate
= env
->cur_state
;
2649 struct bpf_func_state
*state
= vstate
->frame
[vstate
->curframe
];
2650 struct bpf_reg_state
*reg
= &state
->regs
[regno
];
2651 struct bpf_map
*map
= reg
->map_ptr
;
2654 err
= check_mem_region_access(env
, regno
, off
, size
, map
->value_size
,
2659 if (map_value_has_spin_lock(map
)) {
2660 u32 lock
= map
->spin_lock_off
;
2662 /* if any part of struct bpf_spin_lock can be touched by
2663 * load/store reject this program.
2664 * To check that [x1, x2) overlaps with [y1, y2)
2665 * it is sufficient to check x1 < y2 && y1 < x2.
2667 if (reg
->smin_value
+ off
< lock
+ sizeof(struct bpf_spin_lock
) &&
2668 lock
< reg
->umax_value
+ off
+ size
) {
2669 verbose(env
, "bpf_spin_lock cannot be accessed directly by load/store\n");
2676 #define MAX_PACKET_OFF 0xffff
2678 static enum bpf_prog_type
resolve_prog_type(struct bpf_prog
*prog
)
2680 return prog
->aux
->dst_prog
? prog
->aux
->dst_prog
->type
: prog
->type
;
2683 static bool may_access_direct_pkt_data(struct bpf_verifier_env
*env
,
2684 const struct bpf_call_arg_meta
*meta
,
2685 enum bpf_access_type t
)
2687 enum bpf_prog_type prog_type
= resolve_prog_type(env
->prog
);
2689 switch (prog_type
) {
2690 /* Program types only with direct read access go here! */
2691 case BPF_PROG_TYPE_LWT_IN
:
2692 case BPF_PROG_TYPE_LWT_OUT
:
2693 case BPF_PROG_TYPE_LWT_SEG6LOCAL
:
2694 case BPF_PROG_TYPE_SK_REUSEPORT
:
2695 case BPF_PROG_TYPE_FLOW_DISSECTOR
:
2696 case BPF_PROG_TYPE_CGROUP_SKB
:
2701 /* Program types with direct read + write access go here! */
2702 case BPF_PROG_TYPE_SCHED_CLS
:
2703 case BPF_PROG_TYPE_SCHED_ACT
:
2704 case BPF_PROG_TYPE_XDP
:
2705 case BPF_PROG_TYPE_LWT_XMIT
:
2706 case BPF_PROG_TYPE_SK_SKB
:
2707 case BPF_PROG_TYPE_SK_MSG
:
2709 return meta
->pkt_access
;
2711 env
->seen_direct_write
= true;
2714 case BPF_PROG_TYPE_CGROUP_SOCKOPT
:
2716 env
->seen_direct_write
= true;
2725 static int check_packet_access(struct bpf_verifier_env
*env
, u32 regno
, int off
,
2726 int size
, bool zero_size_allowed
)
2728 struct bpf_reg_state
*regs
= cur_regs(env
);
2729 struct bpf_reg_state
*reg
= ®s
[regno
];
2732 /* We may have added a variable offset to the packet pointer; but any
2733 * reg->range we have comes after that. We are only checking the fixed
2737 /* We don't allow negative numbers, because we aren't tracking enough
2738 * detail to prove they're safe.
2740 if (reg
->smin_value
< 0) {
2741 verbose(env
, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
2746 err
= reg
->range
< 0 ? -EINVAL
:
2747 __check_mem_access(env
, regno
, off
, size
, reg
->range
,
2750 verbose(env
, "R%d offset is outside of the packet\n", regno
);
2754 /* __check_mem_access has made sure "off + size - 1" is within u16.
2755 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
2756 * otherwise find_good_pkt_pointers would have refused to set range info
2757 * that __check_mem_access would have rejected this pkt access.
2758 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
2760 env
->prog
->aux
->max_pkt_offset
=
2761 max_t(u32
, env
->prog
->aux
->max_pkt_offset
,
2762 off
+ reg
->umax_value
+ size
- 1);
2767 /* check access to 'struct bpf_context' fields. Supports fixed offsets only */
2768 static int check_ctx_access(struct bpf_verifier_env
*env
, int insn_idx
, int off
, int size
,
2769 enum bpf_access_type t
, enum bpf_reg_type
*reg_type
,
2770 struct btf
**btf
, u32
*btf_id
)
2772 struct bpf_insn_access_aux info
= {
2773 .reg_type
= *reg_type
,
2777 if (env
->ops
->is_valid_access
&&
2778 env
->ops
->is_valid_access(off
, size
, t
, env
->prog
, &info
)) {
2779 /* A non zero info.ctx_field_size indicates that this field is a
2780 * candidate for later verifier transformation to load the whole
2781 * field and then apply a mask when accessed with a narrower
2782 * access than actual ctx access size. A zero info.ctx_field_size
2783 * will only allow for whole field access and rejects any other
2784 * type of narrower access.
2786 *reg_type
= info
.reg_type
;
2788 if (*reg_type
== PTR_TO_BTF_ID
|| *reg_type
== PTR_TO_BTF_ID_OR_NULL
) {
2790 *btf_id
= info
.btf_id
;
2792 env
->insn_aux_data
[insn_idx
].ctx_field_size
= info
.ctx_field_size
;
2794 /* remember the offset of last byte accessed in ctx */
2795 if (env
->prog
->aux
->max_ctx_offset
< off
+ size
)
2796 env
->prog
->aux
->max_ctx_offset
= off
+ size
;
2800 verbose(env
, "invalid bpf_context access off=%d size=%d\n", off
, size
);
2804 static int check_flow_keys_access(struct bpf_verifier_env
*env
, int off
,
2807 if (size
< 0 || off
< 0 ||
2808 (u64
)off
+ size
> sizeof(struct bpf_flow_keys
)) {
2809 verbose(env
, "invalid access to flow keys off=%d size=%d\n",
2816 static int check_sock_access(struct bpf_verifier_env
*env
, int insn_idx
,
2817 u32 regno
, int off
, int size
,
2818 enum bpf_access_type t
)
2820 struct bpf_reg_state
*regs
= cur_regs(env
);
2821 struct bpf_reg_state
*reg
= ®s
[regno
];
2822 struct bpf_insn_access_aux info
= {};
2825 if (reg
->smin_value
< 0) {
2826 verbose(env
, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
2831 switch (reg
->type
) {
2832 case PTR_TO_SOCK_COMMON
:
2833 valid
= bpf_sock_common_is_valid_access(off
, size
, t
, &info
);
2836 valid
= bpf_sock_is_valid_access(off
, size
, t
, &info
);
2838 case PTR_TO_TCP_SOCK
:
2839 valid
= bpf_tcp_sock_is_valid_access(off
, size
, t
, &info
);
2841 case PTR_TO_XDP_SOCK
:
2842 valid
= bpf_xdp_sock_is_valid_access(off
, size
, t
, &info
);
2850 env
->insn_aux_data
[insn_idx
].ctx_field_size
=
2851 info
.ctx_field_size
;
2855 verbose(env
, "R%d invalid %s access off=%d size=%d\n",
2856 regno
, reg_type_str
[reg
->type
], off
, size
);
2861 static struct bpf_reg_state
*reg_state(struct bpf_verifier_env
*env
, int regno
)
2863 return cur_regs(env
) + regno
;
2866 static bool is_pointer_value(struct bpf_verifier_env
*env
, int regno
)
2868 return __is_pointer_value(env
->allow_ptr_leaks
, reg_state(env
, regno
));
2871 static bool is_ctx_reg(struct bpf_verifier_env
*env
, int regno
)
2873 const struct bpf_reg_state
*reg
= reg_state(env
, regno
);
2875 return reg
->type
== PTR_TO_CTX
;
2878 static bool is_sk_reg(struct bpf_verifier_env
*env
, int regno
)
2880 const struct bpf_reg_state
*reg
= reg_state(env
, regno
);
2882 return type_is_sk_pointer(reg
->type
);
2885 static bool is_pkt_reg(struct bpf_verifier_env
*env
, int regno
)
2887 const struct bpf_reg_state
*reg
= reg_state(env
, regno
);
2889 return type_is_pkt_pointer(reg
->type
);
2892 static bool is_flow_key_reg(struct bpf_verifier_env
*env
, int regno
)
2894 const struct bpf_reg_state
*reg
= reg_state(env
, regno
);
2896 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
2897 return reg
->type
== PTR_TO_FLOW_KEYS
;
2900 static int check_pkt_ptr_alignment(struct bpf_verifier_env
*env
,
2901 const struct bpf_reg_state
*reg
,
2902 int off
, int size
, bool strict
)
2904 struct tnum reg_off
;
2907 /* Byte size accesses are always allowed. */
2908 if (!strict
|| size
== 1)
2911 /* For platforms that do not have a Kconfig enabling
2912 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
2913 * NET_IP_ALIGN is universally set to '2'. And on platforms
2914 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
2915 * to this code only in strict mode where we want to emulate
2916 * the NET_IP_ALIGN==2 checking. Therefore use an
2917 * unconditional IP align value of '2'.
2921 reg_off
= tnum_add(reg
->var_off
, tnum_const(ip_align
+ reg
->off
+ off
));
2922 if (!tnum_is_aligned(reg_off
, size
)) {
2925 tnum_strn(tn_buf
, sizeof(tn_buf
), reg
->var_off
);
2927 "misaligned packet access off %d+%s+%d+%d size %d\n",
2928 ip_align
, tn_buf
, reg
->off
, off
, size
);
2935 static int check_generic_ptr_alignment(struct bpf_verifier_env
*env
,
2936 const struct bpf_reg_state
*reg
,
2937 const char *pointer_desc
,
2938 int off
, int size
, bool strict
)
2940 struct tnum reg_off
;
2942 /* Byte size accesses are always allowed. */
2943 if (!strict
|| size
== 1)
2946 reg_off
= tnum_add(reg
->var_off
, tnum_const(reg
->off
+ off
));
2947 if (!tnum_is_aligned(reg_off
, size
)) {
2950 tnum_strn(tn_buf
, sizeof(tn_buf
), reg
->var_off
);
2951 verbose(env
, "misaligned %saccess off %s+%d+%d size %d\n",
2952 pointer_desc
, tn_buf
, reg
->off
, off
, size
);
2959 static int check_ptr_alignment(struct bpf_verifier_env
*env
,
2960 const struct bpf_reg_state
*reg
, int off
,
2961 int size
, bool strict_alignment_once
)
2963 bool strict
= env
->strict_alignment
|| strict_alignment_once
;
2964 const char *pointer_desc
= "";
2966 switch (reg
->type
) {
2968 case PTR_TO_PACKET_META
:
2969 /* Special case, because of NET_IP_ALIGN. Given metadata sits
2970 * right in front, treat it the very same way.
2972 return check_pkt_ptr_alignment(env
, reg
, off
, size
, strict
);
2973 case PTR_TO_FLOW_KEYS
:
2974 pointer_desc
= "flow keys ";
2976 case PTR_TO_MAP_VALUE
:
2977 pointer_desc
= "value ";
2980 pointer_desc
= "context ";
2983 pointer_desc
= "stack ";
2984 /* The stack spill tracking logic in check_stack_write()
2985 * and check_stack_read() relies on stack accesses being
2991 pointer_desc
= "sock ";
2993 case PTR_TO_SOCK_COMMON
:
2994 pointer_desc
= "sock_common ";
2996 case PTR_TO_TCP_SOCK
:
2997 pointer_desc
= "tcp_sock ";
2999 case PTR_TO_XDP_SOCK
:
3000 pointer_desc
= "xdp_sock ";
3005 return check_generic_ptr_alignment(env
, reg
, pointer_desc
, off
, size
,
3009 static int update_stack_depth(struct bpf_verifier_env
*env
,
3010 const struct bpf_func_state
*func
,
3013 u16 stack
= env
->subprog_info
[func
->subprogno
].stack_depth
;
3018 /* update known max for given subprogram */
3019 env
->subprog_info
[func
->subprogno
].stack_depth
= -off
;
3023 /* starting from main bpf function walk all instructions of the function
3024 * and recursively walk all callees that given function can call.
3025 * Ignore jump and exit insns.
3026 * Since recursion is prevented by check_cfg() this algorithm
3027 * only needs a local stack of MAX_CALL_FRAMES to remember callsites
3029 static int check_max_stack_depth(struct bpf_verifier_env
*env
)
3031 int depth
= 0, frame
= 0, idx
= 0, i
= 0, subprog_end
;
3032 struct bpf_subprog_info
*subprog
= env
->subprog_info
;
3033 struct bpf_insn
*insn
= env
->prog
->insnsi
;
3034 bool tail_call_reachable
= false;
3035 int ret_insn
[MAX_CALL_FRAMES
];
3036 int ret_prog
[MAX_CALL_FRAMES
];
3040 /* protect against potential stack overflow that might happen when
3041 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
3042 * depth for such case down to 256 so that the worst case scenario
3043 * would result in 8k stack size (32 which is tailcall limit * 256 =
3046 * To get the idea what might happen, see an example:
3047 * func1 -> sub rsp, 128
3048 * subfunc1 -> sub rsp, 256
3049 * tailcall1 -> add rsp, 256
3050 * func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
3051 * subfunc2 -> sub rsp, 64
3052 * subfunc22 -> sub rsp, 128
3053 * tailcall2 -> add rsp, 128
3054 * func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
3056 * tailcall will unwind the current stack frame but it will not get rid
3057 * of caller's stack as shown on the example above.
3059 if (idx
&& subprog
[idx
].has_tail_call
&& depth
>= 256) {
3061 "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
3065 /* round up to 32-bytes, since this is granularity
3066 * of interpreter stack size
3068 depth
+= round_up(max_t(u32
, subprog
[idx
].stack_depth
, 1), 32);
3069 if (depth
> MAX_BPF_STACK
) {
3070 verbose(env
, "combined stack size of %d calls is %d. Too large\n",
3075 subprog_end
= subprog
[idx
+ 1].start
;
3076 for (; i
< subprog_end
; i
++) {
3077 if (insn
[i
].code
!= (BPF_JMP
| BPF_CALL
))
3079 if (insn
[i
].src_reg
!= BPF_PSEUDO_CALL
)
3081 /* remember insn and function to return to */
3082 ret_insn
[frame
] = i
+ 1;
3083 ret_prog
[frame
] = idx
;
3085 /* find the callee */
3086 i
= i
+ insn
[i
].imm
+ 1;
3087 idx
= find_subprog(env
, i
);
3089 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
3094 if (subprog
[idx
].has_tail_call
)
3095 tail_call_reachable
= true;
3098 if (frame
>= MAX_CALL_FRAMES
) {
3099 verbose(env
, "the call stack of %d frames is too deep !\n",
3105 /* if tail call got detected across bpf2bpf calls then mark each of the
3106 * currently present subprog frames as tail call reachable subprogs;
3107 * this info will be utilized by JIT so that we will be preserving the
3108 * tail call counter throughout bpf2bpf calls combined with tailcalls
3110 if (tail_call_reachable
)
3111 for (j
= 0; j
< frame
; j
++)
3112 subprog
[ret_prog
[j
]].tail_call_reachable
= true;
3114 /* end of for() loop means the last insn of the 'subprog'
3115 * was reached. Doesn't matter whether it was JA or EXIT
3119 depth
-= round_up(max_t(u32
, subprog
[idx
].stack_depth
, 1), 32);
3121 i
= ret_insn
[frame
];
3122 idx
= ret_prog
[frame
];
3126 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
3127 static int get_callee_stack_depth(struct bpf_verifier_env
*env
,
3128 const struct bpf_insn
*insn
, int idx
)
3130 int start
= idx
+ insn
->imm
+ 1, subprog
;
3132 subprog
= find_subprog(env
, start
);
3134 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
3138 return env
->subprog_info
[subprog
].stack_depth
;
3142 int check_ctx_reg(struct bpf_verifier_env
*env
,
3143 const struct bpf_reg_state
*reg
, int regno
)
3145 /* Access to ctx or passing it to a helper is only allowed in
3146 * its original, unmodified form.
3150 verbose(env
, "dereference of modified ctx ptr R%d off=%d disallowed\n",
3155 if (!tnum_is_const(reg
->var_off
) || reg
->var_off
.value
) {
3158 tnum_strn(tn_buf
, sizeof(tn_buf
), reg
->var_off
);
3159 verbose(env
, "variable ctx access var_off=%s disallowed\n", tn_buf
);
3166 static int __check_buffer_access(struct bpf_verifier_env
*env
,
3167 const char *buf_info
,
3168 const struct bpf_reg_state
*reg
,
3169 int regno
, int off
, int size
)
3173 "R%d invalid %s buffer access: off=%d, size=%d\n",
3174 regno
, buf_info
, off
, size
);
3177 if (!tnum_is_const(reg
->var_off
) || reg
->var_off
.value
) {
3180 tnum_strn(tn_buf
, sizeof(tn_buf
), reg
->var_off
);
3182 "R%d invalid variable buffer offset: off=%d, var_off=%s\n",
3183 regno
, off
, tn_buf
);
3190 static int check_tp_buffer_access(struct bpf_verifier_env
*env
,
3191 const struct bpf_reg_state
*reg
,
3192 int regno
, int off
, int size
)
3196 err
= __check_buffer_access(env
, "tracepoint", reg
, regno
, off
, size
);
3200 if (off
+ size
> env
->prog
->aux
->max_tp_access
)
3201 env
->prog
->aux
->max_tp_access
= off
+ size
;
3206 static int check_buffer_access(struct bpf_verifier_env
*env
,
3207 const struct bpf_reg_state
*reg
,
3208 int regno
, int off
, int size
,
3209 bool zero_size_allowed
,
3210 const char *buf_info
,
3215 err
= __check_buffer_access(env
, buf_info
, reg
, regno
, off
, size
);
3219 if (off
+ size
> *max_access
)
3220 *max_access
= off
+ size
;
3225 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
3226 static void zext_32_to_64(struct bpf_reg_state
*reg
)
3228 reg
->var_off
= tnum_subreg(reg
->var_off
);
3229 __reg_assign_32_into_64(reg
);
3232 /* truncate register to smaller size (in bytes)
3233 * must be called with size < BPF_REG_SIZE
3235 static void coerce_reg_to_size(struct bpf_reg_state
*reg
, int size
)
3239 /* clear high bits in bit representation */
3240 reg
->var_off
= tnum_cast(reg
->var_off
, size
);
3242 /* fix arithmetic bounds */
3243 mask
= ((u64
)1 << (size
* 8)) - 1;
3244 if ((reg
->umin_value
& ~mask
) == (reg
->umax_value
& ~mask
)) {
3245 reg
->umin_value
&= mask
;
3246 reg
->umax_value
&= mask
;
3248 reg
->umin_value
= 0;
3249 reg
->umax_value
= mask
;
3251 reg
->smin_value
= reg
->umin_value
;
3252 reg
->smax_value
= reg
->umax_value
;
3254 /* If size is smaller than 32bit register the 32bit register
3255 * values are also truncated so we push 64-bit bounds into
3256 * 32-bit bounds. Above were truncated < 32-bits already.
3260 __reg_combine_64_into_32(reg
);
3263 static bool bpf_map_is_rdonly(const struct bpf_map
*map
)
3265 return (map
->map_flags
& BPF_F_RDONLY_PROG
) && map
->frozen
;
3268 static int bpf_map_direct_read(struct bpf_map
*map
, int off
, int size
, u64
*val
)
3274 err
= map
->ops
->map_direct_value_addr(map
, &addr
, off
);
3277 ptr
= (void *)(long)addr
+ off
;
3281 *val
= (u64
)*(u8
*)ptr
;
3284 *val
= (u64
)*(u16
*)ptr
;
3287 *val
= (u64
)*(u32
*)ptr
;
3298 static int check_ptr_to_btf_access(struct bpf_verifier_env
*env
,
3299 struct bpf_reg_state
*regs
,
3300 int regno
, int off
, int size
,
3301 enum bpf_access_type atype
,
3304 struct bpf_reg_state
*reg
= regs
+ regno
;
3305 const struct btf_type
*t
= btf_type_by_id(reg
->btf
, reg
->btf_id
);
3306 const char *tname
= btf_name_by_offset(reg
->btf
, t
->name_off
);
3312 "R%d is ptr_%s invalid negative access: off=%d\n",
3316 if (!tnum_is_const(reg
->var_off
) || reg
->var_off
.value
) {
3319 tnum_strn(tn_buf
, sizeof(tn_buf
), reg
->var_off
);
3321 "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
3322 regno
, tname
, off
, tn_buf
);
3326 if (env
->ops
->btf_struct_access
) {
3327 ret
= env
->ops
->btf_struct_access(&env
->log
, reg
->btf
, t
,
3328 off
, size
, atype
, &btf_id
);
3330 if (atype
!= BPF_READ
) {
3331 verbose(env
, "only read is supported\n");
3335 ret
= btf_struct_access(&env
->log
, reg
->btf
, t
, off
, size
,
3342 if (atype
== BPF_READ
&& value_regno
>= 0)
3343 mark_btf_ld_reg(env
, regs
, value_regno
, ret
, reg
->btf
, btf_id
);
3348 static int check_ptr_to_map_access(struct bpf_verifier_env
*env
,
3349 struct bpf_reg_state
*regs
,
3350 int regno
, int off
, int size
,
3351 enum bpf_access_type atype
,
3354 struct bpf_reg_state
*reg
= regs
+ regno
;
3355 struct bpf_map
*map
= reg
->map_ptr
;
3356 const struct btf_type
*t
;
3362 verbose(env
, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
3366 if (!map
->ops
->map_btf_id
|| !*map
->ops
->map_btf_id
) {
3367 verbose(env
, "map_ptr access not supported for map type %d\n",
3372 t
= btf_type_by_id(btf_vmlinux
, *map
->ops
->map_btf_id
);
3373 tname
= btf_name_by_offset(btf_vmlinux
, t
->name_off
);
3375 if (!env
->allow_ptr_to_map_access
) {
3377 "%s access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
3383 verbose(env
, "R%d is %s invalid negative access: off=%d\n",
3388 if (atype
!= BPF_READ
) {
3389 verbose(env
, "only read from %s is supported\n", tname
);
3393 ret
= btf_struct_access(&env
->log
, btf_vmlinux
, t
, off
, size
, atype
, &btf_id
);
3397 if (value_regno
>= 0)
3398 mark_btf_ld_reg(env
, regs
, value_regno
, ret
, btf_vmlinux
, btf_id
);
3404 /* check whether memory at (regno + off) is accessible for t = (read | write)
3405 * if t==write, value_regno is a register which value is stored into memory
3406 * if t==read, value_regno is a register which will receive the value from memory
3407 * if t==write && value_regno==-1, some unknown value is stored into memory
3408 * if t==read && value_regno==-1, don't care what we read from memory
3410 static int check_mem_access(struct bpf_verifier_env
*env
, int insn_idx
, u32 regno
,
3411 int off
, int bpf_size
, enum bpf_access_type t
,
3412 int value_regno
, bool strict_alignment_once
)
3414 struct bpf_reg_state
*regs
= cur_regs(env
);
3415 struct bpf_reg_state
*reg
= regs
+ regno
;
3416 struct bpf_func_state
*state
;
3419 size
= bpf_size_to_bytes(bpf_size
);
3423 /* alignment checks will add in reg->off themselves */
3424 err
= check_ptr_alignment(env
, reg
, off
, size
, strict_alignment_once
);
3428 /* for access checks, reg->off is just part of off */
3431 if (reg
->type
== PTR_TO_MAP_VALUE
) {
3432 if (t
== BPF_WRITE
&& value_regno
>= 0 &&
3433 is_pointer_value(env
, value_regno
)) {
3434 verbose(env
, "R%d leaks addr into map\n", value_regno
);
3437 err
= check_map_access_type(env
, regno
, off
, size
, t
);
3440 err
= check_map_access(env
, regno
, off
, size
, false);
3441 if (!err
&& t
== BPF_READ
&& value_regno
>= 0) {
3442 struct bpf_map
*map
= reg
->map_ptr
;
3444 /* if map is read-only, track its contents as scalars */
3445 if (tnum_is_const(reg
->var_off
) &&
3446 bpf_map_is_rdonly(map
) &&
3447 map
->ops
->map_direct_value_addr
) {
3448 int map_off
= off
+ reg
->var_off
.value
;
3451 err
= bpf_map_direct_read(map
, map_off
, size
,
3456 regs
[value_regno
].type
= SCALAR_VALUE
;
3457 __mark_reg_known(®s
[value_regno
], val
);
3459 mark_reg_unknown(env
, regs
, value_regno
);
3462 } else if (reg
->type
== PTR_TO_MEM
) {
3463 if (t
== BPF_WRITE
&& value_regno
>= 0 &&
3464 is_pointer_value(env
, value_regno
)) {
3465 verbose(env
, "R%d leaks addr into mem\n", value_regno
);
3468 err
= check_mem_region_access(env
, regno
, off
, size
,
3469 reg
->mem_size
, false);
3470 if (!err
&& t
== BPF_READ
&& value_regno
>= 0)
3471 mark_reg_unknown(env
, regs
, value_regno
);
3472 } else if (reg
->type
== PTR_TO_CTX
) {
3473 enum bpf_reg_type reg_type
= SCALAR_VALUE
;
3474 struct btf
*btf
= NULL
;
3477 if (t
== BPF_WRITE
&& value_regno
>= 0 &&
3478 is_pointer_value(env
, value_regno
)) {
3479 verbose(env
, "R%d leaks addr into ctx\n", value_regno
);
3483 err
= check_ctx_reg(env
, reg
, regno
);
3487 err
= check_ctx_access(env
, insn_idx
, off
, size
, t
, ®_type
, &btf
, &btf_id
);
3489 verbose_linfo(env
, insn_idx
, "; ");
3490 if (!err
&& t
== BPF_READ
&& value_regno
>= 0) {
3491 /* ctx access returns either a scalar, or a
3492 * PTR_TO_PACKET[_META,_END]. In the latter
3493 * case, we know the offset is zero.
3495 if (reg_type
== SCALAR_VALUE
) {
3496 mark_reg_unknown(env
, regs
, value_regno
);
3498 mark_reg_known_zero(env
, regs
,
3500 if (reg_type_may_be_null(reg_type
))
3501 regs
[value_regno
].id
= ++env
->id_gen
;
3502 /* A load of ctx field could have different
3503 * actual load size with the one encoded in the
3504 * insn. When the dst is PTR, it is for sure not
3507 regs
[value_regno
].subreg_def
= DEF_NOT_SUBREG
;
3508 if (reg_type
== PTR_TO_BTF_ID
||
3509 reg_type
== PTR_TO_BTF_ID_OR_NULL
) {
3510 regs
[value_regno
].btf
= btf
;
3511 regs
[value_regno
].btf_id
= btf_id
;
3514 regs
[value_regno
].type
= reg_type
;
3517 } else if (reg
->type
== PTR_TO_STACK
) {
3518 off
+= reg
->var_off
.value
;
3519 err
= check_stack_access(env
, reg
, off
, size
);
3523 state
= func(env
, reg
);
3524 err
= update_stack_depth(env
, state
, off
);
3529 err
= check_stack_write(env
, state
, off
, size
,
3530 value_regno
, insn_idx
);
3532 err
= check_stack_read(env
, state
, off
, size
,
3534 } else if (reg_is_pkt_pointer(reg
)) {
3535 if (t
== BPF_WRITE
&& !may_access_direct_pkt_data(env
, NULL
, t
)) {
3536 verbose(env
, "cannot write into packet\n");
3539 if (t
== BPF_WRITE
&& value_regno
>= 0 &&
3540 is_pointer_value(env
, value_regno
)) {
3541 verbose(env
, "R%d leaks addr into packet\n",
3545 err
= check_packet_access(env
, regno
, off
, size
, false);
3546 if (!err
&& t
== BPF_READ
&& value_regno
>= 0)
3547 mark_reg_unknown(env
, regs
, value_regno
);
3548 } else if (reg
->type
== PTR_TO_FLOW_KEYS
) {
3549 if (t
== BPF_WRITE
&& value_regno
>= 0 &&
3550 is_pointer_value(env
, value_regno
)) {
3551 verbose(env
, "R%d leaks addr into flow keys\n",
3556 err
= check_flow_keys_access(env
, off
, size
);
3557 if (!err
&& t
== BPF_READ
&& value_regno
>= 0)
3558 mark_reg_unknown(env
, regs
, value_regno
);
3559 } else if (type_is_sk_pointer(reg
->type
)) {
3560 if (t
== BPF_WRITE
) {
3561 verbose(env
, "R%d cannot write into %s\n",
3562 regno
, reg_type_str
[reg
->type
]);
3565 err
= check_sock_access(env
, insn_idx
, regno
, off
, size
, t
);
3566 if (!err
&& value_regno
>= 0)
3567 mark_reg_unknown(env
, regs
, value_regno
);
3568 } else if (reg
->type
== PTR_TO_TP_BUFFER
) {
3569 err
= check_tp_buffer_access(env
, reg
, regno
, off
, size
);
3570 if (!err
&& t
== BPF_READ
&& value_regno
>= 0)
3571 mark_reg_unknown(env
, regs
, value_regno
);
3572 } else if (reg
->type
== PTR_TO_BTF_ID
) {
3573 err
= check_ptr_to_btf_access(env
, regs
, regno
, off
, size
, t
,
3575 } else if (reg
->type
== CONST_PTR_TO_MAP
) {
3576 err
= check_ptr_to_map_access(env
, regs
, regno
, off
, size
, t
,
3578 } else if (reg
->type
== PTR_TO_RDONLY_BUF
) {
3579 if (t
== BPF_WRITE
) {
3580 verbose(env
, "R%d cannot write into %s\n",
3581 regno
, reg_type_str
[reg
->type
]);
3584 err
= check_buffer_access(env
, reg
, regno
, off
, size
, false,
3586 &env
->prog
->aux
->max_rdonly_access
);
3587 if (!err
&& value_regno
>= 0)
3588 mark_reg_unknown(env
, regs
, value_regno
);
3589 } else if (reg
->type
== PTR_TO_RDWR_BUF
) {
3590 err
= check_buffer_access(env
, reg
, regno
, off
, size
, false,
3592 &env
->prog
->aux
->max_rdwr_access
);
3593 if (!err
&& t
== BPF_READ
&& value_regno
>= 0)
3594 mark_reg_unknown(env
, regs
, value_regno
);
3596 verbose(env
, "R%d invalid mem access '%s'\n", regno
,
3597 reg_type_str
[reg
->type
]);
3601 if (!err
&& size
< BPF_REG_SIZE
&& value_regno
>= 0 && t
== BPF_READ
&&
3602 regs
[value_regno
].type
== SCALAR_VALUE
) {
3603 /* b/h/w load zero-extends, mark upper bits as known 0 */
3604 coerce_reg_to_size(®s
[value_regno
], size
);
3609 static int check_xadd(struct bpf_verifier_env
*env
, int insn_idx
, struct bpf_insn
*insn
)
3613 if ((BPF_SIZE(insn
->code
) != BPF_W
&& BPF_SIZE(insn
->code
) != BPF_DW
) ||
3615 verbose(env
, "BPF_XADD uses reserved fields\n");
3619 /* check src1 operand */
3620 err
= check_reg_arg(env
, insn
->src_reg
, SRC_OP
);
3624 /* check src2 operand */
3625 err
= check_reg_arg(env
, insn
->dst_reg
, SRC_OP
);
3629 if (is_pointer_value(env
, insn
->src_reg
)) {
3630 verbose(env
, "R%d leaks addr into mem\n", insn
->src_reg
);
3634 if (is_ctx_reg(env
, insn
->dst_reg
) ||
3635 is_pkt_reg(env
, insn
->dst_reg
) ||
3636 is_flow_key_reg(env
, insn
->dst_reg
) ||
3637 is_sk_reg(env
, insn
->dst_reg
)) {
3638 verbose(env
, "BPF_XADD stores into R%d %s is not allowed\n",
3640 reg_type_str
[reg_state(env
, insn
->dst_reg
)->type
]);
3644 /* check whether atomic_add can read the memory */
3645 err
= check_mem_access(env
, insn_idx
, insn
->dst_reg
, insn
->off
,
3646 BPF_SIZE(insn
->code
), BPF_READ
, -1, true);
3650 /* check whether atomic_add can write into the same memory */
3651 return check_mem_access(env
, insn_idx
, insn
->dst_reg
, insn
->off
,
3652 BPF_SIZE(insn
->code
), BPF_WRITE
, -1, true);
3655 static int __check_stack_boundary(struct bpf_verifier_env
*env
, u32 regno
,
3656 int off
, int access_size
,
3657 bool zero_size_allowed
)
3659 struct bpf_reg_state
*reg
= reg_state(env
, regno
);
3661 if (off
>= 0 || off
< -MAX_BPF_STACK
|| off
+ access_size
> 0 ||
3662 access_size
< 0 || (access_size
== 0 && !zero_size_allowed
)) {
3663 if (tnum_is_const(reg
->var_off
)) {
3664 verbose(env
, "invalid stack type R%d off=%d access_size=%d\n",
3665 regno
, off
, access_size
);
3669 tnum_strn(tn_buf
, sizeof(tn_buf
), reg
->var_off
);
3670 verbose(env
, "invalid stack type R%d var_off=%s access_size=%d\n",
3671 regno
, tn_buf
, access_size
);
3678 /* when register 'regno' is passed into function that will read 'access_size'
3679 * bytes from that pointer, make sure that it's within stack boundary
3680 * and all elements of stack are initialized.
3681 * Unlike most pointer bounds-checking functions, this one doesn't take an
3682 * 'off' argument, so it has to add in reg->off itself.
3684 static int check_stack_boundary(struct bpf_verifier_env
*env
, int regno
,
3685 int access_size
, bool zero_size_allowed
,
3686 struct bpf_call_arg_meta
*meta
)
3688 struct bpf_reg_state
*reg
= reg_state(env
, regno
);
3689 struct bpf_func_state
*state
= func(env
, reg
);
3690 int err
, min_off
, max_off
, i
, j
, slot
, spi
;
3692 if (tnum_is_const(reg
->var_off
)) {
3693 min_off
= max_off
= reg
->var_off
.value
+ reg
->off
;
3694 err
= __check_stack_boundary(env
, regno
, min_off
, access_size
,
3699 /* Variable offset is prohibited for unprivileged mode for
3700 * simplicity since it requires corresponding support in
3701 * Spectre masking for stack ALU.
3702 * See also retrieve_ptr_limit().
3704 if (!env
->bypass_spec_v1
) {
3707 tnum_strn(tn_buf
, sizeof(tn_buf
), reg
->var_off
);
3708 verbose(env
, "R%d indirect variable offset stack access prohibited for !root, var_off=%s\n",
3712 /* Only initialized buffer on stack is allowed to be accessed
3713 * with variable offset. With uninitialized buffer it's hard to
3714 * guarantee that whole memory is marked as initialized on
3715 * helper return since specific bounds are unknown what may
3716 * cause uninitialized stack leaking.
3718 if (meta
&& meta
->raw_mode
)
3721 if (reg
->smax_value
>= BPF_MAX_VAR_OFF
||
3722 reg
->smax_value
<= -BPF_MAX_VAR_OFF
) {
3723 verbose(env
, "R%d unbounded indirect variable offset stack access\n",
3727 min_off
= reg
->smin_value
+ reg
->off
;
3728 max_off
= reg
->smax_value
+ reg
->off
;
3729 err
= __check_stack_boundary(env
, regno
, min_off
, access_size
,
3732 verbose(env
, "R%d min value is outside of stack bound\n",
3736 err
= __check_stack_boundary(env
, regno
, max_off
, access_size
,
3739 verbose(env
, "R%d max value is outside of stack bound\n",
3745 if (meta
&& meta
->raw_mode
) {
3746 meta
->access_size
= access_size
;
3747 meta
->regno
= regno
;
3751 for (i
= min_off
; i
< max_off
+ access_size
; i
++) {
3755 spi
= slot
/ BPF_REG_SIZE
;
3756 if (state
->allocated_stack
<= slot
)
3758 stype
= &state
->stack
[spi
].slot_type
[slot
% BPF_REG_SIZE
];
3759 if (*stype
== STACK_MISC
)
3761 if (*stype
== STACK_ZERO
) {
3762 /* helper can write anything into the stack */
3763 *stype
= STACK_MISC
;
3767 if (state
->stack
[spi
].slot_type
[0] == STACK_SPILL
&&
3768 state
->stack
[spi
].spilled_ptr
.type
== PTR_TO_BTF_ID
)
3771 if (state
->stack
[spi
].slot_type
[0] == STACK_SPILL
&&
3772 (state
->stack
[spi
].spilled_ptr
.type
== SCALAR_VALUE
||
3773 env
->allow_ptr_leaks
)) {
3774 __mark_reg_unknown(env
, &state
->stack
[spi
].spilled_ptr
);
3775 for (j
= 0; j
< BPF_REG_SIZE
; j
++)
3776 state
->stack
[spi
].slot_type
[j
] = STACK_MISC
;
3781 if (tnum_is_const(reg
->var_off
)) {
3782 verbose(env
, "invalid indirect read from stack off %d+%d size %d\n",
3783 min_off
, i
- min_off
, access_size
);
3787 tnum_strn(tn_buf
, sizeof(tn_buf
), reg
->var_off
);
3788 verbose(env
, "invalid indirect read from stack var_off %s+%d size %d\n",
3789 tn_buf
, i
- min_off
, access_size
);
3793 /* reading any byte out of 8-byte 'spill_slot' will cause
3794 * the whole slot to be marked as 'read'
3796 mark_reg_read(env
, &state
->stack
[spi
].spilled_ptr
,
3797 state
->stack
[spi
].spilled_ptr
.parent
,
3800 return update_stack_depth(env
, state
, min_off
);
3803 static int check_helper_mem_access(struct bpf_verifier_env
*env
, int regno
,
3804 int access_size
, bool zero_size_allowed
,
3805 struct bpf_call_arg_meta
*meta
)
3807 struct bpf_reg_state
*regs
= cur_regs(env
), *reg
= ®s
[regno
];
3809 switch (reg
->type
) {
3811 case PTR_TO_PACKET_META
:
3812 return check_packet_access(env
, regno
, reg
->off
, access_size
,
3814 case PTR_TO_MAP_VALUE
:
3815 if (check_map_access_type(env
, regno
, reg
->off
, access_size
,
3816 meta
&& meta
->raw_mode
? BPF_WRITE
:
3819 return check_map_access(env
, regno
, reg
->off
, access_size
,
3822 return check_mem_region_access(env
, regno
, reg
->off
,
3823 access_size
, reg
->mem_size
,
3825 case PTR_TO_RDONLY_BUF
:
3826 if (meta
&& meta
->raw_mode
)
3828 return check_buffer_access(env
, reg
, regno
, reg
->off
,
3829 access_size
, zero_size_allowed
,
3831 &env
->prog
->aux
->max_rdonly_access
);
3832 case PTR_TO_RDWR_BUF
:
3833 return check_buffer_access(env
, reg
, regno
, reg
->off
,
3834 access_size
, zero_size_allowed
,
3836 &env
->prog
->aux
->max_rdwr_access
);
3838 return check_stack_boundary(env
, regno
, access_size
,
3839 zero_size_allowed
, meta
);
3840 default: /* scalar_value or invalid ptr */
3841 /* Allow zero-byte read from NULL, regardless of pointer type */
3842 if (zero_size_allowed
&& access_size
== 0 &&
3843 register_is_null(reg
))
3846 verbose(env
, "R%d type=%s expected=%s\n", regno
,
3847 reg_type_str
[reg
->type
],
3848 reg_type_str
[PTR_TO_STACK
]);
3853 /* Implementation details:
3854 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL
3855 * Two bpf_map_lookups (even with the same key) will have different reg->id.
3856 * For traditional PTR_TO_MAP_VALUE the verifier clears reg->id after
3857 * value_or_null->value transition, since the verifier only cares about
3858 * the range of access to valid map value pointer and doesn't care about actual
3859 * address of the map element.
3860 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
3861 * reg->id > 0 after value_or_null->value transition. By doing so
3862 * two bpf_map_lookups will be considered two different pointers that
3863 * point to different bpf_spin_locks.
3864 * The verifier allows taking only one bpf_spin_lock at a time to avoid
3866 * Since only one bpf_spin_lock is allowed the checks are simpler than
3867 * reg_is_refcounted() logic. The verifier needs to remember only
3868 * one spin_lock instead of array of acquired_refs.
3869 * cur_state->active_spin_lock remembers which map value element got locked
3870 * and clears it after bpf_spin_unlock.
3872 static int process_spin_lock(struct bpf_verifier_env
*env
, int regno
,
3875 struct bpf_reg_state
*regs
= cur_regs(env
), *reg
= ®s
[regno
];
3876 struct bpf_verifier_state
*cur
= env
->cur_state
;
3877 bool is_const
= tnum_is_const(reg
->var_off
);
3878 struct bpf_map
*map
= reg
->map_ptr
;
3879 u64 val
= reg
->var_off
.value
;
3883 "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
3889 "map '%s' has to have BTF in order to use bpf_spin_lock\n",
3893 if (!map_value_has_spin_lock(map
)) {
3894 if (map
->spin_lock_off
== -E2BIG
)
3896 "map '%s' has more than one 'struct bpf_spin_lock'\n",
3898 else if (map
->spin_lock_off
== -ENOENT
)
3900 "map '%s' doesn't have 'struct bpf_spin_lock'\n",
3904 "map '%s' is not a struct type or bpf_spin_lock is mangled\n",
3908 if (map
->spin_lock_off
!= val
+ reg
->off
) {
3909 verbose(env
, "off %lld doesn't point to 'struct bpf_spin_lock'\n",
3914 if (cur
->active_spin_lock
) {
3916 "Locking two bpf_spin_locks are not allowed\n");
3919 cur
->active_spin_lock
= reg
->id
;
3921 if (!cur
->active_spin_lock
) {
3922 verbose(env
, "bpf_spin_unlock without taking a lock\n");
3925 if (cur
->active_spin_lock
!= reg
->id
) {
3926 verbose(env
, "bpf_spin_unlock of different lock\n");
3929 cur
->active_spin_lock
= 0;
3934 static bool arg_type_is_mem_ptr(enum bpf_arg_type type
)
3936 return type
== ARG_PTR_TO_MEM
||
3937 type
== ARG_PTR_TO_MEM_OR_NULL
||
3938 type
== ARG_PTR_TO_UNINIT_MEM
;
3941 static bool arg_type_is_mem_size(enum bpf_arg_type type
)
3943 return type
== ARG_CONST_SIZE
||
3944 type
== ARG_CONST_SIZE_OR_ZERO
;
3947 static bool arg_type_is_alloc_size(enum bpf_arg_type type
)
3949 return type
== ARG_CONST_ALLOC_SIZE_OR_ZERO
;
3952 static bool arg_type_is_int_ptr(enum bpf_arg_type type
)
3954 return type
== ARG_PTR_TO_INT
||
3955 type
== ARG_PTR_TO_LONG
;
3958 static int int_ptr_type_to_size(enum bpf_arg_type type
)
3960 if (type
== ARG_PTR_TO_INT
)
3962 else if (type
== ARG_PTR_TO_LONG
)
3968 static int resolve_map_arg_type(struct bpf_verifier_env
*env
,
3969 const struct bpf_call_arg_meta
*meta
,
3970 enum bpf_arg_type
*arg_type
)
3972 if (!meta
->map_ptr
) {
3973 /* kernel subsystem misconfigured verifier */
3974 verbose(env
, "invalid map_ptr to access map->type\n");
3978 switch (meta
->map_ptr
->map_type
) {
3979 case BPF_MAP_TYPE_SOCKMAP
:
3980 case BPF_MAP_TYPE_SOCKHASH
:
3981 if (*arg_type
== ARG_PTR_TO_MAP_VALUE
) {
3982 *arg_type
= ARG_PTR_TO_BTF_ID_SOCK_COMMON
;
3984 verbose(env
, "invalid arg_type for sockmap/sockhash\n");
3995 struct bpf_reg_types
{
3996 const enum bpf_reg_type types
[10];
4000 static const struct bpf_reg_types map_key_value_types
= {
4009 static const struct bpf_reg_types sock_types
= {
4019 static const struct bpf_reg_types btf_id_sock_common_types
= {
4027 .btf_id
= &btf_sock_ids
[BTF_SOCK_TYPE_SOCK_COMMON
],
4031 static const struct bpf_reg_types mem_types
= {
4043 static const struct bpf_reg_types int_ptr_types
= {
4052 static const struct bpf_reg_types fullsock_types
= { .types
= { PTR_TO_SOCKET
} };
4053 static const struct bpf_reg_types scalar_types
= { .types
= { SCALAR_VALUE
} };
4054 static const struct bpf_reg_types context_types
= { .types
= { PTR_TO_CTX
} };
4055 static const struct bpf_reg_types alloc_mem_types
= { .types
= { PTR_TO_MEM
} };
4056 static const struct bpf_reg_types const_map_ptr_types
= { .types
= { CONST_PTR_TO_MAP
} };
4057 static const struct bpf_reg_types btf_ptr_types
= { .types
= { PTR_TO_BTF_ID
} };
4058 static const struct bpf_reg_types spin_lock_types
= { .types
= { PTR_TO_MAP_VALUE
} };
4059 static const struct bpf_reg_types percpu_btf_ptr_types
= { .types
= { PTR_TO_PERCPU_BTF_ID
} };
4061 static const struct bpf_reg_types
*compatible_reg_types
[__BPF_ARG_TYPE_MAX
] = {
4062 [ARG_PTR_TO_MAP_KEY
] = &map_key_value_types
,
4063 [ARG_PTR_TO_MAP_VALUE
] = &map_key_value_types
,
4064 [ARG_PTR_TO_UNINIT_MAP_VALUE
] = &map_key_value_types
,
4065 [ARG_PTR_TO_MAP_VALUE_OR_NULL
] = &map_key_value_types
,
4066 [ARG_CONST_SIZE
] = &scalar_types
,
4067 [ARG_CONST_SIZE_OR_ZERO
] = &scalar_types
,
4068 [ARG_CONST_ALLOC_SIZE_OR_ZERO
] = &scalar_types
,
4069 [ARG_CONST_MAP_PTR
] = &const_map_ptr_types
,
4070 [ARG_PTR_TO_CTX
] = &context_types
,
4071 [ARG_PTR_TO_CTX_OR_NULL
] = &context_types
,
4072 [ARG_PTR_TO_SOCK_COMMON
] = &sock_types
,
4074 [ARG_PTR_TO_BTF_ID_SOCK_COMMON
] = &btf_id_sock_common_types
,
4076 [ARG_PTR_TO_SOCKET
] = &fullsock_types
,
4077 [ARG_PTR_TO_SOCKET_OR_NULL
] = &fullsock_types
,
4078 [ARG_PTR_TO_BTF_ID
] = &btf_ptr_types
,
4079 [ARG_PTR_TO_SPIN_LOCK
] = &spin_lock_types
,
4080 [ARG_PTR_TO_MEM
] = &mem_types
,
4081 [ARG_PTR_TO_MEM_OR_NULL
] = &mem_types
,
4082 [ARG_PTR_TO_UNINIT_MEM
] = &mem_types
,
4083 [ARG_PTR_TO_ALLOC_MEM
] = &alloc_mem_types
,
4084 [ARG_PTR_TO_ALLOC_MEM_OR_NULL
] = &alloc_mem_types
,
4085 [ARG_PTR_TO_INT
] = &int_ptr_types
,
4086 [ARG_PTR_TO_LONG
] = &int_ptr_types
,
4087 [ARG_PTR_TO_PERCPU_BTF_ID
] = &percpu_btf_ptr_types
,
4090 static int check_reg_type(struct bpf_verifier_env
*env
, u32 regno
,
4091 enum bpf_arg_type arg_type
,
4092 const u32
*arg_btf_id
)
4094 struct bpf_reg_state
*regs
= cur_regs(env
), *reg
= ®s
[regno
];
4095 enum bpf_reg_type expected
, type
= reg
->type
;
4096 const struct bpf_reg_types
*compatible
;
4099 compatible
= compatible_reg_types
[arg_type
];
4101 verbose(env
, "verifier internal error: unsupported arg type %d\n", arg_type
);
4105 for (i
= 0; i
< ARRAY_SIZE(compatible
->types
); i
++) {
4106 expected
= compatible
->types
[i
];
4107 if (expected
== NOT_INIT
)
4110 if (type
== expected
)
4114 verbose(env
, "R%d type=%s expected=", regno
, reg_type_str
[type
]);
4115 for (j
= 0; j
+ 1 < i
; j
++)
4116 verbose(env
, "%s, ", reg_type_str
[compatible
->types
[j
]]);
4117 verbose(env
, "%s\n", reg_type_str
[compatible
->types
[j
]]);
4121 if (type
== PTR_TO_BTF_ID
) {
4123 if (!compatible
->btf_id
) {
4124 verbose(env
, "verifier internal error: missing arg compatible BTF ID\n");
4127 arg_btf_id
= compatible
->btf_id
;
4130 if (!btf_struct_ids_match(&env
->log
, reg
->btf
, reg
->btf_id
, reg
->off
,
4131 btf_vmlinux
, *arg_btf_id
)) {
4132 verbose(env
, "R%d is of type %s but %s is expected\n",
4133 regno
, kernel_type_name(reg
->btf
, reg
->btf_id
),
4134 kernel_type_name(btf_vmlinux
, *arg_btf_id
));
4138 if (!tnum_is_const(reg
->var_off
) || reg
->var_off
.value
) {
4139 verbose(env
, "R%d is a pointer to in-kernel struct with non-zero offset\n",
4148 static int check_func_arg(struct bpf_verifier_env
*env
, u32 arg
,
4149 struct bpf_call_arg_meta
*meta
,
4150 const struct bpf_func_proto
*fn
)
4152 u32 regno
= BPF_REG_1
+ arg
;
4153 struct bpf_reg_state
*regs
= cur_regs(env
), *reg
= ®s
[regno
];
4154 enum bpf_arg_type arg_type
= fn
->arg_type
[arg
];
4155 enum bpf_reg_type type
= reg
->type
;
4158 if (arg_type
== ARG_DONTCARE
)
4161 err
= check_reg_arg(env
, regno
, SRC_OP
);
4165 if (arg_type
== ARG_ANYTHING
) {
4166 if (is_pointer_value(env
, regno
)) {
4167 verbose(env
, "R%d leaks addr into helper function\n",
4174 if (type_is_pkt_pointer(type
) &&
4175 !may_access_direct_pkt_data(env
, meta
, BPF_READ
)) {
4176 verbose(env
, "helper access to the packet is not allowed\n");
4180 if (arg_type
== ARG_PTR_TO_MAP_VALUE
||
4181 arg_type
== ARG_PTR_TO_UNINIT_MAP_VALUE
||
4182 arg_type
== ARG_PTR_TO_MAP_VALUE_OR_NULL
) {
4183 err
= resolve_map_arg_type(env
, meta
, &arg_type
);
4188 if (register_is_null(reg
) && arg_type_may_be_null(arg_type
))
4189 /* A NULL register has a SCALAR_VALUE type, so skip
4192 goto skip_type_check
;
4194 err
= check_reg_type(env
, regno
, arg_type
, fn
->arg_btf_id
[arg
]);
4198 if (type
== PTR_TO_CTX
) {
4199 err
= check_ctx_reg(env
, reg
, regno
);
4205 if (reg
->ref_obj_id
) {
4206 if (meta
->ref_obj_id
) {
4207 verbose(env
, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
4208 regno
, reg
->ref_obj_id
,
4212 meta
->ref_obj_id
= reg
->ref_obj_id
;
4215 if (arg_type
== ARG_CONST_MAP_PTR
) {
4216 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
4217 meta
->map_ptr
= reg
->map_ptr
;
4218 } else if (arg_type
== ARG_PTR_TO_MAP_KEY
) {
4219 /* bpf_map_xxx(..., map_ptr, ..., key) call:
4220 * check that [key, key + map->key_size) are within
4221 * stack limits and initialized
4223 if (!meta
->map_ptr
) {
4224 /* in function declaration map_ptr must come before
4225 * map_key, so that it's verified and known before
4226 * we have to check map_key here. Otherwise it means
4227 * that kernel subsystem misconfigured verifier
4229 verbose(env
, "invalid map_ptr to access map->key\n");
4232 err
= check_helper_mem_access(env
, regno
,
4233 meta
->map_ptr
->key_size
, false,
4235 } else if (arg_type
== ARG_PTR_TO_MAP_VALUE
||
4236 (arg_type
== ARG_PTR_TO_MAP_VALUE_OR_NULL
&&
4237 !register_is_null(reg
)) ||
4238 arg_type
== ARG_PTR_TO_UNINIT_MAP_VALUE
) {
4239 /* bpf_map_xxx(..., map_ptr, ..., value) call:
4240 * check [value, value + map->value_size) validity
4242 if (!meta
->map_ptr
) {
4243 /* kernel subsystem misconfigured verifier */
4244 verbose(env
, "invalid map_ptr to access map->value\n");
4247 meta
->raw_mode
= (arg_type
== ARG_PTR_TO_UNINIT_MAP_VALUE
);
4248 err
= check_helper_mem_access(env
, regno
,
4249 meta
->map_ptr
->value_size
, false,
4251 } else if (arg_type
== ARG_PTR_TO_PERCPU_BTF_ID
) {
4253 verbose(env
, "Helper has invalid btf_id in R%d\n", regno
);
4256 meta
->ret_btf
= reg
->btf
;
4257 meta
->ret_btf_id
= reg
->btf_id
;
4258 } else if (arg_type
== ARG_PTR_TO_SPIN_LOCK
) {
4259 if (meta
->func_id
== BPF_FUNC_spin_lock
) {
4260 if (process_spin_lock(env
, regno
, true))
4262 } else if (meta
->func_id
== BPF_FUNC_spin_unlock
) {
4263 if (process_spin_lock(env
, regno
, false))
4266 verbose(env
, "verifier internal error\n");
4269 } else if (arg_type_is_mem_ptr(arg_type
)) {
4270 /* The access to this pointer is only checked when we hit the
4271 * next is_mem_size argument below.
4273 meta
->raw_mode
= (arg_type
== ARG_PTR_TO_UNINIT_MEM
);
4274 } else if (arg_type_is_mem_size(arg_type
)) {
4275 bool zero_size_allowed
= (arg_type
== ARG_CONST_SIZE_OR_ZERO
);
4277 /* This is used to refine r0 return value bounds for helpers
4278 * that enforce this value as an upper bound on return values.
4279 * See do_refine_retval_range() for helpers that can refine
4280 * the return value. C type of helper is u32 so we pull register
4281 * bound from umax_value however, if negative verifier errors
4282 * out. Only upper bounds can be learned because retval is an
4283 * int type and negative retvals are allowed.
4285 meta
->msize_max_value
= reg
->umax_value
;
4287 /* The register is SCALAR_VALUE; the access check
4288 * happens using its boundaries.
4290 if (!tnum_is_const(reg
->var_off
))
4291 /* For unprivileged variable accesses, disable raw
4292 * mode so that the program is required to
4293 * initialize all the memory that the helper could
4294 * just partially fill up.
4298 if (reg
->smin_value
< 0) {
4299 verbose(env
, "R%d min value is negative, either use unsigned or 'var &= const'\n",
4304 if (reg
->umin_value
== 0) {
4305 err
= check_helper_mem_access(env
, regno
- 1, 0,
4312 if (reg
->umax_value
>= BPF_MAX_VAR_SIZ
) {
4313 verbose(env
, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
4317 err
= check_helper_mem_access(env
, regno
- 1,
4319 zero_size_allowed
, meta
);
4321 err
= mark_chain_precision(env
, regno
);
4322 } else if (arg_type_is_alloc_size(arg_type
)) {
4323 if (!tnum_is_const(reg
->var_off
)) {
4324 verbose(env
, "R%d unbounded size, use 'var &= const' or 'if (var < const)'\n",
4328 meta
->mem_size
= reg
->var_off
.value
;
4329 } else if (arg_type_is_int_ptr(arg_type
)) {
4330 int size
= int_ptr_type_to_size(arg_type
);
4332 err
= check_helper_mem_access(env
, regno
, size
, false, meta
);
4335 err
= check_ptr_alignment(env
, reg
, 0, size
, true);
4341 static bool may_update_sockmap(struct bpf_verifier_env
*env
, int func_id
)
4343 enum bpf_attach_type eatype
= env
->prog
->expected_attach_type
;
4344 enum bpf_prog_type type
= resolve_prog_type(env
->prog
);
4346 if (func_id
!= BPF_FUNC_map_update_elem
)
4349 /* It's not possible to get access to a locked struct sock in these
4350 * contexts, so updating is safe.
4353 case BPF_PROG_TYPE_TRACING
:
4354 if (eatype
== BPF_TRACE_ITER
)
4357 case BPF_PROG_TYPE_SOCKET_FILTER
:
4358 case BPF_PROG_TYPE_SCHED_CLS
:
4359 case BPF_PROG_TYPE_SCHED_ACT
:
4360 case BPF_PROG_TYPE_XDP
:
4361 case BPF_PROG_TYPE_SK_REUSEPORT
:
4362 case BPF_PROG_TYPE_FLOW_DISSECTOR
:
4363 case BPF_PROG_TYPE_SK_LOOKUP
:
4369 verbose(env
, "cannot update sockmap in this context\n");
4373 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env
*env
)
4375 return env
->prog
->jit_requested
&& IS_ENABLED(CONFIG_X86_64
);
4378 static int check_map_func_compatibility(struct bpf_verifier_env
*env
,
4379 struct bpf_map
*map
, int func_id
)
4384 /* We need a two way check, first is from map perspective ... */
4385 switch (map
->map_type
) {
4386 case BPF_MAP_TYPE_PROG_ARRAY
:
4387 if (func_id
!= BPF_FUNC_tail_call
)
4390 case BPF_MAP_TYPE_PERF_EVENT_ARRAY
:
4391 if (func_id
!= BPF_FUNC_perf_event_read
&&
4392 func_id
!= BPF_FUNC_perf_event_output
&&
4393 func_id
!= BPF_FUNC_skb_output
&&
4394 func_id
!= BPF_FUNC_perf_event_read_value
&&
4395 func_id
!= BPF_FUNC_xdp_output
)
4398 case BPF_MAP_TYPE_RINGBUF
:
4399 if (func_id
!= BPF_FUNC_ringbuf_output
&&
4400 func_id
!= BPF_FUNC_ringbuf_reserve
&&
4401 func_id
!= BPF_FUNC_ringbuf_submit
&&
4402 func_id
!= BPF_FUNC_ringbuf_discard
&&
4403 func_id
!= BPF_FUNC_ringbuf_query
)
4406 case BPF_MAP_TYPE_STACK_TRACE
:
4407 if (func_id
!= BPF_FUNC_get_stackid
)
4410 case BPF_MAP_TYPE_CGROUP_ARRAY
:
4411 if (func_id
!= BPF_FUNC_skb_under_cgroup
&&
4412 func_id
!= BPF_FUNC_current_task_under_cgroup
)
4415 case BPF_MAP_TYPE_CGROUP_STORAGE
:
4416 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE
:
4417 if (func_id
!= BPF_FUNC_get_local_storage
)
4420 case BPF_MAP_TYPE_DEVMAP
:
4421 case BPF_MAP_TYPE_DEVMAP_HASH
:
4422 if (func_id
!= BPF_FUNC_redirect_map
&&
4423 func_id
!= BPF_FUNC_map_lookup_elem
)
4426 /* Restrict bpf side of cpumap and xskmap, open when use-cases
4429 case BPF_MAP_TYPE_CPUMAP
:
4430 if (func_id
!= BPF_FUNC_redirect_map
)
4433 case BPF_MAP_TYPE_XSKMAP
:
4434 if (func_id
!= BPF_FUNC_redirect_map
&&
4435 func_id
!= BPF_FUNC_map_lookup_elem
)
4438 case BPF_MAP_TYPE_ARRAY_OF_MAPS
:
4439 case BPF_MAP_TYPE_HASH_OF_MAPS
:
4440 if (func_id
!= BPF_FUNC_map_lookup_elem
)
4443 case BPF_MAP_TYPE_SOCKMAP
:
4444 if (func_id
!= BPF_FUNC_sk_redirect_map
&&
4445 func_id
!= BPF_FUNC_sock_map_update
&&
4446 func_id
!= BPF_FUNC_map_delete_elem
&&
4447 func_id
!= BPF_FUNC_msg_redirect_map
&&
4448 func_id
!= BPF_FUNC_sk_select_reuseport
&&
4449 func_id
!= BPF_FUNC_map_lookup_elem
&&
4450 !may_update_sockmap(env
, func_id
))
4453 case BPF_MAP_TYPE_SOCKHASH
:
4454 if (func_id
!= BPF_FUNC_sk_redirect_hash
&&
4455 func_id
!= BPF_FUNC_sock_hash_update
&&
4456 func_id
!= BPF_FUNC_map_delete_elem
&&
4457 func_id
!= BPF_FUNC_msg_redirect_hash
&&
4458 func_id
!= BPF_FUNC_sk_select_reuseport
&&
4459 func_id
!= BPF_FUNC_map_lookup_elem
&&
4460 !may_update_sockmap(env
, func_id
))
4463 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY
:
4464 if (func_id
!= BPF_FUNC_sk_select_reuseport
)
4467 case BPF_MAP_TYPE_QUEUE
:
4468 case BPF_MAP_TYPE_STACK
:
4469 if (func_id
!= BPF_FUNC_map_peek_elem
&&
4470 func_id
!= BPF_FUNC_map_pop_elem
&&
4471 func_id
!= BPF_FUNC_map_push_elem
)
4474 case BPF_MAP_TYPE_SK_STORAGE
:
4475 if (func_id
!= BPF_FUNC_sk_storage_get
&&
4476 func_id
!= BPF_FUNC_sk_storage_delete
)
4479 case BPF_MAP_TYPE_INODE_STORAGE
:
4480 if (func_id
!= BPF_FUNC_inode_storage_get
&&
4481 func_id
!= BPF_FUNC_inode_storage_delete
)
4484 case BPF_MAP_TYPE_TASK_STORAGE
:
4485 if (func_id
!= BPF_FUNC_task_storage_get
&&
4486 func_id
!= BPF_FUNC_task_storage_delete
)
4493 /* ... and second from the function itself. */
4495 case BPF_FUNC_tail_call
:
4496 if (map
->map_type
!= BPF_MAP_TYPE_PROG_ARRAY
)
4498 if (env
->subprog_cnt
> 1 && !allow_tail_call_in_subprogs(env
)) {
4499 verbose(env
, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
4503 case BPF_FUNC_perf_event_read
:
4504 case BPF_FUNC_perf_event_output
:
4505 case BPF_FUNC_perf_event_read_value
:
4506 case BPF_FUNC_skb_output
:
4507 case BPF_FUNC_xdp_output
:
4508 if (map
->map_type
!= BPF_MAP_TYPE_PERF_EVENT_ARRAY
)
4511 case BPF_FUNC_get_stackid
:
4512 if (map
->map_type
!= BPF_MAP_TYPE_STACK_TRACE
)
4515 case BPF_FUNC_current_task_under_cgroup
:
4516 case BPF_FUNC_skb_under_cgroup
:
4517 if (map
->map_type
!= BPF_MAP_TYPE_CGROUP_ARRAY
)
4520 case BPF_FUNC_redirect_map
:
4521 if (map
->map_type
!= BPF_MAP_TYPE_DEVMAP
&&
4522 map
->map_type
!= BPF_MAP_TYPE_DEVMAP_HASH
&&
4523 map
->map_type
!= BPF_MAP_TYPE_CPUMAP
&&
4524 map
->map_type
!= BPF_MAP_TYPE_XSKMAP
)
4527 case BPF_FUNC_sk_redirect_map
:
4528 case BPF_FUNC_msg_redirect_map
:
4529 case BPF_FUNC_sock_map_update
:
4530 if (map
->map_type
!= BPF_MAP_TYPE_SOCKMAP
)
4533 case BPF_FUNC_sk_redirect_hash
:
4534 case BPF_FUNC_msg_redirect_hash
:
4535 case BPF_FUNC_sock_hash_update
:
4536 if (map
->map_type
!= BPF_MAP_TYPE_SOCKHASH
)
4539 case BPF_FUNC_get_local_storage
:
4540 if (map
->map_type
!= BPF_MAP_TYPE_CGROUP_STORAGE
&&
4541 map
->map_type
!= BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE
)
4544 case BPF_FUNC_sk_select_reuseport
:
4545 if (map
->map_type
!= BPF_MAP_TYPE_REUSEPORT_SOCKARRAY
&&
4546 map
->map_type
!= BPF_MAP_TYPE_SOCKMAP
&&
4547 map
->map_type
!= BPF_MAP_TYPE_SOCKHASH
)
4550 case BPF_FUNC_map_peek_elem
:
4551 case BPF_FUNC_map_pop_elem
:
4552 case BPF_FUNC_map_push_elem
:
4553 if (map
->map_type
!= BPF_MAP_TYPE_QUEUE
&&
4554 map
->map_type
!= BPF_MAP_TYPE_STACK
)
4557 case BPF_FUNC_sk_storage_get
:
4558 case BPF_FUNC_sk_storage_delete
:
4559 if (map
->map_type
!= BPF_MAP_TYPE_SK_STORAGE
)
4562 case BPF_FUNC_inode_storage_get
:
4563 case BPF_FUNC_inode_storage_delete
:
4564 if (map
->map_type
!= BPF_MAP_TYPE_INODE_STORAGE
)
4567 case BPF_FUNC_task_storage_get
:
4568 case BPF_FUNC_task_storage_delete
:
4569 if (map
->map_type
!= BPF_MAP_TYPE_TASK_STORAGE
)
4578 verbose(env
, "cannot pass map_type %d into func %s#%d\n",
4579 map
->map_type
, func_id_name(func_id
), func_id
);
4583 static bool check_raw_mode_ok(const struct bpf_func_proto
*fn
)
4587 if (fn
->arg1_type
== ARG_PTR_TO_UNINIT_MEM
)
4589 if (fn
->arg2_type
== ARG_PTR_TO_UNINIT_MEM
)
4591 if (fn
->arg3_type
== ARG_PTR_TO_UNINIT_MEM
)
4593 if (fn
->arg4_type
== ARG_PTR_TO_UNINIT_MEM
)
4595 if (fn
->arg5_type
== ARG_PTR_TO_UNINIT_MEM
)
4598 /* We only support one arg being in raw mode at the moment,
4599 * which is sufficient for the helper functions we have
4605 static bool check_args_pair_invalid(enum bpf_arg_type arg_curr
,
4606 enum bpf_arg_type arg_next
)
4608 return (arg_type_is_mem_ptr(arg_curr
) &&
4609 !arg_type_is_mem_size(arg_next
)) ||
4610 (!arg_type_is_mem_ptr(arg_curr
) &&
4611 arg_type_is_mem_size(arg_next
));
4614 static bool check_arg_pair_ok(const struct bpf_func_proto
*fn
)
4616 /* bpf_xxx(..., buf, len) call will access 'len'
4617 * bytes from memory 'buf'. Both arg types need
4618 * to be paired, so make sure there's no buggy
4619 * helper function specification.
4621 if (arg_type_is_mem_size(fn
->arg1_type
) ||
4622 arg_type_is_mem_ptr(fn
->arg5_type
) ||
4623 check_args_pair_invalid(fn
->arg1_type
, fn
->arg2_type
) ||
4624 check_args_pair_invalid(fn
->arg2_type
, fn
->arg3_type
) ||
4625 check_args_pair_invalid(fn
->arg3_type
, fn
->arg4_type
) ||
4626 check_args_pair_invalid(fn
->arg4_type
, fn
->arg5_type
))
4632 static bool check_refcount_ok(const struct bpf_func_proto
*fn
, int func_id
)
4636 if (arg_type_may_be_refcounted(fn
->arg1_type
))
4638 if (arg_type_may_be_refcounted(fn
->arg2_type
))
4640 if (arg_type_may_be_refcounted(fn
->arg3_type
))
4642 if (arg_type_may_be_refcounted(fn
->arg4_type
))
4644 if (arg_type_may_be_refcounted(fn
->arg5_type
))
4647 /* A reference acquiring function cannot acquire
4648 * another refcounted ptr.
4650 if (may_be_acquire_function(func_id
) && count
)
4653 /* We only support one arg being unreferenced at the moment,
4654 * which is sufficient for the helper functions we have right now.
4659 static bool check_btf_id_ok(const struct bpf_func_proto
*fn
)
4663 for (i
= 0; i
< ARRAY_SIZE(fn
->arg_type
); i
++) {
4664 if (fn
->arg_type
[i
] == ARG_PTR_TO_BTF_ID
&& !fn
->arg_btf_id
[i
])
4667 if (fn
->arg_type
[i
] != ARG_PTR_TO_BTF_ID
&& fn
->arg_btf_id
[i
])
4674 static int check_func_proto(const struct bpf_func_proto
*fn
, int func_id
)
4676 return check_raw_mode_ok(fn
) &&
4677 check_arg_pair_ok(fn
) &&
4678 check_btf_id_ok(fn
) &&
4679 check_refcount_ok(fn
, func_id
) ? 0 : -EINVAL
;
4682 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
4683 * are now invalid, so turn them into unknown SCALAR_VALUE.
4685 static void __clear_all_pkt_pointers(struct bpf_verifier_env
*env
,
4686 struct bpf_func_state
*state
)
4688 struct bpf_reg_state
*regs
= state
->regs
, *reg
;
4691 for (i
= 0; i
< MAX_BPF_REG
; i
++)
4692 if (reg_is_pkt_pointer_any(®s
[i
]))
4693 mark_reg_unknown(env
, regs
, i
);
4695 bpf_for_each_spilled_reg(i
, state
, reg
) {
4698 if (reg_is_pkt_pointer_any(reg
))
4699 __mark_reg_unknown(env
, reg
);
4703 static void clear_all_pkt_pointers(struct bpf_verifier_env
*env
)
4705 struct bpf_verifier_state
*vstate
= env
->cur_state
;
4708 for (i
= 0; i
<= vstate
->curframe
; i
++)
4709 __clear_all_pkt_pointers(env
, vstate
->frame
[i
]);
4714 BEYOND_PKT_END
= -2,
4717 static void mark_pkt_end(struct bpf_verifier_state
*vstate
, int regn
, bool range_open
)
4719 struct bpf_func_state
*state
= vstate
->frame
[vstate
->curframe
];
4720 struct bpf_reg_state
*reg
= &state
->regs
[regn
];
4722 if (reg
->type
!= PTR_TO_PACKET
)
4723 /* PTR_TO_PACKET_META is not supported yet */
4726 /* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
4727 * How far beyond pkt_end it goes is unknown.
4728 * if (!range_open) it's the case of pkt >= pkt_end
4729 * if (range_open) it's the case of pkt > pkt_end
4730 * hence this pointer is at least 1 byte bigger than pkt_end
4733 reg
->range
= BEYOND_PKT_END
;
4735 reg
->range
= AT_PKT_END
;
4738 static void release_reg_references(struct bpf_verifier_env
*env
,
4739 struct bpf_func_state
*state
,
4742 struct bpf_reg_state
*regs
= state
->regs
, *reg
;
4745 for (i
= 0; i
< MAX_BPF_REG
; i
++)
4746 if (regs
[i
].ref_obj_id
== ref_obj_id
)
4747 mark_reg_unknown(env
, regs
, i
);
4749 bpf_for_each_spilled_reg(i
, state
, reg
) {
4752 if (reg
->ref_obj_id
== ref_obj_id
)
4753 __mark_reg_unknown(env
, reg
);
4757 /* The pointer with the specified id has released its reference to kernel
4758 * resources. Identify all copies of the same pointer and clear the reference.
4760 static int release_reference(struct bpf_verifier_env
*env
,
4763 struct bpf_verifier_state
*vstate
= env
->cur_state
;
4767 err
= release_reference_state(cur_func(env
), ref_obj_id
);
4771 for (i
= 0; i
<= vstate
->curframe
; i
++)
4772 release_reg_references(env
, vstate
->frame
[i
], ref_obj_id
);
4777 static void clear_caller_saved_regs(struct bpf_verifier_env
*env
,
4778 struct bpf_reg_state
*regs
)
4782 /* after the call registers r0 - r5 were scratched */
4783 for (i
= 0; i
< CALLER_SAVED_REGS
; i
++) {
4784 mark_reg_not_init(env
, regs
, caller_saved
[i
]);
4785 check_reg_arg(env
, caller_saved
[i
], DST_OP_NO_MARK
);
4789 static int check_func_call(struct bpf_verifier_env
*env
, struct bpf_insn
*insn
,
4792 struct bpf_verifier_state
*state
= env
->cur_state
;
4793 struct bpf_func_info_aux
*func_info_aux
;
4794 struct bpf_func_state
*caller
, *callee
;
4795 int i
, err
, subprog
, target_insn
;
4796 bool is_global
= false;
4798 if (state
->curframe
+ 1 >= MAX_CALL_FRAMES
) {
4799 verbose(env
, "the call stack of %d frames is too deep\n",
4800 state
->curframe
+ 2);
4804 target_insn
= *insn_idx
+ insn
->imm
;
4805 subprog
= find_subprog(env
, target_insn
+ 1);
4807 verbose(env
, "verifier bug. No program starts at insn %d\n",
4812 caller
= state
->frame
[state
->curframe
];
4813 if (state
->frame
[state
->curframe
+ 1]) {
4814 verbose(env
, "verifier bug. Frame %d already allocated\n",
4815 state
->curframe
+ 1);
4819 func_info_aux
= env
->prog
->aux
->func_info_aux
;
4821 is_global
= func_info_aux
[subprog
].linkage
== BTF_FUNC_GLOBAL
;
4822 err
= btf_check_func_arg_match(env
, subprog
, caller
->regs
);
4827 verbose(env
, "Caller passes invalid args into func#%d\n",
4831 if (env
->log
.level
& BPF_LOG_LEVEL
)
4833 "Func#%d is global and valid. Skipping.\n",
4835 clear_caller_saved_regs(env
, caller
->regs
);
4837 /* All global functions return a 64-bit SCALAR_VALUE */
4838 mark_reg_unknown(env
, caller
->regs
, BPF_REG_0
);
4839 caller
->regs
[BPF_REG_0
].subreg_def
= DEF_NOT_SUBREG
;
4841 /* continue with next insn after call */
4846 callee
= kzalloc(sizeof(*callee
), GFP_KERNEL
);
4849 state
->frame
[state
->curframe
+ 1] = callee
;
4851 /* callee cannot access r0, r6 - r9 for reading and has to write
4852 * into its own stack before reading from it.
4853 * callee can read/write into caller's stack
4855 init_func_state(env
, callee
,
4856 /* remember the callsite, it will be used by bpf_exit */
4857 *insn_idx
/* callsite */,
4858 state
->curframe
+ 1 /* frameno within this callchain */,
4859 subprog
/* subprog number within this prog */);
4861 /* Transfer references to the callee */
4862 err
= transfer_reference_state(callee
, caller
);
4866 /* copy r1 - r5 args that callee can access. The copy includes parent
4867 * pointers, which connects us up to the liveness chain
4869 for (i
= BPF_REG_1
; i
<= BPF_REG_5
; i
++)
4870 callee
->regs
[i
] = caller
->regs
[i
];
4872 clear_caller_saved_regs(env
, caller
->regs
);
4874 /* only increment it after check_reg_arg() finished */
4877 /* and go analyze first insn of the callee */
4878 *insn_idx
= target_insn
;
4880 if (env
->log
.level
& BPF_LOG_LEVEL
) {
4881 verbose(env
, "caller:\n");
4882 print_verifier_state(env
, caller
);
4883 verbose(env
, "callee:\n");
4884 print_verifier_state(env
, callee
);
4889 static int prepare_func_exit(struct bpf_verifier_env
*env
, int *insn_idx
)
4891 struct bpf_verifier_state
*state
= env
->cur_state
;
4892 struct bpf_func_state
*caller
, *callee
;
4893 struct bpf_reg_state
*r0
;
4896 callee
= state
->frame
[state
->curframe
];
4897 r0
= &callee
->regs
[BPF_REG_0
];
4898 if (r0
->type
== PTR_TO_STACK
) {
4899 /* technically it's ok to return caller's stack pointer
4900 * (or caller's caller's pointer) back to the caller,
4901 * since these pointers are valid. Only current stack
4902 * pointer will be invalid as soon as function exits,
4903 * but let's be conservative
4905 verbose(env
, "cannot return stack pointer to the caller\n");
4910 caller
= state
->frame
[state
->curframe
];
4911 /* return to the caller whatever r0 had in the callee */
4912 caller
->regs
[BPF_REG_0
] = *r0
;
4914 /* Transfer references to the caller */
4915 err
= transfer_reference_state(caller
, callee
);
4919 *insn_idx
= callee
->callsite
+ 1;
4920 if (env
->log
.level
& BPF_LOG_LEVEL
) {
4921 verbose(env
, "returning from callee:\n");
4922 print_verifier_state(env
, callee
);
4923 verbose(env
, "to caller at %d:\n", *insn_idx
);
4924 print_verifier_state(env
, caller
);
4926 /* clear everything in the callee */
4927 free_func_state(callee
);
4928 state
->frame
[state
->curframe
+ 1] = NULL
;
4932 static void do_refine_retval_range(struct bpf_reg_state
*regs
, int ret_type
,
4934 struct bpf_call_arg_meta
*meta
)
4936 struct bpf_reg_state
*ret_reg
= ®s
[BPF_REG_0
];
4938 if (ret_type
!= RET_INTEGER
||
4939 (func_id
!= BPF_FUNC_get_stack
&&
4940 func_id
!= BPF_FUNC_probe_read_str
&&
4941 func_id
!= BPF_FUNC_probe_read_kernel_str
&&
4942 func_id
!= BPF_FUNC_probe_read_user_str
))
4945 ret_reg
->smax_value
= meta
->msize_max_value
;
4946 ret_reg
->s32_max_value
= meta
->msize_max_value
;
4947 ret_reg
->smin_value
= -MAX_ERRNO
;
4948 ret_reg
->s32_min_value
= -MAX_ERRNO
;
4949 __reg_deduce_bounds(ret_reg
);
4950 __reg_bound_offset(ret_reg
);
4951 __update_reg_bounds(ret_reg
);
4955 record_func_map(struct bpf_verifier_env
*env
, struct bpf_call_arg_meta
*meta
,
4956 int func_id
, int insn_idx
)
4958 struct bpf_insn_aux_data
*aux
= &env
->insn_aux_data
[insn_idx
];
4959 struct bpf_map
*map
= meta
->map_ptr
;
4961 if (func_id
!= BPF_FUNC_tail_call
&&
4962 func_id
!= BPF_FUNC_map_lookup_elem
&&
4963 func_id
!= BPF_FUNC_map_update_elem
&&
4964 func_id
!= BPF_FUNC_map_delete_elem
&&
4965 func_id
!= BPF_FUNC_map_push_elem
&&
4966 func_id
!= BPF_FUNC_map_pop_elem
&&
4967 func_id
!= BPF_FUNC_map_peek_elem
)
4971 verbose(env
, "kernel subsystem misconfigured verifier\n");
4975 /* In case of read-only, some additional restrictions
4976 * need to be applied in order to prevent altering the
4977 * state of the map from program side.
4979 if ((map
->map_flags
& BPF_F_RDONLY_PROG
) &&
4980 (func_id
== BPF_FUNC_map_delete_elem
||
4981 func_id
== BPF_FUNC_map_update_elem
||
4982 func_id
== BPF_FUNC_map_push_elem
||
4983 func_id
== BPF_FUNC_map_pop_elem
)) {
4984 verbose(env
, "write into map forbidden\n");
4988 if (!BPF_MAP_PTR(aux
->map_ptr_state
))
4989 bpf_map_ptr_store(aux
, meta
->map_ptr
,
4990 !meta
->map_ptr
->bypass_spec_v1
);
4991 else if (BPF_MAP_PTR(aux
->map_ptr_state
) != meta
->map_ptr
)
4992 bpf_map_ptr_store(aux
, BPF_MAP_PTR_POISON
,
4993 !meta
->map_ptr
->bypass_spec_v1
);
4998 record_func_key(struct bpf_verifier_env
*env
, struct bpf_call_arg_meta
*meta
,
4999 int func_id
, int insn_idx
)
5001 struct bpf_insn_aux_data
*aux
= &env
->insn_aux_data
[insn_idx
];
5002 struct bpf_reg_state
*regs
= cur_regs(env
), *reg
;
5003 struct bpf_map
*map
= meta
->map_ptr
;
5008 if (func_id
!= BPF_FUNC_tail_call
)
5010 if (!map
|| map
->map_type
!= BPF_MAP_TYPE_PROG_ARRAY
) {
5011 verbose(env
, "kernel subsystem misconfigured verifier\n");
5015 range
= tnum_range(0, map
->max_entries
- 1);
5016 reg
= ®s
[BPF_REG_3
];
5018 if (!register_is_const(reg
) || !tnum_in(range
, reg
->var_off
)) {
5019 bpf_map_key_store(aux
, BPF_MAP_KEY_POISON
);
5023 err
= mark_chain_precision(env
, BPF_REG_3
);
5027 val
= reg
->var_off
.value
;
5028 if (bpf_map_key_unseen(aux
))
5029 bpf_map_key_store(aux
, val
);
5030 else if (!bpf_map_key_poisoned(aux
) &&
5031 bpf_map_key_immediate(aux
) != val
)
5032 bpf_map_key_store(aux
, BPF_MAP_KEY_POISON
);
5036 static int check_reference_leak(struct bpf_verifier_env
*env
)
5038 struct bpf_func_state
*state
= cur_func(env
);
5041 for (i
= 0; i
< state
->acquired_refs
; i
++) {
5042 verbose(env
, "Unreleased reference id=%d alloc_insn=%d\n",
5043 state
->refs
[i
].id
, state
->refs
[i
].insn_idx
);
5045 return state
->acquired_refs
? -EINVAL
: 0;
5048 static int check_helper_call(struct bpf_verifier_env
*env
, int func_id
, int insn_idx
)
5050 const struct bpf_func_proto
*fn
= NULL
;
5051 struct bpf_reg_state
*regs
;
5052 struct bpf_call_arg_meta meta
;
5056 /* find function prototype */
5057 if (func_id
< 0 || func_id
>= __BPF_FUNC_MAX_ID
) {
5058 verbose(env
, "invalid func %s#%d\n", func_id_name(func_id
),
5063 if (env
->ops
->get_func_proto
)
5064 fn
= env
->ops
->get_func_proto(func_id
, env
->prog
);
5066 verbose(env
, "unknown func %s#%d\n", func_id_name(func_id
),
5071 /* eBPF programs must be GPL compatible to use GPL-ed functions */
5072 if (!env
->prog
->gpl_compatible
&& fn
->gpl_only
) {
5073 verbose(env
, "cannot call GPL-restricted function from non-GPL compatible program\n");
5077 if (fn
->allowed
&& !fn
->allowed(env
->prog
)) {
5078 verbose(env
, "helper call is not allowed in probe\n");
5082 /* With LD_ABS/IND some JITs save/restore skb from r1. */
5083 changes_data
= bpf_helper_changes_pkt_data(fn
->func
);
5084 if (changes_data
&& fn
->arg1_type
!= ARG_PTR_TO_CTX
) {
5085 verbose(env
, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
5086 func_id_name(func_id
), func_id
);
5090 memset(&meta
, 0, sizeof(meta
));
5091 meta
.pkt_access
= fn
->pkt_access
;
5093 err
= check_func_proto(fn
, func_id
);
5095 verbose(env
, "kernel subsystem misconfigured func %s#%d\n",
5096 func_id_name(func_id
), func_id
);
5100 meta
.func_id
= func_id
;
5102 for (i
= 0; i
< 5; i
++) {
5103 err
= check_func_arg(env
, i
, &meta
, fn
);
5108 err
= record_func_map(env
, &meta
, func_id
, insn_idx
);
5112 err
= record_func_key(env
, &meta
, func_id
, insn_idx
);
5116 /* Mark slots with STACK_MISC in case of raw mode, stack offset
5117 * is inferred from register state.
5119 for (i
= 0; i
< meta
.access_size
; i
++) {
5120 err
= check_mem_access(env
, insn_idx
, meta
.regno
, i
, BPF_B
,
5121 BPF_WRITE
, -1, false);
5126 if (func_id
== BPF_FUNC_tail_call
) {
5127 err
= check_reference_leak(env
);
5129 verbose(env
, "tail_call would lead to reference leak\n");
5132 } else if (is_release_function(func_id
)) {
5133 err
= release_reference(env
, meta
.ref_obj_id
);
5135 verbose(env
, "func %s#%d reference has not been acquired before\n",
5136 func_id_name(func_id
), func_id
);
5141 regs
= cur_regs(env
);
5143 /* check that flags argument in get_local_storage(map, flags) is 0,
5144 * this is required because get_local_storage() can't return an error.
5146 if (func_id
== BPF_FUNC_get_local_storage
&&
5147 !register_is_null(®s
[BPF_REG_2
])) {
5148 verbose(env
, "get_local_storage() doesn't support non-zero flags\n");
5152 /* reset caller saved regs */
5153 for (i
= 0; i
< CALLER_SAVED_REGS
; i
++) {
5154 mark_reg_not_init(env
, regs
, caller_saved
[i
]);
5155 check_reg_arg(env
, caller_saved
[i
], DST_OP_NO_MARK
);
5158 /* helper call returns 64-bit value. */
5159 regs
[BPF_REG_0
].subreg_def
= DEF_NOT_SUBREG
;
5161 /* update return register (already marked as written above) */
5162 if (fn
->ret_type
== RET_INTEGER
) {
5163 /* sets type to SCALAR_VALUE */
5164 mark_reg_unknown(env
, regs
, BPF_REG_0
);
5165 } else if (fn
->ret_type
== RET_VOID
) {
5166 regs
[BPF_REG_0
].type
= NOT_INIT
;
5167 } else if (fn
->ret_type
== RET_PTR_TO_MAP_VALUE_OR_NULL
||
5168 fn
->ret_type
== RET_PTR_TO_MAP_VALUE
) {
5169 /* There is no offset yet applied, variable or fixed */
5170 mark_reg_known_zero(env
, regs
, BPF_REG_0
);
5171 /* remember map_ptr, so that check_map_access()
5172 * can check 'value_size' boundary of memory access
5173 * to map element returned from bpf_map_lookup_elem()
5175 if (meta
.map_ptr
== NULL
) {
5177 "kernel subsystem misconfigured verifier\n");
5180 regs
[BPF_REG_0
].map_ptr
= meta
.map_ptr
;
5181 if (fn
->ret_type
== RET_PTR_TO_MAP_VALUE
) {
5182 regs
[BPF_REG_0
].type
= PTR_TO_MAP_VALUE
;
5183 if (map_value_has_spin_lock(meta
.map_ptr
))
5184 regs
[BPF_REG_0
].id
= ++env
->id_gen
;
5186 regs
[BPF_REG_0
].type
= PTR_TO_MAP_VALUE_OR_NULL
;
5188 } else if (fn
->ret_type
== RET_PTR_TO_SOCKET_OR_NULL
) {
5189 mark_reg_known_zero(env
, regs
, BPF_REG_0
);
5190 regs
[BPF_REG_0
].type
= PTR_TO_SOCKET_OR_NULL
;
5191 } else if (fn
->ret_type
== RET_PTR_TO_SOCK_COMMON_OR_NULL
) {
5192 mark_reg_known_zero(env
, regs
, BPF_REG_0
);
5193 regs
[BPF_REG_0
].type
= PTR_TO_SOCK_COMMON_OR_NULL
;
5194 } else if (fn
->ret_type
== RET_PTR_TO_TCP_SOCK_OR_NULL
) {
5195 mark_reg_known_zero(env
, regs
, BPF_REG_0
);
5196 regs
[BPF_REG_0
].type
= PTR_TO_TCP_SOCK_OR_NULL
;
5197 } else if (fn
->ret_type
== RET_PTR_TO_ALLOC_MEM_OR_NULL
) {
5198 mark_reg_known_zero(env
, regs
, BPF_REG_0
);
5199 regs
[BPF_REG_0
].type
= PTR_TO_MEM_OR_NULL
;
5200 regs
[BPF_REG_0
].mem_size
= meta
.mem_size
;
5201 } else if (fn
->ret_type
== RET_PTR_TO_MEM_OR_BTF_ID_OR_NULL
||
5202 fn
->ret_type
== RET_PTR_TO_MEM_OR_BTF_ID
) {
5203 const struct btf_type
*t
;
5205 mark_reg_known_zero(env
, regs
, BPF_REG_0
);
5206 t
= btf_type_skip_modifiers(meta
.ret_btf
, meta
.ret_btf_id
, NULL
);
5207 if (!btf_type_is_struct(t
)) {
5209 const struct btf_type
*ret
;
5212 /* resolve the type size of ksym. */
5213 ret
= btf_resolve_size(meta
.ret_btf
, t
, &tsize
);
5215 tname
= btf_name_by_offset(meta
.ret_btf
, t
->name_off
);
5216 verbose(env
, "unable to resolve the size of type '%s': %ld\n",
5217 tname
, PTR_ERR(ret
));
5220 regs
[BPF_REG_0
].type
=
5221 fn
->ret_type
== RET_PTR_TO_MEM_OR_BTF_ID
?
5222 PTR_TO_MEM
: PTR_TO_MEM_OR_NULL
;
5223 regs
[BPF_REG_0
].mem_size
= tsize
;
5225 regs
[BPF_REG_0
].type
=
5226 fn
->ret_type
== RET_PTR_TO_MEM_OR_BTF_ID
?
5227 PTR_TO_BTF_ID
: PTR_TO_BTF_ID_OR_NULL
;
5228 regs
[BPF_REG_0
].btf
= meta
.ret_btf
;
5229 regs
[BPF_REG_0
].btf_id
= meta
.ret_btf_id
;
5231 } else if (fn
->ret_type
== RET_PTR_TO_BTF_ID_OR_NULL
||
5232 fn
->ret_type
== RET_PTR_TO_BTF_ID
) {
5235 mark_reg_known_zero(env
, regs
, BPF_REG_0
);
5236 regs
[BPF_REG_0
].type
= fn
->ret_type
== RET_PTR_TO_BTF_ID
?
5238 PTR_TO_BTF_ID_OR_NULL
;
5239 ret_btf_id
= *fn
->ret_btf_id
;
5240 if (ret_btf_id
== 0) {
5241 verbose(env
, "invalid return type %d of func %s#%d\n",
5242 fn
->ret_type
, func_id_name(func_id
), func_id
);
5245 /* current BPF helper definitions are only coming from
5246 * built-in code with type IDs from vmlinux BTF
5248 regs
[BPF_REG_0
].btf
= btf_vmlinux
;
5249 regs
[BPF_REG_0
].btf_id
= ret_btf_id
;
5251 verbose(env
, "unknown return type %d of func %s#%d\n",
5252 fn
->ret_type
, func_id_name(func_id
), func_id
);
5256 if (reg_type_may_be_null(regs
[BPF_REG_0
].type
))
5257 regs
[BPF_REG_0
].id
= ++env
->id_gen
;
5259 if (is_ptr_cast_function(func_id
)) {
5260 /* For release_reference() */
5261 regs
[BPF_REG_0
].ref_obj_id
= meta
.ref_obj_id
;
5262 } else if (is_acquire_function(func_id
, meta
.map_ptr
)) {
5263 int id
= acquire_reference_state(env
, insn_idx
);
5267 /* For mark_ptr_or_null_reg() */
5268 regs
[BPF_REG_0
].id
= id
;
5269 /* For release_reference() */
5270 regs
[BPF_REG_0
].ref_obj_id
= id
;
5273 do_refine_retval_range(regs
, fn
->ret_type
, func_id
, &meta
);
5275 err
= check_map_func_compatibility(env
, meta
.map_ptr
, func_id
);
5279 if ((func_id
== BPF_FUNC_get_stack
||
5280 func_id
== BPF_FUNC_get_task_stack
) &&
5281 !env
->prog
->has_callchain_buf
) {
5282 const char *err_str
;
5284 #ifdef CONFIG_PERF_EVENTS
5285 err
= get_callchain_buffers(sysctl_perf_event_max_stack
);
5286 err_str
= "cannot get callchain buffer for func %s#%d\n";
5289 err_str
= "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
5292 verbose(env
, err_str
, func_id_name(func_id
), func_id
);
5296 env
->prog
->has_callchain_buf
= true;
5299 if (func_id
== BPF_FUNC_get_stackid
|| func_id
== BPF_FUNC_get_stack
)
5300 env
->prog
->call_get_stack
= true;
5303 clear_all_pkt_pointers(env
);
5307 static bool signed_add_overflows(s64 a
, s64 b
)
5309 /* Do the add in u64, where overflow is well-defined */
5310 s64 res
= (s64
)((u64
)a
+ (u64
)b
);
5317 static bool signed_add32_overflows(s32 a
, s32 b
)
5319 /* Do the add in u32, where overflow is well-defined */
5320 s32 res
= (s32
)((u32
)a
+ (u32
)b
);
5327 static bool signed_sub_overflows(s64 a
, s64 b
)
5329 /* Do the sub in u64, where overflow is well-defined */
5330 s64 res
= (s64
)((u64
)a
- (u64
)b
);
5337 static bool signed_sub32_overflows(s32 a
, s32 b
)
5339 /* Do the sub in u32, where overflow is well-defined */
5340 s32 res
= (s32
)((u32
)a
- (u32
)b
);
5347 static bool check_reg_sane_offset(struct bpf_verifier_env
*env
,
5348 const struct bpf_reg_state
*reg
,
5349 enum bpf_reg_type type
)
5351 bool known
= tnum_is_const(reg
->var_off
);
5352 s64 val
= reg
->var_off
.value
;
5353 s64 smin
= reg
->smin_value
;
5355 if (known
&& (val
>= BPF_MAX_VAR_OFF
|| val
<= -BPF_MAX_VAR_OFF
)) {
5356 verbose(env
, "math between %s pointer and %lld is not allowed\n",
5357 reg_type_str
[type
], val
);
5361 if (reg
->off
>= BPF_MAX_VAR_OFF
|| reg
->off
<= -BPF_MAX_VAR_OFF
) {
5362 verbose(env
, "%s pointer offset %d is not allowed\n",
5363 reg_type_str
[type
], reg
->off
);
5367 if (smin
== S64_MIN
) {
5368 verbose(env
, "math between %s pointer and register with unbounded min value is not allowed\n",
5369 reg_type_str
[type
]);
5373 if (smin
>= BPF_MAX_VAR_OFF
|| smin
<= -BPF_MAX_VAR_OFF
) {
5374 verbose(env
, "value %lld makes %s pointer be out of bounds\n",
5375 smin
, reg_type_str
[type
]);
5382 static struct bpf_insn_aux_data
*cur_aux(struct bpf_verifier_env
*env
)
5384 return &env
->insn_aux_data
[env
->insn_idx
];
5387 static int retrieve_ptr_limit(const struct bpf_reg_state
*ptr_reg
,
5388 u32
*ptr_limit
, u8 opcode
, bool off_is_neg
)
5390 bool mask_to_left
= (opcode
== BPF_ADD
&& off_is_neg
) ||
5391 (opcode
== BPF_SUB
&& !off_is_neg
);
5394 switch (ptr_reg
->type
) {
5396 /* Indirect variable offset stack access is prohibited in
5397 * unprivileged mode so it's not handled here.
5399 off
= ptr_reg
->off
+ ptr_reg
->var_off
.value
;
5401 *ptr_limit
= MAX_BPF_STACK
+ off
+ 1;
5405 case PTR_TO_MAP_VALUE
:
5407 *ptr_limit
= ptr_reg
->umax_value
+ ptr_reg
->off
+ 1;
5409 off
= ptr_reg
->smin_value
+ ptr_reg
->off
;
5410 *ptr_limit
= ptr_reg
->map_ptr
->value_size
- off
;
5418 static bool can_skip_alu_sanitation(const struct bpf_verifier_env
*env
,
5419 const struct bpf_insn
*insn
)
5421 return env
->bypass_spec_v1
|| BPF_SRC(insn
->code
) == BPF_K
;
5424 static int update_alu_sanitation_state(struct bpf_insn_aux_data
*aux
,
5425 u32 alu_state
, u32 alu_limit
)
5427 /* If we arrived here from different branches with different
5428 * state or limits to sanitize, then this won't work.
5430 if (aux
->alu_state
&&
5431 (aux
->alu_state
!= alu_state
||
5432 aux
->alu_limit
!= alu_limit
))
5435 /* Corresponding fixup done in fixup_bpf_calls(). */
5436 aux
->alu_state
= alu_state
;
5437 aux
->alu_limit
= alu_limit
;
5441 static int sanitize_val_alu(struct bpf_verifier_env
*env
,
5442 struct bpf_insn
*insn
)
5444 struct bpf_insn_aux_data
*aux
= cur_aux(env
);
5446 if (can_skip_alu_sanitation(env
, insn
))
5449 return update_alu_sanitation_state(aux
, BPF_ALU_NON_POINTER
, 0);
5452 static int sanitize_ptr_alu(struct bpf_verifier_env
*env
,
5453 struct bpf_insn
*insn
,
5454 const struct bpf_reg_state
*ptr_reg
,
5455 struct bpf_reg_state
*dst_reg
,
5458 struct bpf_verifier_state
*vstate
= env
->cur_state
;
5459 struct bpf_insn_aux_data
*aux
= cur_aux(env
);
5460 bool ptr_is_dst_reg
= ptr_reg
== dst_reg
;
5461 u8 opcode
= BPF_OP(insn
->code
);
5462 u32 alu_state
, alu_limit
;
5463 struct bpf_reg_state tmp
;
5467 if (can_skip_alu_sanitation(env
, insn
))
5470 /* We already marked aux for masking from non-speculative
5471 * paths, thus we got here in the first place. We only care
5472 * to explore bad access from here.
5474 if (vstate
->speculative
)
5477 alu_state
= off_is_neg
? BPF_ALU_NEG_VALUE
: 0;
5478 alu_state
|= ptr_is_dst_reg
?
5479 BPF_ALU_SANITIZE_SRC
: BPF_ALU_SANITIZE_DST
;
5481 err
= retrieve_ptr_limit(ptr_reg
, &alu_limit
, opcode
, off_is_neg
);
5485 err
= update_alu_sanitation_state(aux
, alu_state
, alu_limit
);
5489 /* Simulate and find potential out-of-bounds access under
5490 * speculative execution from truncation as a result of
5491 * masking when off was not within expected range. If off
5492 * sits in dst, then we temporarily need to move ptr there
5493 * to simulate dst (== 0) +/-= ptr. Needed, for example,
5494 * for cases where we use K-based arithmetic in one direction
5495 * and truncated reg-based in the other in order to explore
5498 if (!ptr_is_dst_reg
) {
5500 *dst_reg
= *ptr_reg
;
5502 ret
= push_stack(env
, env
->insn_idx
+ 1, env
->insn_idx
, true);
5503 if (!ptr_is_dst_reg
&& ret
)
5505 return !ret
? -EFAULT
: 0;
5508 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
5509 * Caller should also handle BPF_MOV case separately.
5510 * If we return -EACCES, caller may want to try again treating pointer as a
5511 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks.
5513 static int adjust_ptr_min_max_vals(struct bpf_verifier_env
*env
,
5514 struct bpf_insn
*insn
,
5515 const struct bpf_reg_state
*ptr_reg
,
5516 const struct bpf_reg_state
*off_reg
)
5518 struct bpf_verifier_state
*vstate
= env
->cur_state
;
5519 struct bpf_func_state
*state
= vstate
->frame
[vstate
->curframe
];
5520 struct bpf_reg_state
*regs
= state
->regs
, *dst_reg
;
5521 bool known
= tnum_is_const(off_reg
->var_off
);
5522 s64 smin_val
= off_reg
->smin_value
, smax_val
= off_reg
->smax_value
,
5523 smin_ptr
= ptr_reg
->smin_value
, smax_ptr
= ptr_reg
->smax_value
;
5524 u64 umin_val
= off_reg
->umin_value
, umax_val
= off_reg
->umax_value
,
5525 umin_ptr
= ptr_reg
->umin_value
, umax_ptr
= ptr_reg
->umax_value
;
5526 u32 dst
= insn
->dst_reg
, src
= insn
->src_reg
;
5527 u8 opcode
= BPF_OP(insn
->code
);
5530 dst_reg
= ®s
[dst
];
5532 if ((known
&& (smin_val
!= smax_val
|| umin_val
!= umax_val
)) ||
5533 smin_val
> smax_val
|| umin_val
> umax_val
) {
5534 /* Taint dst register if offset had invalid bounds derived from
5535 * e.g. dead branches.
5537 __mark_reg_unknown(env
, dst_reg
);
5541 if (BPF_CLASS(insn
->code
) != BPF_ALU64
) {
5542 /* 32-bit ALU ops on pointers produce (meaningless) scalars */
5543 if (opcode
== BPF_SUB
&& env
->allow_ptr_leaks
) {
5544 __mark_reg_unknown(env
, dst_reg
);
5549 "R%d 32-bit pointer arithmetic prohibited\n",
5554 switch (ptr_reg
->type
) {
5555 case PTR_TO_MAP_VALUE_OR_NULL
:
5556 verbose(env
, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
5557 dst
, reg_type_str
[ptr_reg
->type
]);
5559 case CONST_PTR_TO_MAP
:
5560 /* smin_val represents the known value */
5561 if (known
&& smin_val
== 0 && opcode
== BPF_ADD
)
5564 case PTR_TO_PACKET_END
:
5566 case PTR_TO_SOCKET_OR_NULL
:
5567 case PTR_TO_SOCK_COMMON
:
5568 case PTR_TO_SOCK_COMMON_OR_NULL
:
5569 case PTR_TO_TCP_SOCK
:
5570 case PTR_TO_TCP_SOCK_OR_NULL
:
5571 case PTR_TO_XDP_SOCK
:
5572 verbose(env
, "R%d pointer arithmetic on %s prohibited\n",
5573 dst
, reg_type_str
[ptr_reg
->type
]);
5575 case PTR_TO_MAP_VALUE
:
5576 if (!env
->allow_ptr_leaks
&& !known
&& (smin_val
< 0) != (smax_val
< 0)) {
5577 verbose(env
, "R%d has unknown scalar with mixed signed bounds, pointer arithmetic with it prohibited for !root\n",
5578 off_reg
== dst_reg
? dst
: src
);
5586 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
5587 * The id may be overwritten later if we create a new variable offset.
5589 dst_reg
->type
= ptr_reg
->type
;
5590 dst_reg
->id
= ptr_reg
->id
;
5592 if (!check_reg_sane_offset(env
, off_reg
, ptr_reg
->type
) ||
5593 !check_reg_sane_offset(env
, ptr_reg
, ptr_reg
->type
))
5596 /* pointer types do not carry 32-bit bounds at the moment. */
5597 __mark_reg32_unbounded(dst_reg
);
5601 ret
= sanitize_ptr_alu(env
, insn
, ptr_reg
, dst_reg
, smin_val
< 0);
5603 verbose(env
, "R%d tried to add from different maps, paths, or prohibited types\n", dst
);
5606 /* We can take a fixed offset as long as it doesn't overflow
5607 * the s32 'off' field
5609 if (known
&& (ptr_reg
->off
+ smin_val
==
5610 (s64
)(s32
)(ptr_reg
->off
+ smin_val
))) {
5611 /* pointer += K. Accumulate it into fixed offset */
5612 dst_reg
->smin_value
= smin_ptr
;
5613 dst_reg
->smax_value
= smax_ptr
;
5614 dst_reg
->umin_value
= umin_ptr
;
5615 dst_reg
->umax_value
= umax_ptr
;
5616 dst_reg
->var_off
= ptr_reg
->var_off
;
5617 dst_reg
->off
= ptr_reg
->off
+ smin_val
;
5618 dst_reg
->raw
= ptr_reg
->raw
;
5621 /* A new variable offset is created. Note that off_reg->off
5622 * == 0, since it's a scalar.
5623 * dst_reg gets the pointer type and since some positive
5624 * integer value was added to the pointer, give it a new 'id'
5625 * if it's a PTR_TO_PACKET.
5626 * this creates a new 'base' pointer, off_reg (variable) gets
5627 * added into the variable offset, and we copy the fixed offset
5630 if (signed_add_overflows(smin_ptr
, smin_val
) ||
5631 signed_add_overflows(smax_ptr
, smax_val
)) {
5632 dst_reg
->smin_value
= S64_MIN
;
5633 dst_reg
->smax_value
= S64_MAX
;
5635 dst_reg
->smin_value
= smin_ptr
+ smin_val
;
5636 dst_reg
->smax_value
= smax_ptr
+ smax_val
;
5638 if (umin_ptr
+ umin_val
< umin_ptr
||
5639 umax_ptr
+ umax_val
< umax_ptr
) {
5640 dst_reg
->umin_value
= 0;
5641 dst_reg
->umax_value
= U64_MAX
;
5643 dst_reg
->umin_value
= umin_ptr
+ umin_val
;
5644 dst_reg
->umax_value
= umax_ptr
+ umax_val
;
5646 dst_reg
->var_off
= tnum_add(ptr_reg
->var_off
, off_reg
->var_off
);
5647 dst_reg
->off
= ptr_reg
->off
;
5648 dst_reg
->raw
= ptr_reg
->raw
;
5649 if (reg_is_pkt_pointer(ptr_reg
)) {
5650 dst_reg
->id
= ++env
->id_gen
;
5651 /* something was added to pkt_ptr, set range to zero */
5652 memset(&dst_reg
->raw
, 0, sizeof(dst_reg
->raw
));
5656 ret
= sanitize_ptr_alu(env
, insn
, ptr_reg
, dst_reg
, smin_val
< 0);
5658 verbose(env
, "R%d tried to sub from different maps, paths, or prohibited types\n", dst
);
5661 if (dst_reg
== off_reg
) {
5662 /* scalar -= pointer. Creates an unknown scalar */
5663 verbose(env
, "R%d tried to subtract pointer from scalar\n",
5667 /* We don't allow subtraction from FP, because (according to
5668 * test_verifier.c test "invalid fp arithmetic", JITs might not
5669 * be able to deal with it.
5671 if (ptr_reg
->type
== PTR_TO_STACK
) {
5672 verbose(env
, "R%d subtraction from stack pointer prohibited\n",
5676 if (known
&& (ptr_reg
->off
- smin_val
==
5677 (s64
)(s32
)(ptr_reg
->off
- smin_val
))) {
5678 /* pointer -= K. Subtract it from fixed offset */
5679 dst_reg
->smin_value
= smin_ptr
;
5680 dst_reg
->smax_value
= smax_ptr
;
5681 dst_reg
->umin_value
= umin_ptr
;
5682 dst_reg
->umax_value
= umax_ptr
;
5683 dst_reg
->var_off
= ptr_reg
->var_off
;
5684 dst_reg
->id
= ptr_reg
->id
;
5685 dst_reg
->off
= ptr_reg
->off
- smin_val
;
5686 dst_reg
->raw
= ptr_reg
->raw
;
5689 /* A new variable offset is created. If the subtrahend is known
5690 * nonnegative, then any reg->range we had before is still good.
5692 if (signed_sub_overflows(smin_ptr
, smax_val
) ||
5693 signed_sub_overflows(smax_ptr
, 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
= smin_ptr
- smax_val
;
5699 dst_reg
->smax_value
= smax_ptr
- smin_val
;
5701 if (umin_ptr
< 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
= umin_ptr
- umax_val
;
5708 dst_reg
->umax_value
= umax_ptr
- umin_val
;
5710 dst_reg
->var_off
= tnum_sub(ptr_reg
->var_off
, off_reg
->var_off
);
5711 dst_reg
->off
= ptr_reg
->off
;
5712 dst_reg
->raw
= ptr_reg
->raw
;
5713 if (reg_is_pkt_pointer(ptr_reg
)) {
5714 dst_reg
->id
= ++env
->id_gen
;
5715 /* something was added to pkt_ptr, set range to zero */
5717 memset(&dst_reg
->raw
, 0, sizeof(dst_reg
->raw
));
5723 /* bitwise ops on pointers are troublesome, prohibit. */
5724 verbose(env
, "R%d bitwise operator %s on pointer prohibited\n",
5725 dst
, bpf_alu_string
[opcode
>> 4]);
5728 /* other operators (e.g. MUL,LSH) produce non-pointer results */
5729 verbose(env
, "R%d pointer arithmetic with %s operator prohibited\n",
5730 dst
, bpf_alu_string
[opcode
>> 4]);
5734 if (!check_reg_sane_offset(env
, dst_reg
, ptr_reg
->type
))
5737 __update_reg_bounds(dst_reg
);
5738 __reg_deduce_bounds(dst_reg
);
5739 __reg_bound_offset(dst_reg
);
5741 /* For unprivileged we require that resulting offset must be in bounds
5742 * in order to be able to sanitize access later on.
5744 if (!env
->bypass_spec_v1
) {
5745 if (dst_reg
->type
== PTR_TO_MAP_VALUE
&&
5746 check_map_access(env
, dst
, dst_reg
->off
, 1, false)) {
5747 verbose(env
, "R%d pointer arithmetic of map value goes out of range, "
5748 "prohibited for !root\n", dst
);
5750 } else if (dst_reg
->type
== PTR_TO_STACK
&&
5751 check_stack_access(env
, dst_reg
, dst_reg
->off
+
5752 dst_reg
->var_off
.value
, 1)) {
5753 verbose(env
, "R%d stack pointer arithmetic goes out of range, "
5754 "prohibited for !root\n", dst
);
5762 static void scalar32_min_max_add(struct bpf_reg_state
*dst_reg
,
5763 struct bpf_reg_state
*src_reg
)
5765 s32 smin_val
= src_reg
->s32_min_value
;
5766 s32 smax_val
= src_reg
->s32_max_value
;
5767 u32 umin_val
= src_reg
->u32_min_value
;
5768 u32 umax_val
= src_reg
->u32_max_value
;
5770 if (signed_add32_overflows(dst_reg
->s32_min_value
, smin_val
) ||
5771 signed_add32_overflows(dst_reg
->s32_max_value
, smax_val
)) {
5772 dst_reg
->s32_min_value
= S32_MIN
;
5773 dst_reg
->s32_max_value
= S32_MAX
;
5775 dst_reg
->s32_min_value
+= smin_val
;
5776 dst_reg
->s32_max_value
+= smax_val
;
5778 if (dst_reg
->u32_min_value
+ umin_val
< umin_val
||
5779 dst_reg
->u32_max_value
+ umax_val
< umax_val
) {
5780 dst_reg
->u32_min_value
= 0;
5781 dst_reg
->u32_max_value
= U32_MAX
;
5783 dst_reg
->u32_min_value
+= umin_val
;
5784 dst_reg
->u32_max_value
+= umax_val
;
5788 static void scalar_min_max_add(struct bpf_reg_state
*dst_reg
,
5789 struct bpf_reg_state
*src_reg
)
5791 s64 smin_val
= src_reg
->smin_value
;
5792 s64 smax_val
= src_reg
->smax_value
;
5793 u64 umin_val
= src_reg
->umin_value
;
5794 u64 umax_val
= src_reg
->umax_value
;
5796 if (signed_add_overflows(dst_reg
->smin_value
, smin_val
) ||
5797 signed_add_overflows(dst_reg
->smax_value
, smax_val
)) {
5798 dst_reg
->smin_value
= S64_MIN
;
5799 dst_reg
->smax_value
= S64_MAX
;
5801 dst_reg
->smin_value
+= smin_val
;
5802 dst_reg
->smax_value
+= smax_val
;
5804 if (dst_reg
->umin_value
+ umin_val
< umin_val
||
5805 dst_reg
->umax_value
+ umax_val
< umax_val
) {
5806 dst_reg
->umin_value
= 0;
5807 dst_reg
->umax_value
= U64_MAX
;
5809 dst_reg
->umin_value
+= umin_val
;
5810 dst_reg
->umax_value
+= umax_val
;
5814 static void scalar32_min_max_sub(struct bpf_reg_state
*dst_reg
,
5815 struct bpf_reg_state
*src_reg
)
5817 s32 smin_val
= src_reg
->s32_min_value
;
5818 s32 smax_val
= src_reg
->s32_max_value
;
5819 u32 umin_val
= src_reg
->u32_min_value
;
5820 u32 umax_val
= src_reg
->u32_max_value
;
5822 if (signed_sub32_overflows(dst_reg
->s32_min_value
, smax_val
) ||
5823 signed_sub32_overflows(dst_reg
->s32_max_value
, smin_val
)) {
5824 /* Overflow possible, we know nothing */
5825 dst_reg
->s32_min_value
= S32_MIN
;
5826 dst_reg
->s32_max_value
= S32_MAX
;
5828 dst_reg
->s32_min_value
-= smax_val
;
5829 dst_reg
->s32_max_value
-= smin_val
;
5831 if (dst_reg
->u32_min_value
< umax_val
) {
5832 /* Overflow possible, we know nothing */
5833 dst_reg
->u32_min_value
= 0;
5834 dst_reg
->u32_max_value
= U32_MAX
;
5836 /* Cannot overflow (as long as bounds are consistent) */
5837 dst_reg
->u32_min_value
-= umax_val
;
5838 dst_reg
->u32_max_value
-= umin_val
;
5842 static void scalar_min_max_sub(struct bpf_reg_state
*dst_reg
,
5843 struct bpf_reg_state
*src_reg
)
5845 s64 smin_val
= src_reg
->smin_value
;
5846 s64 smax_val
= src_reg
->smax_value
;
5847 u64 umin_val
= src_reg
->umin_value
;
5848 u64 umax_val
= src_reg
->umax_value
;
5850 if (signed_sub_overflows(dst_reg
->smin_value
, smax_val
) ||
5851 signed_sub_overflows(dst_reg
->smax_value
, smin_val
)) {
5852 /* Overflow possible, we know nothing */
5853 dst_reg
->smin_value
= S64_MIN
;
5854 dst_reg
->smax_value
= S64_MAX
;
5856 dst_reg
->smin_value
-= smax_val
;
5857 dst_reg
->smax_value
-= smin_val
;
5859 if (dst_reg
->umin_value
< umax_val
) {
5860 /* Overflow possible, we know nothing */
5861 dst_reg
->umin_value
= 0;
5862 dst_reg
->umax_value
= U64_MAX
;
5864 /* Cannot overflow (as long as bounds are consistent) */
5865 dst_reg
->umin_value
-= umax_val
;
5866 dst_reg
->umax_value
-= umin_val
;
5870 static void scalar32_min_max_mul(struct bpf_reg_state
*dst_reg
,
5871 struct bpf_reg_state
*src_reg
)
5873 s32 smin_val
= src_reg
->s32_min_value
;
5874 u32 umin_val
= src_reg
->u32_min_value
;
5875 u32 umax_val
= src_reg
->u32_max_value
;
5877 if (smin_val
< 0 || dst_reg
->s32_min_value
< 0) {
5878 /* Ain't nobody got time to multiply that sign */
5879 __mark_reg32_unbounded(dst_reg
);
5882 /* Both values are positive, so we can work with unsigned and
5883 * copy the result to signed (unless it exceeds S32_MAX).
5885 if (umax_val
> U16_MAX
|| dst_reg
->u32_max_value
> U16_MAX
) {
5886 /* Potential overflow, we know nothing */
5887 __mark_reg32_unbounded(dst_reg
);
5890 dst_reg
->u32_min_value
*= umin_val
;
5891 dst_reg
->u32_max_value
*= umax_val
;
5892 if (dst_reg
->u32_max_value
> S32_MAX
) {
5893 /* Overflow possible, we know nothing */
5894 dst_reg
->s32_min_value
= S32_MIN
;
5895 dst_reg
->s32_max_value
= S32_MAX
;
5897 dst_reg
->s32_min_value
= dst_reg
->u32_min_value
;
5898 dst_reg
->s32_max_value
= dst_reg
->u32_max_value
;
5902 static void scalar_min_max_mul(struct bpf_reg_state
*dst_reg
,
5903 struct bpf_reg_state
*src_reg
)
5905 s64 smin_val
= src_reg
->smin_value
;
5906 u64 umin_val
= src_reg
->umin_value
;
5907 u64 umax_val
= src_reg
->umax_value
;
5909 if (smin_val
< 0 || dst_reg
->smin_value
< 0) {
5910 /* Ain't nobody got time to multiply that sign */
5911 __mark_reg64_unbounded(dst_reg
);
5914 /* Both values are positive, so we can work with unsigned and
5915 * copy the result to signed (unless it exceeds S64_MAX).
5917 if (umax_val
> U32_MAX
|| dst_reg
->umax_value
> U32_MAX
) {
5918 /* Potential overflow, we know nothing */
5919 __mark_reg64_unbounded(dst_reg
);
5922 dst_reg
->umin_value
*= umin_val
;
5923 dst_reg
->umax_value
*= umax_val
;
5924 if (dst_reg
->umax_value
> S64_MAX
) {
5925 /* Overflow possible, we know nothing */
5926 dst_reg
->smin_value
= S64_MIN
;
5927 dst_reg
->smax_value
= S64_MAX
;
5929 dst_reg
->smin_value
= dst_reg
->umin_value
;
5930 dst_reg
->smax_value
= dst_reg
->umax_value
;
5934 static void scalar32_min_max_and(struct bpf_reg_state
*dst_reg
,
5935 struct bpf_reg_state
*src_reg
)
5937 bool src_known
= tnum_subreg_is_const(src_reg
->var_off
);
5938 bool dst_known
= tnum_subreg_is_const(dst_reg
->var_off
);
5939 struct tnum var32_off
= tnum_subreg(dst_reg
->var_off
);
5940 s32 smin_val
= src_reg
->s32_min_value
;
5941 u32 umax_val
= src_reg
->u32_max_value
;
5943 /* Assuming scalar64_min_max_and will be called so its safe
5944 * to skip updating register for known 32-bit case.
5946 if (src_known
&& dst_known
)
5949 /* We get our minimum from the var_off, since that's inherently
5950 * bitwise. Our maximum is the minimum of the operands' maxima.
5952 dst_reg
->u32_min_value
= var32_off
.value
;
5953 dst_reg
->u32_max_value
= min(dst_reg
->u32_max_value
, umax_val
);
5954 if (dst_reg
->s32_min_value
< 0 || smin_val
< 0) {
5955 /* Lose signed bounds when ANDing negative numbers,
5956 * ain't nobody got time for that.
5958 dst_reg
->s32_min_value
= S32_MIN
;
5959 dst_reg
->s32_max_value
= S32_MAX
;
5961 /* ANDing two positives gives a positive, so safe to
5962 * cast result into s64.
5964 dst_reg
->s32_min_value
= dst_reg
->u32_min_value
;
5965 dst_reg
->s32_max_value
= dst_reg
->u32_max_value
;
5970 static void scalar_min_max_and(struct bpf_reg_state
*dst_reg
,
5971 struct bpf_reg_state
*src_reg
)
5973 bool src_known
= tnum_is_const(src_reg
->var_off
);
5974 bool dst_known
= tnum_is_const(dst_reg
->var_off
);
5975 s64 smin_val
= src_reg
->smin_value
;
5976 u64 umax_val
= src_reg
->umax_value
;
5978 if (src_known
&& dst_known
) {
5979 __mark_reg_known(dst_reg
, dst_reg
->var_off
.value
);
5983 /* We get our minimum from the var_off, since that's inherently
5984 * bitwise. Our maximum is the minimum of the operands' maxima.
5986 dst_reg
->umin_value
= dst_reg
->var_off
.value
;
5987 dst_reg
->umax_value
= min(dst_reg
->umax_value
, umax_val
);
5988 if (dst_reg
->smin_value
< 0 || smin_val
< 0) {
5989 /* Lose signed bounds when ANDing negative numbers,
5990 * ain't nobody got time for that.
5992 dst_reg
->smin_value
= S64_MIN
;
5993 dst_reg
->smax_value
= S64_MAX
;
5995 /* ANDing two positives gives a positive, so safe to
5996 * cast result into s64.
5998 dst_reg
->smin_value
= dst_reg
->umin_value
;
5999 dst_reg
->smax_value
= dst_reg
->umax_value
;
6001 /* We may learn something more from the var_off */
6002 __update_reg_bounds(dst_reg
);
6005 static void scalar32_min_max_or(struct bpf_reg_state
*dst_reg
,
6006 struct bpf_reg_state
*src_reg
)
6008 bool src_known
= tnum_subreg_is_const(src_reg
->var_off
);
6009 bool dst_known
= tnum_subreg_is_const(dst_reg
->var_off
);
6010 struct tnum var32_off
= tnum_subreg(dst_reg
->var_off
);
6011 s32 smin_val
= src_reg
->s32_min_value
;
6012 u32 umin_val
= src_reg
->u32_min_value
;
6014 /* Assuming scalar64_min_max_or will be called so it is safe
6015 * to skip updating register for known case.
6017 if (src_known
&& dst_known
)
6020 /* We get our maximum from the var_off, and our minimum is the
6021 * maximum of the operands' minima
6023 dst_reg
->u32_min_value
= max(dst_reg
->u32_min_value
, umin_val
);
6024 dst_reg
->u32_max_value
= var32_off
.value
| var32_off
.mask
;
6025 if (dst_reg
->s32_min_value
< 0 || smin_val
< 0) {
6026 /* Lose signed bounds when ORing negative numbers,
6027 * ain't nobody got time for that.
6029 dst_reg
->s32_min_value
= S32_MIN
;
6030 dst_reg
->s32_max_value
= S32_MAX
;
6032 /* ORing two positives gives a positive, so safe to
6033 * cast result into s64.
6035 dst_reg
->s32_min_value
= dst_reg
->u32_min_value
;
6036 dst_reg
->s32_max_value
= dst_reg
->u32_max_value
;
6040 static void scalar_min_max_or(struct bpf_reg_state
*dst_reg
,
6041 struct bpf_reg_state
*src_reg
)
6043 bool src_known
= tnum_is_const(src_reg
->var_off
);
6044 bool dst_known
= tnum_is_const(dst_reg
->var_off
);
6045 s64 smin_val
= src_reg
->smin_value
;
6046 u64 umin_val
= src_reg
->umin_value
;
6048 if (src_known
&& dst_known
) {
6049 __mark_reg_known(dst_reg
, dst_reg
->var_off
.value
);
6053 /* We get our maximum from the var_off, and our minimum is the
6054 * maximum of the operands' minima
6056 dst_reg
->umin_value
= max(dst_reg
->umin_value
, umin_val
);
6057 dst_reg
->umax_value
= dst_reg
->var_off
.value
| dst_reg
->var_off
.mask
;
6058 if (dst_reg
->smin_value
< 0 || smin_val
< 0) {
6059 /* Lose signed bounds when ORing negative numbers,
6060 * ain't nobody got time for that.
6062 dst_reg
->smin_value
= S64_MIN
;
6063 dst_reg
->smax_value
= S64_MAX
;
6065 /* ORing two positives gives a positive, so safe to
6066 * cast result into s64.
6068 dst_reg
->smin_value
= dst_reg
->umin_value
;
6069 dst_reg
->smax_value
= dst_reg
->umax_value
;
6071 /* We may learn something more from the var_off */
6072 __update_reg_bounds(dst_reg
);
6075 static void scalar32_min_max_xor(struct bpf_reg_state
*dst_reg
,
6076 struct bpf_reg_state
*src_reg
)
6078 bool src_known
= tnum_subreg_is_const(src_reg
->var_off
);
6079 bool dst_known
= tnum_subreg_is_const(dst_reg
->var_off
);
6080 struct tnum var32_off
= tnum_subreg(dst_reg
->var_off
);
6081 s32 smin_val
= src_reg
->s32_min_value
;
6083 /* Assuming scalar64_min_max_xor will be called so it is safe
6084 * to skip updating register for known case.
6086 if (src_known
&& dst_known
)
6089 /* We get both minimum and maximum from the var32_off. */
6090 dst_reg
->u32_min_value
= var32_off
.value
;
6091 dst_reg
->u32_max_value
= var32_off
.value
| var32_off
.mask
;
6093 if (dst_reg
->s32_min_value
>= 0 && smin_val
>= 0) {
6094 /* XORing two positive sign numbers gives a positive,
6095 * so safe to cast u32 result into s32.
6097 dst_reg
->s32_min_value
= dst_reg
->u32_min_value
;
6098 dst_reg
->s32_max_value
= dst_reg
->u32_max_value
;
6100 dst_reg
->s32_min_value
= S32_MIN
;
6101 dst_reg
->s32_max_value
= S32_MAX
;
6105 static void scalar_min_max_xor(struct bpf_reg_state
*dst_reg
,
6106 struct bpf_reg_state
*src_reg
)
6108 bool src_known
= tnum_is_const(src_reg
->var_off
);
6109 bool dst_known
= tnum_is_const(dst_reg
->var_off
);
6110 s64 smin_val
= src_reg
->smin_value
;
6112 if (src_known
&& dst_known
) {
6113 /* dst_reg->var_off.value has been updated earlier */
6114 __mark_reg_known(dst_reg
, dst_reg
->var_off
.value
);
6118 /* We get both minimum and maximum from the var_off. */
6119 dst_reg
->umin_value
= dst_reg
->var_off
.value
;
6120 dst_reg
->umax_value
= dst_reg
->var_off
.value
| dst_reg
->var_off
.mask
;
6122 if (dst_reg
->smin_value
>= 0 && smin_val
>= 0) {
6123 /* XORing two positive sign numbers gives a positive,
6124 * so safe to cast u64 result into s64.
6126 dst_reg
->smin_value
= dst_reg
->umin_value
;
6127 dst_reg
->smax_value
= dst_reg
->umax_value
;
6129 dst_reg
->smin_value
= S64_MIN
;
6130 dst_reg
->smax_value
= S64_MAX
;
6133 __update_reg_bounds(dst_reg
);
6136 static void __scalar32_min_max_lsh(struct bpf_reg_state
*dst_reg
,
6137 u64 umin_val
, u64 umax_val
)
6139 /* We lose all sign bit information (except what we can pick
6142 dst_reg
->s32_min_value
= S32_MIN
;
6143 dst_reg
->s32_max_value
= S32_MAX
;
6144 /* If we might shift our top bit out, then we know nothing */
6145 if (umax_val
> 31 || dst_reg
->u32_max_value
> 1ULL << (31 - umax_val
)) {
6146 dst_reg
->u32_min_value
= 0;
6147 dst_reg
->u32_max_value
= U32_MAX
;
6149 dst_reg
->u32_min_value
<<= umin_val
;
6150 dst_reg
->u32_max_value
<<= umax_val
;
6154 static void scalar32_min_max_lsh(struct bpf_reg_state
*dst_reg
,
6155 struct bpf_reg_state
*src_reg
)
6157 u32 umax_val
= src_reg
->u32_max_value
;
6158 u32 umin_val
= src_reg
->u32_min_value
;
6159 /* u32 alu operation will zext upper bits */
6160 struct tnum subreg
= tnum_subreg(dst_reg
->var_off
);
6162 __scalar32_min_max_lsh(dst_reg
, umin_val
, umax_val
);
6163 dst_reg
->var_off
= tnum_subreg(tnum_lshift(subreg
, umin_val
));
6164 /* Not required but being careful mark reg64 bounds as unknown so
6165 * that we are forced to pick them up from tnum and zext later and
6166 * if some path skips this step we are still safe.
6168 __mark_reg64_unbounded(dst_reg
);
6169 __update_reg32_bounds(dst_reg
);
6172 static void __scalar64_min_max_lsh(struct bpf_reg_state
*dst_reg
,
6173 u64 umin_val
, u64 umax_val
)
6175 /* Special case <<32 because it is a common compiler pattern to sign
6176 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
6177 * positive we know this shift will also be positive so we can track
6178 * bounds correctly. Otherwise we lose all sign bit information except
6179 * what we can pick up from var_off. Perhaps we can generalize this
6180 * later to shifts of any length.
6182 if (umin_val
== 32 && umax_val
== 32 && dst_reg
->s32_max_value
>= 0)
6183 dst_reg
->smax_value
= (s64
)dst_reg
->s32_max_value
<< 32;
6185 dst_reg
->smax_value
= S64_MAX
;
6187 if (umin_val
== 32 && umax_val
== 32 && dst_reg
->s32_min_value
>= 0)
6188 dst_reg
->smin_value
= (s64
)dst_reg
->s32_min_value
<< 32;
6190 dst_reg
->smin_value
= S64_MIN
;
6192 /* If we might shift our top bit out, then we know nothing */
6193 if (dst_reg
->umax_value
> 1ULL << (63 - umax_val
)) {
6194 dst_reg
->umin_value
= 0;
6195 dst_reg
->umax_value
= U64_MAX
;
6197 dst_reg
->umin_value
<<= umin_val
;
6198 dst_reg
->umax_value
<<= umax_val
;
6202 static void scalar_min_max_lsh(struct bpf_reg_state
*dst_reg
,
6203 struct bpf_reg_state
*src_reg
)
6205 u64 umax_val
= src_reg
->umax_value
;
6206 u64 umin_val
= src_reg
->umin_value
;
6208 /* scalar64 calc uses 32bit unshifted bounds so must be called first */
6209 __scalar64_min_max_lsh(dst_reg
, umin_val
, umax_val
);
6210 __scalar32_min_max_lsh(dst_reg
, umin_val
, umax_val
);
6212 dst_reg
->var_off
= tnum_lshift(dst_reg
->var_off
, umin_val
);
6213 /* We may learn something more from the var_off */
6214 __update_reg_bounds(dst_reg
);
6217 static void scalar32_min_max_rsh(struct bpf_reg_state
*dst_reg
,
6218 struct bpf_reg_state
*src_reg
)
6220 struct tnum subreg
= tnum_subreg(dst_reg
->var_off
);
6221 u32 umax_val
= src_reg
->u32_max_value
;
6222 u32 umin_val
= src_reg
->u32_min_value
;
6224 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
6225 * be negative, then either:
6226 * 1) src_reg might be zero, so the sign bit of the result is
6227 * unknown, so we lose our signed bounds
6228 * 2) it's known negative, thus the unsigned bounds capture the
6230 * 3) the signed bounds cross zero, so they tell us nothing
6232 * If the value in dst_reg is known nonnegative, then again the
6233 * unsigned bounts capture the signed bounds.
6234 * Thus, in all cases it suffices to blow away our signed bounds
6235 * and rely on inferring new ones from the unsigned bounds and
6236 * var_off of the result.
6238 dst_reg
->s32_min_value
= S32_MIN
;
6239 dst_reg
->s32_max_value
= S32_MAX
;
6241 dst_reg
->var_off
= tnum_rshift(subreg
, umin_val
);
6242 dst_reg
->u32_min_value
>>= umax_val
;
6243 dst_reg
->u32_max_value
>>= umin_val
;
6245 __mark_reg64_unbounded(dst_reg
);
6246 __update_reg32_bounds(dst_reg
);
6249 static void scalar_min_max_rsh(struct bpf_reg_state
*dst_reg
,
6250 struct bpf_reg_state
*src_reg
)
6252 u64 umax_val
= src_reg
->umax_value
;
6253 u64 umin_val
= src_reg
->umin_value
;
6255 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
6256 * be negative, then either:
6257 * 1) src_reg might be zero, so the sign bit of the result is
6258 * unknown, so we lose our signed bounds
6259 * 2) it's known negative, thus the unsigned bounds capture the
6261 * 3) the signed bounds cross zero, so they tell us nothing
6263 * If the value in dst_reg is known nonnegative, then again the
6264 * unsigned bounts capture the signed bounds.
6265 * Thus, in all cases it suffices to blow away our signed bounds
6266 * and rely on inferring new ones from the unsigned bounds and
6267 * var_off of the result.
6269 dst_reg
->smin_value
= S64_MIN
;
6270 dst_reg
->smax_value
= S64_MAX
;
6271 dst_reg
->var_off
= tnum_rshift(dst_reg
->var_off
, umin_val
);
6272 dst_reg
->umin_value
>>= umax_val
;
6273 dst_reg
->umax_value
>>= umin_val
;
6275 /* Its not easy to operate on alu32 bounds here because it depends
6276 * on bits being shifted in. Take easy way out and mark unbounded
6277 * so we can recalculate later from tnum.
6279 __mark_reg32_unbounded(dst_reg
);
6280 __update_reg_bounds(dst_reg
);
6283 static void scalar32_min_max_arsh(struct bpf_reg_state
*dst_reg
,
6284 struct bpf_reg_state
*src_reg
)
6286 u64 umin_val
= src_reg
->u32_min_value
;
6288 /* Upon reaching here, src_known is true and
6289 * umax_val is equal to umin_val.
6291 dst_reg
->s32_min_value
= (u32
)(((s32
)dst_reg
->s32_min_value
) >> umin_val
);
6292 dst_reg
->s32_max_value
= (u32
)(((s32
)dst_reg
->s32_max_value
) >> umin_val
);
6294 dst_reg
->var_off
= tnum_arshift(tnum_subreg(dst_reg
->var_off
), umin_val
, 32);
6296 /* blow away the dst_reg umin_value/umax_value and rely on
6297 * dst_reg var_off to refine the result.
6299 dst_reg
->u32_min_value
= 0;
6300 dst_reg
->u32_max_value
= U32_MAX
;
6302 __mark_reg64_unbounded(dst_reg
);
6303 __update_reg32_bounds(dst_reg
);
6306 static void scalar_min_max_arsh(struct bpf_reg_state
*dst_reg
,
6307 struct bpf_reg_state
*src_reg
)
6309 u64 umin_val
= src_reg
->umin_value
;
6311 /* Upon reaching here, src_known is true and umax_val is equal
6314 dst_reg
->smin_value
>>= umin_val
;
6315 dst_reg
->smax_value
>>= umin_val
;
6317 dst_reg
->var_off
= tnum_arshift(dst_reg
->var_off
, umin_val
, 64);
6319 /* blow away the dst_reg umin_value/umax_value and rely on
6320 * dst_reg var_off to refine the result.
6322 dst_reg
->umin_value
= 0;
6323 dst_reg
->umax_value
= U64_MAX
;
6325 /* Its not easy to operate on alu32 bounds here because it depends
6326 * on bits being shifted in from upper 32-bits. Take easy way out
6327 * and mark unbounded so we can recalculate later from tnum.
6329 __mark_reg32_unbounded(dst_reg
);
6330 __update_reg_bounds(dst_reg
);
6333 /* WARNING: This function does calculations on 64-bit values, but the actual
6334 * execution may occur on 32-bit values. Therefore, things like bitshifts
6335 * need extra checks in the 32-bit case.
6337 static int adjust_scalar_min_max_vals(struct bpf_verifier_env
*env
,
6338 struct bpf_insn
*insn
,
6339 struct bpf_reg_state
*dst_reg
,
6340 struct bpf_reg_state src_reg
)
6342 struct bpf_reg_state
*regs
= cur_regs(env
);
6343 u8 opcode
= BPF_OP(insn
->code
);
6345 s64 smin_val
, smax_val
;
6346 u64 umin_val
, umax_val
;
6347 s32 s32_min_val
, s32_max_val
;
6348 u32 u32_min_val
, u32_max_val
;
6349 u64 insn_bitness
= (BPF_CLASS(insn
->code
) == BPF_ALU64
) ? 64 : 32;
6350 u32 dst
= insn
->dst_reg
;
6352 bool alu32
= (BPF_CLASS(insn
->code
) != BPF_ALU64
);
6354 smin_val
= src_reg
.smin_value
;
6355 smax_val
= src_reg
.smax_value
;
6356 umin_val
= src_reg
.umin_value
;
6357 umax_val
= src_reg
.umax_value
;
6359 s32_min_val
= src_reg
.s32_min_value
;
6360 s32_max_val
= src_reg
.s32_max_value
;
6361 u32_min_val
= src_reg
.u32_min_value
;
6362 u32_max_val
= src_reg
.u32_max_value
;
6365 src_known
= tnum_subreg_is_const(src_reg
.var_off
);
6367 (s32_min_val
!= s32_max_val
|| u32_min_val
!= u32_max_val
)) ||
6368 s32_min_val
> s32_max_val
|| u32_min_val
> u32_max_val
) {
6369 /* Taint dst register if offset had invalid bounds
6370 * derived from e.g. dead branches.
6372 __mark_reg_unknown(env
, dst_reg
);
6376 src_known
= tnum_is_const(src_reg
.var_off
);
6378 (smin_val
!= smax_val
|| umin_val
!= umax_val
)) ||
6379 smin_val
> smax_val
|| umin_val
> umax_val
) {
6380 /* Taint dst register if offset had invalid bounds
6381 * derived from e.g. dead branches.
6383 __mark_reg_unknown(env
, dst_reg
);
6389 opcode
!= BPF_ADD
&& opcode
!= BPF_SUB
&& opcode
!= BPF_AND
) {
6390 __mark_reg_unknown(env
, dst_reg
);
6394 /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
6395 * There are two classes of instructions: The first class we track both
6396 * alu32 and alu64 sign/unsigned bounds independently this provides the
6397 * greatest amount of precision when alu operations are mixed with jmp32
6398 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
6399 * and BPF_OR. This is possible because these ops have fairly easy to
6400 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
6401 * See alu32 verifier tests for examples. The second class of
6402 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
6403 * with regards to tracking sign/unsigned bounds because the bits may
6404 * cross subreg boundaries in the alu64 case. When this happens we mark
6405 * the reg unbounded in the subreg bound space and use the resulting
6406 * tnum to calculate an approximation of the sign/unsigned bounds.
6410 ret
= sanitize_val_alu(env
, insn
);
6412 verbose(env
, "R%d tried to add from different pointers or scalars\n", dst
);
6415 scalar32_min_max_add(dst_reg
, &src_reg
);
6416 scalar_min_max_add(dst_reg
, &src_reg
);
6417 dst_reg
->var_off
= tnum_add(dst_reg
->var_off
, src_reg
.var_off
);
6420 ret
= sanitize_val_alu(env
, insn
);
6422 verbose(env
, "R%d tried to sub from different pointers or scalars\n", dst
);
6425 scalar32_min_max_sub(dst_reg
, &src_reg
);
6426 scalar_min_max_sub(dst_reg
, &src_reg
);
6427 dst_reg
->var_off
= tnum_sub(dst_reg
->var_off
, src_reg
.var_off
);
6430 dst_reg
->var_off
= tnum_mul(dst_reg
->var_off
, src_reg
.var_off
);
6431 scalar32_min_max_mul(dst_reg
, &src_reg
);
6432 scalar_min_max_mul(dst_reg
, &src_reg
);
6435 dst_reg
->var_off
= tnum_and(dst_reg
->var_off
, src_reg
.var_off
);
6436 scalar32_min_max_and(dst_reg
, &src_reg
);
6437 scalar_min_max_and(dst_reg
, &src_reg
);
6440 dst_reg
->var_off
= tnum_or(dst_reg
->var_off
, src_reg
.var_off
);
6441 scalar32_min_max_or(dst_reg
, &src_reg
);
6442 scalar_min_max_or(dst_reg
, &src_reg
);
6445 dst_reg
->var_off
= tnum_xor(dst_reg
->var_off
, src_reg
.var_off
);
6446 scalar32_min_max_xor(dst_reg
, &src_reg
);
6447 scalar_min_max_xor(dst_reg
, &src_reg
);
6450 if (umax_val
>= insn_bitness
) {
6451 /* Shifts greater than 31 or 63 are undefined.
6452 * This includes shifts by a negative number.
6454 mark_reg_unknown(env
, regs
, insn
->dst_reg
);
6458 scalar32_min_max_lsh(dst_reg
, &src_reg
);
6460 scalar_min_max_lsh(dst_reg
, &src_reg
);
6463 if (umax_val
>= insn_bitness
) {
6464 /* Shifts greater than 31 or 63 are undefined.
6465 * This includes shifts by a negative number.
6467 mark_reg_unknown(env
, regs
, insn
->dst_reg
);
6471 scalar32_min_max_rsh(dst_reg
, &src_reg
);
6473 scalar_min_max_rsh(dst_reg
, &src_reg
);
6476 if (umax_val
>= insn_bitness
) {
6477 /* Shifts greater than 31 or 63 are undefined.
6478 * This includes shifts by a negative number.
6480 mark_reg_unknown(env
, regs
, insn
->dst_reg
);
6484 scalar32_min_max_arsh(dst_reg
, &src_reg
);
6486 scalar_min_max_arsh(dst_reg
, &src_reg
);
6489 mark_reg_unknown(env
, regs
, insn
->dst_reg
);
6493 /* ALU32 ops are zero extended into 64bit register */
6495 zext_32_to_64(dst_reg
);
6497 __update_reg_bounds(dst_reg
);
6498 __reg_deduce_bounds(dst_reg
);
6499 __reg_bound_offset(dst_reg
);
6503 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
6506 static int adjust_reg_min_max_vals(struct bpf_verifier_env
*env
,
6507 struct bpf_insn
*insn
)
6509 struct bpf_verifier_state
*vstate
= env
->cur_state
;
6510 struct bpf_func_state
*state
= vstate
->frame
[vstate
->curframe
];
6511 struct bpf_reg_state
*regs
= state
->regs
, *dst_reg
, *src_reg
;
6512 struct bpf_reg_state
*ptr_reg
= NULL
, off_reg
= {0};
6513 u8 opcode
= BPF_OP(insn
->code
);
6516 dst_reg
= ®s
[insn
->dst_reg
];
6518 if (dst_reg
->type
!= SCALAR_VALUE
)
6521 /* Make sure ID is cleared otherwise dst_reg min/max could be
6522 * incorrectly propagated into other registers by find_equal_scalars()
6525 if (BPF_SRC(insn
->code
) == BPF_X
) {
6526 src_reg
= ®s
[insn
->src_reg
];
6527 if (src_reg
->type
!= SCALAR_VALUE
) {
6528 if (dst_reg
->type
!= SCALAR_VALUE
) {
6529 /* Combining two pointers by any ALU op yields
6530 * an arbitrary scalar. Disallow all math except
6531 * pointer subtraction
6533 if (opcode
== BPF_SUB
&& env
->allow_ptr_leaks
) {
6534 mark_reg_unknown(env
, regs
, insn
->dst_reg
);
6537 verbose(env
, "R%d pointer %s pointer prohibited\n",
6539 bpf_alu_string
[opcode
>> 4]);
6542 /* scalar += pointer
6543 * This is legal, but we have to reverse our
6544 * src/dest handling in computing the range
6546 err
= mark_chain_precision(env
, insn
->dst_reg
);
6549 return adjust_ptr_min_max_vals(env
, insn
,
6552 } else if (ptr_reg
) {
6553 /* pointer += scalar */
6554 err
= mark_chain_precision(env
, insn
->src_reg
);
6557 return adjust_ptr_min_max_vals(env
, insn
,
6561 /* Pretend the src is a reg with a known value, since we only
6562 * need to be able to read from this state.
6564 off_reg
.type
= SCALAR_VALUE
;
6565 __mark_reg_known(&off_reg
, insn
->imm
);
6567 if (ptr_reg
) /* pointer += K */
6568 return adjust_ptr_min_max_vals(env
, insn
,
6572 /* Got here implies adding two SCALAR_VALUEs */
6573 if (WARN_ON_ONCE(ptr_reg
)) {
6574 print_verifier_state(env
, state
);
6575 verbose(env
, "verifier internal error: unexpected ptr_reg\n");
6578 if (WARN_ON(!src_reg
)) {
6579 print_verifier_state(env
, state
);
6580 verbose(env
, "verifier internal error: no src_reg\n");
6583 return adjust_scalar_min_max_vals(env
, insn
, dst_reg
, *src_reg
);
6586 /* check validity of 32-bit and 64-bit arithmetic operations */
6587 static int check_alu_op(struct bpf_verifier_env
*env
, struct bpf_insn
*insn
)
6589 struct bpf_reg_state
*regs
= cur_regs(env
);
6590 u8 opcode
= BPF_OP(insn
->code
);
6593 if (opcode
== BPF_END
|| opcode
== BPF_NEG
) {
6594 if (opcode
== BPF_NEG
) {
6595 if (BPF_SRC(insn
->code
) != 0 ||
6596 insn
->src_reg
!= BPF_REG_0
||
6597 insn
->off
!= 0 || insn
->imm
!= 0) {
6598 verbose(env
, "BPF_NEG uses reserved fields\n");
6602 if (insn
->src_reg
!= BPF_REG_0
|| insn
->off
!= 0 ||
6603 (insn
->imm
!= 16 && insn
->imm
!= 32 && insn
->imm
!= 64) ||
6604 BPF_CLASS(insn
->code
) == BPF_ALU64
) {
6605 verbose(env
, "BPF_END uses reserved fields\n");
6610 /* check src operand */
6611 err
= check_reg_arg(env
, insn
->dst_reg
, SRC_OP
);
6615 if (is_pointer_value(env
, insn
->dst_reg
)) {
6616 verbose(env
, "R%d pointer arithmetic prohibited\n",
6621 /* check dest operand */
6622 err
= check_reg_arg(env
, insn
->dst_reg
, DST_OP
);
6626 } else if (opcode
== BPF_MOV
) {
6628 if (BPF_SRC(insn
->code
) == BPF_X
) {
6629 if (insn
->imm
!= 0 || insn
->off
!= 0) {
6630 verbose(env
, "BPF_MOV uses reserved fields\n");
6634 /* check src operand */
6635 err
= check_reg_arg(env
, insn
->src_reg
, SRC_OP
);
6639 if (insn
->src_reg
!= BPF_REG_0
|| insn
->off
!= 0) {
6640 verbose(env
, "BPF_MOV uses reserved fields\n");
6645 /* check dest operand, mark as required later */
6646 err
= check_reg_arg(env
, insn
->dst_reg
, DST_OP_NO_MARK
);
6650 if (BPF_SRC(insn
->code
) == BPF_X
) {
6651 struct bpf_reg_state
*src_reg
= regs
+ insn
->src_reg
;
6652 struct bpf_reg_state
*dst_reg
= regs
+ insn
->dst_reg
;
6654 if (BPF_CLASS(insn
->code
) == BPF_ALU64
) {
6656 * copy register state to dest reg
6658 if (src_reg
->type
== SCALAR_VALUE
&& !src_reg
->id
)
6659 /* Assign src and dst registers the same ID
6660 * that will be used by find_equal_scalars()
6661 * to propagate min/max range.
6663 src_reg
->id
= ++env
->id_gen
;
6664 *dst_reg
= *src_reg
;
6665 dst_reg
->live
|= REG_LIVE_WRITTEN
;
6666 dst_reg
->subreg_def
= DEF_NOT_SUBREG
;
6669 if (is_pointer_value(env
, insn
->src_reg
)) {
6671 "R%d partial copy of pointer\n",
6674 } else if (src_reg
->type
== SCALAR_VALUE
) {
6675 *dst_reg
= *src_reg
;
6676 /* Make sure ID is cleared otherwise
6677 * dst_reg min/max could be incorrectly
6678 * propagated into src_reg by find_equal_scalars()
6681 dst_reg
->live
|= REG_LIVE_WRITTEN
;
6682 dst_reg
->subreg_def
= env
->insn_idx
+ 1;
6684 mark_reg_unknown(env
, regs
,
6687 zext_32_to_64(dst_reg
);
6691 * remember the value we stored into this reg
6693 /* clear any state __mark_reg_known doesn't set */
6694 mark_reg_unknown(env
, regs
, insn
->dst_reg
);
6695 regs
[insn
->dst_reg
].type
= SCALAR_VALUE
;
6696 if (BPF_CLASS(insn
->code
) == BPF_ALU64
) {
6697 __mark_reg_known(regs
+ insn
->dst_reg
,
6700 __mark_reg_known(regs
+ insn
->dst_reg
,
6705 } else if (opcode
> BPF_END
) {
6706 verbose(env
, "invalid BPF_ALU opcode %x\n", opcode
);
6709 } else { /* all other ALU ops: and, sub, xor, add, ... */
6711 if (BPF_SRC(insn
->code
) == BPF_X
) {
6712 if (insn
->imm
!= 0 || insn
->off
!= 0) {
6713 verbose(env
, "BPF_ALU uses reserved fields\n");
6716 /* check src1 operand */
6717 err
= check_reg_arg(env
, insn
->src_reg
, SRC_OP
);
6721 if (insn
->src_reg
!= BPF_REG_0
|| insn
->off
!= 0) {
6722 verbose(env
, "BPF_ALU uses reserved fields\n");
6727 /* check src2 operand */
6728 err
= check_reg_arg(env
, insn
->dst_reg
, SRC_OP
);
6732 if ((opcode
== BPF_MOD
|| opcode
== BPF_DIV
) &&
6733 BPF_SRC(insn
->code
) == BPF_K
&& insn
->imm
== 0) {
6734 verbose(env
, "div by zero\n");
6738 if ((opcode
== BPF_LSH
|| opcode
== BPF_RSH
||
6739 opcode
== BPF_ARSH
) && BPF_SRC(insn
->code
) == BPF_K
) {
6740 int size
= BPF_CLASS(insn
->code
) == BPF_ALU64
? 64 : 32;
6742 if (insn
->imm
< 0 || insn
->imm
>= size
) {
6743 verbose(env
, "invalid shift %d\n", insn
->imm
);
6748 /* check dest operand */
6749 err
= check_reg_arg(env
, insn
->dst_reg
, DST_OP_NO_MARK
);
6753 return adjust_reg_min_max_vals(env
, insn
);
6759 static void __find_good_pkt_pointers(struct bpf_func_state
*state
,
6760 struct bpf_reg_state
*dst_reg
,
6761 enum bpf_reg_type type
, int new_range
)
6763 struct bpf_reg_state
*reg
;
6766 for (i
= 0; i
< MAX_BPF_REG
; i
++) {
6767 reg
= &state
->regs
[i
];
6768 if (reg
->type
== type
&& reg
->id
== dst_reg
->id
)
6769 /* keep the maximum range already checked */
6770 reg
->range
= max(reg
->range
, new_range
);
6773 bpf_for_each_spilled_reg(i
, state
, reg
) {
6776 if (reg
->type
== type
&& reg
->id
== dst_reg
->id
)
6777 reg
->range
= max(reg
->range
, new_range
);
6781 static void find_good_pkt_pointers(struct bpf_verifier_state
*vstate
,
6782 struct bpf_reg_state
*dst_reg
,
6783 enum bpf_reg_type type
,
6784 bool range_right_open
)
6788 if (dst_reg
->off
< 0 ||
6789 (dst_reg
->off
== 0 && range_right_open
))
6790 /* This doesn't give us any range */
6793 if (dst_reg
->umax_value
> MAX_PACKET_OFF
||
6794 dst_reg
->umax_value
+ dst_reg
->off
> MAX_PACKET_OFF
)
6795 /* Risk of overflow. For instance, ptr + (1<<63) may be less
6796 * than pkt_end, but that's because it's also less than pkt.
6800 new_range
= dst_reg
->off
;
6801 if (range_right_open
)
6804 /* Examples for register markings:
6806 * pkt_data in dst register:
6810 * if (r2 > pkt_end) goto <handle exception>
6815 * if (r2 < pkt_end) goto <access okay>
6816 * <handle exception>
6819 * r2 == dst_reg, pkt_end == src_reg
6820 * r2=pkt(id=n,off=8,r=0)
6821 * r3=pkt(id=n,off=0,r=0)
6823 * pkt_data in src register:
6827 * if (pkt_end >= r2) goto <access okay>
6828 * <handle exception>
6832 * if (pkt_end <= r2) goto <handle exception>
6836 * pkt_end == dst_reg, r2 == src_reg
6837 * r2=pkt(id=n,off=8,r=0)
6838 * r3=pkt(id=n,off=0,r=0)
6840 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
6841 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
6842 * and [r3, r3 + 8-1) respectively is safe to access depending on
6846 /* If our ids match, then we must have the same max_value. And we
6847 * don't care about the other reg's fixed offset, since if it's too big
6848 * the range won't allow anything.
6849 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
6851 for (i
= 0; i
<= vstate
->curframe
; i
++)
6852 __find_good_pkt_pointers(vstate
->frame
[i
], dst_reg
, type
,
6856 static int is_branch32_taken(struct bpf_reg_state
*reg
, u32 val
, u8 opcode
)
6858 struct tnum subreg
= tnum_subreg(reg
->var_off
);
6859 s32 sval
= (s32
)val
;
6863 if (tnum_is_const(subreg
))
6864 return !!tnum_equals_const(subreg
, val
);
6867 if (tnum_is_const(subreg
))
6868 return !tnum_equals_const(subreg
, val
);
6871 if ((~subreg
.mask
& subreg
.value
) & val
)
6873 if (!((subreg
.mask
| subreg
.value
) & val
))
6877 if (reg
->u32_min_value
> val
)
6879 else if (reg
->u32_max_value
<= val
)
6883 if (reg
->s32_min_value
> sval
)
6885 else if (reg
->s32_max_value
<= sval
)
6889 if (reg
->u32_max_value
< val
)
6891 else if (reg
->u32_min_value
>= val
)
6895 if (reg
->s32_max_value
< sval
)
6897 else if (reg
->s32_min_value
>= sval
)
6901 if (reg
->u32_min_value
>= val
)
6903 else if (reg
->u32_max_value
< val
)
6907 if (reg
->s32_min_value
>= sval
)
6909 else if (reg
->s32_max_value
< sval
)
6913 if (reg
->u32_max_value
<= val
)
6915 else if (reg
->u32_min_value
> val
)
6919 if (reg
->s32_max_value
<= sval
)
6921 else if (reg
->s32_min_value
> sval
)
6930 static int is_branch64_taken(struct bpf_reg_state
*reg
, u64 val
, u8 opcode
)
6932 s64 sval
= (s64
)val
;
6936 if (tnum_is_const(reg
->var_off
))
6937 return !!tnum_equals_const(reg
->var_off
, val
);
6940 if (tnum_is_const(reg
->var_off
))
6941 return !tnum_equals_const(reg
->var_off
, val
);
6944 if ((~reg
->var_off
.mask
& reg
->var_off
.value
) & val
)
6946 if (!((reg
->var_off
.mask
| reg
->var_off
.value
) & val
))
6950 if (reg
->umin_value
> val
)
6952 else if (reg
->umax_value
<= val
)
6956 if (reg
->smin_value
> sval
)
6958 else if (reg
->smax_value
<= sval
)
6962 if (reg
->umax_value
< val
)
6964 else if (reg
->umin_value
>= val
)
6968 if (reg
->smax_value
< sval
)
6970 else if (reg
->smin_value
>= sval
)
6974 if (reg
->umin_value
>= val
)
6976 else if (reg
->umax_value
< val
)
6980 if (reg
->smin_value
>= sval
)
6982 else if (reg
->smax_value
< sval
)
6986 if (reg
->umax_value
<= val
)
6988 else if (reg
->umin_value
> val
)
6992 if (reg
->smax_value
<= sval
)
6994 else if (reg
->smin_value
> sval
)
7002 /* compute branch direction of the expression "if (reg opcode val) goto target;"
7004 * 1 - branch will be taken and "goto target" will be executed
7005 * 0 - branch will not be taken and fall-through to next insn
7006 * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
7009 static int is_branch_taken(struct bpf_reg_state
*reg
, u64 val
, u8 opcode
,
7012 if (__is_pointer_value(false, reg
)) {
7013 if (!reg_type_not_null(reg
->type
))
7016 /* If pointer is valid tests against zero will fail so we can
7017 * use this to direct branch taken.
7033 return is_branch32_taken(reg
, val
, opcode
);
7034 return is_branch64_taken(reg
, val
, opcode
);
7037 static int flip_opcode(u32 opcode
)
7039 /* How can we transform "a <op> b" into "b <op> a"? */
7040 static const u8 opcode_flip
[16] = {
7041 /* these stay the same */
7042 [BPF_JEQ
>> 4] = BPF_JEQ
,
7043 [BPF_JNE
>> 4] = BPF_JNE
,
7044 [BPF_JSET
>> 4] = BPF_JSET
,
7045 /* these swap "lesser" and "greater" (L and G in the opcodes) */
7046 [BPF_JGE
>> 4] = BPF_JLE
,
7047 [BPF_JGT
>> 4] = BPF_JLT
,
7048 [BPF_JLE
>> 4] = BPF_JGE
,
7049 [BPF_JLT
>> 4] = BPF_JGT
,
7050 [BPF_JSGE
>> 4] = BPF_JSLE
,
7051 [BPF_JSGT
>> 4] = BPF_JSLT
,
7052 [BPF_JSLE
>> 4] = BPF_JSGE
,
7053 [BPF_JSLT
>> 4] = BPF_JSGT
7055 return opcode_flip
[opcode
>> 4];
7058 static int is_pkt_ptr_branch_taken(struct bpf_reg_state
*dst_reg
,
7059 struct bpf_reg_state
*src_reg
,
7062 struct bpf_reg_state
*pkt
;
7064 if (src_reg
->type
== PTR_TO_PACKET_END
) {
7066 } else if (dst_reg
->type
== PTR_TO_PACKET_END
) {
7068 opcode
= flip_opcode(opcode
);
7073 if (pkt
->range
>= 0)
7078 /* pkt <= pkt_end */
7082 if (pkt
->range
== BEYOND_PKT_END
)
7083 /* pkt has at last one extra byte beyond pkt_end */
7084 return opcode
== BPF_JGT
;
7090 /* pkt >= pkt_end */
7091 if (pkt
->range
== BEYOND_PKT_END
|| pkt
->range
== AT_PKT_END
)
7092 return opcode
== BPF_JGE
;
7098 /* Adjusts the register min/max values in the case that the dst_reg is the
7099 * variable register that we are working on, and src_reg is a constant or we're
7100 * simply doing a BPF_K check.
7101 * In JEQ/JNE cases we also adjust the var_off values.
7103 static void reg_set_min_max(struct bpf_reg_state
*true_reg
,
7104 struct bpf_reg_state
*false_reg
,
7106 u8 opcode
, bool is_jmp32
)
7108 struct tnum false_32off
= tnum_subreg(false_reg
->var_off
);
7109 struct tnum false_64off
= false_reg
->var_off
;
7110 struct tnum true_32off
= tnum_subreg(true_reg
->var_off
);
7111 struct tnum true_64off
= true_reg
->var_off
;
7112 s64 sval
= (s64
)val
;
7113 s32 sval32
= (s32
)val32
;
7115 /* If the dst_reg is a pointer, we can't learn anything about its
7116 * variable offset from the compare (unless src_reg were a pointer into
7117 * the same object, but we don't bother with that.
7118 * Since false_reg and true_reg have the same type by construction, we
7119 * only need to check one of them for pointerness.
7121 if (__is_pointer_value(false, false_reg
))
7128 struct bpf_reg_state
*reg
=
7129 opcode
== BPF_JEQ
? true_reg
: false_reg
;
7131 /* JEQ/JNE comparison doesn't change the register equivalence.
7133 * if (r1 == 42) goto label;
7135 * label: // here both r1 and r2 are known to be 42.
7137 * Hence when marking register as known preserve it's ID.
7140 __mark_reg32_known(reg
, val32
);
7142 ___mark_reg_known(reg
, val
);
7147 false_32off
= tnum_and(false_32off
, tnum_const(~val32
));
7148 if (is_power_of_2(val32
))
7149 true_32off
= tnum_or(true_32off
,
7152 false_64off
= tnum_and(false_64off
, tnum_const(~val
));
7153 if (is_power_of_2(val
))
7154 true_64off
= tnum_or(true_64off
,
7162 u32 false_umax
= opcode
== BPF_JGT
? val32
: val32
- 1;
7163 u32 true_umin
= opcode
== BPF_JGT
? val32
+ 1 : val32
;
7165 false_reg
->u32_max_value
= min(false_reg
->u32_max_value
,
7167 true_reg
->u32_min_value
= max(true_reg
->u32_min_value
,
7170 u64 false_umax
= opcode
== BPF_JGT
? val
: val
- 1;
7171 u64 true_umin
= opcode
== BPF_JGT
? val
+ 1 : val
;
7173 false_reg
->umax_value
= min(false_reg
->umax_value
, false_umax
);
7174 true_reg
->umin_value
= max(true_reg
->umin_value
, true_umin
);
7182 s32 false_smax
= opcode
== BPF_JSGT
? sval32
: sval32
- 1;
7183 s32 true_smin
= opcode
== BPF_JSGT
? sval32
+ 1 : sval32
;
7185 false_reg
->s32_max_value
= min(false_reg
->s32_max_value
, false_smax
);
7186 true_reg
->s32_min_value
= max(true_reg
->s32_min_value
, true_smin
);
7188 s64 false_smax
= opcode
== BPF_JSGT
? sval
: sval
- 1;
7189 s64 true_smin
= opcode
== BPF_JSGT
? sval
+ 1 : sval
;
7191 false_reg
->smax_value
= min(false_reg
->smax_value
, false_smax
);
7192 true_reg
->smin_value
= max(true_reg
->smin_value
, true_smin
);
7200 u32 false_umin
= opcode
== BPF_JLT
? val32
: val32
+ 1;
7201 u32 true_umax
= opcode
== BPF_JLT
? val32
- 1 : val32
;
7203 false_reg
->u32_min_value
= max(false_reg
->u32_min_value
,
7205 true_reg
->u32_max_value
= min(true_reg
->u32_max_value
,
7208 u64 false_umin
= opcode
== BPF_JLT
? val
: val
+ 1;
7209 u64 true_umax
= opcode
== BPF_JLT
? val
- 1 : val
;
7211 false_reg
->umin_value
= max(false_reg
->umin_value
, false_umin
);
7212 true_reg
->umax_value
= min(true_reg
->umax_value
, true_umax
);
7220 s32 false_smin
= opcode
== BPF_JSLT
? sval32
: sval32
+ 1;
7221 s32 true_smax
= opcode
== BPF_JSLT
? sval32
- 1 : sval32
;
7223 false_reg
->s32_min_value
= max(false_reg
->s32_min_value
, false_smin
);
7224 true_reg
->s32_max_value
= min(true_reg
->s32_max_value
, true_smax
);
7226 s64 false_smin
= opcode
== BPF_JSLT
? sval
: sval
+ 1;
7227 s64 true_smax
= opcode
== BPF_JSLT
? sval
- 1 : sval
;
7229 false_reg
->smin_value
= max(false_reg
->smin_value
, false_smin
);
7230 true_reg
->smax_value
= min(true_reg
->smax_value
, true_smax
);
7239 false_reg
->var_off
= tnum_or(tnum_clear_subreg(false_64off
),
7240 tnum_subreg(false_32off
));
7241 true_reg
->var_off
= tnum_or(tnum_clear_subreg(true_64off
),
7242 tnum_subreg(true_32off
));
7243 __reg_combine_32_into_64(false_reg
);
7244 __reg_combine_32_into_64(true_reg
);
7246 false_reg
->var_off
= false_64off
;
7247 true_reg
->var_off
= true_64off
;
7248 __reg_combine_64_into_32(false_reg
);
7249 __reg_combine_64_into_32(true_reg
);
7253 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
7256 static void reg_set_min_max_inv(struct bpf_reg_state
*true_reg
,
7257 struct bpf_reg_state
*false_reg
,
7259 u8 opcode
, bool is_jmp32
)
7261 opcode
= flip_opcode(opcode
);
7262 /* This uses zero as "not present in table"; luckily the zero opcode,
7263 * BPF_JA, can't get here.
7266 reg_set_min_max(true_reg
, false_reg
, val
, val32
, opcode
, is_jmp32
);
7269 /* Regs are known to be equal, so intersect their min/max/var_off */
7270 static void __reg_combine_min_max(struct bpf_reg_state
*src_reg
,
7271 struct bpf_reg_state
*dst_reg
)
7273 src_reg
->umin_value
= dst_reg
->umin_value
= max(src_reg
->umin_value
,
7274 dst_reg
->umin_value
);
7275 src_reg
->umax_value
= dst_reg
->umax_value
= min(src_reg
->umax_value
,
7276 dst_reg
->umax_value
);
7277 src_reg
->smin_value
= dst_reg
->smin_value
= max(src_reg
->smin_value
,
7278 dst_reg
->smin_value
);
7279 src_reg
->smax_value
= dst_reg
->smax_value
= min(src_reg
->smax_value
,
7280 dst_reg
->smax_value
);
7281 src_reg
->var_off
= dst_reg
->var_off
= tnum_intersect(src_reg
->var_off
,
7283 /* We might have learned new bounds from the var_off. */
7284 __update_reg_bounds(src_reg
);
7285 __update_reg_bounds(dst_reg
);
7286 /* We might have learned something about the sign bit. */
7287 __reg_deduce_bounds(src_reg
);
7288 __reg_deduce_bounds(dst_reg
);
7289 /* We might have learned some bits from the bounds. */
7290 __reg_bound_offset(src_reg
);
7291 __reg_bound_offset(dst_reg
);
7292 /* Intersecting with the old var_off might have improved our bounds
7293 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
7294 * then new var_off is (0; 0x7f...fc) which improves our umax.
7296 __update_reg_bounds(src_reg
);
7297 __update_reg_bounds(dst_reg
);
7300 static void reg_combine_min_max(struct bpf_reg_state
*true_src
,
7301 struct bpf_reg_state
*true_dst
,
7302 struct bpf_reg_state
*false_src
,
7303 struct bpf_reg_state
*false_dst
,
7308 __reg_combine_min_max(true_src
, true_dst
);
7311 __reg_combine_min_max(false_src
, false_dst
);
7316 static void mark_ptr_or_null_reg(struct bpf_func_state
*state
,
7317 struct bpf_reg_state
*reg
, u32 id
,
7320 if (reg_type_may_be_null(reg
->type
) && reg
->id
== id
&&
7321 !WARN_ON_ONCE(!reg
->id
)) {
7322 /* Old offset (both fixed and variable parts) should
7323 * have been known-zero, because we don't allow pointer
7324 * arithmetic on pointers that might be NULL.
7326 if (WARN_ON_ONCE(reg
->smin_value
|| reg
->smax_value
||
7327 !tnum_equals_const(reg
->var_off
, 0) ||
7329 __mark_reg_known_zero(reg
);
7333 reg
->type
= SCALAR_VALUE
;
7334 } else if (reg
->type
== PTR_TO_MAP_VALUE_OR_NULL
) {
7335 const struct bpf_map
*map
= reg
->map_ptr
;
7337 if (map
->inner_map_meta
) {
7338 reg
->type
= CONST_PTR_TO_MAP
;
7339 reg
->map_ptr
= map
->inner_map_meta
;
7340 } else if (map
->map_type
== BPF_MAP_TYPE_XSKMAP
) {
7341 reg
->type
= PTR_TO_XDP_SOCK
;
7342 } else if (map
->map_type
== BPF_MAP_TYPE_SOCKMAP
||
7343 map
->map_type
== BPF_MAP_TYPE_SOCKHASH
) {
7344 reg
->type
= PTR_TO_SOCKET
;
7346 reg
->type
= PTR_TO_MAP_VALUE
;
7348 } else if (reg
->type
== PTR_TO_SOCKET_OR_NULL
) {
7349 reg
->type
= PTR_TO_SOCKET
;
7350 } else if (reg
->type
== PTR_TO_SOCK_COMMON_OR_NULL
) {
7351 reg
->type
= PTR_TO_SOCK_COMMON
;
7352 } else if (reg
->type
== PTR_TO_TCP_SOCK_OR_NULL
) {
7353 reg
->type
= PTR_TO_TCP_SOCK
;
7354 } else if (reg
->type
== PTR_TO_BTF_ID_OR_NULL
) {
7355 reg
->type
= PTR_TO_BTF_ID
;
7356 } else if (reg
->type
== PTR_TO_MEM_OR_NULL
) {
7357 reg
->type
= PTR_TO_MEM
;
7358 } else if (reg
->type
== PTR_TO_RDONLY_BUF_OR_NULL
) {
7359 reg
->type
= PTR_TO_RDONLY_BUF
;
7360 } else if (reg
->type
== PTR_TO_RDWR_BUF_OR_NULL
) {
7361 reg
->type
= PTR_TO_RDWR_BUF
;
7364 /* We don't need id and ref_obj_id from this point
7365 * onwards anymore, thus we should better reset it,
7366 * so that state pruning has chances to take effect.
7369 reg
->ref_obj_id
= 0;
7370 } else if (!reg_may_point_to_spin_lock(reg
)) {
7371 /* For not-NULL ptr, reg->ref_obj_id will be reset
7372 * in release_reg_references().
7374 * reg->id is still used by spin_lock ptr. Other
7375 * than spin_lock ptr type, reg->id can be reset.
7382 static void __mark_ptr_or_null_regs(struct bpf_func_state
*state
, u32 id
,
7385 struct bpf_reg_state
*reg
;
7388 for (i
= 0; i
< MAX_BPF_REG
; i
++)
7389 mark_ptr_or_null_reg(state
, &state
->regs
[i
], id
, is_null
);
7391 bpf_for_each_spilled_reg(i
, state
, reg
) {
7394 mark_ptr_or_null_reg(state
, reg
, id
, is_null
);
7398 /* The logic is similar to find_good_pkt_pointers(), both could eventually
7399 * be folded together at some point.
7401 static void mark_ptr_or_null_regs(struct bpf_verifier_state
*vstate
, u32 regno
,
7404 struct bpf_func_state
*state
= vstate
->frame
[vstate
->curframe
];
7405 struct bpf_reg_state
*regs
= state
->regs
;
7406 u32 ref_obj_id
= regs
[regno
].ref_obj_id
;
7407 u32 id
= regs
[regno
].id
;
7410 if (ref_obj_id
&& ref_obj_id
== id
&& is_null
)
7411 /* regs[regno] is in the " == NULL" branch.
7412 * No one could have freed the reference state before
7413 * doing the NULL check.
7415 WARN_ON_ONCE(release_reference_state(state
, id
));
7417 for (i
= 0; i
<= vstate
->curframe
; i
++)
7418 __mark_ptr_or_null_regs(vstate
->frame
[i
], id
, is_null
);
7421 static bool try_match_pkt_pointers(const struct bpf_insn
*insn
,
7422 struct bpf_reg_state
*dst_reg
,
7423 struct bpf_reg_state
*src_reg
,
7424 struct bpf_verifier_state
*this_branch
,
7425 struct bpf_verifier_state
*other_branch
)
7427 if (BPF_SRC(insn
->code
) != BPF_X
)
7430 /* Pointers are always 64-bit. */
7431 if (BPF_CLASS(insn
->code
) == BPF_JMP32
)
7434 switch (BPF_OP(insn
->code
)) {
7436 if ((dst_reg
->type
== PTR_TO_PACKET
&&
7437 src_reg
->type
== PTR_TO_PACKET_END
) ||
7438 (dst_reg
->type
== PTR_TO_PACKET_META
&&
7439 reg_is_init_pkt_pointer(src_reg
, PTR_TO_PACKET
))) {
7440 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
7441 find_good_pkt_pointers(this_branch
, dst_reg
,
7442 dst_reg
->type
, false);
7443 mark_pkt_end(other_branch
, insn
->dst_reg
, true);
7444 } else if ((dst_reg
->type
== PTR_TO_PACKET_END
&&
7445 src_reg
->type
== PTR_TO_PACKET
) ||
7446 (reg_is_init_pkt_pointer(dst_reg
, PTR_TO_PACKET
) &&
7447 src_reg
->type
== PTR_TO_PACKET_META
)) {
7448 /* pkt_end > pkt_data', pkt_data > pkt_meta' */
7449 find_good_pkt_pointers(other_branch
, src_reg
,
7450 src_reg
->type
, true);
7451 mark_pkt_end(this_branch
, insn
->src_reg
, false);
7457 if ((dst_reg
->type
== PTR_TO_PACKET
&&
7458 src_reg
->type
== PTR_TO_PACKET_END
) ||
7459 (dst_reg
->type
== PTR_TO_PACKET_META
&&
7460 reg_is_init_pkt_pointer(src_reg
, PTR_TO_PACKET
))) {
7461 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
7462 find_good_pkt_pointers(other_branch
, dst_reg
,
7463 dst_reg
->type
, true);
7464 mark_pkt_end(this_branch
, insn
->dst_reg
, false);
7465 } else if ((dst_reg
->type
== PTR_TO_PACKET_END
&&
7466 src_reg
->type
== PTR_TO_PACKET
) ||
7467 (reg_is_init_pkt_pointer(dst_reg
, PTR_TO_PACKET
) &&
7468 src_reg
->type
== PTR_TO_PACKET_META
)) {
7469 /* pkt_end < pkt_data', pkt_data > pkt_meta' */
7470 find_good_pkt_pointers(this_branch
, src_reg
,
7471 src_reg
->type
, false);
7472 mark_pkt_end(other_branch
, insn
->src_reg
, true);
7478 if ((dst_reg
->type
== PTR_TO_PACKET
&&
7479 src_reg
->type
== PTR_TO_PACKET_END
) ||
7480 (dst_reg
->type
== PTR_TO_PACKET_META
&&
7481 reg_is_init_pkt_pointer(src_reg
, PTR_TO_PACKET
))) {
7482 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
7483 find_good_pkt_pointers(this_branch
, dst_reg
,
7484 dst_reg
->type
, true);
7485 mark_pkt_end(other_branch
, insn
->dst_reg
, false);
7486 } else if ((dst_reg
->type
== PTR_TO_PACKET_END
&&
7487 src_reg
->type
== PTR_TO_PACKET
) ||
7488 (reg_is_init_pkt_pointer(dst_reg
, PTR_TO_PACKET
) &&
7489 src_reg
->type
== PTR_TO_PACKET_META
)) {
7490 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
7491 find_good_pkt_pointers(other_branch
, src_reg
,
7492 src_reg
->type
, false);
7493 mark_pkt_end(this_branch
, insn
->src_reg
, true);
7499 if ((dst_reg
->type
== PTR_TO_PACKET
&&
7500 src_reg
->type
== PTR_TO_PACKET_END
) ||
7501 (dst_reg
->type
== PTR_TO_PACKET_META
&&
7502 reg_is_init_pkt_pointer(src_reg
, PTR_TO_PACKET
))) {
7503 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
7504 find_good_pkt_pointers(other_branch
, dst_reg
,
7505 dst_reg
->type
, false);
7506 mark_pkt_end(this_branch
, insn
->dst_reg
, true);
7507 } else if ((dst_reg
->type
== PTR_TO_PACKET_END
&&
7508 src_reg
->type
== PTR_TO_PACKET
) ||
7509 (reg_is_init_pkt_pointer(dst_reg
, PTR_TO_PACKET
) &&
7510 src_reg
->type
== PTR_TO_PACKET_META
)) {
7511 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
7512 find_good_pkt_pointers(this_branch
, src_reg
,
7513 src_reg
->type
, true);
7514 mark_pkt_end(other_branch
, insn
->src_reg
, false);
7526 static void find_equal_scalars(struct bpf_verifier_state
*vstate
,
7527 struct bpf_reg_state
*known_reg
)
7529 struct bpf_func_state
*state
;
7530 struct bpf_reg_state
*reg
;
7533 for (i
= 0; i
<= vstate
->curframe
; i
++) {
7534 state
= vstate
->frame
[i
];
7535 for (j
= 0; j
< MAX_BPF_REG
; j
++) {
7536 reg
= &state
->regs
[j
];
7537 if (reg
->type
== SCALAR_VALUE
&& reg
->id
== known_reg
->id
)
7541 bpf_for_each_spilled_reg(j
, state
, reg
) {
7544 if (reg
->type
== SCALAR_VALUE
&& reg
->id
== known_reg
->id
)
7550 static int check_cond_jmp_op(struct bpf_verifier_env
*env
,
7551 struct bpf_insn
*insn
, int *insn_idx
)
7553 struct bpf_verifier_state
*this_branch
= env
->cur_state
;
7554 struct bpf_verifier_state
*other_branch
;
7555 struct bpf_reg_state
*regs
= this_branch
->frame
[this_branch
->curframe
]->regs
;
7556 struct bpf_reg_state
*dst_reg
, *other_branch_regs
, *src_reg
= NULL
;
7557 u8 opcode
= BPF_OP(insn
->code
);
7562 /* Only conditional jumps are expected to reach here. */
7563 if (opcode
== BPF_JA
|| opcode
> BPF_JSLE
) {
7564 verbose(env
, "invalid BPF_JMP/JMP32 opcode %x\n", opcode
);
7568 if (BPF_SRC(insn
->code
) == BPF_X
) {
7569 if (insn
->imm
!= 0) {
7570 verbose(env
, "BPF_JMP/JMP32 uses reserved fields\n");
7574 /* check src1 operand */
7575 err
= check_reg_arg(env
, insn
->src_reg
, SRC_OP
);
7579 if (is_pointer_value(env
, insn
->src_reg
)) {
7580 verbose(env
, "R%d pointer comparison prohibited\n",
7584 src_reg
= ®s
[insn
->src_reg
];
7586 if (insn
->src_reg
!= BPF_REG_0
) {
7587 verbose(env
, "BPF_JMP/JMP32 uses reserved fields\n");
7592 /* check src2 operand */
7593 err
= check_reg_arg(env
, insn
->dst_reg
, SRC_OP
);
7597 dst_reg
= ®s
[insn
->dst_reg
];
7598 is_jmp32
= BPF_CLASS(insn
->code
) == BPF_JMP32
;
7600 if (BPF_SRC(insn
->code
) == BPF_K
) {
7601 pred
= is_branch_taken(dst_reg
, insn
->imm
, opcode
, is_jmp32
);
7602 } else if (src_reg
->type
== SCALAR_VALUE
&&
7603 is_jmp32
&& tnum_is_const(tnum_subreg(src_reg
->var_off
))) {
7604 pred
= is_branch_taken(dst_reg
,
7605 tnum_subreg(src_reg
->var_off
).value
,
7608 } else if (src_reg
->type
== SCALAR_VALUE
&&
7609 !is_jmp32
&& tnum_is_const(src_reg
->var_off
)) {
7610 pred
= is_branch_taken(dst_reg
,
7611 src_reg
->var_off
.value
,
7614 } else if (reg_is_pkt_pointer_any(dst_reg
) &&
7615 reg_is_pkt_pointer_any(src_reg
) &&
7617 pred
= is_pkt_ptr_branch_taken(dst_reg
, src_reg
, opcode
);
7621 /* If we get here with a dst_reg pointer type it is because
7622 * above is_branch_taken() special cased the 0 comparison.
7624 if (!__is_pointer_value(false, dst_reg
))
7625 err
= mark_chain_precision(env
, insn
->dst_reg
);
7626 if (BPF_SRC(insn
->code
) == BPF_X
&& !err
&&
7627 !__is_pointer_value(false, src_reg
))
7628 err
= mark_chain_precision(env
, insn
->src_reg
);
7633 /* only follow the goto, ignore fall-through */
7634 *insn_idx
+= insn
->off
;
7636 } else if (pred
== 0) {
7637 /* only follow fall-through branch, since
7638 * that's where the program will go
7643 other_branch
= push_stack(env
, *insn_idx
+ insn
->off
+ 1, *insn_idx
,
7647 other_branch_regs
= other_branch
->frame
[other_branch
->curframe
]->regs
;
7649 /* detect if we are comparing against a constant value so we can adjust
7650 * our min/max values for our dst register.
7651 * this is only legit if both are scalars (or pointers to the same
7652 * object, I suppose, but we don't support that right now), because
7653 * otherwise the different base pointers mean the offsets aren't
7656 if (BPF_SRC(insn
->code
) == BPF_X
) {
7657 struct bpf_reg_state
*src_reg
= ®s
[insn
->src_reg
];
7659 if (dst_reg
->type
== SCALAR_VALUE
&&
7660 src_reg
->type
== SCALAR_VALUE
) {
7661 if (tnum_is_const(src_reg
->var_off
) ||
7663 tnum_is_const(tnum_subreg(src_reg
->var_off
))))
7664 reg_set_min_max(&other_branch_regs
[insn
->dst_reg
],
7666 src_reg
->var_off
.value
,
7667 tnum_subreg(src_reg
->var_off
).value
,
7669 else if (tnum_is_const(dst_reg
->var_off
) ||
7671 tnum_is_const(tnum_subreg(dst_reg
->var_off
))))
7672 reg_set_min_max_inv(&other_branch_regs
[insn
->src_reg
],
7674 dst_reg
->var_off
.value
,
7675 tnum_subreg(dst_reg
->var_off
).value
,
7677 else if (!is_jmp32
&&
7678 (opcode
== BPF_JEQ
|| opcode
== BPF_JNE
))
7679 /* Comparing for equality, we can combine knowledge */
7680 reg_combine_min_max(&other_branch_regs
[insn
->src_reg
],
7681 &other_branch_regs
[insn
->dst_reg
],
7682 src_reg
, dst_reg
, opcode
);
7684 !WARN_ON_ONCE(src_reg
->id
!= other_branch_regs
[insn
->src_reg
].id
)) {
7685 find_equal_scalars(this_branch
, src_reg
);
7686 find_equal_scalars(other_branch
, &other_branch_regs
[insn
->src_reg
]);
7690 } else if (dst_reg
->type
== SCALAR_VALUE
) {
7691 reg_set_min_max(&other_branch_regs
[insn
->dst_reg
],
7692 dst_reg
, insn
->imm
, (u32
)insn
->imm
,
7696 if (dst_reg
->type
== SCALAR_VALUE
&& dst_reg
->id
&&
7697 !WARN_ON_ONCE(dst_reg
->id
!= other_branch_regs
[insn
->dst_reg
].id
)) {
7698 find_equal_scalars(this_branch
, dst_reg
);
7699 find_equal_scalars(other_branch
, &other_branch_regs
[insn
->dst_reg
]);
7702 /* detect if R == 0 where R is returned from bpf_map_lookup_elem().
7703 * NOTE: these optimizations below are related with pointer comparison
7704 * which will never be JMP32.
7706 if (!is_jmp32
&& BPF_SRC(insn
->code
) == BPF_K
&&
7707 insn
->imm
== 0 && (opcode
== BPF_JEQ
|| opcode
== BPF_JNE
) &&
7708 reg_type_may_be_null(dst_reg
->type
)) {
7709 /* Mark all identical registers in each branch as either
7710 * safe or unknown depending R == 0 or R != 0 conditional.
7712 mark_ptr_or_null_regs(this_branch
, insn
->dst_reg
,
7714 mark_ptr_or_null_regs(other_branch
, insn
->dst_reg
,
7716 } else if (!try_match_pkt_pointers(insn
, dst_reg
, ®s
[insn
->src_reg
],
7717 this_branch
, other_branch
) &&
7718 is_pointer_value(env
, insn
->dst_reg
)) {
7719 verbose(env
, "R%d pointer comparison prohibited\n",
7723 if (env
->log
.level
& BPF_LOG_LEVEL
)
7724 print_verifier_state(env
, this_branch
->frame
[this_branch
->curframe
]);
7728 /* verify BPF_LD_IMM64 instruction */
7729 static int check_ld_imm(struct bpf_verifier_env
*env
, struct bpf_insn
*insn
)
7731 struct bpf_insn_aux_data
*aux
= cur_aux(env
);
7732 struct bpf_reg_state
*regs
= cur_regs(env
);
7733 struct bpf_reg_state
*dst_reg
;
7734 struct bpf_map
*map
;
7737 if (BPF_SIZE(insn
->code
) != BPF_DW
) {
7738 verbose(env
, "invalid BPF_LD_IMM insn\n");
7741 if (insn
->off
!= 0) {
7742 verbose(env
, "BPF_LD_IMM64 uses reserved fields\n");
7746 err
= check_reg_arg(env
, insn
->dst_reg
, DST_OP
);
7750 dst_reg
= ®s
[insn
->dst_reg
];
7751 if (insn
->src_reg
== 0) {
7752 u64 imm
= ((u64
)(insn
+ 1)->imm
<< 32) | (u32
)insn
->imm
;
7754 dst_reg
->type
= SCALAR_VALUE
;
7755 __mark_reg_known(®s
[insn
->dst_reg
], imm
);
7759 if (insn
->src_reg
== BPF_PSEUDO_BTF_ID
) {
7760 mark_reg_known_zero(env
, regs
, insn
->dst_reg
);
7762 dst_reg
->type
= aux
->btf_var
.reg_type
;
7763 switch (dst_reg
->type
) {
7765 dst_reg
->mem_size
= aux
->btf_var
.mem_size
;
7768 case PTR_TO_PERCPU_BTF_ID
:
7769 dst_reg
->btf
= aux
->btf_var
.btf
;
7770 dst_reg
->btf_id
= aux
->btf_var
.btf_id
;
7773 verbose(env
, "bpf verifier is misconfigured\n");
7779 map
= env
->used_maps
[aux
->map_index
];
7780 mark_reg_known_zero(env
, regs
, insn
->dst_reg
);
7781 dst_reg
->map_ptr
= map
;
7783 if (insn
->src_reg
== BPF_PSEUDO_MAP_VALUE
) {
7784 dst_reg
->type
= PTR_TO_MAP_VALUE
;
7785 dst_reg
->off
= aux
->map_off
;
7786 if (map_value_has_spin_lock(map
))
7787 dst_reg
->id
= ++env
->id_gen
;
7788 } else if (insn
->src_reg
== BPF_PSEUDO_MAP_FD
) {
7789 dst_reg
->type
= CONST_PTR_TO_MAP
;
7791 verbose(env
, "bpf verifier is misconfigured\n");
7798 static bool may_access_skb(enum bpf_prog_type type
)
7801 case BPF_PROG_TYPE_SOCKET_FILTER
:
7802 case BPF_PROG_TYPE_SCHED_CLS
:
7803 case BPF_PROG_TYPE_SCHED_ACT
:
7810 /* verify safety of LD_ABS|LD_IND instructions:
7811 * - they can only appear in the programs where ctx == skb
7812 * - since they are wrappers of function calls, they scratch R1-R5 registers,
7813 * preserve R6-R9, and store return value into R0
7816 * ctx == skb == R6 == CTX
7819 * SRC == any register
7820 * IMM == 32-bit immediate
7823 * R0 - 8/16/32-bit skb data converted to cpu endianness
7825 static int check_ld_abs(struct bpf_verifier_env
*env
, struct bpf_insn
*insn
)
7827 struct bpf_reg_state
*regs
= cur_regs(env
);
7828 static const int ctx_reg
= BPF_REG_6
;
7829 u8 mode
= BPF_MODE(insn
->code
);
7832 if (!may_access_skb(resolve_prog_type(env
->prog
))) {
7833 verbose(env
, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
7837 if (!env
->ops
->gen_ld_abs
) {
7838 verbose(env
, "bpf verifier is misconfigured\n");
7842 if (insn
->dst_reg
!= BPF_REG_0
|| insn
->off
!= 0 ||
7843 BPF_SIZE(insn
->code
) == BPF_DW
||
7844 (mode
== BPF_ABS
&& insn
->src_reg
!= BPF_REG_0
)) {
7845 verbose(env
, "BPF_LD_[ABS|IND] uses reserved fields\n");
7849 /* check whether implicit source operand (register R6) is readable */
7850 err
= check_reg_arg(env
, ctx_reg
, SRC_OP
);
7854 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
7855 * gen_ld_abs() may terminate the program at runtime, leading to
7858 err
= check_reference_leak(env
);
7860 verbose(env
, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
7864 if (env
->cur_state
->active_spin_lock
) {
7865 verbose(env
, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
7869 if (regs
[ctx_reg
].type
!= PTR_TO_CTX
) {
7871 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
7875 if (mode
== BPF_IND
) {
7876 /* check explicit source operand */
7877 err
= check_reg_arg(env
, insn
->src_reg
, SRC_OP
);
7882 err
= check_ctx_reg(env
, ®s
[ctx_reg
], ctx_reg
);
7886 /* reset caller saved regs to unreadable */
7887 for (i
= 0; i
< CALLER_SAVED_REGS
; i
++) {
7888 mark_reg_not_init(env
, regs
, caller_saved
[i
]);
7889 check_reg_arg(env
, caller_saved
[i
], DST_OP_NO_MARK
);
7892 /* mark destination R0 register as readable, since it contains
7893 * the value fetched from the packet.
7894 * Already marked as written above.
7896 mark_reg_unknown(env
, regs
, BPF_REG_0
);
7897 /* ld_abs load up to 32-bit skb data. */
7898 regs
[BPF_REG_0
].subreg_def
= env
->insn_idx
+ 1;
7902 static int check_return_code(struct bpf_verifier_env
*env
)
7904 struct tnum enforce_attach_type_range
= tnum_unknown
;
7905 const struct bpf_prog
*prog
= env
->prog
;
7906 struct bpf_reg_state
*reg
;
7907 struct tnum range
= tnum_range(0, 1);
7908 enum bpf_prog_type prog_type
= resolve_prog_type(env
->prog
);
7910 const bool is_subprog
= env
->cur_state
->frame
[0]->subprogno
;
7912 /* LSM and struct_ops func-ptr's return type could be "void" */
7914 (prog_type
== BPF_PROG_TYPE_STRUCT_OPS
||
7915 prog_type
== BPF_PROG_TYPE_LSM
) &&
7916 !prog
->aux
->attach_func_proto
->type
)
7919 /* eBPF calling convetion is such that R0 is used
7920 * to return the value from eBPF program.
7921 * Make sure that it's readable at this time
7922 * of bpf_exit, which means that program wrote
7923 * something into it earlier
7925 err
= check_reg_arg(env
, BPF_REG_0
, SRC_OP
);
7929 if (is_pointer_value(env
, BPF_REG_0
)) {
7930 verbose(env
, "R0 leaks addr as return value\n");
7934 reg
= cur_regs(env
) + BPF_REG_0
;
7936 if (reg
->type
!= SCALAR_VALUE
) {
7937 verbose(env
, "At subprogram exit the register R0 is not a scalar value (%s)\n",
7938 reg_type_str
[reg
->type
]);
7944 switch (prog_type
) {
7945 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR
:
7946 if (env
->prog
->expected_attach_type
== BPF_CGROUP_UDP4_RECVMSG
||
7947 env
->prog
->expected_attach_type
== BPF_CGROUP_UDP6_RECVMSG
||
7948 env
->prog
->expected_attach_type
== BPF_CGROUP_INET4_GETPEERNAME
||
7949 env
->prog
->expected_attach_type
== BPF_CGROUP_INET6_GETPEERNAME
||
7950 env
->prog
->expected_attach_type
== BPF_CGROUP_INET4_GETSOCKNAME
||
7951 env
->prog
->expected_attach_type
== BPF_CGROUP_INET6_GETSOCKNAME
)
7952 range
= tnum_range(1, 1);
7954 case BPF_PROG_TYPE_CGROUP_SKB
:
7955 if (env
->prog
->expected_attach_type
== BPF_CGROUP_INET_EGRESS
) {
7956 range
= tnum_range(0, 3);
7957 enforce_attach_type_range
= tnum_range(2, 3);
7960 case BPF_PROG_TYPE_CGROUP_SOCK
:
7961 case BPF_PROG_TYPE_SOCK_OPS
:
7962 case BPF_PROG_TYPE_CGROUP_DEVICE
:
7963 case BPF_PROG_TYPE_CGROUP_SYSCTL
:
7964 case BPF_PROG_TYPE_CGROUP_SOCKOPT
:
7966 case BPF_PROG_TYPE_RAW_TRACEPOINT
:
7967 if (!env
->prog
->aux
->attach_btf_id
)
7969 range
= tnum_const(0);
7971 case BPF_PROG_TYPE_TRACING
:
7972 switch (env
->prog
->expected_attach_type
) {
7973 case BPF_TRACE_FENTRY
:
7974 case BPF_TRACE_FEXIT
:
7975 range
= tnum_const(0);
7977 case BPF_TRACE_RAW_TP
:
7978 case BPF_MODIFY_RETURN
:
7980 case BPF_TRACE_ITER
:
7986 case BPF_PROG_TYPE_SK_LOOKUP
:
7987 range
= tnum_range(SK_DROP
, SK_PASS
);
7989 case BPF_PROG_TYPE_EXT
:
7990 /* freplace program can return anything as its return value
7991 * depends on the to-be-replaced kernel func or bpf program.
7997 if (reg
->type
!= SCALAR_VALUE
) {
7998 verbose(env
, "At program exit the register R0 is not a known value (%s)\n",
7999 reg_type_str
[reg
->type
]);
8003 if (!tnum_in(range
, reg
->var_off
)) {
8006 verbose(env
, "At program exit the register R0 ");
8007 if (!tnum_is_unknown(reg
->var_off
)) {
8008 tnum_strn(tn_buf
, sizeof(tn_buf
), reg
->var_off
);
8009 verbose(env
, "has value %s", tn_buf
);
8011 verbose(env
, "has unknown scalar value");
8013 tnum_strn(tn_buf
, sizeof(tn_buf
), range
);
8014 verbose(env
, " should have been in %s\n", tn_buf
);
8018 if (!tnum_is_unknown(enforce_attach_type_range
) &&
8019 tnum_in(enforce_attach_type_range
, reg
->var_off
))
8020 env
->prog
->enforce_expected_attach_type
= 1;
8024 /* non-recursive DFS pseudo code
8025 * 1 procedure DFS-iterative(G,v):
8026 * 2 label v as discovered
8027 * 3 let S be a stack
8029 * 5 while S is not empty
8031 * 7 if t is what we're looking for:
8033 * 9 for all edges e in G.adjacentEdges(t) do
8034 * 10 if edge e is already labelled
8035 * 11 continue with the next edge
8036 * 12 w <- G.adjacentVertex(t,e)
8037 * 13 if vertex w is not discovered and not explored
8038 * 14 label e as tree-edge
8039 * 15 label w as discovered
8042 * 18 else if vertex w is discovered
8043 * 19 label e as back-edge
8045 * 21 // vertex w is explored
8046 * 22 label e as forward- or cross-edge
8047 * 23 label t as explored
8052 * 0x11 - discovered and fall-through edge labelled
8053 * 0x12 - discovered and fall-through and branch edges labelled
8064 static u32
state_htab_size(struct bpf_verifier_env
*env
)
8066 return env
->prog
->len
;
8069 static struct bpf_verifier_state_list
**explored_state(
8070 struct bpf_verifier_env
*env
,
8073 struct bpf_verifier_state
*cur
= env
->cur_state
;
8074 struct bpf_func_state
*state
= cur
->frame
[cur
->curframe
];
8076 return &env
->explored_states
[(idx
^ state
->callsite
) % state_htab_size(env
)];
8079 static void init_explored_state(struct bpf_verifier_env
*env
, int idx
)
8081 env
->insn_aux_data
[idx
].prune_point
= true;
8089 /* t, w, e - match pseudo-code above:
8090 * t - index of current instruction
8091 * w - next instruction
8094 static int push_insn(int t
, int w
, int e
, struct bpf_verifier_env
*env
,
8097 int *insn_stack
= env
->cfg
.insn_stack
;
8098 int *insn_state
= env
->cfg
.insn_state
;
8100 if (e
== FALLTHROUGH
&& insn_state
[t
] >= (DISCOVERED
| FALLTHROUGH
))
8101 return DONE_EXPLORING
;
8103 if (e
== BRANCH
&& insn_state
[t
] >= (DISCOVERED
| BRANCH
))
8104 return DONE_EXPLORING
;
8106 if (w
< 0 || w
>= env
->prog
->len
) {
8107 verbose_linfo(env
, t
, "%d: ", t
);
8108 verbose(env
, "jump out of range from insn %d to %d\n", t
, w
);
8113 /* mark branch target for state pruning */
8114 init_explored_state(env
, w
);
8116 if (insn_state
[w
] == 0) {
8118 insn_state
[t
] = DISCOVERED
| e
;
8119 insn_state
[w
] = DISCOVERED
;
8120 if (env
->cfg
.cur_stack
>= env
->prog
->len
)
8122 insn_stack
[env
->cfg
.cur_stack
++] = w
;
8123 return KEEP_EXPLORING
;
8124 } else if ((insn_state
[w
] & 0xF0) == DISCOVERED
) {
8125 if (loop_ok
&& env
->bpf_capable
)
8126 return DONE_EXPLORING
;
8127 verbose_linfo(env
, t
, "%d: ", t
);
8128 verbose_linfo(env
, w
, "%d: ", w
);
8129 verbose(env
, "back-edge from insn %d to %d\n", t
, w
);
8131 } else if (insn_state
[w
] == EXPLORED
) {
8132 /* forward- or cross-edge */
8133 insn_state
[t
] = DISCOVERED
| e
;
8135 verbose(env
, "insn state internal bug\n");
8138 return DONE_EXPLORING
;
8141 /* Visits the instruction at index t and returns one of the following:
8142 * < 0 - an error occurred
8143 * DONE_EXPLORING - the instruction was fully explored
8144 * KEEP_EXPLORING - there is still work to be done before it is fully explored
8146 static int visit_insn(int t
, int insn_cnt
, struct bpf_verifier_env
*env
)
8148 struct bpf_insn
*insns
= env
->prog
->insnsi
;
8151 /* All non-branch instructions have a single fall-through edge. */
8152 if (BPF_CLASS(insns
[t
].code
) != BPF_JMP
&&
8153 BPF_CLASS(insns
[t
].code
) != BPF_JMP32
)
8154 return push_insn(t
, t
+ 1, FALLTHROUGH
, env
, false);
8156 switch (BPF_OP(insns
[t
].code
)) {
8158 return DONE_EXPLORING
;
8161 ret
= push_insn(t
, t
+ 1, FALLTHROUGH
, env
, false);
8165 if (t
+ 1 < insn_cnt
)
8166 init_explored_state(env
, t
+ 1);
8167 if (insns
[t
].src_reg
== BPF_PSEUDO_CALL
) {
8168 init_explored_state(env
, t
);
8169 ret
= push_insn(t
, t
+ insns
[t
].imm
+ 1, BRANCH
,
8175 if (BPF_SRC(insns
[t
].code
) != BPF_K
)
8178 /* unconditional jump with single edge */
8179 ret
= push_insn(t
, t
+ insns
[t
].off
+ 1, FALLTHROUGH
, env
,
8184 /* unconditional jmp is not a good pruning point,
8185 * but it's marked, since backtracking needs
8186 * to record jmp history in is_state_visited().
8188 init_explored_state(env
, t
+ insns
[t
].off
+ 1);
8189 /* tell verifier to check for equivalent states
8190 * after every call and jump
8192 if (t
+ 1 < insn_cnt
)
8193 init_explored_state(env
, t
+ 1);
8198 /* conditional jump with two edges */
8199 init_explored_state(env
, t
);
8200 ret
= push_insn(t
, t
+ 1, FALLTHROUGH
, env
, true);
8204 return push_insn(t
, t
+ insns
[t
].off
+ 1, BRANCH
, env
, true);
8208 /* non-recursive depth-first-search to detect loops in BPF program
8209 * loop == back-edge in directed graph
8211 static int check_cfg(struct bpf_verifier_env
*env
)
8213 int insn_cnt
= env
->prog
->len
;
8214 int *insn_stack
, *insn_state
;
8218 insn_state
= env
->cfg
.insn_state
= kvcalloc(insn_cnt
, sizeof(int), GFP_KERNEL
);
8222 insn_stack
= env
->cfg
.insn_stack
= kvcalloc(insn_cnt
, sizeof(int), GFP_KERNEL
);
8228 insn_state
[0] = DISCOVERED
; /* mark 1st insn as discovered */
8229 insn_stack
[0] = 0; /* 0 is the first instruction */
8230 env
->cfg
.cur_stack
= 1;
8232 while (env
->cfg
.cur_stack
> 0) {
8233 int t
= insn_stack
[env
->cfg
.cur_stack
- 1];
8235 ret
= visit_insn(t
, insn_cnt
, env
);
8237 case DONE_EXPLORING
:
8238 insn_state
[t
] = EXPLORED
;
8239 env
->cfg
.cur_stack
--;
8241 case KEEP_EXPLORING
:
8245 verbose(env
, "visit_insn internal bug\n");
8252 if (env
->cfg
.cur_stack
< 0) {
8253 verbose(env
, "pop stack internal bug\n");
8258 for (i
= 0; i
< insn_cnt
; i
++) {
8259 if (insn_state
[i
] != EXPLORED
) {
8260 verbose(env
, "unreachable insn %d\n", i
);
8265 ret
= 0; /* cfg looks good */
8270 env
->cfg
.insn_state
= env
->cfg
.insn_stack
= NULL
;
8274 static int check_abnormal_return(struct bpf_verifier_env
*env
)
8278 for (i
= 1; i
< env
->subprog_cnt
; i
++) {
8279 if (env
->subprog_info
[i
].has_ld_abs
) {
8280 verbose(env
, "LD_ABS is not allowed in subprogs without BTF\n");
8283 if (env
->subprog_info
[i
].has_tail_call
) {
8284 verbose(env
, "tail_call is not allowed in subprogs without BTF\n");
8291 /* The minimum supported BTF func info size */
8292 #define MIN_BPF_FUNCINFO_SIZE 8
8293 #define MAX_FUNCINFO_REC_SIZE 252
8295 static int check_btf_func(struct bpf_verifier_env
*env
,
8296 const union bpf_attr
*attr
,
8297 union bpf_attr __user
*uattr
)
8299 const struct btf_type
*type
, *func_proto
, *ret_type
;
8300 u32 i
, nfuncs
, urec_size
, min_size
;
8301 u32 krec_size
= sizeof(struct bpf_func_info
);
8302 struct bpf_func_info
*krecord
;
8303 struct bpf_func_info_aux
*info_aux
= NULL
;
8304 struct bpf_prog
*prog
;
8305 const struct btf
*btf
;
8306 void __user
*urecord
;
8307 u32 prev_offset
= 0;
8311 nfuncs
= attr
->func_info_cnt
;
8313 if (check_abnormal_return(env
))
8318 if (nfuncs
!= env
->subprog_cnt
) {
8319 verbose(env
, "number of funcs in func_info doesn't match number of subprogs\n");
8323 urec_size
= attr
->func_info_rec_size
;
8324 if (urec_size
< MIN_BPF_FUNCINFO_SIZE
||
8325 urec_size
> MAX_FUNCINFO_REC_SIZE
||
8326 urec_size
% sizeof(u32
)) {
8327 verbose(env
, "invalid func info rec size %u\n", urec_size
);
8332 btf
= prog
->aux
->btf
;
8334 urecord
= u64_to_user_ptr(attr
->func_info
);
8335 min_size
= min_t(u32
, krec_size
, urec_size
);
8337 krecord
= kvcalloc(nfuncs
, krec_size
, GFP_KERNEL
| __GFP_NOWARN
);
8340 info_aux
= kcalloc(nfuncs
, sizeof(*info_aux
), GFP_KERNEL
| __GFP_NOWARN
);
8344 for (i
= 0; i
< nfuncs
; i
++) {
8345 ret
= bpf_check_uarg_tail_zero(urecord
, krec_size
, urec_size
);
8347 if (ret
== -E2BIG
) {
8348 verbose(env
, "nonzero tailing record in func info");
8349 /* set the size kernel expects so loader can zero
8350 * out the rest of the record.
8352 if (put_user(min_size
, &uattr
->func_info_rec_size
))
8358 if (copy_from_user(&krecord
[i
], urecord
, min_size
)) {
8363 /* check insn_off */
8366 if (krecord
[i
].insn_off
) {
8368 "nonzero insn_off %u for the first func info record",
8369 krecord
[i
].insn_off
);
8372 } else if (krecord
[i
].insn_off
<= prev_offset
) {
8374 "same or smaller insn offset (%u) than previous func info record (%u)",
8375 krecord
[i
].insn_off
, prev_offset
);
8379 if (env
->subprog_info
[i
].start
!= krecord
[i
].insn_off
) {
8380 verbose(env
, "func_info BTF section doesn't match subprog layout in BPF program\n");
8385 type
= btf_type_by_id(btf
, krecord
[i
].type_id
);
8386 if (!type
|| !btf_type_is_func(type
)) {
8387 verbose(env
, "invalid type id %d in func info",
8388 krecord
[i
].type_id
);
8391 info_aux
[i
].linkage
= BTF_INFO_VLEN(type
->info
);
8393 func_proto
= btf_type_by_id(btf
, type
->type
);
8394 if (unlikely(!func_proto
|| !btf_type_is_func_proto(func_proto
)))
8395 /* btf_func_check() already verified it during BTF load */
8397 ret_type
= btf_type_skip_modifiers(btf
, func_proto
->type
, NULL
);
8399 btf_type_is_small_int(ret_type
) || btf_type_is_enum(ret_type
);
8400 if (i
&& !scalar_return
&& env
->subprog_info
[i
].has_ld_abs
) {
8401 verbose(env
, "LD_ABS is only allowed in functions that return 'int'.\n");
8404 if (i
&& !scalar_return
&& env
->subprog_info
[i
].has_tail_call
) {
8405 verbose(env
, "tail_call is only allowed in functions that return 'int'.\n");
8409 prev_offset
= krecord
[i
].insn_off
;
8410 urecord
+= urec_size
;
8413 prog
->aux
->func_info
= krecord
;
8414 prog
->aux
->func_info_cnt
= nfuncs
;
8415 prog
->aux
->func_info_aux
= info_aux
;
8424 static void adjust_btf_func(struct bpf_verifier_env
*env
)
8426 struct bpf_prog_aux
*aux
= env
->prog
->aux
;
8429 if (!aux
->func_info
)
8432 for (i
= 0; i
< env
->subprog_cnt
; i
++)
8433 aux
->func_info
[i
].insn_off
= env
->subprog_info
[i
].start
;
8436 #define MIN_BPF_LINEINFO_SIZE (offsetof(struct bpf_line_info, line_col) + \
8437 sizeof(((struct bpf_line_info *)(0))->line_col))
8438 #define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE
8440 static int check_btf_line(struct bpf_verifier_env
*env
,
8441 const union bpf_attr
*attr
,
8442 union bpf_attr __user
*uattr
)
8444 u32 i
, s
, nr_linfo
, ncopy
, expected_size
, rec_size
, prev_offset
= 0;
8445 struct bpf_subprog_info
*sub
;
8446 struct bpf_line_info
*linfo
;
8447 struct bpf_prog
*prog
;
8448 const struct btf
*btf
;
8449 void __user
*ulinfo
;
8452 nr_linfo
= attr
->line_info_cnt
;
8456 rec_size
= attr
->line_info_rec_size
;
8457 if (rec_size
< MIN_BPF_LINEINFO_SIZE
||
8458 rec_size
> MAX_LINEINFO_REC_SIZE
||
8459 rec_size
& (sizeof(u32
) - 1))
8462 /* Need to zero it in case the userspace may
8463 * pass in a smaller bpf_line_info object.
8465 linfo
= kvcalloc(nr_linfo
, sizeof(struct bpf_line_info
),
8466 GFP_KERNEL
| __GFP_NOWARN
);
8471 btf
= prog
->aux
->btf
;
8474 sub
= env
->subprog_info
;
8475 ulinfo
= u64_to_user_ptr(attr
->line_info
);
8476 expected_size
= sizeof(struct bpf_line_info
);
8477 ncopy
= min_t(u32
, expected_size
, rec_size
);
8478 for (i
= 0; i
< nr_linfo
; i
++) {
8479 err
= bpf_check_uarg_tail_zero(ulinfo
, expected_size
, rec_size
);
8481 if (err
== -E2BIG
) {
8482 verbose(env
, "nonzero tailing record in line_info");
8483 if (put_user(expected_size
,
8484 &uattr
->line_info_rec_size
))
8490 if (copy_from_user(&linfo
[i
], ulinfo
, ncopy
)) {
8496 * Check insn_off to ensure
8497 * 1) strictly increasing AND
8498 * 2) bounded by prog->len
8500 * The linfo[0].insn_off == 0 check logically falls into
8501 * the later "missing bpf_line_info for func..." case
8502 * because the first linfo[0].insn_off must be the
8503 * first sub also and the first sub must have
8504 * subprog_info[0].start == 0.
8506 if ((i
&& linfo
[i
].insn_off
<= prev_offset
) ||
8507 linfo
[i
].insn_off
>= prog
->len
) {
8508 verbose(env
, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
8509 i
, linfo
[i
].insn_off
, prev_offset
,
8515 if (!prog
->insnsi
[linfo
[i
].insn_off
].code
) {
8517 "Invalid insn code at line_info[%u].insn_off\n",
8523 if (!btf_name_by_offset(btf
, linfo
[i
].line_off
) ||
8524 !btf_name_by_offset(btf
, linfo
[i
].file_name_off
)) {
8525 verbose(env
, "Invalid line_info[%u].line_off or .file_name_off\n", i
);
8530 if (s
!= env
->subprog_cnt
) {
8531 if (linfo
[i
].insn_off
== sub
[s
].start
) {
8532 sub
[s
].linfo_idx
= i
;
8534 } else if (sub
[s
].start
< linfo
[i
].insn_off
) {
8535 verbose(env
, "missing bpf_line_info for func#%u\n", s
);
8541 prev_offset
= linfo
[i
].insn_off
;
8545 if (s
!= env
->subprog_cnt
) {
8546 verbose(env
, "missing bpf_line_info for %u funcs starting from func#%u\n",
8547 env
->subprog_cnt
- s
, s
);
8552 prog
->aux
->linfo
= linfo
;
8553 prog
->aux
->nr_linfo
= nr_linfo
;
8562 static int check_btf_info(struct bpf_verifier_env
*env
,
8563 const union bpf_attr
*attr
,
8564 union bpf_attr __user
*uattr
)
8569 if (!attr
->func_info_cnt
&& !attr
->line_info_cnt
) {
8570 if (check_abnormal_return(env
))
8575 btf
= btf_get_by_fd(attr
->prog_btf_fd
);
8577 return PTR_ERR(btf
);
8578 env
->prog
->aux
->btf
= btf
;
8580 err
= check_btf_func(env
, attr
, uattr
);
8584 err
= check_btf_line(env
, attr
, uattr
);
8591 /* check %cur's range satisfies %old's */
8592 static bool range_within(struct bpf_reg_state
*old
,
8593 struct bpf_reg_state
*cur
)
8595 return old
->umin_value
<= cur
->umin_value
&&
8596 old
->umax_value
>= cur
->umax_value
&&
8597 old
->smin_value
<= cur
->smin_value
&&
8598 old
->smax_value
>= cur
->smax_value
&&
8599 old
->u32_min_value
<= cur
->u32_min_value
&&
8600 old
->u32_max_value
>= cur
->u32_max_value
&&
8601 old
->s32_min_value
<= cur
->s32_min_value
&&
8602 old
->s32_max_value
>= cur
->s32_max_value
;
8605 /* Maximum number of register states that can exist at once */
8606 #define ID_MAP_SIZE (MAX_BPF_REG + MAX_BPF_STACK / BPF_REG_SIZE)
8612 /* If in the old state two registers had the same id, then they need to have
8613 * the same id in the new state as well. But that id could be different from
8614 * the old state, so we need to track the mapping from old to new ids.
8615 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
8616 * regs with old id 5 must also have new id 9 for the new state to be safe. But
8617 * regs with a different old id could still have new id 9, we don't care about
8619 * So we look through our idmap to see if this old id has been seen before. If
8620 * so, we require the new id to match; otherwise, we add the id pair to the map.
8622 static bool check_ids(u32 old_id
, u32 cur_id
, struct idpair
*idmap
)
8626 for (i
= 0; i
< ID_MAP_SIZE
; i
++) {
8627 if (!idmap
[i
].old
) {
8628 /* Reached an empty slot; haven't seen this id before */
8629 idmap
[i
].old
= old_id
;
8630 idmap
[i
].cur
= cur_id
;
8633 if (idmap
[i
].old
== old_id
)
8634 return idmap
[i
].cur
== cur_id
;
8636 /* We ran out of idmap slots, which should be impossible */
8641 static void clean_func_state(struct bpf_verifier_env
*env
,
8642 struct bpf_func_state
*st
)
8644 enum bpf_reg_liveness live
;
8647 for (i
= 0; i
< BPF_REG_FP
; i
++) {
8648 live
= st
->regs
[i
].live
;
8649 /* liveness must not touch this register anymore */
8650 st
->regs
[i
].live
|= REG_LIVE_DONE
;
8651 if (!(live
& REG_LIVE_READ
))
8652 /* since the register is unused, clear its state
8653 * to make further comparison simpler
8655 __mark_reg_not_init(env
, &st
->regs
[i
]);
8658 for (i
= 0; i
< st
->allocated_stack
/ BPF_REG_SIZE
; i
++) {
8659 live
= st
->stack
[i
].spilled_ptr
.live
;
8660 /* liveness must not touch this stack slot anymore */
8661 st
->stack
[i
].spilled_ptr
.live
|= REG_LIVE_DONE
;
8662 if (!(live
& REG_LIVE_READ
)) {
8663 __mark_reg_not_init(env
, &st
->stack
[i
].spilled_ptr
);
8664 for (j
= 0; j
< BPF_REG_SIZE
; j
++)
8665 st
->stack
[i
].slot_type
[j
] = STACK_INVALID
;
8670 static void clean_verifier_state(struct bpf_verifier_env
*env
,
8671 struct bpf_verifier_state
*st
)
8675 if (st
->frame
[0]->regs
[0].live
& REG_LIVE_DONE
)
8676 /* all regs in this state in all frames were already marked */
8679 for (i
= 0; i
<= st
->curframe
; i
++)
8680 clean_func_state(env
, st
->frame
[i
]);
8683 /* the parentage chains form a tree.
8684 * the verifier states are added to state lists at given insn and
8685 * pushed into state stack for future exploration.
8686 * when the verifier reaches bpf_exit insn some of the verifer states
8687 * stored in the state lists have their final liveness state already,
8688 * but a lot of states will get revised from liveness point of view when
8689 * the verifier explores other branches.
8692 * 2: if r1 == 100 goto pc+1
8695 * when the verifier reaches exit insn the register r0 in the state list of
8696 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
8697 * of insn 2 and goes exploring further. At the insn 4 it will walk the
8698 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
8700 * Since the verifier pushes the branch states as it sees them while exploring
8701 * the program the condition of walking the branch instruction for the second
8702 * time means that all states below this branch were already explored and
8703 * their final liveness markes are already propagated.
8704 * Hence when the verifier completes the search of state list in is_state_visited()
8705 * we can call this clean_live_states() function to mark all liveness states
8706 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
8708 * This function also clears the registers and stack for states that !READ
8709 * to simplify state merging.
8711 * Important note here that walking the same branch instruction in the callee
8712 * doesn't meant that the states are DONE. The verifier has to compare
8715 static void clean_live_states(struct bpf_verifier_env
*env
, int insn
,
8716 struct bpf_verifier_state
*cur
)
8718 struct bpf_verifier_state_list
*sl
;
8721 sl
= *explored_state(env
, insn
);
8723 if (sl
->state
.branches
)
8725 if (sl
->state
.insn_idx
!= insn
||
8726 sl
->state
.curframe
!= cur
->curframe
)
8728 for (i
= 0; i
<= cur
->curframe
; i
++)
8729 if (sl
->state
.frame
[i
]->callsite
!= cur
->frame
[i
]->callsite
)
8731 clean_verifier_state(env
, &sl
->state
);
8737 /* Returns true if (rold safe implies rcur safe) */
8738 static bool regsafe(struct bpf_reg_state
*rold
, struct bpf_reg_state
*rcur
,
8739 struct idpair
*idmap
)
8743 if (!(rold
->live
& REG_LIVE_READ
))
8744 /* explored state didn't use this */
8747 equal
= memcmp(rold
, rcur
, offsetof(struct bpf_reg_state
, parent
)) == 0;
8749 if (rold
->type
== PTR_TO_STACK
)
8750 /* two stack pointers are equal only if they're pointing to
8751 * the same stack frame, since fp-8 in foo != fp-8 in bar
8753 return equal
&& rold
->frameno
== rcur
->frameno
;
8758 if (rold
->type
== NOT_INIT
)
8759 /* explored state can't have used this */
8761 if (rcur
->type
== NOT_INIT
)
8763 switch (rold
->type
) {
8765 if (rcur
->type
== SCALAR_VALUE
) {
8766 if (!rold
->precise
&& !rcur
->precise
)
8768 /* new val must satisfy old val knowledge */
8769 return range_within(rold
, rcur
) &&
8770 tnum_in(rold
->var_off
, rcur
->var_off
);
8772 /* We're trying to use a pointer in place of a scalar.
8773 * Even if the scalar was unbounded, this could lead to
8774 * pointer leaks because scalars are allowed to leak
8775 * while pointers are not. We could make this safe in
8776 * special cases if root is calling us, but it's
8777 * probably not worth the hassle.
8781 case PTR_TO_MAP_VALUE
:
8782 /* If the new min/max/var_off satisfy the old ones and
8783 * everything else matches, we are OK.
8784 * 'id' is not compared, since it's only used for maps with
8785 * bpf_spin_lock inside map element and in such cases if
8786 * the rest of the prog is valid for one map element then
8787 * it's valid for all map elements regardless of the key
8788 * used in bpf_map_lookup()
8790 return memcmp(rold
, rcur
, offsetof(struct bpf_reg_state
, id
)) == 0 &&
8791 range_within(rold
, rcur
) &&
8792 tnum_in(rold
->var_off
, rcur
->var_off
);
8793 case PTR_TO_MAP_VALUE_OR_NULL
:
8794 /* a PTR_TO_MAP_VALUE could be safe to use as a
8795 * PTR_TO_MAP_VALUE_OR_NULL into the same map.
8796 * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
8797 * checked, doing so could have affected others with the same
8798 * id, and we can't check for that because we lost the id when
8799 * we converted to a PTR_TO_MAP_VALUE.
8801 if (rcur
->type
!= PTR_TO_MAP_VALUE_OR_NULL
)
8803 if (memcmp(rold
, rcur
, offsetof(struct bpf_reg_state
, id
)))
8805 /* Check our ids match any regs they're supposed to */
8806 return check_ids(rold
->id
, rcur
->id
, idmap
);
8807 case PTR_TO_PACKET_META
:
8809 if (rcur
->type
!= rold
->type
)
8811 /* We must have at least as much range as the old ptr
8812 * did, so that any accesses which were safe before are
8813 * still safe. This is true even if old range < old off,
8814 * since someone could have accessed through (ptr - k), or
8815 * even done ptr -= k in a register, to get a safe access.
8817 if (rold
->range
> rcur
->range
)
8819 /* If the offsets don't match, we can't trust our alignment;
8820 * nor can we be sure that we won't fall out of range.
8822 if (rold
->off
!= rcur
->off
)
8824 /* id relations must be preserved */
8825 if (rold
->id
&& !check_ids(rold
->id
, rcur
->id
, idmap
))
8827 /* new val must satisfy old val knowledge */
8828 return range_within(rold
, rcur
) &&
8829 tnum_in(rold
->var_off
, rcur
->var_off
);
8831 case CONST_PTR_TO_MAP
:
8832 case PTR_TO_PACKET_END
:
8833 case PTR_TO_FLOW_KEYS
:
8835 case PTR_TO_SOCKET_OR_NULL
:
8836 case PTR_TO_SOCK_COMMON
:
8837 case PTR_TO_SOCK_COMMON_OR_NULL
:
8838 case PTR_TO_TCP_SOCK
:
8839 case PTR_TO_TCP_SOCK_OR_NULL
:
8840 case PTR_TO_XDP_SOCK
:
8841 /* Only valid matches are exact, which memcmp() above
8842 * would have accepted
8845 /* Don't know what's going on, just say it's not safe */
8849 /* Shouldn't get here; if we do, say it's not safe */
8854 static bool stacksafe(struct bpf_func_state
*old
,
8855 struct bpf_func_state
*cur
,
8856 struct idpair
*idmap
)
8860 /* walk slots of the explored stack and ignore any additional
8861 * slots in the current stack, since explored(safe) state
8864 for (i
= 0; i
< old
->allocated_stack
; i
++) {
8865 spi
= i
/ BPF_REG_SIZE
;
8867 if (!(old
->stack
[spi
].spilled_ptr
.live
& REG_LIVE_READ
)) {
8868 i
+= BPF_REG_SIZE
- 1;
8869 /* explored state didn't use this */
8873 if (old
->stack
[spi
].slot_type
[i
% BPF_REG_SIZE
] == STACK_INVALID
)
8876 /* explored stack has more populated slots than current stack
8877 * and these slots were used
8879 if (i
>= cur
->allocated_stack
)
8882 /* if old state was safe with misc data in the stack
8883 * it will be safe with zero-initialized stack.
8884 * The opposite is not true
8886 if (old
->stack
[spi
].slot_type
[i
% BPF_REG_SIZE
] == STACK_MISC
&&
8887 cur
->stack
[spi
].slot_type
[i
% BPF_REG_SIZE
] == STACK_ZERO
)
8889 if (old
->stack
[spi
].slot_type
[i
% BPF_REG_SIZE
] !=
8890 cur
->stack
[spi
].slot_type
[i
% BPF_REG_SIZE
])
8891 /* Ex: old explored (safe) state has STACK_SPILL in
8892 * this stack slot, but current has STACK_MISC ->
8893 * this verifier states are not equivalent,
8894 * return false to continue verification of this path
8897 if (i
% BPF_REG_SIZE
)
8899 if (old
->stack
[spi
].slot_type
[0] != STACK_SPILL
)
8901 if (!regsafe(&old
->stack
[spi
].spilled_ptr
,
8902 &cur
->stack
[spi
].spilled_ptr
,
8904 /* when explored and current stack slot are both storing
8905 * spilled registers, check that stored pointers types
8906 * are the same as well.
8907 * Ex: explored safe path could have stored
8908 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
8909 * but current path has stored:
8910 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
8911 * such verifier states are not equivalent.
8912 * return false to continue verification of this path
8919 static bool refsafe(struct bpf_func_state
*old
, struct bpf_func_state
*cur
)
8921 if (old
->acquired_refs
!= cur
->acquired_refs
)
8923 return !memcmp(old
->refs
, cur
->refs
,
8924 sizeof(*old
->refs
) * old
->acquired_refs
);
8927 /* compare two verifier states
8929 * all states stored in state_list are known to be valid, since
8930 * verifier reached 'bpf_exit' instruction through them
8932 * this function is called when verifier exploring different branches of
8933 * execution popped from the state stack. If it sees an old state that has
8934 * more strict register state and more strict stack state then this execution
8935 * branch doesn't need to be explored further, since verifier already
8936 * concluded that more strict state leads to valid finish.
8938 * Therefore two states are equivalent if register state is more conservative
8939 * and explored stack state is more conservative than the current one.
8942 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
8943 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
8945 * In other words if current stack state (one being explored) has more
8946 * valid slots than old one that already passed validation, it means
8947 * the verifier can stop exploring and conclude that current state is valid too
8949 * Similarly with registers. If explored state has register type as invalid
8950 * whereas register type in current state is meaningful, it means that
8951 * the current state will reach 'bpf_exit' instruction safely
8953 static bool func_states_equal(struct bpf_func_state
*old
,
8954 struct bpf_func_state
*cur
)
8956 struct idpair
*idmap
;
8960 idmap
= kcalloc(ID_MAP_SIZE
, sizeof(struct idpair
), GFP_KERNEL
);
8961 /* If we failed to allocate the idmap, just say it's not safe */
8965 for (i
= 0; i
< MAX_BPF_REG
; i
++) {
8966 if (!regsafe(&old
->regs
[i
], &cur
->regs
[i
], idmap
))
8970 if (!stacksafe(old
, cur
, idmap
))
8973 if (!refsafe(old
, cur
))
8981 static bool states_equal(struct bpf_verifier_env
*env
,
8982 struct bpf_verifier_state
*old
,
8983 struct bpf_verifier_state
*cur
)
8987 if (old
->curframe
!= cur
->curframe
)
8990 /* Verification state from speculative execution simulation
8991 * must never prune a non-speculative execution one.
8993 if (old
->speculative
&& !cur
->speculative
)
8996 if (old
->active_spin_lock
!= cur
->active_spin_lock
)
8999 /* for states to be equal callsites have to be the same
9000 * and all frame states need to be equivalent
9002 for (i
= 0; i
<= old
->curframe
; i
++) {
9003 if (old
->frame
[i
]->callsite
!= cur
->frame
[i
]->callsite
)
9005 if (!func_states_equal(old
->frame
[i
], cur
->frame
[i
]))
9011 /* Return 0 if no propagation happened. Return negative error code if error
9012 * happened. Otherwise, return the propagated bit.
9014 static int propagate_liveness_reg(struct bpf_verifier_env
*env
,
9015 struct bpf_reg_state
*reg
,
9016 struct bpf_reg_state
*parent_reg
)
9018 u8 parent_flag
= parent_reg
->live
& REG_LIVE_READ
;
9019 u8 flag
= reg
->live
& REG_LIVE_READ
;
9022 /* When comes here, read flags of PARENT_REG or REG could be any of
9023 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
9024 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
9026 if (parent_flag
== REG_LIVE_READ64
||
9027 /* Or if there is no read flag from REG. */
9029 /* Or if the read flag from REG is the same as PARENT_REG. */
9030 parent_flag
== flag
)
9033 err
= mark_reg_read(env
, reg
, parent_reg
, flag
);
9040 /* A write screens off any subsequent reads; but write marks come from the
9041 * straight-line code between a state and its parent. When we arrive at an
9042 * equivalent state (jump target or such) we didn't arrive by the straight-line
9043 * code, so read marks in the state must propagate to the parent regardless
9044 * of the state's write marks. That's what 'parent == state->parent' comparison
9045 * in mark_reg_read() is for.
9047 static int propagate_liveness(struct bpf_verifier_env
*env
,
9048 const struct bpf_verifier_state
*vstate
,
9049 struct bpf_verifier_state
*vparent
)
9051 struct bpf_reg_state
*state_reg
, *parent_reg
;
9052 struct bpf_func_state
*state
, *parent
;
9053 int i
, frame
, err
= 0;
9055 if (vparent
->curframe
!= vstate
->curframe
) {
9056 WARN(1, "propagate_live: parent frame %d current frame %d\n",
9057 vparent
->curframe
, vstate
->curframe
);
9060 /* Propagate read liveness of registers... */
9061 BUILD_BUG_ON(BPF_REG_FP
+ 1 != MAX_BPF_REG
);
9062 for (frame
= 0; frame
<= vstate
->curframe
; frame
++) {
9063 parent
= vparent
->frame
[frame
];
9064 state
= vstate
->frame
[frame
];
9065 parent_reg
= parent
->regs
;
9066 state_reg
= state
->regs
;
9067 /* We don't need to worry about FP liveness, it's read-only */
9068 for (i
= frame
< vstate
->curframe
? BPF_REG_6
: 0; i
< BPF_REG_FP
; i
++) {
9069 err
= propagate_liveness_reg(env
, &state_reg
[i
],
9073 if (err
== REG_LIVE_READ64
)
9074 mark_insn_zext(env
, &parent_reg
[i
]);
9077 /* Propagate stack slots. */
9078 for (i
= 0; i
< state
->allocated_stack
/ BPF_REG_SIZE
&&
9079 i
< parent
->allocated_stack
/ BPF_REG_SIZE
; i
++) {
9080 parent_reg
= &parent
->stack
[i
].spilled_ptr
;
9081 state_reg
= &state
->stack
[i
].spilled_ptr
;
9082 err
= propagate_liveness_reg(env
, state_reg
,
9091 /* find precise scalars in the previous equivalent state and
9092 * propagate them into the current state
9094 static int propagate_precision(struct bpf_verifier_env
*env
,
9095 const struct bpf_verifier_state
*old
)
9097 struct bpf_reg_state
*state_reg
;
9098 struct bpf_func_state
*state
;
9101 state
= old
->frame
[old
->curframe
];
9102 state_reg
= state
->regs
;
9103 for (i
= 0; i
< BPF_REG_FP
; i
++, state_reg
++) {
9104 if (state_reg
->type
!= SCALAR_VALUE
||
9105 !state_reg
->precise
)
9107 if (env
->log
.level
& BPF_LOG_LEVEL2
)
9108 verbose(env
, "propagating r%d\n", i
);
9109 err
= mark_chain_precision(env
, i
);
9114 for (i
= 0; i
< state
->allocated_stack
/ BPF_REG_SIZE
; i
++) {
9115 if (state
->stack
[i
].slot_type
[0] != STACK_SPILL
)
9117 state_reg
= &state
->stack
[i
].spilled_ptr
;
9118 if (state_reg
->type
!= SCALAR_VALUE
||
9119 !state_reg
->precise
)
9121 if (env
->log
.level
& BPF_LOG_LEVEL2
)
9122 verbose(env
, "propagating fp%d\n",
9123 (-i
- 1) * BPF_REG_SIZE
);
9124 err
= mark_chain_precision_stack(env
, i
);
9131 static bool states_maybe_looping(struct bpf_verifier_state
*old
,
9132 struct bpf_verifier_state
*cur
)
9134 struct bpf_func_state
*fold
, *fcur
;
9135 int i
, fr
= cur
->curframe
;
9137 if (old
->curframe
!= fr
)
9140 fold
= old
->frame
[fr
];
9141 fcur
= cur
->frame
[fr
];
9142 for (i
= 0; i
< MAX_BPF_REG
; i
++)
9143 if (memcmp(&fold
->regs
[i
], &fcur
->regs
[i
],
9144 offsetof(struct bpf_reg_state
, parent
)))
9150 static int is_state_visited(struct bpf_verifier_env
*env
, int insn_idx
)
9152 struct bpf_verifier_state_list
*new_sl
;
9153 struct bpf_verifier_state_list
*sl
, **pprev
;
9154 struct bpf_verifier_state
*cur
= env
->cur_state
, *new;
9155 int i
, j
, err
, states_cnt
= 0;
9156 bool add_new_state
= env
->test_state_freq
? true : false;
9158 cur
->last_insn_idx
= env
->prev_insn_idx
;
9159 if (!env
->insn_aux_data
[insn_idx
].prune_point
)
9160 /* this 'insn_idx' instruction wasn't marked, so we will not
9161 * be doing state search here
9165 /* bpf progs typically have pruning point every 4 instructions
9166 * http://vger.kernel.org/bpfconf2019.html#session-1
9167 * Do not add new state for future pruning if the verifier hasn't seen
9168 * at least 2 jumps and at least 8 instructions.
9169 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
9170 * In tests that amounts to up to 50% reduction into total verifier
9171 * memory consumption and 20% verifier time speedup.
9173 if (env
->jmps_processed
- env
->prev_jmps_processed
>= 2 &&
9174 env
->insn_processed
- env
->prev_insn_processed
>= 8)
9175 add_new_state
= true;
9177 pprev
= explored_state(env
, insn_idx
);
9180 clean_live_states(env
, insn_idx
, cur
);
9184 if (sl
->state
.insn_idx
!= insn_idx
)
9186 if (sl
->state
.branches
) {
9187 if (states_maybe_looping(&sl
->state
, cur
) &&
9188 states_equal(env
, &sl
->state
, cur
)) {
9189 verbose_linfo(env
, insn_idx
, "; ");
9190 verbose(env
, "infinite loop detected at insn %d\n", insn_idx
);
9193 /* if the verifier is processing a loop, avoid adding new state
9194 * too often, since different loop iterations have distinct
9195 * states and may not help future pruning.
9196 * This threshold shouldn't be too low to make sure that
9197 * a loop with large bound will be rejected quickly.
9198 * The most abusive loop will be:
9200 * if r1 < 1000000 goto pc-2
9201 * 1M insn_procssed limit / 100 == 10k peak states.
9202 * This threshold shouldn't be too high either, since states
9203 * at the end of the loop are likely to be useful in pruning.
9205 if (env
->jmps_processed
- env
->prev_jmps_processed
< 20 &&
9206 env
->insn_processed
- env
->prev_insn_processed
< 100)
9207 add_new_state
= false;
9210 if (states_equal(env
, &sl
->state
, cur
)) {
9212 /* reached equivalent register/stack state,
9214 * Registers read by the continuation are read by us.
9215 * If we have any write marks in env->cur_state, they
9216 * will prevent corresponding reads in the continuation
9217 * from reaching our parent (an explored_state). Our
9218 * own state will get the read marks recorded, but
9219 * they'll be immediately forgotten as we're pruning
9220 * this state and will pop a new one.
9222 err
= propagate_liveness(env
, &sl
->state
, cur
);
9224 /* if previous state reached the exit with precision and
9225 * current state is equivalent to it (except precsion marks)
9226 * the precision needs to be propagated back in
9227 * the current state.
9229 err
= err
? : push_jmp_history(env
, cur
);
9230 err
= err
? : propagate_precision(env
, &sl
->state
);
9236 /* when new state is not going to be added do not increase miss count.
9237 * Otherwise several loop iterations will remove the state
9238 * recorded earlier. The goal of these heuristics is to have
9239 * states from some iterations of the loop (some in the beginning
9240 * and some at the end) to help pruning.
9244 /* heuristic to determine whether this state is beneficial
9245 * to keep checking from state equivalence point of view.
9246 * Higher numbers increase max_states_per_insn and verification time,
9247 * but do not meaningfully decrease insn_processed.
9249 if (sl
->miss_cnt
> sl
->hit_cnt
* 3 + 3) {
9250 /* the state is unlikely to be useful. Remove it to
9251 * speed up verification
9254 if (sl
->state
.frame
[0]->regs
[0].live
& REG_LIVE_DONE
) {
9255 u32 br
= sl
->state
.branches
;
9258 "BUG live_done but branches_to_explore %d\n",
9260 free_verifier_state(&sl
->state
, false);
9264 /* cannot free this state, since parentage chain may
9265 * walk it later. Add it for free_list instead to
9266 * be freed at the end of verification
9268 sl
->next
= env
->free_list
;
9269 env
->free_list
= sl
;
9279 if (env
->max_states_per_insn
< states_cnt
)
9280 env
->max_states_per_insn
= states_cnt
;
9282 if (!env
->bpf_capable
&& states_cnt
> BPF_COMPLEXITY_LIMIT_STATES
)
9283 return push_jmp_history(env
, cur
);
9286 return push_jmp_history(env
, cur
);
9288 /* There were no equivalent states, remember the current one.
9289 * Technically the current state is not proven to be safe yet,
9290 * but it will either reach outer most bpf_exit (which means it's safe)
9291 * or it will be rejected. When there are no loops the verifier won't be
9292 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
9293 * again on the way to bpf_exit.
9294 * When looping the sl->state.branches will be > 0 and this state
9295 * will not be considered for equivalence until branches == 0.
9297 new_sl
= kzalloc(sizeof(struct bpf_verifier_state_list
), GFP_KERNEL
);
9300 env
->total_states
++;
9302 env
->prev_jmps_processed
= env
->jmps_processed
;
9303 env
->prev_insn_processed
= env
->insn_processed
;
9305 /* add new state to the head of linked list */
9306 new = &new_sl
->state
;
9307 err
= copy_verifier_state(new, cur
);
9309 free_verifier_state(new, false);
9313 new->insn_idx
= insn_idx
;
9314 WARN_ONCE(new->branches
!= 1,
9315 "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches
, insn_idx
);
9318 cur
->first_insn_idx
= insn_idx
;
9319 clear_jmp_history(cur
);
9320 new_sl
->next
= *explored_state(env
, insn_idx
);
9321 *explored_state(env
, insn_idx
) = new_sl
;
9322 /* connect new state to parentage chain. Current frame needs all
9323 * registers connected. Only r6 - r9 of the callers are alive (pushed
9324 * to the stack implicitly by JITs) so in callers' frames connect just
9325 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
9326 * the state of the call instruction (with WRITTEN set), and r0 comes
9327 * from callee with its full parentage chain, anyway.
9329 /* clear write marks in current state: the writes we did are not writes
9330 * our child did, so they don't screen off its reads from us.
9331 * (There are no read marks in current state, because reads always mark
9332 * their parent and current state never has children yet. Only
9333 * explored_states can get read marks.)
9335 for (j
= 0; j
<= cur
->curframe
; j
++) {
9336 for (i
= j
< cur
->curframe
? BPF_REG_6
: 0; i
< BPF_REG_FP
; i
++)
9337 cur
->frame
[j
]->regs
[i
].parent
= &new->frame
[j
]->regs
[i
];
9338 for (i
= 0; i
< BPF_REG_FP
; i
++)
9339 cur
->frame
[j
]->regs
[i
].live
= REG_LIVE_NONE
;
9342 /* all stack frames are accessible from callee, clear them all */
9343 for (j
= 0; j
<= cur
->curframe
; j
++) {
9344 struct bpf_func_state
*frame
= cur
->frame
[j
];
9345 struct bpf_func_state
*newframe
= new->frame
[j
];
9347 for (i
= 0; i
< frame
->allocated_stack
/ BPF_REG_SIZE
; i
++) {
9348 frame
->stack
[i
].spilled_ptr
.live
= REG_LIVE_NONE
;
9349 frame
->stack
[i
].spilled_ptr
.parent
=
9350 &newframe
->stack
[i
].spilled_ptr
;
9356 /* Return true if it's OK to have the same insn return a different type. */
9357 static bool reg_type_mismatch_ok(enum bpf_reg_type type
)
9362 case PTR_TO_SOCKET_OR_NULL
:
9363 case PTR_TO_SOCK_COMMON
:
9364 case PTR_TO_SOCK_COMMON_OR_NULL
:
9365 case PTR_TO_TCP_SOCK
:
9366 case PTR_TO_TCP_SOCK_OR_NULL
:
9367 case PTR_TO_XDP_SOCK
:
9369 case PTR_TO_BTF_ID_OR_NULL
:
9376 /* If an instruction was previously used with particular pointer types, then we
9377 * need to be careful to avoid cases such as the below, where it may be ok
9378 * for one branch accessing the pointer, but not ok for the other branch:
9383 * R1 = some_other_valid_ptr;
9386 * R2 = *(u32 *)(R1 + 0);
9388 static bool reg_type_mismatch(enum bpf_reg_type src
, enum bpf_reg_type prev
)
9390 return src
!= prev
&& (!reg_type_mismatch_ok(src
) ||
9391 !reg_type_mismatch_ok(prev
));
9394 static int do_check(struct bpf_verifier_env
*env
)
9396 bool pop_log
= !(env
->log
.level
& BPF_LOG_LEVEL2
);
9397 struct bpf_verifier_state
*state
= env
->cur_state
;
9398 struct bpf_insn
*insns
= env
->prog
->insnsi
;
9399 struct bpf_reg_state
*regs
;
9400 int insn_cnt
= env
->prog
->len
;
9401 bool do_print_state
= false;
9402 int prev_insn_idx
= -1;
9405 struct bpf_insn
*insn
;
9409 env
->prev_insn_idx
= prev_insn_idx
;
9410 if (env
->insn_idx
>= insn_cnt
) {
9411 verbose(env
, "invalid insn idx %d insn_cnt %d\n",
9412 env
->insn_idx
, insn_cnt
);
9416 insn
= &insns
[env
->insn_idx
];
9417 class = BPF_CLASS(insn
->code
);
9419 if (++env
->insn_processed
> BPF_COMPLEXITY_LIMIT_INSNS
) {
9421 "BPF program is too large. Processed %d insn\n",
9422 env
->insn_processed
);
9426 err
= is_state_visited(env
, env
->insn_idx
);
9430 /* found equivalent state, can prune the search */
9431 if (env
->log
.level
& BPF_LOG_LEVEL
) {
9433 verbose(env
, "\nfrom %d to %d%s: safe\n",
9434 env
->prev_insn_idx
, env
->insn_idx
,
9435 env
->cur_state
->speculative
?
9436 " (speculative execution)" : "");
9438 verbose(env
, "%d: safe\n", env
->insn_idx
);
9440 goto process_bpf_exit
;
9443 if (signal_pending(current
))
9449 if (env
->log
.level
& BPF_LOG_LEVEL2
||
9450 (env
->log
.level
& BPF_LOG_LEVEL
&& do_print_state
)) {
9451 if (env
->log
.level
& BPF_LOG_LEVEL2
)
9452 verbose(env
, "%d:", env
->insn_idx
);
9454 verbose(env
, "\nfrom %d to %d%s:",
9455 env
->prev_insn_idx
, env
->insn_idx
,
9456 env
->cur_state
->speculative
?
9457 " (speculative execution)" : "");
9458 print_verifier_state(env
, state
->frame
[state
->curframe
]);
9459 do_print_state
= false;
9462 if (env
->log
.level
& BPF_LOG_LEVEL
) {
9463 const struct bpf_insn_cbs cbs
= {
9464 .cb_print
= verbose
,
9465 .private_data
= env
,
9468 verbose_linfo(env
, env
->insn_idx
, "; ");
9469 verbose(env
, "%d: ", env
->insn_idx
);
9470 print_bpf_insn(&cbs
, insn
, env
->allow_ptr_leaks
);
9473 if (bpf_prog_is_dev_bound(env
->prog
->aux
)) {
9474 err
= bpf_prog_offload_verify_insn(env
, env
->insn_idx
,
9475 env
->prev_insn_idx
);
9480 regs
= cur_regs(env
);
9481 env
->insn_aux_data
[env
->insn_idx
].seen
= env
->pass_cnt
;
9482 prev_insn_idx
= env
->insn_idx
;
9484 if (class == BPF_ALU
|| class == BPF_ALU64
) {
9485 err
= check_alu_op(env
, insn
);
9489 } else if (class == BPF_LDX
) {
9490 enum bpf_reg_type
*prev_src_type
, src_reg_type
;
9492 /* check for reserved fields is already done */
9494 /* check src operand */
9495 err
= check_reg_arg(env
, insn
->src_reg
, SRC_OP
);
9499 err
= check_reg_arg(env
, insn
->dst_reg
, DST_OP_NO_MARK
);
9503 src_reg_type
= regs
[insn
->src_reg
].type
;
9505 /* check that memory (src_reg + off) is readable,
9506 * the state of dst_reg will be updated by this func
9508 err
= check_mem_access(env
, env
->insn_idx
, insn
->src_reg
,
9509 insn
->off
, BPF_SIZE(insn
->code
),
9510 BPF_READ
, insn
->dst_reg
, false);
9514 prev_src_type
= &env
->insn_aux_data
[env
->insn_idx
].ptr_type
;
9516 if (*prev_src_type
== NOT_INIT
) {
9518 * dst_reg = *(u32 *)(src_reg + off)
9519 * save type to validate intersecting paths
9521 *prev_src_type
= src_reg_type
;
9523 } else if (reg_type_mismatch(src_reg_type
, *prev_src_type
)) {
9524 /* ABuser program is trying to use the same insn
9525 * dst_reg = *(u32*) (src_reg + off)
9526 * with different pointer types:
9527 * src_reg == ctx in one branch and
9528 * src_reg == stack|map in some other branch.
9531 verbose(env
, "same insn cannot be used with different pointers\n");
9535 } else if (class == BPF_STX
) {
9536 enum bpf_reg_type
*prev_dst_type
, dst_reg_type
;
9538 if (BPF_MODE(insn
->code
) == BPF_XADD
) {
9539 err
= check_xadd(env
, env
->insn_idx
, insn
);
9546 /* check src1 operand */
9547 err
= check_reg_arg(env
, insn
->src_reg
, SRC_OP
);
9550 /* check src2 operand */
9551 err
= check_reg_arg(env
, insn
->dst_reg
, SRC_OP
);
9555 dst_reg_type
= regs
[insn
->dst_reg
].type
;
9557 /* check that memory (dst_reg + off) is writeable */
9558 err
= check_mem_access(env
, env
->insn_idx
, insn
->dst_reg
,
9559 insn
->off
, BPF_SIZE(insn
->code
),
9560 BPF_WRITE
, insn
->src_reg
, false);
9564 prev_dst_type
= &env
->insn_aux_data
[env
->insn_idx
].ptr_type
;
9566 if (*prev_dst_type
== NOT_INIT
) {
9567 *prev_dst_type
= dst_reg_type
;
9568 } else if (reg_type_mismatch(dst_reg_type
, *prev_dst_type
)) {
9569 verbose(env
, "same insn cannot be used with different pointers\n");
9573 } else if (class == BPF_ST
) {
9574 if (BPF_MODE(insn
->code
) != BPF_MEM
||
9575 insn
->src_reg
!= BPF_REG_0
) {
9576 verbose(env
, "BPF_ST uses reserved fields\n");
9579 /* check src operand */
9580 err
= check_reg_arg(env
, insn
->dst_reg
, SRC_OP
);
9584 if (is_ctx_reg(env
, insn
->dst_reg
)) {
9585 verbose(env
, "BPF_ST stores into R%d %s is not allowed\n",
9587 reg_type_str
[reg_state(env
, insn
->dst_reg
)->type
]);
9591 /* check that memory (dst_reg + off) is writeable */
9592 err
= check_mem_access(env
, env
->insn_idx
, insn
->dst_reg
,
9593 insn
->off
, BPF_SIZE(insn
->code
),
9594 BPF_WRITE
, -1, false);
9598 } else if (class == BPF_JMP
|| class == BPF_JMP32
) {
9599 u8 opcode
= BPF_OP(insn
->code
);
9601 env
->jmps_processed
++;
9602 if (opcode
== BPF_CALL
) {
9603 if (BPF_SRC(insn
->code
) != BPF_K
||
9605 (insn
->src_reg
!= BPF_REG_0
&&
9606 insn
->src_reg
!= BPF_PSEUDO_CALL
) ||
9607 insn
->dst_reg
!= BPF_REG_0
||
9608 class == BPF_JMP32
) {
9609 verbose(env
, "BPF_CALL uses reserved fields\n");
9613 if (env
->cur_state
->active_spin_lock
&&
9614 (insn
->src_reg
== BPF_PSEUDO_CALL
||
9615 insn
->imm
!= BPF_FUNC_spin_unlock
)) {
9616 verbose(env
, "function calls are not allowed while holding a lock\n");
9619 if (insn
->src_reg
== BPF_PSEUDO_CALL
)
9620 err
= check_func_call(env
, insn
, &env
->insn_idx
);
9622 err
= check_helper_call(env
, insn
->imm
, env
->insn_idx
);
9626 } else if (opcode
== BPF_JA
) {
9627 if (BPF_SRC(insn
->code
) != BPF_K
||
9629 insn
->src_reg
!= BPF_REG_0
||
9630 insn
->dst_reg
!= BPF_REG_0
||
9631 class == BPF_JMP32
) {
9632 verbose(env
, "BPF_JA uses reserved fields\n");
9636 env
->insn_idx
+= insn
->off
+ 1;
9639 } else if (opcode
== BPF_EXIT
) {
9640 if (BPF_SRC(insn
->code
) != BPF_K
||
9642 insn
->src_reg
!= BPF_REG_0
||
9643 insn
->dst_reg
!= BPF_REG_0
||
9644 class == BPF_JMP32
) {
9645 verbose(env
, "BPF_EXIT uses reserved fields\n");
9649 if (env
->cur_state
->active_spin_lock
) {
9650 verbose(env
, "bpf_spin_unlock is missing\n");
9654 if (state
->curframe
) {
9655 /* exit from nested function */
9656 err
= prepare_func_exit(env
, &env
->insn_idx
);
9659 do_print_state
= true;
9663 err
= check_reference_leak(env
);
9667 err
= check_return_code(env
);
9671 update_branch_counts(env
, env
->cur_state
);
9672 err
= pop_stack(env
, &prev_insn_idx
,
9673 &env
->insn_idx
, pop_log
);
9679 do_print_state
= true;
9683 err
= check_cond_jmp_op(env
, insn
, &env
->insn_idx
);
9687 } else if (class == BPF_LD
) {
9688 u8 mode
= BPF_MODE(insn
->code
);
9690 if (mode
== BPF_ABS
|| mode
== BPF_IND
) {
9691 err
= check_ld_abs(env
, insn
);
9695 } else if (mode
== BPF_IMM
) {
9696 err
= check_ld_imm(env
, insn
);
9701 env
->insn_aux_data
[env
->insn_idx
].seen
= env
->pass_cnt
;
9703 verbose(env
, "invalid BPF_LD mode\n");
9707 verbose(env
, "unknown insn class %d\n", class);
9717 /* replace pseudo btf_id with kernel symbol address */
9718 static int check_pseudo_btf_id(struct bpf_verifier_env
*env
,
9719 struct bpf_insn
*insn
,
9720 struct bpf_insn_aux_data
*aux
)
9722 const struct btf_var_secinfo
*vsi
;
9723 const struct btf_type
*datasec
;
9724 const struct btf_type
*t
;
9725 const char *sym_name
;
9726 bool percpu
= false;
9727 u32 type
, id
= insn
->imm
;
9733 verbose(env
, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
9737 if (insn
[1].imm
!= 0) {
9738 verbose(env
, "reserved field (insn[1].imm) is used in pseudo_btf_id ldimm64 insn.\n");
9742 t
= btf_type_by_id(btf_vmlinux
, id
);
9744 verbose(env
, "ldimm64 insn specifies invalid btf_id %d.\n", id
);
9748 if (!btf_type_is_var(t
)) {
9749 verbose(env
, "pseudo btf_id %d in ldimm64 isn't KIND_VAR.\n",
9754 sym_name
= btf_name_by_offset(btf_vmlinux
, t
->name_off
);
9755 addr
= kallsyms_lookup_name(sym_name
);
9757 verbose(env
, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
9762 datasec_id
= btf_find_by_name_kind(btf_vmlinux
, ".data..percpu",
9764 if (datasec_id
> 0) {
9765 datasec
= btf_type_by_id(btf_vmlinux
, datasec_id
);
9766 for_each_vsi(i
, datasec
, vsi
) {
9767 if (vsi
->type
== id
) {
9774 insn
[0].imm
= (u32
)addr
;
9775 insn
[1].imm
= addr
>> 32;
9778 t
= btf_type_skip_modifiers(btf_vmlinux
, type
, NULL
);
9780 aux
->btf_var
.reg_type
= PTR_TO_PERCPU_BTF_ID
;
9781 aux
->btf_var
.btf
= btf_vmlinux
;
9782 aux
->btf_var
.btf_id
= type
;
9783 } else if (!btf_type_is_struct(t
)) {
9784 const struct btf_type
*ret
;
9788 /* resolve the type size of ksym. */
9789 ret
= btf_resolve_size(btf_vmlinux
, t
, &tsize
);
9791 tname
= btf_name_by_offset(btf_vmlinux
, t
->name_off
);
9792 verbose(env
, "ldimm64 unable to resolve the size of type '%s': %ld\n",
9793 tname
, PTR_ERR(ret
));
9796 aux
->btf_var
.reg_type
= PTR_TO_MEM
;
9797 aux
->btf_var
.mem_size
= tsize
;
9799 aux
->btf_var
.reg_type
= PTR_TO_BTF_ID
;
9800 aux
->btf_var
.btf
= btf_vmlinux
;
9801 aux
->btf_var
.btf_id
= type
;
9806 static int check_map_prealloc(struct bpf_map
*map
)
9808 return (map
->map_type
!= BPF_MAP_TYPE_HASH
&&
9809 map
->map_type
!= BPF_MAP_TYPE_PERCPU_HASH
&&
9810 map
->map_type
!= BPF_MAP_TYPE_HASH_OF_MAPS
) ||
9811 !(map
->map_flags
& BPF_F_NO_PREALLOC
);
9814 static bool is_tracing_prog_type(enum bpf_prog_type type
)
9817 case BPF_PROG_TYPE_KPROBE
:
9818 case BPF_PROG_TYPE_TRACEPOINT
:
9819 case BPF_PROG_TYPE_PERF_EVENT
:
9820 case BPF_PROG_TYPE_RAW_TRACEPOINT
:
9827 static bool is_preallocated_map(struct bpf_map
*map
)
9829 if (!check_map_prealloc(map
))
9831 if (map
->inner_map_meta
&& !check_map_prealloc(map
->inner_map_meta
))
9836 static int check_map_prog_compatibility(struct bpf_verifier_env
*env
,
9837 struct bpf_map
*map
,
9838 struct bpf_prog
*prog
)
9841 enum bpf_prog_type prog_type
= resolve_prog_type(prog
);
9843 * Validate that trace type programs use preallocated hash maps.
9845 * For programs attached to PERF events this is mandatory as the
9846 * perf NMI can hit any arbitrary code sequence.
9848 * All other trace types using preallocated hash maps are unsafe as
9849 * well because tracepoint or kprobes can be inside locked regions
9850 * of the memory allocator or at a place where a recursion into the
9851 * memory allocator would see inconsistent state.
9853 * On RT enabled kernels run-time allocation of all trace type
9854 * programs is strictly prohibited due to lock type constraints. On
9855 * !RT kernels it is allowed for backwards compatibility reasons for
9856 * now, but warnings are emitted so developers are made aware of
9857 * the unsafety and can fix their programs before this is enforced.
9859 if (is_tracing_prog_type(prog_type
) && !is_preallocated_map(map
)) {
9860 if (prog_type
== BPF_PROG_TYPE_PERF_EVENT
) {
9861 verbose(env
, "perf_event programs can only use preallocated hash map\n");
9864 if (IS_ENABLED(CONFIG_PREEMPT_RT
)) {
9865 verbose(env
, "trace type programs can only use preallocated hash map\n");
9868 WARN_ONCE(1, "trace type BPF program uses run-time allocation\n");
9869 verbose(env
, "trace type programs with run-time allocated hash maps are unsafe. Switch to preallocated hash maps.\n");
9872 if (map_value_has_spin_lock(map
)) {
9873 if (prog_type
== BPF_PROG_TYPE_SOCKET_FILTER
) {
9874 verbose(env
, "socket filter progs cannot use bpf_spin_lock yet\n");
9878 if (is_tracing_prog_type(prog_type
)) {
9879 verbose(env
, "tracing progs cannot use bpf_spin_lock yet\n");
9883 if (prog
->aux
->sleepable
) {
9884 verbose(env
, "sleepable progs cannot use bpf_spin_lock yet\n");
9889 if ((bpf_prog_is_dev_bound(prog
->aux
) || bpf_map_is_dev_bound(map
)) &&
9890 !bpf_offload_prog_map_match(prog
, map
)) {
9891 verbose(env
, "offload device mismatch between prog and map\n");
9895 if (map
->map_type
== BPF_MAP_TYPE_STRUCT_OPS
) {
9896 verbose(env
, "bpf_struct_ops map cannot be used in prog\n");
9900 if (prog
->aux
->sleepable
)
9901 switch (map
->map_type
) {
9902 case BPF_MAP_TYPE_HASH
:
9903 case BPF_MAP_TYPE_LRU_HASH
:
9904 case BPF_MAP_TYPE_ARRAY
:
9905 if (!is_preallocated_map(map
)) {
9907 "Sleepable programs can only use preallocated hash maps\n");
9913 "Sleepable programs can only use array and hash maps\n");
9920 static bool bpf_map_is_cgroup_storage(struct bpf_map
*map
)
9922 return (map
->map_type
== BPF_MAP_TYPE_CGROUP_STORAGE
||
9923 map
->map_type
== BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE
);
9926 /* find and rewrite pseudo imm in ld_imm64 instructions:
9928 * 1. if it accesses map FD, replace it with actual map pointer.
9929 * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
9931 * NOTE: btf_vmlinux is required for converting pseudo btf_id.
9933 static int resolve_pseudo_ldimm64(struct bpf_verifier_env
*env
)
9935 struct bpf_insn
*insn
= env
->prog
->insnsi
;
9936 int insn_cnt
= env
->prog
->len
;
9939 err
= bpf_prog_calc_tag(env
->prog
);
9943 for (i
= 0; i
< insn_cnt
; i
++, insn
++) {
9944 if (BPF_CLASS(insn
->code
) == BPF_LDX
&&
9945 (BPF_MODE(insn
->code
) != BPF_MEM
|| insn
->imm
!= 0)) {
9946 verbose(env
, "BPF_LDX uses reserved fields\n");
9950 if (BPF_CLASS(insn
->code
) == BPF_STX
&&
9951 ((BPF_MODE(insn
->code
) != BPF_MEM
&&
9952 BPF_MODE(insn
->code
) != BPF_XADD
) || insn
->imm
!= 0)) {
9953 verbose(env
, "BPF_STX uses reserved fields\n");
9957 if (insn
[0].code
== (BPF_LD
| BPF_IMM
| BPF_DW
)) {
9958 struct bpf_insn_aux_data
*aux
;
9959 struct bpf_map
*map
;
9963 if (i
== insn_cnt
- 1 || insn
[1].code
!= 0 ||
9964 insn
[1].dst_reg
!= 0 || insn
[1].src_reg
!= 0 ||
9966 verbose(env
, "invalid bpf_ld_imm64 insn\n");
9970 if (insn
[0].src_reg
== 0)
9971 /* valid generic load 64-bit imm */
9974 if (insn
[0].src_reg
== BPF_PSEUDO_BTF_ID
) {
9975 aux
= &env
->insn_aux_data
[i
];
9976 err
= check_pseudo_btf_id(env
, insn
, aux
);
9982 /* In final convert_pseudo_ld_imm64() step, this is
9983 * converted into regular 64-bit imm load insn.
9985 if ((insn
[0].src_reg
!= BPF_PSEUDO_MAP_FD
&&
9986 insn
[0].src_reg
!= BPF_PSEUDO_MAP_VALUE
) ||
9987 (insn
[0].src_reg
== BPF_PSEUDO_MAP_FD
&&
9988 insn
[1].imm
!= 0)) {
9990 "unrecognized bpf_ld_imm64 insn\n");
9994 f
= fdget(insn
[0].imm
);
9995 map
= __bpf_map_get(f
);
9997 verbose(env
, "fd %d is not pointing to valid bpf_map\n",
9999 return PTR_ERR(map
);
10002 err
= check_map_prog_compatibility(env
, map
, env
->prog
);
10008 aux
= &env
->insn_aux_data
[i
];
10009 if (insn
->src_reg
== BPF_PSEUDO_MAP_FD
) {
10010 addr
= (unsigned long)map
;
10012 u32 off
= insn
[1].imm
;
10014 if (off
>= BPF_MAX_VAR_OFF
) {
10015 verbose(env
, "direct value offset of %u is not allowed\n", off
);
10020 if (!map
->ops
->map_direct_value_addr
) {
10021 verbose(env
, "no direct value access support for this map type\n");
10026 err
= map
->ops
->map_direct_value_addr(map
, &addr
, off
);
10028 verbose(env
, "invalid access to map value pointer, value_size=%u off=%u\n",
10029 map
->value_size
, off
);
10034 aux
->map_off
= off
;
10038 insn
[0].imm
= (u32
)addr
;
10039 insn
[1].imm
= addr
>> 32;
10041 /* check whether we recorded this map already */
10042 for (j
= 0; j
< env
->used_map_cnt
; j
++) {
10043 if (env
->used_maps
[j
] == map
) {
10044 aux
->map_index
= j
;
10050 if (env
->used_map_cnt
>= MAX_USED_MAPS
) {
10055 /* hold the map. If the program is rejected by verifier,
10056 * the map will be released by release_maps() or it
10057 * will be used by the valid program until it's unloaded
10058 * and all maps are released in free_used_maps()
10062 aux
->map_index
= env
->used_map_cnt
;
10063 env
->used_maps
[env
->used_map_cnt
++] = map
;
10065 if (bpf_map_is_cgroup_storage(map
) &&
10066 bpf_cgroup_storage_assign(env
->prog
->aux
, map
)) {
10067 verbose(env
, "only one cgroup storage of each type is allowed\n");
10079 /* Basic sanity check before we invest more work here. */
10080 if (!bpf_opcode_in_insntable(insn
->code
)) {
10081 verbose(env
, "unknown opcode %02x\n", insn
->code
);
10086 /* now all pseudo BPF_LD_IMM64 instructions load valid
10087 * 'struct bpf_map *' into a register instead of user map_fd.
10088 * These pointers will be used later by verifier to validate map access.
10093 /* drop refcnt of maps used by the rejected program */
10094 static void release_maps(struct bpf_verifier_env
*env
)
10096 __bpf_free_used_maps(env
->prog
->aux
, env
->used_maps
,
10097 env
->used_map_cnt
);
10100 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
10101 static void convert_pseudo_ld_imm64(struct bpf_verifier_env
*env
)
10103 struct bpf_insn
*insn
= env
->prog
->insnsi
;
10104 int insn_cnt
= env
->prog
->len
;
10107 for (i
= 0; i
< insn_cnt
; i
++, insn
++)
10108 if (insn
->code
== (BPF_LD
| BPF_IMM
| BPF_DW
))
10112 /* single env->prog->insni[off] instruction was replaced with the range
10113 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying
10114 * [0, off) and [off, end) to new locations, so the patched range stays zero
10116 static int adjust_insn_aux_data(struct bpf_verifier_env
*env
,
10117 struct bpf_prog
*new_prog
, u32 off
, u32 cnt
)
10119 struct bpf_insn_aux_data
*new_data
, *old_data
= env
->insn_aux_data
;
10120 struct bpf_insn
*insn
= new_prog
->insnsi
;
10124 /* aux info at OFF always needs adjustment, no matter fast path
10125 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
10126 * original insn at old prog.
10128 old_data
[off
].zext_dst
= insn_has_def32(env
, insn
+ off
+ cnt
- 1);
10132 prog_len
= new_prog
->len
;
10133 new_data
= vzalloc(array_size(prog_len
,
10134 sizeof(struct bpf_insn_aux_data
)));
10137 memcpy(new_data
, old_data
, sizeof(struct bpf_insn_aux_data
) * off
);
10138 memcpy(new_data
+ off
+ cnt
- 1, old_data
+ off
,
10139 sizeof(struct bpf_insn_aux_data
) * (prog_len
- off
- cnt
+ 1));
10140 for (i
= off
; i
< off
+ cnt
- 1; i
++) {
10141 new_data
[i
].seen
= env
->pass_cnt
;
10142 new_data
[i
].zext_dst
= insn_has_def32(env
, insn
+ i
);
10144 env
->insn_aux_data
= new_data
;
10149 static void adjust_subprog_starts(struct bpf_verifier_env
*env
, u32 off
, u32 len
)
10155 /* NOTE: fake 'exit' subprog should be updated as well. */
10156 for (i
= 0; i
<= env
->subprog_cnt
; i
++) {
10157 if (env
->subprog_info
[i
].start
<= off
)
10159 env
->subprog_info
[i
].start
+= len
- 1;
10163 static void adjust_poke_descs(struct bpf_prog
*prog
, u32 len
)
10165 struct bpf_jit_poke_descriptor
*tab
= prog
->aux
->poke_tab
;
10166 int i
, sz
= prog
->aux
->size_poke_tab
;
10167 struct bpf_jit_poke_descriptor
*desc
;
10169 for (i
= 0; i
< sz
; i
++) {
10171 desc
->insn_idx
+= len
- 1;
10175 static struct bpf_prog
*bpf_patch_insn_data(struct bpf_verifier_env
*env
, u32 off
,
10176 const struct bpf_insn
*patch
, u32 len
)
10178 struct bpf_prog
*new_prog
;
10180 new_prog
= bpf_patch_insn_single(env
->prog
, off
, patch
, len
);
10181 if (IS_ERR(new_prog
)) {
10182 if (PTR_ERR(new_prog
) == -ERANGE
)
10184 "insn %d cannot be patched due to 16-bit range\n",
10185 env
->insn_aux_data
[off
].orig_idx
);
10188 if (adjust_insn_aux_data(env
, new_prog
, off
, len
))
10190 adjust_subprog_starts(env
, off
, len
);
10191 adjust_poke_descs(new_prog
, len
);
10195 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env
*env
,
10200 /* find first prog starting at or after off (first to remove) */
10201 for (i
= 0; i
< env
->subprog_cnt
; i
++)
10202 if (env
->subprog_info
[i
].start
>= off
)
10204 /* find first prog starting at or after off + cnt (first to stay) */
10205 for (j
= i
; j
< env
->subprog_cnt
; j
++)
10206 if (env
->subprog_info
[j
].start
>= off
+ cnt
)
10208 /* if j doesn't start exactly at off + cnt, we are just removing
10209 * the front of previous prog
10211 if (env
->subprog_info
[j
].start
!= off
+ cnt
)
10215 struct bpf_prog_aux
*aux
= env
->prog
->aux
;
10218 /* move fake 'exit' subprog as well */
10219 move
= env
->subprog_cnt
+ 1 - j
;
10221 memmove(env
->subprog_info
+ i
,
10222 env
->subprog_info
+ j
,
10223 sizeof(*env
->subprog_info
) * move
);
10224 env
->subprog_cnt
-= j
- i
;
10226 /* remove func_info */
10227 if (aux
->func_info
) {
10228 move
= aux
->func_info_cnt
- j
;
10230 memmove(aux
->func_info
+ i
,
10231 aux
->func_info
+ j
,
10232 sizeof(*aux
->func_info
) * move
);
10233 aux
->func_info_cnt
-= j
- i
;
10234 /* func_info->insn_off is set after all code rewrites,
10235 * in adjust_btf_func() - no need to adjust
10239 /* convert i from "first prog to remove" to "first to adjust" */
10240 if (env
->subprog_info
[i
].start
== off
)
10244 /* update fake 'exit' subprog as well */
10245 for (; i
<= env
->subprog_cnt
; i
++)
10246 env
->subprog_info
[i
].start
-= cnt
;
10251 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env
*env
, u32 off
,
10254 struct bpf_prog
*prog
= env
->prog
;
10255 u32 i
, l_off
, l_cnt
, nr_linfo
;
10256 struct bpf_line_info
*linfo
;
10258 nr_linfo
= prog
->aux
->nr_linfo
;
10262 linfo
= prog
->aux
->linfo
;
10264 /* find first line info to remove, count lines to be removed */
10265 for (i
= 0; i
< nr_linfo
; i
++)
10266 if (linfo
[i
].insn_off
>= off
)
10271 for (; i
< nr_linfo
; i
++)
10272 if (linfo
[i
].insn_off
< off
+ cnt
)
10277 /* First live insn doesn't match first live linfo, it needs to "inherit"
10278 * last removed linfo. prog is already modified, so prog->len == off
10279 * means no live instructions after (tail of the program was removed).
10281 if (prog
->len
!= off
&& l_cnt
&&
10282 (i
== nr_linfo
|| linfo
[i
].insn_off
!= off
+ cnt
)) {
10284 linfo
[--i
].insn_off
= off
+ cnt
;
10287 /* remove the line info which refer to the removed instructions */
10289 memmove(linfo
+ l_off
, linfo
+ i
,
10290 sizeof(*linfo
) * (nr_linfo
- i
));
10292 prog
->aux
->nr_linfo
-= l_cnt
;
10293 nr_linfo
= prog
->aux
->nr_linfo
;
10296 /* pull all linfo[i].insn_off >= off + cnt in by cnt */
10297 for (i
= l_off
; i
< nr_linfo
; i
++)
10298 linfo
[i
].insn_off
-= cnt
;
10300 /* fix up all subprogs (incl. 'exit') which start >= off */
10301 for (i
= 0; i
<= env
->subprog_cnt
; i
++)
10302 if (env
->subprog_info
[i
].linfo_idx
> l_off
) {
10303 /* program may have started in the removed region but
10304 * may not be fully removed
10306 if (env
->subprog_info
[i
].linfo_idx
>= l_off
+ l_cnt
)
10307 env
->subprog_info
[i
].linfo_idx
-= l_cnt
;
10309 env
->subprog_info
[i
].linfo_idx
= l_off
;
10315 static int verifier_remove_insns(struct bpf_verifier_env
*env
, u32 off
, u32 cnt
)
10317 struct bpf_insn_aux_data
*aux_data
= env
->insn_aux_data
;
10318 unsigned int orig_prog_len
= env
->prog
->len
;
10321 if (bpf_prog_is_dev_bound(env
->prog
->aux
))
10322 bpf_prog_offload_remove_insns(env
, off
, cnt
);
10324 err
= bpf_remove_insns(env
->prog
, off
, cnt
);
10328 err
= adjust_subprog_starts_after_remove(env
, off
, cnt
);
10332 err
= bpf_adj_linfo_after_remove(env
, off
, cnt
);
10336 memmove(aux_data
+ off
, aux_data
+ off
+ cnt
,
10337 sizeof(*aux_data
) * (orig_prog_len
- off
- cnt
));
10342 /* The verifier does more data flow analysis than llvm and will not
10343 * explore branches that are dead at run time. Malicious programs can
10344 * have dead code too. Therefore replace all dead at-run-time code
10347 * Just nops are not optimal, e.g. if they would sit at the end of the
10348 * program and through another bug we would manage to jump there, then
10349 * we'd execute beyond program memory otherwise. Returning exception
10350 * code also wouldn't work since we can have subprogs where the dead
10351 * code could be located.
10353 static void sanitize_dead_code(struct bpf_verifier_env
*env
)
10355 struct bpf_insn_aux_data
*aux_data
= env
->insn_aux_data
;
10356 struct bpf_insn trap
= BPF_JMP_IMM(BPF_JA
, 0, 0, -1);
10357 struct bpf_insn
*insn
= env
->prog
->insnsi
;
10358 const int insn_cnt
= env
->prog
->len
;
10361 for (i
= 0; i
< insn_cnt
; i
++) {
10362 if (aux_data
[i
].seen
)
10364 memcpy(insn
+ i
, &trap
, sizeof(trap
));
10368 static bool insn_is_cond_jump(u8 code
)
10372 if (BPF_CLASS(code
) == BPF_JMP32
)
10375 if (BPF_CLASS(code
) != BPF_JMP
)
10379 return op
!= BPF_JA
&& op
!= BPF_EXIT
&& op
!= BPF_CALL
;
10382 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env
*env
)
10384 struct bpf_insn_aux_data
*aux_data
= env
->insn_aux_data
;
10385 struct bpf_insn ja
= BPF_JMP_IMM(BPF_JA
, 0, 0, 0);
10386 struct bpf_insn
*insn
= env
->prog
->insnsi
;
10387 const int insn_cnt
= env
->prog
->len
;
10390 for (i
= 0; i
< insn_cnt
; i
++, insn
++) {
10391 if (!insn_is_cond_jump(insn
->code
))
10394 if (!aux_data
[i
+ 1].seen
)
10395 ja
.off
= insn
->off
;
10396 else if (!aux_data
[i
+ 1 + insn
->off
].seen
)
10401 if (bpf_prog_is_dev_bound(env
->prog
->aux
))
10402 bpf_prog_offload_replace_insn(env
, i
, &ja
);
10404 memcpy(insn
, &ja
, sizeof(ja
));
10408 static int opt_remove_dead_code(struct bpf_verifier_env
*env
)
10410 struct bpf_insn_aux_data
*aux_data
= env
->insn_aux_data
;
10411 int insn_cnt
= env
->prog
->len
;
10414 for (i
= 0; i
< insn_cnt
; i
++) {
10418 while (i
+ j
< insn_cnt
&& !aux_data
[i
+ j
].seen
)
10423 err
= verifier_remove_insns(env
, i
, j
);
10426 insn_cnt
= env
->prog
->len
;
10432 static int opt_remove_nops(struct bpf_verifier_env
*env
)
10434 const struct bpf_insn ja
= BPF_JMP_IMM(BPF_JA
, 0, 0, 0);
10435 struct bpf_insn
*insn
= env
->prog
->insnsi
;
10436 int insn_cnt
= env
->prog
->len
;
10439 for (i
= 0; i
< insn_cnt
; i
++) {
10440 if (memcmp(&insn
[i
], &ja
, sizeof(ja
)))
10443 err
= verifier_remove_insns(env
, i
, 1);
10453 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env
*env
,
10454 const union bpf_attr
*attr
)
10456 struct bpf_insn
*patch
, zext_patch
[2], rnd_hi32_patch
[4];
10457 struct bpf_insn_aux_data
*aux
= env
->insn_aux_data
;
10458 int i
, patch_len
, delta
= 0, len
= env
->prog
->len
;
10459 struct bpf_insn
*insns
= env
->prog
->insnsi
;
10460 struct bpf_prog
*new_prog
;
10463 rnd_hi32
= attr
->prog_flags
& BPF_F_TEST_RND_HI32
;
10464 zext_patch
[1] = BPF_ZEXT_REG(0);
10465 rnd_hi32_patch
[1] = BPF_ALU64_IMM(BPF_MOV
, BPF_REG_AX
, 0);
10466 rnd_hi32_patch
[2] = BPF_ALU64_IMM(BPF_LSH
, BPF_REG_AX
, 32);
10467 rnd_hi32_patch
[3] = BPF_ALU64_REG(BPF_OR
, 0, BPF_REG_AX
);
10468 for (i
= 0; i
< len
; i
++) {
10469 int adj_idx
= i
+ delta
;
10470 struct bpf_insn insn
;
10472 insn
= insns
[adj_idx
];
10473 if (!aux
[adj_idx
].zext_dst
) {
10481 class = BPF_CLASS(code
);
10482 if (insn_no_def(&insn
))
10485 /* NOTE: arg "reg" (the fourth one) is only used for
10486 * BPF_STX which has been ruled out in above
10487 * check, it is safe to pass NULL here.
10489 if (is_reg64(env
, &insn
, insn
.dst_reg
, NULL
, DST_OP
)) {
10490 if (class == BPF_LD
&&
10491 BPF_MODE(code
) == BPF_IMM
)
10496 /* ctx load could be transformed into wider load. */
10497 if (class == BPF_LDX
&&
10498 aux
[adj_idx
].ptr_type
== PTR_TO_CTX
)
10501 imm_rnd
= get_random_int();
10502 rnd_hi32_patch
[0] = insn
;
10503 rnd_hi32_patch
[1].imm
= imm_rnd
;
10504 rnd_hi32_patch
[3].dst_reg
= insn
.dst_reg
;
10505 patch
= rnd_hi32_patch
;
10507 goto apply_patch_buffer
;
10510 if (!bpf_jit_needs_zext())
10513 zext_patch
[0] = insn
;
10514 zext_patch
[1].dst_reg
= insn
.dst_reg
;
10515 zext_patch
[1].src_reg
= insn
.dst_reg
;
10516 patch
= zext_patch
;
10518 apply_patch_buffer
:
10519 new_prog
= bpf_patch_insn_data(env
, adj_idx
, patch
, patch_len
);
10522 env
->prog
= new_prog
;
10523 insns
= new_prog
->insnsi
;
10524 aux
= env
->insn_aux_data
;
10525 delta
+= patch_len
- 1;
10531 /* convert load instructions that access fields of a context type into a
10532 * sequence of instructions that access fields of the underlying structure:
10533 * struct __sk_buff -> struct sk_buff
10534 * struct bpf_sock_ops -> struct sock
10536 static int convert_ctx_accesses(struct bpf_verifier_env
*env
)
10538 const struct bpf_verifier_ops
*ops
= env
->ops
;
10539 int i
, cnt
, size
, ctx_field_size
, delta
= 0;
10540 const int insn_cnt
= env
->prog
->len
;
10541 struct bpf_insn insn_buf
[16], *insn
;
10542 u32 target_size
, size_default
, off
;
10543 struct bpf_prog
*new_prog
;
10544 enum bpf_access_type type
;
10545 bool is_narrower_load
;
10547 if (ops
->gen_prologue
|| env
->seen_direct_write
) {
10548 if (!ops
->gen_prologue
) {
10549 verbose(env
, "bpf verifier is misconfigured\n");
10552 cnt
= ops
->gen_prologue(insn_buf
, env
->seen_direct_write
,
10554 if (cnt
>= ARRAY_SIZE(insn_buf
)) {
10555 verbose(env
, "bpf verifier is misconfigured\n");
10558 new_prog
= bpf_patch_insn_data(env
, 0, insn_buf
, cnt
);
10562 env
->prog
= new_prog
;
10567 if (bpf_prog_is_dev_bound(env
->prog
->aux
))
10570 insn
= env
->prog
->insnsi
+ delta
;
10572 for (i
= 0; i
< insn_cnt
; i
++, insn
++) {
10573 bpf_convert_ctx_access_t convert_ctx_access
;
10575 if (insn
->code
== (BPF_LDX
| BPF_MEM
| BPF_B
) ||
10576 insn
->code
== (BPF_LDX
| BPF_MEM
| BPF_H
) ||
10577 insn
->code
== (BPF_LDX
| BPF_MEM
| BPF_W
) ||
10578 insn
->code
== (BPF_LDX
| BPF_MEM
| BPF_DW
))
10580 else if (insn
->code
== (BPF_STX
| BPF_MEM
| BPF_B
) ||
10581 insn
->code
== (BPF_STX
| BPF_MEM
| BPF_H
) ||
10582 insn
->code
== (BPF_STX
| BPF_MEM
| BPF_W
) ||
10583 insn
->code
== (BPF_STX
| BPF_MEM
| BPF_DW
))
10588 if (type
== BPF_WRITE
&&
10589 env
->insn_aux_data
[i
+ delta
].sanitize_stack_off
) {
10590 struct bpf_insn patch
[] = {
10591 /* Sanitize suspicious stack slot with zero.
10592 * There are no memory dependencies for this store,
10593 * since it's only using frame pointer and immediate
10596 BPF_ST_MEM(BPF_DW
, BPF_REG_FP
,
10597 env
->insn_aux_data
[i
+ delta
].sanitize_stack_off
,
10599 /* the original STX instruction will immediately
10600 * overwrite the same stack slot with appropriate value
10605 cnt
= ARRAY_SIZE(patch
);
10606 new_prog
= bpf_patch_insn_data(env
, i
+ delta
, patch
, cnt
);
10611 env
->prog
= new_prog
;
10612 insn
= new_prog
->insnsi
+ i
+ delta
;
10616 switch (env
->insn_aux_data
[i
+ delta
].ptr_type
) {
10618 if (!ops
->convert_ctx_access
)
10620 convert_ctx_access
= ops
->convert_ctx_access
;
10622 case PTR_TO_SOCKET
:
10623 case PTR_TO_SOCK_COMMON
:
10624 convert_ctx_access
= bpf_sock_convert_ctx_access
;
10626 case PTR_TO_TCP_SOCK
:
10627 convert_ctx_access
= bpf_tcp_sock_convert_ctx_access
;
10629 case PTR_TO_XDP_SOCK
:
10630 convert_ctx_access
= bpf_xdp_sock_convert_ctx_access
;
10632 case PTR_TO_BTF_ID
:
10633 if (type
== BPF_READ
) {
10634 insn
->code
= BPF_LDX
| BPF_PROBE_MEM
|
10635 BPF_SIZE((insn
)->code
);
10636 env
->prog
->aux
->num_exentries
++;
10637 } else if (resolve_prog_type(env
->prog
) != BPF_PROG_TYPE_STRUCT_OPS
) {
10638 verbose(env
, "Writes through BTF pointers are not allowed\n");
10646 ctx_field_size
= env
->insn_aux_data
[i
+ delta
].ctx_field_size
;
10647 size
= BPF_LDST_BYTES(insn
);
10649 /* If the read access is a narrower load of the field,
10650 * convert to a 4/8-byte load, to minimum program type specific
10651 * convert_ctx_access changes. If conversion is successful,
10652 * we will apply proper mask to the result.
10654 is_narrower_load
= size
< ctx_field_size
;
10655 size_default
= bpf_ctx_off_adjust_machine(ctx_field_size
);
10657 if (is_narrower_load
) {
10660 if (type
== BPF_WRITE
) {
10661 verbose(env
, "bpf verifier narrow ctx access misconfigured\n");
10666 if (ctx_field_size
== 4)
10668 else if (ctx_field_size
== 8)
10669 size_code
= BPF_DW
;
10671 insn
->off
= off
& ~(size_default
- 1);
10672 insn
->code
= BPF_LDX
| BPF_MEM
| size_code
;
10676 cnt
= convert_ctx_access(type
, insn
, insn_buf
, env
->prog
,
10678 if (cnt
== 0 || cnt
>= ARRAY_SIZE(insn_buf
) ||
10679 (ctx_field_size
&& !target_size
)) {
10680 verbose(env
, "bpf verifier is misconfigured\n");
10684 if (is_narrower_load
&& size
< target_size
) {
10685 u8 shift
= bpf_ctx_narrow_access_offset(
10686 off
, size
, size_default
) * 8;
10687 if (ctx_field_size
<= 4) {
10689 insn_buf
[cnt
++] = BPF_ALU32_IMM(BPF_RSH
,
10692 insn_buf
[cnt
++] = BPF_ALU32_IMM(BPF_AND
, insn
->dst_reg
,
10693 (1 << size
* 8) - 1);
10696 insn_buf
[cnt
++] = BPF_ALU64_IMM(BPF_RSH
,
10699 insn_buf
[cnt
++] = BPF_ALU64_IMM(BPF_AND
, insn
->dst_reg
,
10700 (1ULL << size
* 8) - 1);
10704 new_prog
= bpf_patch_insn_data(env
, i
+ delta
, insn_buf
, cnt
);
10710 /* keep walking new program and skip insns we just inserted */
10711 env
->prog
= new_prog
;
10712 insn
= new_prog
->insnsi
+ i
+ delta
;
10718 static int jit_subprogs(struct bpf_verifier_env
*env
)
10720 struct bpf_prog
*prog
= env
->prog
, **func
, *tmp
;
10721 int i
, j
, subprog_start
, subprog_end
= 0, len
, subprog
;
10722 struct bpf_map
*map_ptr
;
10723 struct bpf_insn
*insn
;
10724 void *old_bpf_func
;
10725 int err
, num_exentries
;
10727 if (env
->subprog_cnt
<= 1)
10730 for (i
= 0, insn
= prog
->insnsi
; i
< prog
->len
; i
++, insn
++) {
10731 if (insn
->code
!= (BPF_JMP
| BPF_CALL
) ||
10732 insn
->src_reg
!= BPF_PSEUDO_CALL
)
10734 /* Upon error here we cannot fall back to interpreter but
10735 * need a hard reject of the program. Thus -EFAULT is
10736 * propagated in any case.
10738 subprog
= find_subprog(env
, i
+ insn
->imm
+ 1);
10740 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
10741 i
+ insn
->imm
+ 1);
10744 /* temporarily remember subprog id inside insn instead of
10745 * aux_data, since next loop will split up all insns into funcs
10747 insn
->off
= subprog
;
10748 /* remember original imm in case JIT fails and fallback
10749 * to interpreter will be needed
10751 env
->insn_aux_data
[i
].call_imm
= insn
->imm
;
10752 /* point imm to __bpf_call_base+1 from JITs point of view */
10756 err
= bpf_prog_alloc_jited_linfo(prog
);
10758 goto out_undo_insn
;
10761 func
= kcalloc(env
->subprog_cnt
, sizeof(prog
), GFP_KERNEL
);
10763 goto out_undo_insn
;
10765 for (i
= 0; i
< env
->subprog_cnt
; i
++) {
10766 subprog_start
= subprog_end
;
10767 subprog_end
= env
->subprog_info
[i
+ 1].start
;
10769 len
= subprog_end
- subprog_start
;
10770 /* BPF_PROG_RUN doesn't call subprogs directly,
10771 * hence main prog stats include the runtime of subprogs.
10772 * subprogs don't have IDs and not reachable via prog_get_next_id
10773 * func[i]->aux->stats will never be accessed and stays NULL
10775 func
[i
] = bpf_prog_alloc_no_stats(bpf_prog_size(len
), GFP_USER
);
10778 memcpy(func
[i
]->insnsi
, &prog
->insnsi
[subprog_start
],
10779 len
* sizeof(struct bpf_insn
));
10780 func
[i
]->type
= prog
->type
;
10781 func
[i
]->len
= len
;
10782 if (bpf_prog_calc_tag(func
[i
]))
10784 func
[i
]->is_func
= 1;
10785 func
[i
]->aux
->func_idx
= i
;
10786 /* the btf and func_info will be freed only at prog->aux */
10787 func
[i
]->aux
->btf
= prog
->aux
->btf
;
10788 func
[i
]->aux
->func_info
= prog
->aux
->func_info
;
10790 for (j
= 0; j
< prog
->aux
->size_poke_tab
; j
++) {
10791 u32 insn_idx
= prog
->aux
->poke_tab
[j
].insn_idx
;
10794 if (!(insn_idx
>= subprog_start
&&
10795 insn_idx
<= subprog_end
))
10798 ret
= bpf_jit_add_poke_descriptor(func
[i
],
10799 &prog
->aux
->poke_tab
[j
]);
10801 verbose(env
, "adding tail call poke descriptor failed\n");
10805 func
[i
]->insnsi
[insn_idx
- subprog_start
].imm
= ret
+ 1;
10807 map_ptr
= func
[i
]->aux
->poke_tab
[ret
].tail_call
.map
;
10808 ret
= map_ptr
->ops
->map_poke_track(map_ptr
, func
[i
]->aux
);
10810 verbose(env
, "tracking tail call prog failed\n");
10815 /* Use bpf_prog_F_tag to indicate functions in stack traces.
10816 * Long term would need debug info to populate names
10818 func
[i
]->aux
->name
[0] = 'F';
10819 func
[i
]->aux
->stack_depth
= env
->subprog_info
[i
].stack_depth
;
10820 func
[i
]->jit_requested
= 1;
10821 func
[i
]->aux
->linfo
= prog
->aux
->linfo
;
10822 func
[i
]->aux
->nr_linfo
= prog
->aux
->nr_linfo
;
10823 func
[i
]->aux
->jited_linfo
= prog
->aux
->jited_linfo
;
10824 func
[i
]->aux
->linfo_idx
= env
->subprog_info
[i
].linfo_idx
;
10826 insn
= func
[i
]->insnsi
;
10827 for (j
= 0; j
< func
[i
]->len
; j
++, insn
++) {
10828 if (BPF_CLASS(insn
->code
) == BPF_LDX
&&
10829 BPF_MODE(insn
->code
) == BPF_PROBE_MEM
)
10832 func
[i
]->aux
->num_exentries
= num_exentries
;
10833 func
[i
]->aux
->tail_call_reachable
= env
->subprog_info
[i
].tail_call_reachable
;
10834 func
[i
] = bpf_int_jit_compile(func
[i
]);
10835 if (!func
[i
]->jited
) {
10842 /* Untrack main program's aux structs so that during map_poke_run()
10843 * we will not stumble upon the unfilled poke descriptors; each
10844 * of the main program's poke descs got distributed across subprogs
10845 * and got tracked onto map, so we are sure that none of them will
10846 * be missed after the operation below
10848 for (i
= 0; i
< prog
->aux
->size_poke_tab
; i
++) {
10849 map_ptr
= prog
->aux
->poke_tab
[i
].tail_call
.map
;
10851 map_ptr
->ops
->map_poke_untrack(map_ptr
, prog
->aux
);
10854 /* at this point all bpf functions were successfully JITed
10855 * now populate all bpf_calls with correct addresses and
10856 * run last pass of JIT
10858 for (i
= 0; i
< env
->subprog_cnt
; i
++) {
10859 insn
= func
[i
]->insnsi
;
10860 for (j
= 0; j
< func
[i
]->len
; j
++, insn
++) {
10861 if (insn
->code
!= (BPF_JMP
| BPF_CALL
) ||
10862 insn
->src_reg
!= BPF_PSEUDO_CALL
)
10864 subprog
= insn
->off
;
10865 insn
->imm
= BPF_CAST_CALL(func
[subprog
]->bpf_func
) -
10869 /* we use the aux data to keep a list of the start addresses
10870 * of the JITed images for each function in the program
10872 * for some architectures, such as powerpc64, the imm field
10873 * might not be large enough to hold the offset of the start
10874 * address of the callee's JITed image from __bpf_call_base
10876 * in such cases, we can lookup the start address of a callee
10877 * by using its subprog id, available from the off field of
10878 * the call instruction, as an index for this list
10880 func
[i
]->aux
->func
= func
;
10881 func
[i
]->aux
->func_cnt
= env
->subprog_cnt
;
10883 for (i
= 0; i
< env
->subprog_cnt
; i
++) {
10884 old_bpf_func
= func
[i
]->bpf_func
;
10885 tmp
= bpf_int_jit_compile(func
[i
]);
10886 if (tmp
!= func
[i
] || func
[i
]->bpf_func
!= old_bpf_func
) {
10887 verbose(env
, "JIT doesn't support bpf-to-bpf calls\n");
10894 /* finally lock prog and jit images for all functions and
10895 * populate kallsysm
10897 for (i
= 0; i
< env
->subprog_cnt
; i
++) {
10898 bpf_prog_lock_ro(func
[i
]);
10899 bpf_prog_kallsyms_add(func
[i
]);
10902 /* Last step: make now unused interpreter insns from main
10903 * prog consistent for later dump requests, so they can
10904 * later look the same as if they were interpreted only.
10906 for (i
= 0, insn
= prog
->insnsi
; i
< prog
->len
; i
++, insn
++) {
10907 if (insn
->code
!= (BPF_JMP
| BPF_CALL
) ||
10908 insn
->src_reg
!= BPF_PSEUDO_CALL
)
10910 insn
->off
= env
->insn_aux_data
[i
].call_imm
;
10911 subprog
= find_subprog(env
, i
+ insn
->off
+ 1);
10912 insn
->imm
= subprog
;
10916 prog
->bpf_func
= func
[0]->bpf_func
;
10917 prog
->aux
->func
= func
;
10918 prog
->aux
->func_cnt
= env
->subprog_cnt
;
10919 bpf_prog_free_unused_jited_linfo(prog
);
10922 for (i
= 0; i
< env
->subprog_cnt
; i
++) {
10926 for (j
= 0; j
< func
[i
]->aux
->size_poke_tab
; j
++) {
10927 map_ptr
= func
[i
]->aux
->poke_tab
[j
].tail_call
.map
;
10928 map_ptr
->ops
->map_poke_untrack(map_ptr
, func
[i
]->aux
);
10930 bpf_jit_free(func
[i
]);
10934 /* cleanup main prog to be interpreted */
10935 prog
->jit_requested
= 0;
10936 for (i
= 0, insn
= prog
->insnsi
; i
< prog
->len
; i
++, insn
++) {
10937 if (insn
->code
!= (BPF_JMP
| BPF_CALL
) ||
10938 insn
->src_reg
!= BPF_PSEUDO_CALL
)
10941 insn
->imm
= env
->insn_aux_data
[i
].call_imm
;
10943 bpf_prog_free_jited_linfo(prog
);
10947 static int fixup_call_args(struct bpf_verifier_env
*env
)
10949 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
10950 struct bpf_prog
*prog
= env
->prog
;
10951 struct bpf_insn
*insn
= prog
->insnsi
;
10956 if (env
->prog
->jit_requested
&&
10957 !bpf_prog_is_dev_bound(env
->prog
->aux
)) {
10958 err
= jit_subprogs(env
);
10961 if (err
== -EFAULT
)
10964 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
10965 if (env
->subprog_cnt
> 1 && env
->prog
->aux
->tail_call_reachable
) {
10966 /* When JIT fails the progs with bpf2bpf calls and tail_calls
10967 * have to be rejected, since interpreter doesn't support them yet.
10969 verbose(env
, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
10972 for (i
= 0; i
< prog
->len
; i
++, insn
++) {
10973 if (insn
->code
!= (BPF_JMP
| BPF_CALL
) ||
10974 insn
->src_reg
!= BPF_PSEUDO_CALL
)
10976 depth
= get_callee_stack_depth(env
, insn
, i
);
10979 bpf_patch_call_args(insn
, depth
);
10986 /* fixup insn->imm field of bpf_call instructions
10987 * and inline eligible helpers as explicit sequence of BPF instructions
10989 * this function is called after eBPF program passed verification
10991 static int fixup_bpf_calls(struct bpf_verifier_env
*env
)
10993 struct bpf_prog
*prog
= env
->prog
;
10994 bool expect_blinding
= bpf_jit_blinding_enabled(prog
);
10995 struct bpf_insn
*insn
= prog
->insnsi
;
10996 const struct bpf_func_proto
*fn
;
10997 const int insn_cnt
= prog
->len
;
10998 const struct bpf_map_ops
*ops
;
10999 struct bpf_insn_aux_data
*aux
;
11000 struct bpf_insn insn_buf
[16];
11001 struct bpf_prog
*new_prog
;
11002 struct bpf_map
*map_ptr
;
11003 int i
, ret
, cnt
, delta
= 0;
11005 for (i
= 0; i
< insn_cnt
; i
++, insn
++) {
11006 if (insn
->code
== (BPF_ALU64
| BPF_MOD
| BPF_X
) ||
11007 insn
->code
== (BPF_ALU64
| BPF_DIV
| BPF_X
) ||
11008 insn
->code
== (BPF_ALU
| BPF_MOD
| BPF_X
) ||
11009 insn
->code
== (BPF_ALU
| BPF_DIV
| BPF_X
)) {
11010 bool is64
= BPF_CLASS(insn
->code
) == BPF_ALU64
;
11011 bool isdiv
= BPF_OP(insn
->code
) == BPF_DIV
;
11012 struct bpf_insn
*patchlet
;
11013 struct bpf_insn chk_and_div
[] = {
11014 /* [R,W]x div 0 -> 0 */
11015 BPF_RAW_INSN((is64
? BPF_JMP
: BPF_JMP32
) |
11016 BPF_JNE
| BPF_K
, insn
->src_reg
,
11018 BPF_ALU32_REG(BPF_XOR
, insn
->dst_reg
, insn
->dst_reg
),
11019 BPF_JMP_IMM(BPF_JA
, 0, 0, 1),
11022 struct bpf_insn chk_and_mod
[] = {
11023 /* [R,W]x mod 0 -> [R,W]x */
11024 BPF_RAW_INSN((is64
? BPF_JMP
: BPF_JMP32
) |
11025 BPF_JEQ
| BPF_K
, insn
->src_reg
,
11026 0, 1 + (is64
? 0 : 1), 0),
11028 BPF_JMP_IMM(BPF_JA
, 0, 0, 1),
11029 BPF_MOV32_REG(insn
->dst_reg
, insn
->dst_reg
),
11032 patchlet
= isdiv
? chk_and_div
: chk_and_mod
;
11033 cnt
= isdiv
? ARRAY_SIZE(chk_and_div
) :
11034 ARRAY_SIZE(chk_and_mod
) - (is64
? 2 : 0);
11036 new_prog
= bpf_patch_insn_data(env
, i
+ delta
, patchlet
, cnt
);
11041 env
->prog
= prog
= new_prog
;
11042 insn
= new_prog
->insnsi
+ i
+ delta
;
11046 if (BPF_CLASS(insn
->code
) == BPF_LD
&&
11047 (BPF_MODE(insn
->code
) == BPF_ABS
||
11048 BPF_MODE(insn
->code
) == BPF_IND
)) {
11049 cnt
= env
->ops
->gen_ld_abs(insn
, insn_buf
);
11050 if (cnt
== 0 || cnt
>= ARRAY_SIZE(insn_buf
)) {
11051 verbose(env
, "bpf verifier is misconfigured\n");
11055 new_prog
= bpf_patch_insn_data(env
, i
+ delta
, insn_buf
, cnt
);
11060 env
->prog
= prog
= new_prog
;
11061 insn
= new_prog
->insnsi
+ i
+ delta
;
11065 if (insn
->code
== (BPF_ALU64
| BPF_ADD
| BPF_X
) ||
11066 insn
->code
== (BPF_ALU64
| BPF_SUB
| BPF_X
)) {
11067 const u8 code_add
= BPF_ALU64
| BPF_ADD
| BPF_X
;
11068 const u8 code_sub
= BPF_ALU64
| BPF_SUB
| BPF_X
;
11069 struct bpf_insn insn_buf
[16];
11070 struct bpf_insn
*patch
= &insn_buf
[0];
11074 aux
= &env
->insn_aux_data
[i
+ delta
];
11075 if (!aux
->alu_state
||
11076 aux
->alu_state
== BPF_ALU_NON_POINTER
)
11079 isneg
= aux
->alu_state
& BPF_ALU_NEG_VALUE
;
11080 issrc
= (aux
->alu_state
& BPF_ALU_SANITIZE
) ==
11081 BPF_ALU_SANITIZE_SRC
;
11083 off_reg
= issrc
? insn
->src_reg
: insn
->dst_reg
;
11085 *patch
++ = BPF_ALU64_IMM(BPF_MUL
, off_reg
, -1);
11086 *patch
++ = BPF_MOV32_IMM(BPF_REG_AX
, aux
->alu_limit
- 1);
11087 *patch
++ = BPF_ALU64_REG(BPF_SUB
, BPF_REG_AX
, off_reg
);
11088 *patch
++ = BPF_ALU64_REG(BPF_OR
, BPF_REG_AX
, off_reg
);
11089 *patch
++ = BPF_ALU64_IMM(BPF_NEG
, BPF_REG_AX
, 0);
11090 *patch
++ = BPF_ALU64_IMM(BPF_ARSH
, BPF_REG_AX
, 63);
11092 *patch
++ = BPF_ALU64_REG(BPF_AND
, BPF_REG_AX
,
11094 insn
->src_reg
= BPF_REG_AX
;
11096 *patch
++ = BPF_ALU64_REG(BPF_AND
, off_reg
,
11100 insn
->code
= insn
->code
== code_add
?
11101 code_sub
: code_add
;
11103 if (issrc
&& isneg
)
11104 *patch
++ = BPF_ALU64_IMM(BPF_MUL
, off_reg
, -1);
11105 cnt
= patch
- insn_buf
;
11107 new_prog
= bpf_patch_insn_data(env
, i
+ delta
, insn_buf
, cnt
);
11112 env
->prog
= prog
= new_prog
;
11113 insn
= new_prog
->insnsi
+ i
+ delta
;
11117 if (insn
->code
!= (BPF_JMP
| BPF_CALL
))
11119 if (insn
->src_reg
== BPF_PSEUDO_CALL
)
11122 if (insn
->imm
== BPF_FUNC_get_route_realm
)
11123 prog
->dst_needed
= 1;
11124 if (insn
->imm
== BPF_FUNC_get_prandom_u32
)
11125 bpf_user_rnd_init_once();
11126 if (insn
->imm
== BPF_FUNC_override_return
)
11127 prog
->kprobe_override
= 1;
11128 if (insn
->imm
== BPF_FUNC_tail_call
) {
11129 /* If we tail call into other programs, we
11130 * cannot make any assumptions since they can
11131 * be replaced dynamically during runtime in
11132 * the program array.
11134 prog
->cb_access
= 1;
11135 if (!allow_tail_call_in_subprogs(env
))
11136 prog
->aux
->stack_depth
= MAX_BPF_STACK
;
11137 prog
->aux
->max_pkt_offset
= MAX_PACKET_OFF
;
11139 /* mark bpf_tail_call as different opcode to avoid
11140 * conditional branch in the interpeter for every normal
11141 * call and to prevent accidental JITing by JIT compiler
11142 * that doesn't support bpf_tail_call yet
11145 insn
->code
= BPF_JMP
| BPF_TAIL_CALL
;
11147 aux
= &env
->insn_aux_data
[i
+ delta
];
11148 if (env
->bpf_capable
&& !expect_blinding
&&
11149 prog
->jit_requested
&&
11150 !bpf_map_key_poisoned(aux
) &&
11151 !bpf_map_ptr_poisoned(aux
) &&
11152 !bpf_map_ptr_unpriv(aux
)) {
11153 struct bpf_jit_poke_descriptor desc
= {
11154 .reason
= BPF_POKE_REASON_TAIL_CALL
,
11155 .tail_call
.map
= BPF_MAP_PTR(aux
->map_ptr_state
),
11156 .tail_call
.key
= bpf_map_key_immediate(aux
),
11157 .insn_idx
= i
+ delta
,
11160 ret
= bpf_jit_add_poke_descriptor(prog
, &desc
);
11162 verbose(env
, "adding tail call poke descriptor failed\n");
11166 insn
->imm
= ret
+ 1;
11170 if (!bpf_map_ptr_unpriv(aux
))
11173 /* instead of changing every JIT dealing with tail_call
11174 * emit two extra insns:
11175 * if (index >= max_entries) goto out;
11176 * index &= array->index_mask;
11177 * to avoid out-of-bounds cpu speculation
11179 if (bpf_map_ptr_poisoned(aux
)) {
11180 verbose(env
, "tail_call abusing map_ptr\n");
11184 map_ptr
= BPF_MAP_PTR(aux
->map_ptr_state
);
11185 insn_buf
[0] = BPF_JMP_IMM(BPF_JGE
, BPF_REG_3
,
11186 map_ptr
->max_entries
, 2);
11187 insn_buf
[1] = BPF_ALU32_IMM(BPF_AND
, BPF_REG_3
,
11188 container_of(map_ptr
,
11191 insn_buf
[2] = *insn
;
11193 new_prog
= bpf_patch_insn_data(env
, i
+ delta
, insn_buf
, cnt
);
11198 env
->prog
= prog
= new_prog
;
11199 insn
= new_prog
->insnsi
+ i
+ delta
;
11203 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
11204 * and other inlining handlers are currently limited to 64 bit
11207 if (prog
->jit_requested
&& BITS_PER_LONG
== 64 &&
11208 (insn
->imm
== BPF_FUNC_map_lookup_elem
||
11209 insn
->imm
== BPF_FUNC_map_update_elem
||
11210 insn
->imm
== BPF_FUNC_map_delete_elem
||
11211 insn
->imm
== BPF_FUNC_map_push_elem
||
11212 insn
->imm
== BPF_FUNC_map_pop_elem
||
11213 insn
->imm
== BPF_FUNC_map_peek_elem
)) {
11214 aux
= &env
->insn_aux_data
[i
+ delta
];
11215 if (bpf_map_ptr_poisoned(aux
))
11216 goto patch_call_imm
;
11218 map_ptr
= BPF_MAP_PTR(aux
->map_ptr_state
);
11219 ops
= map_ptr
->ops
;
11220 if (insn
->imm
== BPF_FUNC_map_lookup_elem
&&
11221 ops
->map_gen_lookup
) {
11222 cnt
= ops
->map_gen_lookup(map_ptr
, insn_buf
);
11223 if (cnt
== -EOPNOTSUPP
)
11224 goto patch_map_ops_generic
;
11225 if (cnt
<= 0 || cnt
>= ARRAY_SIZE(insn_buf
)) {
11226 verbose(env
, "bpf verifier is misconfigured\n");
11230 new_prog
= bpf_patch_insn_data(env
, i
+ delta
,
11236 env
->prog
= prog
= new_prog
;
11237 insn
= new_prog
->insnsi
+ i
+ delta
;
11241 BUILD_BUG_ON(!__same_type(ops
->map_lookup_elem
,
11242 (void *(*)(struct bpf_map
*map
, void *key
))NULL
));
11243 BUILD_BUG_ON(!__same_type(ops
->map_delete_elem
,
11244 (int (*)(struct bpf_map
*map
, void *key
))NULL
));
11245 BUILD_BUG_ON(!__same_type(ops
->map_update_elem
,
11246 (int (*)(struct bpf_map
*map
, void *key
, void *value
,
11248 BUILD_BUG_ON(!__same_type(ops
->map_push_elem
,
11249 (int (*)(struct bpf_map
*map
, void *value
,
11251 BUILD_BUG_ON(!__same_type(ops
->map_pop_elem
,
11252 (int (*)(struct bpf_map
*map
, void *value
))NULL
));
11253 BUILD_BUG_ON(!__same_type(ops
->map_peek_elem
,
11254 (int (*)(struct bpf_map
*map
, void *value
))NULL
));
11255 patch_map_ops_generic
:
11256 switch (insn
->imm
) {
11257 case BPF_FUNC_map_lookup_elem
:
11258 insn
->imm
= BPF_CAST_CALL(ops
->map_lookup_elem
) -
11261 case BPF_FUNC_map_update_elem
:
11262 insn
->imm
= BPF_CAST_CALL(ops
->map_update_elem
) -
11265 case BPF_FUNC_map_delete_elem
:
11266 insn
->imm
= BPF_CAST_CALL(ops
->map_delete_elem
) -
11269 case BPF_FUNC_map_push_elem
:
11270 insn
->imm
= BPF_CAST_CALL(ops
->map_push_elem
) -
11273 case BPF_FUNC_map_pop_elem
:
11274 insn
->imm
= BPF_CAST_CALL(ops
->map_pop_elem
) -
11277 case BPF_FUNC_map_peek_elem
:
11278 insn
->imm
= BPF_CAST_CALL(ops
->map_peek_elem
) -
11283 goto patch_call_imm
;
11286 if (prog
->jit_requested
&& BITS_PER_LONG
== 64 &&
11287 insn
->imm
== BPF_FUNC_jiffies64
) {
11288 struct bpf_insn ld_jiffies_addr
[2] = {
11289 BPF_LD_IMM64(BPF_REG_0
,
11290 (unsigned long)&jiffies
),
11293 insn_buf
[0] = ld_jiffies_addr
[0];
11294 insn_buf
[1] = ld_jiffies_addr
[1];
11295 insn_buf
[2] = BPF_LDX_MEM(BPF_DW
, BPF_REG_0
,
11299 new_prog
= bpf_patch_insn_data(env
, i
+ delta
, insn_buf
,
11305 env
->prog
= prog
= new_prog
;
11306 insn
= new_prog
->insnsi
+ i
+ delta
;
11311 fn
= env
->ops
->get_func_proto(insn
->imm
, env
->prog
);
11312 /* all functions that have prototype and verifier allowed
11313 * programs to call them, must be real in-kernel functions
11317 "kernel subsystem misconfigured func %s#%d\n",
11318 func_id_name(insn
->imm
), insn
->imm
);
11321 insn
->imm
= fn
->func
- __bpf_call_base
;
11324 /* Since poke tab is now finalized, publish aux to tracker. */
11325 for (i
= 0; i
< prog
->aux
->size_poke_tab
; i
++) {
11326 map_ptr
= prog
->aux
->poke_tab
[i
].tail_call
.map
;
11327 if (!map_ptr
->ops
->map_poke_track
||
11328 !map_ptr
->ops
->map_poke_untrack
||
11329 !map_ptr
->ops
->map_poke_run
) {
11330 verbose(env
, "bpf verifier is misconfigured\n");
11334 ret
= map_ptr
->ops
->map_poke_track(map_ptr
, prog
->aux
);
11336 verbose(env
, "tracking tail call prog failed\n");
11344 static void free_states(struct bpf_verifier_env
*env
)
11346 struct bpf_verifier_state_list
*sl
, *sln
;
11349 sl
= env
->free_list
;
11352 free_verifier_state(&sl
->state
, false);
11356 env
->free_list
= NULL
;
11358 if (!env
->explored_states
)
11361 for (i
= 0; i
< state_htab_size(env
); i
++) {
11362 sl
= env
->explored_states
[i
];
11366 free_verifier_state(&sl
->state
, false);
11370 env
->explored_states
[i
] = NULL
;
11374 /* The verifier is using insn_aux_data[] to store temporary data during
11375 * verification and to store information for passes that run after the
11376 * verification like dead code sanitization. do_check_common() for subprogram N
11377 * may analyze many other subprograms. sanitize_insn_aux_data() clears all
11378 * temporary data after do_check_common() finds that subprogram N cannot be
11379 * verified independently. pass_cnt counts the number of times
11380 * do_check_common() was run and insn->aux->seen tells the pass number
11381 * insn_aux_data was touched. These variables are compared to clear temporary
11382 * data from failed pass. For testing and experiments do_check_common() can be
11383 * run multiple times even when prior attempt to verify is unsuccessful.
11385 static void sanitize_insn_aux_data(struct bpf_verifier_env
*env
)
11387 struct bpf_insn
*insn
= env
->prog
->insnsi
;
11388 struct bpf_insn_aux_data
*aux
;
11391 for (i
= 0; i
< env
->prog
->len
; i
++) {
11392 class = BPF_CLASS(insn
[i
].code
);
11393 if (class != BPF_LDX
&& class != BPF_STX
)
11395 aux
= &env
->insn_aux_data
[i
];
11396 if (aux
->seen
!= env
->pass_cnt
)
11398 memset(aux
, 0, offsetof(typeof(*aux
), orig_idx
));
11402 static int do_check_common(struct bpf_verifier_env
*env
, int subprog
)
11404 bool pop_log
= !(env
->log
.level
& BPF_LOG_LEVEL2
);
11405 struct bpf_verifier_state
*state
;
11406 struct bpf_reg_state
*regs
;
11409 env
->prev_linfo
= NULL
;
11412 state
= kzalloc(sizeof(struct bpf_verifier_state
), GFP_KERNEL
);
11415 state
->curframe
= 0;
11416 state
->speculative
= false;
11417 state
->branches
= 1;
11418 state
->frame
[0] = kzalloc(sizeof(struct bpf_func_state
), GFP_KERNEL
);
11419 if (!state
->frame
[0]) {
11423 env
->cur_state
= state
;
11424 init_func_state(env
, state
->frame
[0],
11425 BPF_MAIN_FUNC
/* callsite */,
11429 regs
= state
->frame
[state
->curframe
]->regs
;
11430 if (subprog
|| env
->prog
->type
== BPF_PROG_TYPE_EXT
) {
11431 ret
= btf_prepare_func_args(env
, subprog
, regs
);
11434 for (i
= BPF_REG_1
; i
<= BPF_REG_5
; i
++) {
11435 if (regs
[i
].type
== PTR_TO_CTX
)
11436 mark_reg_known_zero(env
, regs
, i
);
11437 else if (regs
[i
].type
== SCALAR_VALUE
)
11438 mark_reg_unknown(env
, regs
, i
);
11441 /* 1st arg to a function */
11442 regs
[BPF_REG_1
].type
= PTR_TO_CTX
;
11443 mark_reg_known_zero(env
, regs
, BPF_REG_1
);
11444 ret
= btf_check_func_arg_match(env
, subprog
, regs
);
11445 if (ret
== -EFAULT
)
11446 /* unlikely verifier bug. abort.
11447 * ret == 0 and ret < 0 are sadly acceptable for
11448 * main() function due to backward compatibility.
11449 * Like socket filter program may be written as:
11450 * int bpf_prog(struct pt_regs *ctx)
11451 * and never dereference that ctx in the program.
11452 * 'struct pt_regs' is a type mismatch for socket
11453 * filter that should be using 'struct __sk_buff'.
11458 ret
= do_check(env
);
11460 /* check for NULL is necessary, since cur_state can be freed inside
11461 * do_check() under memory pressure.
11463 if (env
->cur_state
) {
11464 free_verifier_state(env
->cur_state
, true);
11465 env
->cur_state
= NULL
;
11467 while (!pop_stack(env
, NULL
, NULL
, false));
11468 if (!ret
&& pop_log
)
11469 bpf_vlog_reset(&env
->log
, 0);
11472 /* clean aux data in case subprog was rejected */
11473 sanitize_insn_aux_data(env
);
11477 /* Verify all global functions in a BPF program one by one based on their BTF.
11478 * All global functions must pass verification. Otherwise the whole program is rejected.
11489 * foo() will be verified first for R1=any_scalar_value. During verification it
11490 * will be assumed that bar() already verified successfully and call to bar()
11491 * from foo() will be checked for type match only. Later bar() will be verified
11492 * independently to check that it's safe for R1=any_scalar_value.
11494 static int do_check_subprogs(struct bpf_verifier_env
*env
)
11496 struct bpf_prog_aux
*aux
= env
->prog
->aux
;
11499 if (!aux
->func_info
)
11502 for (i
= 1; i
< env
->subprog_cnt
; i
++) {
11503 if (aux
->func_info_aux
[i
].linkage
!= BTF_FUNC_GLOBAL
)
11505 env
->insn_idx
= env
->subprog_info
[i
].start
;
11506 WARN_ON_ONCE(env
->insn_idx
== 0);
11507 ret
= do_check_common(env
, i
);
11510 } else if (env
->log
.level
& BPF_LOG_LEVEL
) {
11512 "Func#%d is safe for any args that match its prototype\n",
11519 static int do_check_main(struct bpf_verifier_env
*env
)
11524 ret
= do_check_common(env
, 0);
11526 env
->prog
->aux
->stack_depth
= env
->subprog_info
[0].stack_depth
;
11531 static void print_verification_stats(struct bpf_verifier_env
*env
)
11535 if (env
->log
.level
& BPF_LOG_STATS
) {
11536 verbose(env
, "verification time %lld usec\n",
11537 div_u64(env
->verification_time
, 1000));
11538 verbose(env
, "stack depth ");
11539 for (i
= 0; i
< env
->subprog_cnt
; i
++) {
11540 u32 depth
= env
->subprog_info
[i
].stack_depth
;
11542 verbose(env
, "%d", depth
);
11543 if (i
+ 1 < env
->subprog_cnt
)
11546 verbose(env
, "\n");
11548 verbose(env
, "processed %d insns (limit %d) max_states_per_insn %d "
11549 "total_states %d peak_states %d mark_read %d\n",
11550 env
->insn_processed
, BPF_COMPLEXITY_LIMIT_INSNS
,
11551 env
->max_states_per_insn
, env
->total_states
,
11552 env
->peak_states
, env
->longest_mark_read_walk
);
11555 static int check_struct_ops_btf_id(struct bpf_verifier_env
*env
)
11557 const struct btf_type
*t
, *func_proto
;
11558 const struct bpf_struct_ops
*st_ops
;
11559 const struct btf_member
*member
;
11560 struct bpf_prog
*prog
= env
->prog
;
11561 u32 btf_id
, member_idx
;
11564 btf_id
= prog
->aux
->attach_btf_id
;
11565 st_ops
= bpf_struct_ops_find(btf_id
);
11567 verbose(env
, "attach_btf_id %u is not a supported struct\n",
11573 member_idx
= prog
->expected_attach_type
;
11574 if (member_idx
>= btf_type_vlen(t
)) {
11575 verbose(env
, "attach to invalid member idx %u of struct %s\n",
11576 member_idx
, st_ops
->name
);
11580 member
= &btf_type_member(t
)[member_idx
];
11581 mname
= btf_name_by_offset(btf_vmlinux
, member
->name_off
);
11582 func_proto
= btf_type_resolve_func_ptr(btf_vmlinux
, member
->type
,
11585 verbose(env
, "attach to invalid member %s(@idx %u) of struct %s\n",
11586 mname
, member_idx
, st_ops
->name
);
11590 if (st_ops
->check_member
) {
11591 int err
= st_ops
->check_member(t
, member
);
11594 verbose(env
, "attach to unsupported member %s of struct %s\n",
11595 mname
, st_ops
->name
);
11600 prog
->aux
->attach_func_proto
= func_proto
;
11601 prog
->aux
->attach_func_name
= mname
;
11602 env
->ops
= st_ops
->verifier_ops
;
11606 #define SECURITY_PREFIX "security_"
11608 static int check_attach_modify_return(unsigned long addr
, const char *func_name
)
11610 if (within_error_injection_list(addr
) ||
11611 !strncmp(SECURITY_PREFIX
, func_name
, sizeof(SECURITY_PREFIX
) - 1))
11617 /* list of non-sleepable functions that are otherwise on
11618 * ALLOW_ERROR_INJECTION list
11620 BTF_SET_START(btf_non_sleepable_error_inject
)
11621 /* Three functions below can be called from sleepable and non-sleepable context.
11622 * Assume non-sleepable from bpf safety point of view.
11624 BTF_ID(func
, __add_to_page_cache_locked
)
11625 BTF_ID(func
, should_fail_alloc_page
)
11626 BTF_ID(func
, should_failslab
)
11627 BTF_SET_END(btf_non_sleepable_error_inject
)
11629 static int check_non_sleepable_error_inject(u32 btf_id
)
11631 return btf_id_set_contains(&btf_non_sleepable_error_inject
, btf_id
);
11634 int bpf_check_attach_target(struct bpf_verifier_log
*log
,
11635 const struct bpf_prog
*prog
,
11636 const struct bpf_prog
*tgt_prog
,
11638 struct bpf_attach_target_info
*tgt_info
)
11640 bool prog_extension
= prog
->type
== BPF_PROG_TYPE_EXT
;
11641 const char prefix
[] = "btf_trace_";
11642 int ret
= 0, subprog
= -1, i
;
11643 const struct btf_type
*t
;
11644 bool conservative
= true;
11650 bpf_log(log
, "Tracing programs must provide btf_id\n");
11653 btf
= tgt_prog
? tgt_prog
->aux
->btf
: prog
->aux
->attach_btf
;
11656 "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
11659 t
= btf_type_by_id(btf
, btf_id
);
11661 bpf_log(log
, "attach_btf_id %u is invalid\n", btf_id
);
11664 tname
= btf_name_by_offset(btf
, t
->name_off
);
11666 bpf_log(log
, "attach_btf_id %u doesn't have a name\n", btf_id
);
11670 struct bpf_prog_aux
*aux
= tgt_prog
->aux
;
11672 for (i
= 0; i
< aux
->func_info_cnt
; i
++)
11673 if (aux
->func_info
[i
].type_id
== btf_id
) {
11677 if (subprog
== -1) {
11678 bpf_log(log
, "Subprog %s doesn't exist\n", tname
);
11681 conservative
= aux
->func_info_aux
[subprog
].unreliable
;
11682 if (prog_extension
) {
11683 if (conservative
) {
11685 "Cannot replace static functions\n");
11688 if (!prog
->jit_requested
) {
11690 "Extension programs should be JITed\n");
11694 if (!tgt_prog
->jited
) {
11695 bpf_log(log
, "Can attach to only JITed progs\n");
11698 if (tgt_prog
->type
== prog
->type
) {
11699 /* Cannot fentry/fexit another fentry/fexit program.
11700 * Cannot attach program extension to another extension.
11701 * It's ok to attach fentry/fexit to extension program.
11703 bpf_log(log
, "Cannot recursively attach\n");
11706 if (tgt_prog
->type
== BPF_PROG_TYPE_TRACING
&&
11708 (tgt_prog
->expected_attach_type
== BPF_TRACE_FENTRY
||
11709 tgt_prog
->expected_attach_type
== BPF_TRACE_FEXIT
)) {
11710 /* Program extensions can extend all program types
11711 * except fentry/fexit. The reason is the following.
11712 * The fentry/fexit programs are used for performance
11713 * analysis, stats and can be attached to any program
11714 * type except themselves. When extension program is
11715 * replacing XDP function it is necessary to allow
11716 * performance analysis of all functions. Both original
11717 * XDP program and its program extension. Hence
11718 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
11719 * allowed. If extending of fentry/fexit was allowed it
11720 * would be possible to create long call chain
11721 * fentry->extension->fentry->extension beyond
11722 * reasonable stack size. Hence extending fentry is not
11725 bpf_log(log
, "Cannot extend fentry/fexit\n");
11729 if (prog_extension
) {
11730 bpf_log(log
, "Cannot replace kernel functions\n");
11735 switch (prog
->expected_attach_type
) {
11736 case BPF_TRACE_RAW_TP
:
11739 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
11742 if (!btf_type_is_typedef(t
)) {
11743 bpf_log(log
, "attach_btf_id %u is not a typedef\n",
11747 if (strncmp(prefix
, tname
, sizeof(prefix
) - 1)) {
11748 bpf_log(log
, "attach_btf_id %u points to wrong type name %s\n",
11752 tname
+= sizeof(prefix
) - 1;
11753 t
= btf_type_by_id(btf
, t
->type
);
11754 if (!btf_type_is_ptr(t
))
11755 /* should never happen in valid vmlinux build */
11757 t
= btf_type_by_id(btf
, t
->type
);
11758 if (!btf_type_is_func_proto(t
))
11759 /* should never happen in valid vmlinux build */
11763 case BPF_TRACE_ITER
:
11764 if (!btf_type_is_func(t
)) {
11765 bpf_log(log
, "attach_btf_id %u is not a function\n",
11769 t
= btf_type_by_id(btf
, t
->type
);
11770 if (!btf_type_is_func_proto(t
))
11772 ret
= btf_distill_func_proto(log
, btf
, t
, tname
, &tgt_info
->fmodel
);
11777 if (!prog_extension
)
11780 case BPF_MODIFY_RETURN
:
11782 case BPF_TRACE_FENTRY
:
11783 case BPF_TRACE_FEXIT
:
11784 if (!btf_type_is_func(t
)) {
11785 bpf_log(log
, "attach_btf_id %u is not a function\n",
11789 if (prog_extension
&&
11790 btf_check_type_match(log
, prog
, btf
, t
))
11792 t
= btf_type_by_id(btf
, t
->type
);
11793 if (!btf_type_is_func_proto(t
))
11796 if ((prog
->aux
->saved_dst_prog_type
|| prog
->aux
->saved_dst_attach_type
) &&
11797 (!tgt_prog
|| prog
->aux
->saved_dst_prog_type
!= tgt_prog
->type
||
11798 prog
->aux
->saved_dst_attach_type
!= tgt_prog
->expected_attach_type
))
11801 if (tgt_prog
&& conservative
)
11804 ret
= btf_distill_func_proto(log
, btf
, t
, tname
, &tgt_info
->fmodel
);
11810 addr
= (long) tgt_prog
->bpf_func
;
11812 addr
= (long) tgt_prog
->aux
->func
[subprog
]->bpf_func
;
11814 addr
= kallsyms_lookup_name(tname
);
11817 "The address of function %s cannot be found\n",
11823 if (prog
->aux
->sleepable
) {
11825 switch (prog
->type
) {
11826 case BPF_PROG_TYPE_TRACING
:
11827 /* fentry/fexit/fmod_ret progs can be sleepable only if they are
11828 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
11830 if (!check_non_sleepable_error_inject(btf_id
) &&
11831 within_error_injection_list(addr
))
11834 case BPF_PROG_TYPE_LSM
:
11835 /* LSM progs check that they are attached to bpf_lsm_*() funcs.
11836 * Only some of them are sleepable.
11838 if (bpf_lsm_is_sleepable_hook(btf_id
))
11845 bpf_log(log
, "%s is not sleepable\n", tname
);
11848 } else if (prog
->expected_attach_type
== BPF_MODIFY_RETURN
) {
11850 bpf_log(log
, "can't modify return codes of BPF programs\n");
11853 ret
= check_attach_modify_return(addr
, tname
);
11855 bpf_log(log
, "%s() is not modifiable\n", tname
);
11862 tgt_info
->tgt_addr
= addr
;
11863 tgt_info
->tgt_name
= tname
;
11864 tgt_info
->tgt_type
= t
;
11868 static int check_attach_btf_id(struct bpf_verifier_env
*env
)
11870 struct bpf_prog
*prog
= env
->prog
;
11871 struct bpf_prog
*tgt_prog
= prog
->aux
->dst_prog
;
11872 struct bpf_attach_target_info tgt_info
= {};
11873 u32 btf_id
= prog
->aux
->attach_btf_id
;
11874 struct bpf_trampoline
*tr
;
11878 if (prog
->aux
->sleepable
&& prog
->type
!= BPF_PROG_TYPE_TRACING
&&
11879 prog
->type
!= BPF_PROG_TYPE_LSM
) {
11880 verbose(env
, "Only fentry/fexit/fmod_ret and lsm programs can be sleepable\n");
11884 if (prog
->type
== BPF_PROG_TYPE_STRUCT_OPS
)
11885 return check_struct_ops_btf_id(env
);
11887 if (prog
->type
!= BPF_PROG_TYPE_TRACING
&&
11888 prog
->type
!= BPF_PROG_TYPE_LSM
&&
11889 prog
->type
!= BPF_PROG_TYPE_EXT
)
11892 ret
= bpf_check_attach_target(&env
->log
, prog
, tgt_prog
, btf_id
, &tgt_info
);
11896 if (tgt_prog
&& prog
->type
== BPF_PROG_TYPE_EXT
) {
11897 /* to make freplace equivalent to their targets, they need to
11898 * inherit env->ops and expected_attach_type for the rest of the
11901 env
->ops
= bpf_verifier_ops
[tgt_prog
->type
];
11902 prog
->expected_attach_type
= tgt_prog
->expected_attach_type
;
11905 /* store info about the attachment target that will be used later */
11906 prog
->aux
->attach_func_proto
= tgt_info
.tgt_type
;
11907 prog
->aux
->attach_func_name
= tgt_info
.tgt_name
;
11910 prog
->aux
->saved_dst_prog_type
= tgt_prog
->type
;
11911 prog
->aux
->saved_dst_attach_type
= tgt_prog
->expected_attach_type
;
11914 if (prog
->expected_attach_type
== BPF_TRACE_RAW_TP
) {
11915 prog
->aux
->attach_btf_trace
= true;
11917 } else if (prog
->expected_attach_type
== BPF_TRACE_ITER
) {
11918 if (!bpf_iter_prog_supported(prog
))
11923 if (prog
->type
== BPF_PROG_TYPE_LSM
) {
11924 ret
= bpf_lsm_verify_prog(&env
->log
, prog
);
11929 key
= bpf_trampoline_compute_key(tgt_prog
, prog
->aux
->attach_btf
, btf_id
);
11930 tr
= bpf_trampoline_get(key
, &tgt_info
);
11934 prog
->aux
->dst_trampoline
= tr
;
11938 struct btf
*bpf_get_btf_vmlinux(void)
11940 if (!btf_vmlinux
&& IS_ENABLED(CONFIG_DEBUG_INFO_BTF
)) {
11941 mutex_lock(&bpf_verifier_lock
);
11943 btf_vmlinux
= btf_parse_vmlinux();
11944 mutex_unlock(&bpf_verifier_lock
);
11946 return btf_vmlinux
;
11949 int bpf_check(struct bpf_prog
**prog
, union bpf_attr
*attr
,
11950 union bpf_attr __user
*uattr
)
11952 u64 start_time
= ktime_get_ns();
11953 struct bpf_verifier_env
*env
;
11954 struct bpf_verifier_log
*log
;
11955 int i
, len
, ret
= -EINVAL
;
11958 /* no program is valid */
11959 if (ARRAY_SIZE(bpf_verifier_ops
) == 0)
11962 /* 'struct bpf_verifier_env' can be global, but since it's not small,
11963 * allocate/free it every time bpf_check() is called
11965 env
= kzalloc(sizeof(struct bpf_verifier_env
), GFP_KERNEL
);
11970 len
= (*prog
)->len
;
11971 env
->insn_aux_data
=
11972 vzalloc(array_size(sizeof(struct bpf_insn_aux_data
), len
));
11974 if (!env
->insn_aux_data
)
11976 for (i
= 0; i
< len
; i
++)
11977 env
->insn_aux_data
[i
].orig_idx
= i
;
11979 env
->ops
= bpf_verifier_ops
[env
->prog
->type
];
11980 is_priv
= bpf_capable();
11982 bpf_get_btf_vmlinux();
11984 /* grab the mutex to protect few globals used by verifier */
11986 mutex_lock(&bpf_verifier_lock
);
11988 if (attr
->log_level
|| attr
->log_buf
|| attr
->log_size
) {
11989 /* user requested verbose verifier output
11990 * and supplied buffer to store the verification trace
11992 log
->level
= attr
->log_level
;
11993 log
->ubuf
= (char __user
*) (unsigned long) attr
->log_buf
;
11994 log
->len_total
= attr
->log_size
;
11997 /* log attributes have to be sane */
11998 if (log
->len_total
< 128 || log
->len_total
> UINT_MAX
>> 2 ||
11999 !log
->level
|| !log
->ubuf
|| log
->level
& ~BPF_LOG_MASK
)
12003 if (IS_ERR(btf_vmlinux
)) {
12004 /* Either gcc or pahole or kernel are broken. */
12005 verbose(env
, "in-kernel BTF is malformed\n");
12006 ret
= PTR_ERR(btf_vmlinux
);
12007 goto skip_full_check
;
12010 env
->strict_alignment
= !!(attr
->prog_flags
& BPF_F_STRICT_ALIGNMENT
);
12011 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS
))
12012 env
->strict_alignment
= true;
12013 if (attr
->prog_flags
& BPF_F_ANY_ALIGNMENT
)
12014 env
->strict_alignment
= false;
12016 env
->allow_ptr_leaks
= bpf_allow_ptr_leaks();
12017 env
->allow_ptr_to_map_access
= bpf_allow_ptr_to_map_access();
12018 env
->bypass_spec_v1
= bpf_bypass_spec_v1();
12019 env
->bypass_spec_v4
= bpf_bypass_spec_v4();
12020 env
->bpf_capable
= bpf_capable();
12023 env
->test_state_freq
= attr
->prog_flags
& BPF_F_TEST_STATE_FREQ
;
12025 if (bpf_prog_is_dev_bound(env
->prog
->aux
)) {
12026 ret
= bpf_prog_offload_verifier_prep(env
->prog
);
12028 goto skip_full_check
;
12031 env
->explored_states
= kvcalloc(state_htab_size(env
),
12032 sizeof(struct bpf_verifier_state_list
*),
12035 if (!env
->explored_states
)
12036 goto skip_full_check
;
12038 ret
= check_subprogs(env
);
12040 goto skip_full_check
;
12042 ret
= check_btf_info(env
, attr
, uattr
);
12044 goto skip_full_check
;
12046 ret
= check_attach_btf_id(env
);
12048 goto skip_full_check
;
12050 ret
= resolve_pseudo_ldimm64(env
);
12052 goto skip_full_check
;
12054 ret
= check_cfg(env
);
12056 goto skip_full_check
;
12058 ret
= do_check_subprogs(env
);
12059 ret
= ret
?: do_check_main(env
);
12061 if (ret
== 0 && bpf_prog_is_dev_bound(env
->prog
->aux
))
12062 ret
= bpf_prog_offload_finalize(env
);
12065 kvfree(env
->explored_states
);
12068 ret
= check_max_stack_depth(env
);
12070 /* instruction rewrites happen after this point */
12073 opt_hard_wire_dead_code_branches(env
);
12075 ret
= opt_remove_dead_code(env
);
12077 ret
= opt_remove_nops(env
);
12080 sanitize_dead_code(env
);
12084 /* program is valid, convert *(u32*)(ctx + off) accesses */
12085 ret
= convert_ctx_accesses(env
);
12088 ret
= fixup_bpf_calls(env
);
12090 /* do 32-bit optimization after insn patching has done so those patched
12091 * insns could be handled correctly.
12093 if (ret
== 0 && !bpf_prog_is_dev_bound(env
->prog
->aux
)) {
12094 ret
= opt_subreg_zext_lo32_rnd_hi32(env
, attr
);
12095 env
->prog
->aux
->verifier_zext
= bpf_jit_needs_zext() ? !ret
12100 ret
= fixup_call_args(env
);
12102 env
->verification_time
= ktime_get_ns() - start_time
;
12103 print_verification_stats(env
);
12105 if (log
->level
&& bpf_verifier_log_full(log
))
12107 if (log
->level
&& !log
->ubuf
) {
12109 goto err_release_maps
;
12112 if (ret
== 0 && env
->used_map_cnt
) {
12113 /* if program passed verifier, update used_maps in bpf_prog_info */
12114 env
->prog
->aux
->used_maps
= kmalloc_array(env
->used_map_cnt
,
12115 sizeof(env
->used_maps
[0]),
12118 if (!env
->prog
->aux
->used_maps
) {
12120 goto err_release_maps
;
12123 memcpy(env
->prog
->aux
->used_maps
, env
->used_maps
,
12124 sizeof(env
->used_maps
[0]) * env
->used_map_cnt
);
12125 env
->prog
->aux
->used_map_cnt
= env
->used_map_cnt
;
12127 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
12128 * bpf_ld_imm64 instructions
12130 convert_pseudo_ld_imm64(env
);
12134 adjust_btf_func(env
);
12137 if (!env
->prog
->aux
->used_maps
)
12138 /* if we didn't copy map pointers into bpf_prog_info, release
12139 * them now. Otherwise free_used_maps() will release them.
12143 /* extension progs temporarily inherit the attach_type of their targets
12144 for verification purposes, so set it back to zero before returning
12146 if (env
->prog
->type
== BPF_PROG_TYPE_EXT
)
12147 env
->prog
->expected_attach_type
= 0;
12152 mutex_unlock(&bpf_verifier_lock
);
12153 vfree(env
->insn_aux_data
);