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 return a
> U32_MIN
&& a
< U32_MAX
;
1310 static void __reg_combine_64_into_32(struct bpf_reg_state
*reg
)
1312 __mark_reg32_unbounded(reg
);
1314 if (__reg64_bound_s32(reg
->smin_value
) && __reg64_bound_s32(reg
->smax_value
)) {
1315 reg
->s32_min_value
= (s32
)reg
->smin_value
;
1316 reg
->s32_max_value
= (s32
)reg
->smax_value
;
1318 if (__reg64_bound_u32(reg
->umin_value
) && __reg64_bound_u32(reg
->umax_value
)) {
1319 reg
->u32_min_value
= (u32
)reg
->umin_value
;
1320 reg
->u32_max_value
= (u32
)reg
->umax_value
;
1323 /* Intersecting with the old var_off might have improved our bounds
1324 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1325 * then new var_off is (0; 0x7f...fc) which improves our umax.
1327 __reg_deduce_bounds(reg
);
1328 __reg_bound_offset(reg
);
1329 __update_reg_bounds(reg
);
1332 /* Mark a register as having a completely unknown (scalar) value. */
1333 static void __mark_reg_unknown(const struct bpf_verifier_env
*env
,
1334 struct bpf_reg_state
*reg
)
1337 * Clear type, id, off, and union(map_ptr, range) and
1338 * padding between 'type' and union
1340 memset(reg
, 0, offsetof(struct bpf_reg_state
, var_off
));
1341 reg
->type
= SCALAR_VALUE
;
1342 reg
->var_off
= tnum_unknown
;
1344 reg
->precise
= env
->subprog_cnt
> 1 || !env
->bpf_capable
;
1345 __mark_reg_unbounded(reg
);
1348 static void mark_reg_unknown(struct bpf_verifier_env
*env
,
1349 struct bpf_reg_state
*regs
, u32 regno
)
1351 if (WARN_ON(regno
>= MAX_BPF_REG
)) {
1352 verbose(env
, "mark_reg_unknown(regs, %u)\n", regno
);
1353 /* Something bad happened, let's kill all regs except FP */
1354 for (regno
= 0; regno
< BPF_REG_FP
; regno
++)
1355 __mark_reg_not_init(env
, regs
+ regno
);
1358 __mark_reg_unknown(env
, regs
+ regno
);
1361 static void __mark_reg_not_init(const struct bpf_verifier_env
*env
,
1362 struct bpf_reg_state
*reg
)
1364 __mark_reg_unknown(env
, reg
);
1365 reg
->type
= NOT_INIT
;
1368 static void mark_reg_not_init(struct bpf_verifier_env
*env
,
1369 struct bpf_reg_state
*regs
, u32 regno
)
1371 if (WARN_ON(regno
>= MAX_BPF_REG
)) {
1372 verbose(env
, "mark_reg_not_init(regs, %u)\n", regno
);
1373 /* Something bad happened, let's kill all regs except FP */
1374 for (regno
= 0; regno
< BPF_REG_FP
; regno
++)
1375 __mark_reg_not_init(env
, regs
+ regno
);
1378 __mark_reg_not_init(env
, regs
+ regno
);
1381 static void mark_btf_ld_reg(struct bpf_verifier_env
*env
,
1382 struct bpf_reg_state
*regs
, u32 regno
,
1383 enum bpf_reg_type reg_type
,
1384 struct btf
*btf
, u32 btf_id
)
1386 if (reg_type
== SCALAR_VALUE
) {
1387 mark_reg_unknown(env
, regs
, regno
);
1390 mark_reg_known_zero(env
, regs
, regno
);
1391 regs
[regno
].type
= PTR_TO_BTF_ID
;
1392 regs
[regno
].btf
= btf
;
1393 regs
[regno
].btf_id
= btf_id
;
1396 #define DEF_NOT_SUBREG (0)
1397 static void init_reg_state(struct bpf_verifier_env
*env
,
1398 struct bpf_func_state
*state
)
1400 struct bpf_reg_state
*regs
= state
->regs
;
1403 for (i
= 0; i
< MAX_BPF_REG
; i
++) {
1404 mark_reg_not_init(env
, regs
, i
);
1405 regs
[i
].live
= REG_LIVE_NONE
;
1406 regs
[i
].parent
= NULL
;
1407 regs
[i
].subreg_def
= DEF_NOT_SUBREG
;
1411 regs
[BPF_REG_FP
].type
= PTR_TO_STACK
;
1412 mark_reg_known_zero(env
, regs
, BPF_REG_FP
);
1413 regs
[BPF_REG_FP
].frameno
= state
->frameno
;
1416 #define BPF_MAIN_FUNC (-1)
1417 static void init_func_state(struct bpf_verifier_env
*env
,
1418 struct bpf_func_state
*state
,
1419 int callsite
, int frameno
, int subprogno
)
1421 state
->callsite
= callsite
;
1422 state
->frameno
= frameno
;
1423 state
->subprogno
= subprogno
;
1424 init_reg_state(env
, state
);
1428 SRC_OP
, /* register is used as source operand */
1429 DST_OP
, /* register is used as destination operand */
1430 DST_OP_NO_MARK
/* same as above, check only, don't mark */
1433 static int cmp_subprogs(const void *a
, const void *b
)
1435 return ((struct bpf_subprog_info
*)a
)->start
-
1436 ((struct bpf_subprog_info
*)b
)->start
;
1439 static int find_subprog(struct bpf_verifier_env
*env
, int off
)
1441 struct bpf_subprog_info
*p
;
1443 p
= bsearch(&off
, env
->subprog_info
, env
->subprog_cnt
,
1444 sizeof(env
->subprog_info
[0]), cmp_subprogs
);
1447 return p
- env
->subprog_info
;
1451 static int add_subprog(struct bpf_verifier_env
*env
, int off
)
1453 int insn_cnt
= env
->prog
->len
;
1456 if (off
>= insn_cnt
|| off
< 0) {
1457 verbose(env
, "call to invalid destination\n");
1460 ret
= find_subprog(env
, off
);
1463 if (env
->subprog_cnt
>= BPF_MAX_SUBPROGS
) {
1464 verbose(env
, "too many subprograms\n");
1467 env
->subprog_info
[env
->subprog_cnt
++].start
= off
;
1468 sort(env
->subprog_info
, env
->subprog_cnt
,
1469 sizeof(env
->subprog_info
[0]), cmp_subprogs
, NULL
);
1473 static int check_subprogs(struct bpf_verifier_env
*env
)
1475 int i
, ret
, subprog_start
, subprog_end
, off
, cur_subprog
= 0;
1476 struct bpf_subprog_info
*subprog
= env
->subprog_info
;
1477 struct bpf_insn
*insn
= env
->prog
->insnsi
;
1478 int insn_cnt
= env
->prog
->len
;
1480 /* Add entry function. */
1481 ret
= add_subprog(env
, 0);
1485 /* determine subprog starts. The end is one before the next starts */
1486 for (i
= 0; i
< insn_cnt
; i
++) {
1487 if (insn
[i
].code
!= (BPF_JMP
| BPF_CALL
))
1489 if (insn
[i
].src_reg
!= BPF_PSEUDO_CALL
)
1491 if (!env
->bpf_capable
) {
1493 "function calls to other bpf functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
1496 ret
= add_subprog(env
, i
+ insn
[i
].imm
+ 1);
1501 /* Add a fake 'exit' subprog which could simplify subprog iteration
1502 * logic. 'subprog_cnt' should not be increased.
1504 subprog
[env
->subprog_cnt
].start
= insn_cnt
;
1506 if (env
->log
.level
& BPF_LOG_LEVEL2
)
1507 for (i
= 0; i
< env
->subprog_cnt
; i
++)
1508 verbose(env
, "func#%d @%d\n", i
, subprog
[i
].start
);
1510 /* now check that all jumps are within the same subprog */
1511 subprog_start
= subprog
[cur_subprog
].start
;
1512 subprog_end
= subprog
[cur_subprog
+ 1].start
;
1513 for (i
= 0; i
< insn_cnt
; i
++) {
1514 u8 code
= insn
[i
].code
;
1516 if (code
== (BPF_JMP
| BPF_CALL
) &&
1517 insn
[i
].imm
== BPF_FUNC_tail_call
&&
1518 insn
[i
].src_reg
!= BPF_PSEUDO_CALL
)
1519 subprog
[cur_subprog
].has_tail_call
= true;
1520 if (BPF_CLASS(code
) == BPF_LD
&&
1521 (BPF_MODE(code
) == BPF_ABS
|| BPF_MODE(code
) == BPF_IND
))
1522 subprog
[cur_subprog
].has_ld_abs
= true;
1523 if (BPF_CLASS(code
) != BPF_JMP
&& BPF_CLASS(code
) != BPF_JMP32
)
1525 if (BPF_OP(code
) == BPF_EXIT
|| BPF_OP(code
) == BPF_CALL
)
1527 off
= i
+ insn
[i
].off
+ 1;
1528 if (off
< subprog_start
|| off
>= subprog_end
) {
1529 verbose(env
, "jump out of range from insn %d to %d\n", i
, off
);
1533 if (i
== subprog_end
- 1) {
1534 /* to avoid fall-through from one subprog into another
1535 * the last insn of the subprog should be either exit
1536 * or unconditional jump back
1538 if (code
!= (BPF_JMP
| BPF_EXIT
) &&
1539 code
!= (BPF_JMP
| BPF_JA
)) {
1540 verbose(env
, "last insn is not an exit or jmp\n");
1543 subprog_start
= subprog_end
;
1545 if (cur_subprog
< env
->subprog_cnt
)
1546 subprog_end
= subprog
[cur_subprog
+ 1].start
;
1552 /* Parentage chain of this register (or stack slot) should take care of all
1553 * issues like callee-saved registers, stack slot allocation time, etc.
1555 static int mark_reg_read(struct bpf_verifier_env
*env
,
1556 const struct bpf_reg_state
*state
,
1557 struct bpf_reg_state
*parent
, u8 flag
)
1559 bool writes
= parent
== state
->parent
; /* Observe write marks */
1563 /* if read wasn't screened by an earlier write ... */
1564 if (writes
&& state
->live
& REG_LIVE_WRITTEN
)
1566 if (parent
->live
& REG_LIVE_DONE
) {
1567 verbose(env
, "verifier BUG type %s var_off %lld off %d\n",
1568 reg_type_str
[parent
->type
],
1569 parent
->var_off
.value
, parent
->off
);
1572 /* The first condition is more likely to be true than the
1573 * second, checked it first.
1575 if ((parent
->live
& REG_LIVE_READ
) == flag
||
1576 parent
->live
& REG_LIVE_READ64
)
1577 /* The parentage chain never changes and
1578 * this parent was already marked as LIVE_READ.
1579 * There is no need to keep walking the chain again and
1580 * keep re-marking all parents as LIVE_READ.
1581 * This case happens when the same register is read
1582 * multiple times without writes into it in-between.
1583 * Also, if parent has the stronger REG_LIVE_READ64 set,
1584 * then no need to set the weak REG_LIVE_READ32.
1587 /* ... then we depend on parent's value */
1588 parent
->live
|= flag
;
1589 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
1590 if (flag
== REG_LIVE_READ64
)
1591 parent
->live
&= ~REG_LIVE_READ32
;
1593 parent
= state
->parent
;
1598 if (env
->longest_mark_read_walk
< cnt
)
1599 env
->longest_mark_read_walk
= cnt
;
1603 /* This function is supposed to be used by the following 32-bit optimization
1604 * code only. It returns TRUE if the source or destination register operates
1605 * on 64-bit, otherwise return FALSE.
1607 static bool is_reg64(struct bpf_verifier_env
*env
, struct bpf_insn
*insn
,
1608 u32 regno
, struct bpf_reg_state
*reg
, enum reg_arg_type t
)
1613 class = BPF_CLASS(code
);
1615 if (class == BPF_JMP
) {
1616 /* BPF_EXIT for "main" will reach here. Return TRUE
1621 if (op
== BPF_CALL
) {
1622 /* BPF to BPF call will reach here because of marking
1623 * caller saved clobber with DST_OP_NO_MARK for which we
1624 * don't care the register def because they are anyway
1625 * marked as NOT_INIT already.
1627 if (insn
->src_reg
== BPF_PSEUDO_CALL
)
1629 /* Helper call will reach here because of arg type
1630 * check, conservatively return TRUE.
1639 if (class == BPF_ALU64
|| class == BPF_JMP
||
1640 /* BPF_END always use BPF_ALU class. */
1641 (class == BPF_ALU
&& op
== BPF_END
&& insn
->imm
== 64))
1644 if (class == BPF_ALU
|| class == BPF_JMP32
)
1647 if (class == BPF_LDX
) {
1649 return BPF_SIZE(code
) == BPF_DW
;
1650 /* LDX source must be ptr. */
1654 if (class == BPF_STX
) {
1655 if (reg
->type
!= SCALAR_VALUE
)
1657 return BPF_SIZE(code
) == BPF_DW
;
1660 if (class == BPF_LD
) {
1661 u8 mode
= BPF_MODE(code
);
1664 if (mode
== BPF_IMM
)
1667 /* Both LD_IND and LD_ABS return 32-bit data. */
1671 /* Implicit ctx ptr. */
1672 if (regno
== BPF_REG_6
)
1675 /* Explicit source could be any width. */
1679 if (class == BPF_ST
)
1680 /* The only source register for BPF_ST is a ptr. */
1683 /* Conservatively return true at default. */
1687 /* Return TRUE if INSN doesn't have explicit value define. */
1688 static bool insn_no_def(struct bpf_insn
*insn
)
1690 u8
class = BPF_CLASS(insn
->code
);
1692 return (class == BPF_JMP
|| class == BPF_JMP32
||
1693 class == BPF_STX
|| class == BPF_ST
);
1696 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
1697 static bool insn_has_def32(struct bpf_verifier_env
*env
, struct bpf_insn
*insn
)
1699 if (insn_no_def(insn
))
1702 return !is_reg64(env
, insn
, insn
->dst_reg
, NULL
, DST_OP
);
1705 static void mark_insn_zext(struct bpf_verifier_env
*env
,
1706 struct bpf_reg_state
*reg
)
1708 s32 def_idx
= reg
->subreg_def
;
1710 if (def_idx
== DEF_NOT_SUBREG
)
1713 env
->insn_aux_data
[def_idx
- 1].zext_dst
= true;
1714 /* The dst will be zero extended, so won't be sub-register anymore. */
1715 reg
->subreg_def
= DEF_NOT_SUBREG
;
1718 static int check_reg_arg(struct bpf_verifier_env
*env
, u32 regno
,
1719 enum reg_arg_type t
)
1721 struct bpf_verifier_state
*vstate
= env
->cur_state
;
1722 struct bpf_func_state
*state
= vstate
->frame
[vstate
->curframe
];
1723 struct bpf_insn
*insn
= env
->prog
->insnsi
+ env
->insn_idx
;
1724 struct bpf_reg_state
*reg
, *regs
= state
->regs
;
1727 if (regno
>= MAX_BPF_REG
) {
1728 verbose(env
, "R%d is invalid\n", regno
);
1733 rw64
= is_reg64(env
, insn
, regno
, reg
, t
);
1735 /* check whether register used as source operand can be read */
1736 if (reg
->type
== NOT_INIT
) {
1737 verbose(env
, "R%d !read_ok\n", regno
);
1740 /* We don't need to worry about FP liveness because it's read-only */
1741 if (regno
== BPF_REG_FP
)
1745 mark_insn_zext(env
, reg
);
1747 return mark_reg_read(env
, reg
, reg
->parent
,
1748 rw64
? REG_LIVE_READ64
: REG_LIVE_READ32
);
1750 /* check whether register used as dest operand can be written to */
1751 if (regno
== BPF_REG_FP
) {
1752 verbose(env
, "frame pointer is read only\n");
1755 reg
->live
|= REG_LIVE_WRITTEN
;
1756 reg
->subreg_def
= rw64
? DEF_NOT_SUBREG
: env
->insn_idx
+ 1;
1758 mark_reg_unknown(env
, regs
, regno
);
1763 /* for any branch, call, exit record the history of jmps in the given state */
1764 static int push_jmp_history(struct bpf_verifier_env
*env
,
1765 struct bpf_verifier_state
*cur
)
1767 u32 cnt
= cur
->jmp_history_cnt
;
1768 struct bpf_idx_pair
*p
;
1771 p
= krealloc(cur
->jmp_history
, cnt
* sizeof(*p
), GFP_USER
);
1774 p
[cnt
- 1].idx
= env
->insn_idx
;
1775 p
[cnt
- 1].prev_idx
= env
->prev_insn_idx
;
1776 cur
->jmp_history
= p
;
1777 cur
->jmp_history_cnt
= cnt
;
1781 /* Backtrack one insn at a time. If idx is not at the top of recorded
1782 * history then previous instruction came from straight line execution.
1784 static int get_prev_insn_idx(struct bpf_verifier_state
*st
, int i
,
1789 if (cnt
&& st
->jmp_history
[cnt
- 1].idx
== i
) {
1790 i
= st
->jmp_history
[cnt
- 1].prev_idx
;
1798 /* For given verifier state backtrack_insn() is called from the last insn to
1799 * the first insn. Its purpose is to compute a bitmask of registers and
1800 * stack slots that needs precision in the parent verifier state.
1802 static int backtrack_insn(struct bpf_verifier_env
*env
, int idx
,
1803 u32
*reg_mask
, u64
*stack_mask
)
1805 const struct bpf_insn_cbs cbs
= {
1806 .cb_print
= verbose
,
1807 .private_data
= env
,
1809 struct bpf_insn
*insn
= env
->prog
->insnsi
+ idx
;
1810 u8
class = BPF_CLASS(insn
->code
);
1811 u8 opcode
= BPF_OP(insn
->code
);
1812 u8 mode
= BPF_MODE(insn
->code
);
1813 u32 dreg
= 1u << insn
->dst_reg
;
1814 u32 sreg
= 1u << insn
->src_reg
;
1817 if (insn
->code
== 0)
1819 if (env
->log
.level
& BPF_LOG_LEVEL
) {
1820 verbose(env
, "regs=%x stack=%llx before ", *reg_mask
, *stack_mask
);
1821 verbose(env
, "%d: ", idx
);
1822 print_bpf_insn(&cbs
, insn
, env
->allow_ptr_leaks
);
1825 if (class == BPF_ALU
|| class == BPF_ALU64
) {
1826 if (!(*reg_mask
& dreg
))
1828 if (opcode
== BPF_MOV
) {
1829 if (BPF_SRC(insn
->code
) == BPF_X
) {
1831 * dreg needs precision after this insn
1832 * sreg needs precision before this insn
1838 * dreg needs precision after this insn.
1839 * Corresponding register is already marked
1840 * as precise=true in this verifier state.
1841 * No further markings in parent are necessary
1846 if (BPF_SRC(insn
->code
) == BPF_X
) {
1848 * both dreg and sreg need precision
1853 * dreg still needs precision before this insn
1856 } else if (class == BPF_LDX
) {
1857 if (!(*reg_mask
& dreg
))
1861 /* scalars can only be spilled into stack w/o losing precision.
1862 * Load from any other memory can be zero extended.
1863 * The desire to keep that precision is already indicated
1864 * by 'precise' mark in corresponding register of this state.
1865 * No further tracking necessary.
1867 if (insn
->src_reg
!= BPF_REG_FP
)
1869 if (BPF_SIZE(insn
->code
) != BPF_DW
)
1872 /* dreg = *(u64 *)[fp - off] was a fill from the stack.
1873 * that [fp - off] slot contains scalar that needs to be
1874 * tracked with precision
1876 spi
= (-insn
->off
- 1) / BPF_REG_SIZE
;
1878 verbose(env
, "BUG spi %d\n", spi
);
1879 WARN_ONCE(1, "verifier backtracking bug");
1882 *stack_mask
|= 1ull << spi
;
1883 } else if (class == BPF_STX
|| class == BPF_ST
) {
1884 if (*reg_mask
& dreg
)
1885 /* stx & st shouldn't be using _scalar_ dst_reg
1886 * to access memory. It means backtracking
1887 * encountered a case of pointer subtraction.
1890 /* scalars can only be spilled into stack */
1891 if (insn
->dst_reg
!= BPF_REG_FP
)
1893 if (BPF_SIZE(insn
->code
) != BPF_DW
)
1895 spi
= (-insn
->off
- 1) / BPF_REG_SIZE
;
1897 verbose(env
, "BUG spi %d\n", spi
);
1898 WARN_ONCE(1, "verifier backtracking bug");
1901 if (!(*stack_mask
& (1ull << spi
)))
1903 *stack_mask
&= ~(1ull << spi
);
1904 if (class == BPF_STX
)
1906 } else if (class == BPF_JMP
|| class == BPF_JMP32
) {
1907 if (opcode
== BPF_CALL
) {
1908 if (insn
->src_reg
== BPF_PSEUDO_CALL
)
1910 /* regular helper call sets R0 */
1912 if (*reg_mask
& 0x3f) {
1913 /* if backtracing was looking for registers R1-R5
1914 * they should have been found already.
1916 verbose(env
, "BUG regs %x\n", *reg_mask
);
1917 WARN_ONCE(1, "verifier backtracking bug");
1920 } else if (opcode
== BPF_EXIT
) {
1923 } else if (class == BPF_LD
) {
1924 if (!(*reg_mask
& dreg
))
1927 /* It's ld_imm64 or ld_abs or ld_ind.
1928 * For ld_imm64 no further tracking of precision
1929 * into parent is necessary
1931 if (mode
== BPF_IND
|| mode
== BPF_ABS
)
1932 /* to be analyzed */
1938 /* the scalar precision tracking algorithm:
1939 * . at the start all registers have precise=false.
1940 * . scalar ranges are tracked as normal through alu and jmp insns.
1941 * . once precise value of the scalar register is used in:
1942 * . ptr + scalar alu
1943 * . if (scalar cond K|scalar)
1944 * . helper_call(.., scalar, ...) where ARG_CONST is expected
1945 * backtrack through the verifier states and mark all registers and
1946 * stack slots with spilled constants that these scalar regisers
1947 * should be precise.
1948 * . during state pruning two registers (or spilled stack slots)
1949 * are equivalent if both are not precise.
1951 * Note the verifier cannot simply walk register parentage chain,
1952 * since many different registers and stack slots could have been
1953 * used to compute single precise scalar.
1955 * The approach of starting with precise=true for all registers and then
1956 * backtrack to mark a register as not precise when the verifier detects
1957 * that program doesn't care about specific value (e.g., when helper
1958 * takes register as ARG_ANYTHING parameter) is not safe.
1960 * It's ok to walk single parentage chain of the verifier states.
1961 * It's possible that this backtracking will go all the way till 1st insn.
1962 * All other branches will be explored for needing precision later.
1964 * The backtracking needs to deal with cases like:
1965 * 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)
1968 * if r5 > 0x79f goto pc+7
1969 * R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
1972 * call bpf_perf_event_output#25
1973 * where .arg5_type = ARG_CONST_SIZE_OR_ZERO
1977 * call foo // uses callee's r6 inside to compute r0
1981 * to track above reg_mask/stack_mask needs to be independent for each frame.
1983 * Also if parent's curframe > frame where backtracking started,
1984 * the verifier need to mark registers in both frames, otherwise callees
1985 * may incorrectly prune callers. This is similar to
1986 * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
1988 * For now backtracking falls back into conservative marking.
1990 static void mark_all_scalars_precise(struct bpf_verifier_env
*env
,
1991 struct bpf_verifier_state
*st
)
1993 struct bpf_func_state
*func
;
1994 struct bpf_reg_state
*reg
;
1997 /* big hammer: mark all scalars precise in this path.
1998 * pop_stack may still get !precise scalars.
2000 for (; st
; st
= st
->parent
)
2001 for (i
= 0; i
<= st
->curframe
; i
++) {
2002 func
= st
->frame
[i
];
2003 for (j
= 0; j
< BPF_REG_FP
; j
++) {
2004 reg
= &func
->regs
[j
];
2005 if (reg
->type
!= SCALAR_VALUE
)
2007 reg
->precise
= true;
2009 for (j
= 0; j
< func
->allocated_stack
/ BPF_REG_SIZE
; j
++) {
2010 if (func
->stack
[j
].slot_type
[0] != STACK_SPILL
)
2012 reg
= &func
->stack
[j
].spilled_ptr
;
2013 if (reg
->type
!= SCALAR_VALUE
)
2015 reg
->precise
= true;
2020 static int __mark_chain_precision(struct bpf_verifier_env
*env
, int regno
,
2023 struct bpf_verifier_state
*st
= env
->cur_state
;
2024 int first_idx
= st
->first_insn_idx
;
2025 int last_idx
= env
->insn_idx
;
2026 struct bpf_func_state
*func
;
2027 struct bpf_reg_state
*reg
;
2028 u32 reg_mask
= regno
>= 0 ? 1u << regno
: 0;
2029 u64 stack_mask
= spi
>= 0 ? 1ull << spi
: 0;
2030 bool skip_first
= true;
2031 bool new_marks
= false;
2034 if (!env
->bpf_capable
)
2037 func
= st
->frame
[st
->curframe
];
2039 reg
= &func
->regs
[regno
];
2040 if (reg
->type
!= SCALAR_VALUE
) {
2041 WARN_ONCE(1, "backtracing misuse");
2048 reg
->precise
= true;
2052 if (func
->stack
[spi
].slot_type
[0] != STACK_SPILL
) {
2056 reg
= &func
->stack
[spi
].spilled_ptr
;
2057 if (reg
->type
!= SCALAR_VALUE
) {
2065 reg
->precise
= true;
2071 if (!reg_mask
&& !stack_mask
)
2074 DECLARE_BITMAP(mask
, 64);
2075 u32 history
= st
->jmp_history_cnt
;
2077 if (env
->log
.level
& BPF_LOG_LEVEL
)
2078 verbose(env
, "last_idx %d first_idx %d\n", last_idx
, first_idx
);
2079 for (i
= last_idx
;;) {
2084 err
= backtrack_insn(env
, i
, ®_mask
, &stack_mask
);
2086 if (err
== -ENOTSUPP
) {
2087 mark_all_scalars_precise(env
, st
);
2092 if (!reg_mask
&& !stack_mask
)
2093 /* Found assignment(s) into tracked register in this state.
2094 * Since this state is already marked, just return.
2095 * Nothing to be tracked further in the parent state.
2100 i
= get_prev_insn_idx(st
, i
, &history
);
2101 if (i
>= env
->prog
->len
) {
2102 /* This can happen if backtracking reached insn 0
2103 * and there are still reg_mask or stack_mask
2105 * It means the backtracking missed the spot where
2106 * particular register was initialized with a constant.
2108 verbose(env
, "BUG backtracking idx %d\n", i
);
2109 WARN_ONCE(1, "verifier backtracking bug");
2118 func
= st
->frame
[st
->curframe
];
2119 bitmap_from_u64(mask
, reg_mask
);
2120 for_each_set_bit(i
, mask
, 32) {
2121 reg
= &func
->regs
[i
];
2122 if (reg
->type
!= SCALAR_VALUE
) {
2123 reg_mask
&= ~(1u << i
);
2128 reg
->precise
= true;
2131 bitmap_from_u64(mask
, stack_mask
);
2132 for_each_set_bit(i
, mask
, 64) {
2133 if (i
>= func
->allocated_stack
/ BPF_REG_SIZE
) {
2134 /* the sequence of instructions:
2136 * 3: (7b) *(u64 *)(r3 -8) = r0
2137 * 4: (79) r4 = *(u64 *)(r10 -8)
2138 * doesn't contain jmps. It's backtracked
2139 * as a single block.
2140 * During backtracking insn 3 is not recognized as
2141 * stack access, so at the end of backtracking
2142 * stack slot fp-8 is still marked in stack_mask.
2143 * However the parent state may not have accessed
2144 * fp-8 and it's "unallocated" stack space.
2145 * In such case fallback to conservative.
2147 mark_all_scalars_precise(env
, st
);
2151 if (func
->stack
[i
].slot_type
[0] != STACK_SPILL
) {
2152 stack_mask
&= ~(1ull << i
);
2155 reg
= &func
->stack
[i
].spilled_ptr
;
2156 if (reg
->type
!= SCALAR_VALUE
) {
2157 stack_mask
&= ~(1ull << i
);
2162 reg
->precise
= true;
2164 if (env
->log
.level
& BPF_LOG_LEVEL
) {
2165 print_verifier_state(env
, func
);
2166 verbose(env
, "parent %s regs=%x stack=%llx marks\n",
2167 new_marks
? "didn't have" : "already had",
2168 reg_mask
, stack_mask
);
2171 if (!reg_mask
&& !stack_mask
)
2176 last_idx
= st
->last_insn_idx
;
2177 first_idx
= st
->first_insn_idx
;
2182 static int mark_chain_precision(struct bpf_verifier_env
*env
, int regno
)
2184 return __mark_chain_precision(env
, regno
, -1);
2187 static int mark_chain_precision_stack(struct bpf_verifier_env
*env
, int spi
)
2189 return __mark_chain_precision(env
, -1, spi
);
2192 static bool is_spillable_regtype(enum bpf_reg_type type
)
2195 case PTR_TO_MAP_VALUE
:
2196 case PTR_TO_MAP_VALUE_OR_NULL
:
2200 case PTR_TO_PACKET_META
:
2201 case PTR_TO_PACKET_END
:
2202 case PTR_TO_FLOW_KEYS
:
2203 case CONST_PTR_TO_MAP
:
2205 case PTR_TO_SOCKET_OR_NULL
:
2206 case PTR_TO_SOCK_COMMON
:
2207 case PTR_TO_SOCK_COMMON_OR_NULL
:
2208 case PTR_TO_TCP_SOCK
:
2209 case PTR_TO_TCP_SOCK_OR_NULL
:
2210 case PTR_TO_XDP_SOCK
:
2212 case PTR_TO_BTF_ID_OR_NULL
:
2213 case PTR_TO_RDONLY_BUF
:
2214 case PTR_TO_RDONLY_BUF_OR_NULL
:
2215 case PTR_TO_RDWR_BUF
:
2216 case PTR_TO_RDWR_BUF_OR_NULL
:
2217 case PTR_TO_PERCPU_BTF_ID
:
2219 case PTR_TO_MEM_OR_NULL
:
2226 /* Does this register contain a constant zero? */
2227 static bool register_is_null(struct bpf_reg_state
*reg
)
2229 return reg
->type
== SCALAR_VALUE
&& tnum_equals_const(reg
->var_off
, 0);
2232 static bool register_is_const(struct bpf_reg_state
*reg
)
2234 return reg
->type
== SCALAR_VALUE
&& tnum_is_const(reg
->var_off
);
2237 static bool __is_scalar_unbounded(struct bpf_reg_state
*reg
)
2239 return tnum_is_unknown(reg
->var_off
) &&
2240 reg
->smin_value
== S64_MIN
&& reg
->smax_value
== S64_MAX
&&
2241 reg
->umin_value
== 0 && reg
->umax_value
== U64_MAX
&&
2242 reg
->s32_min_value
== S32_MIN
&& reg
->s32_max_value
== S32_MAX
&&
2243 reg
->u32_min_value
== 0 && reg
->u32_max_value
== U32_MAX
;
2246 static bool register_is_bounded(struct bpf_reg_state
*reg
)
2248 return reg
->type
== SCALAR_VALUE
&& !__is_scalar_unbounded(reg
);
2251 static bool __is_pointer_value(bool allow_ptr_leaks
,
2252 const struct bpf_reg_state
*reg
)
2254 if (allow_ptr_leaks
)
2257 return reg
->type
!= SCALAR_VALUE
;
2260 static void save_register_state(struct bpf_func_state
*state
,
2261 int spi
, struct bpf_reg_state
*reg
)
2265 state
->stack
[spi
].spilled_ptr
= *reg
;
2266 state
->stack
[spi
].spilled_ptr
.live
|= REG_LIVE_WRITTEN
;
2268 for (i
= 0; i
< BPF_REG_SIZE
; i
++)
2269 state
->stack
[spi
].slot_type
[i
] = STACK_SPILL
;
2272 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
2273 * stack boundary and alignment are checked in check_mem_access()
2275 static int check_stack_write_fixed_off(struct bpf_verifier_env
*env
,
2276 /* stack frame we're writing to */
2277 struct bpf_func_state
*state
,
2278 int off
, int size
, int value_regno
,
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 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
2406 * known to contain a variable offset.
2407 * This function checks whether the write is permitted and conservatively
2408 * tracks the effects of the write, considering that each stack slot in the
2409 * dynamic range is potentially written to.
2411 * 'off' includes 'regno->off'.
2412 * 'value_regno' can be -1, meaning that an unknown value is being written to
2415 * Spilled pointers in range are not marked as written because we don't know
2416 * what's going to be actually written. This means that read propagation for
2417 * future reads cannot be terminated by this write.
2419 * For privileged programs, uninitialized stack slots are considered
2420 * initialized by this write (even though we don't know exactly what offsets
2421 * are going to be written to). The idea is that we don't want the verifier to
2422 * reject future reads that access slots written to through variable offsets.
2424 static int check_stack_write_var_off(struct bpf_verifier_env
*env
,
2425 /* func where register points to */
2426 struct bpf_func_state
*state
,
2427 int ptr_regno
, int off
, int size
,
2428 int value_regno
, int insn_idx
)
2430 struct bpf_func_state
*cur
; /* state of the current function */
2431 int min_off
, max_off
;
2433 struct bpf_reg_state
*ptr_reg
= NULL
, *value_reg
= NULL
;
2434 bool writing_zero
= false;
2435 /* set if the fact that we're writing a zero is used to let any
2436 * stack slots remain STACK_ZERO
2438 bool zero_used
= false;
2440 cur
= env
->cur_state
->frame
[env
->cur_state
->curframe
];
2441 ptr_reg
= &cur
->regs
[ptr_regno
];
2442 min_off
= ptr_reg
->smin_value
+ off
;
2443 max_off
= ptr_reg
->smax_value
+ off
+ size
;
2444 if (value_regno
>= 0)
2445 value_reg
= &cur
->regs
[value_regno
];
2446 if (value_reg
&& register_is_null(value_reg
))
2447 writing_zero
= true;
2449 err
= realloc_func_state(state
, round_up(-min_off
, BPF_REG_SIZE
),
2450 state
->acquired_refs
, true);
2455 /* Variable offset writes destroy any spilled pointers in range. */
2456 for (i
= min_off
; i
< max_off
; i
++) {
2457 u8 new_type
, *stype
;
2461 spi
= slot
/ BPF_REG_SIZE
;
2462 stype
= &state
->stack
[spi
].slot_type
[slot
% BPF_REG_SIZE
];
2464 if (!env
->allow_ptr_leaks
2465 && *stype
!= NOT_INIT
2466 && *stype
!= SCALAR_VALUE
) {
2467 /* Reject the write if there's are spilled pointers in
2468 * range. If we didn't reject here, the ptr status
2469 * would be erased below (even though not all slots are
2470 * actually overwritten), possibly opening the door to
2473 verbose(env
, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
2478 /* Erase all spilled pointers. */
2479 state
->stack
[spi
].spilled_ptr
.type
= NOT_INIT
;
2481 /* Update the slot type. */
2482 new_type
= STACK_MISC
;
2483 if (writing_zero
&& *stype
== STACK_ZERO
) {
2484 new_type
= STACK_ZERO
;
2487 /* If the slot is STACK_INVALID, we check whether it's OK to
2488 * pretend that it will be initialized by this write. The slot
2489 * might not actually be written to, and so if we mark it as
2490 * initialized future reads might leak uninitialized memory.
2491 * For privileged programs, we will accept such reads to slots
2492 * that may or may not be written because, if we're reject
2493 * them, the error would be too confusing.
2495 if (*stype
== STACK_INVALID
&& !env
->allow_uninit_stack
) {
2496 verbose(env
, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
2503 /* backtracking doesn't work for STACK_ZERO yet. */
2504 err
= mark_chain_precision(env
, value_regno
);
2511 /* When register 'dst_regno' is assigned some values from stack[min_off,
2512 * max_off), we set the register's type according to the types of the
2513 * respective stack slots. If all the stack values are known to be zeros, then
2514 * so is the destination reg. Otherwise, the register is considered to be
2515 * SCALAR. This function does not deal with register filling; the caller must
2516 * ensure that all spilled registers in the stack range have been marked as
2519 static void mark_reg_stack_read(struct bpf_verifier_env
*env
,
2520 /* func where src register points to */
2521 struct bpf_func_state
*ptr_state
,
2522 int min_off
, int max_off
, int dst_regno
)
2524 struct bpf_verifier_state
*vstate
= env
->cur_state
;
2525 struct bpf_func_state
*state
= vstate
->frame
[vstate
->curframe
];
2530 for (i
= min_off
; i
< max_off
; i
++) {
2532 spi
= slot
/ BPF_REG_SIZE
;
2533 stype
= ptr_state
->stack
[spi
].slot_type
;
2534 if (stype
[slot
% BPF_REG_SIZE
] != STACK_ZERO
)
2538 if (zeros
== max_off
- min_off
) {
2539 /* any access_size read into register is zero extended,
2540 * so the whole register == const_zero
2542 __mark_reg_const_zero(&state
->regs
[dst_regno
]);
2543 /* backtracking doesn't support STACK_ZERO yet,
2544 * so mark it precise here, so that later
2545 * backtracking can stop here.
2546 * Backtracking may not need this if this register
2547 * doesn't participate in pointer adjustment.
2548 * Forward propagation of precise flag is not
2549 * necessary either. This mark is only to stop
2550 * backtracking. Any register that contributed
2551 * to const 0 was marked precise before spill.
2553 state
->regs
[dst_regno
].precise
= true;
2555 /* have read misc data from the stack */
2556 mark_reg_unknown(env
, state
->regs
, dst_regno
);
2558 state
->regs
[dst_regno
].live
|= REG_LIVE_WRITTEN
;
2561 /* Read the stack at 'off' and put the results into the register indicated by
2562 * 'dst_regno'. It handles reg filling if the addressed stack slot is a
2565 * 'dst_regno' can be -1, meaning that the read value is not going to a
2568 * The access is assumed to be within the current stack bounds.
2570 static int check_stack_read_fixed_off(struct bpf_verifier_env
*env
,
2571 /* func where src register points to */
2572 struct bpf_func_state
*reg_state
,
2573 int off
, int size
, int dst_regno
)
2575 struct bpf_verifier_state
*vstate
= env
->cur_state
;
2576 struct bpf_func_state
*state
= vstate
->frame
[vstate
->curframe
];
2577 int i
, slot
= -off
- 1, spi
= slot
/ BPF_REG_SIZE
;
2578 struct bpf_reg_state
*reg
;
2581 stype
= reg_state
->stack
[spi
].slot_type
;
2582 reg
= ®_state
->stack
[spi
].spilled_ptr
;
2584 if (stype
[0] == STACK_SPILL
) {
2585 if (size
!= BPF_REG_SIZE
) {
2586 if (reg
->type
!= SCALAR_VALUE
) {
2587 verbose_linfo(env
, env
->insn_idx
, "; ");
2588 verbose(env
, "invalid size of register fill\n");
2591 if (dst_regno
>= 0) {
2592 mark_reg_unknown(env
, state
->regs
, dst_regno
);
2593 state
->regs
[dst_regno
].live
|= REG_LIVE_WRITTEN
;
2595 mark_reg_read(env
, reg
, reg
->parent
, REG_LIVE_READ64
);
2598 for (i
= 1; i
< BPF_REG_SIZE
; i
++) {
2599 if (stype
[(slot
- i
) % BPF_REG_SIZE
] != STACK_SPILL
) {
2600 verbose(env
, "corrupted spill memory\n");
2605 if (dst_regno
>= 0) {
2606 /* restore register state from stack */
2607 state
->regs
[dst_regno
] = *reg
;
2608 /* mark reg as written since spilled pointer state likely
2609 * has its liveness marks cleared by is_state_visited()
2610 * which resets stack/reg liveness for state transitions
2612 state
->regs
[dst_regno
].live
|= REG_LIVE_WRITTEN
;
2613 } else if (__is_pointer_value(env
->allow_ptr_leaks
, reg
)) {
2614 /* If dst_regno==-1, the caller is asking us whether
2615 * it is acceptable to use this value as a SCALAR_VALUE
2617 * We must not allow unprivileged callers to do that
2618 * with spilled pointers.
2620 verbose(env
, "leaking pointer from stack off %d\n",
2624 mark_reg_read(env
, reg
, reg
->parent
, REG_LIVE_READ64
);
2628 for (i
= 0; i
< size
; i
++) {
2629 type
= stype
[(slot
- i
) % BPF_REG_SIZE
];
2630 if (type
== STACK_MISC
)
2632 if (type
== STACK_ZERO
)
2634 verbose(env
, "invalid read from stack off %d+%d size %d\n",
2638 mark_reg_read(env
, reg
, reg
->parent
, REG_LIVE_READ64
);
2640 mark_reg_stack_read(env
, reg_state
, off
, off
+ size
, dst_regno
);
2645 enum stack_access_src
{
2646 ACCESS_DIRECT
= 1, /* the access is performed by an instruction */
2647 ACCESS_HELPER
= 2, /* the access is performed by a helper */
2650 static int check_stack_range_initialized(struct bpf_verifier_env
*env
,
2651 int regno
, int off
, int access_size
,
2652 bool zero_size_allowed
,
2653 enum stack_access_src type
,
2654 struct bpf_call_arg_meta
*meta
);
2656 static struct bpf_reg_state
*reg_state(struct bpf_verifier_env
*env
, int regno
)
2658 return cur_regs(env
) + regno
;
2661 /* Read the stack at 'ptr_regno + off' and put the result into the register
2663 * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
2664 * but not its variable offset.
2665 * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
2667 * As opposed to check_stack_read_fixed_off, this function doesn't deal with
2668 * filling registers (i.e. reads of spilled register cannot be detected when
2669 * the offset is not fixed). We conservatively mark 'dst_regno' as containing
2670 * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
2671 * offset; for a fixed offset check_stack_read_fixed_off should be used
2674 static int check_stack_read_var_off(struct bpf_verifier_env
*env
,
2675 int ptr_regno
, int off
, int size
, int dst_regno
)
2677 /* The state of the source register. */
2678 struct bpf_reg_state
*reg
= reg_state(env
, ptr_regno
);
2679 struct bpf_func_state
*ptr_state
= func(env
, reg
);
2681 int min_off
, max_off
;
2683 /* Note that we pass a NULL meta, so raw access will not be permitted.
2685 err
= check_stack_range_initialized(env
, ptr_regno
, off
, size
,
2686 false, ACCESS_DIRECT
, NULL
);
2690 min_off
= reg
->smin_value
+ off
;
2691 max_off
= reg
->smax_value
+ off
;
2692 mark_reg_stack_read(env
, ptr_state
, min_off
, max_off
+ size
, dst_regno
);
2696 /* check_stack_read dispatches to check_stack_read_fixed_off or
2697 * check_stack_read_var_off.
2699 * The caller must ensure that the offset falls within the allocated stack
2702 * 'dst_regno' is a register which will receive the value from the stack. It
2703 * can be -1, meaning that the read value is not going to a register.
2705 static int check_stack_read(struct bpf_verifier_env
*env
,
2706 int ptr_regno
, int off
, int size
,
2709 struct bpf_reg_state
*reg
= reg_state(env
, ptr_regno
);
2710 struct bpf_func_state
*state
= func(env
, reg
);
2712 /* Some accesses are only permitted with a static offset. */
2713 bool var_off
= !tnum_is_const(reg
->var_off
);
2715 /* The offset is required to be static when reads don't go to a
2716 * register, in order to not leak pointers (see
2717 * check_stack_read_fixed_off).
2719 if (dst_regno
< 0 && var_off
) {
2722 tnum_strn(tn_buf
, sizeof(tn_buf
), reg
->var_off
);
2723 verbose(env
, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
2727 /* Variable offset is prohibited for unprivileged mode for simplicity
2728 * since it requires corresponding support in Spectre masking for stack
2729 * ALU. See also retrieve_ptr_limit().
2731 if (!env
->bypass_spec_v1
&& var_off
) {
2734 tnum_strn(tn_buf
, sizeof(tn_buf
), reg
->var_off
);
2735 verbose(env
, "R%d variable offset stack access prohibited for !root, var_off=%s\n",
2741 off
+= reg
->var_off
.value
;
2742 err
= check_stack_read_fixed_off(env
, state
, off
, size
,
2745 /* Variable offset stack reads need more conservative handling
2746 * than fixed offset ones. Note that dst_regno >= 0 on this
2749 err
= check_stack_read_var_off(env
, ptr_regno
, off
, size
,
2756 /* check_stack_write dispatches to check_stack_write_fixed_off or
2757 * check_stack_write_var_off.
2759 * 'ptr_regno' is the register used as a pointer into the stack.
2760 * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
2761 * 'value_regno' is the register whose value we're writing to the stack. It can
2762 * be -1, meaning that we're not writing from a register.
2764 * The caller must ensure that the offset falls within the maximum stack size.
2766 static int check_stack_write(struct bpf_verifier_env
*env
,
2767 int ptr_regno
, int off
, int size
,
2768 int value_regno
, int insn_idx
)
2770 struct bpf_reg_state
*reg
= reg_state(env
, ptr_regno
);
2771 struct bpf_func_state
*state
= func(env
, reg
);
2774 if (tnum_is_const(reg
->var_off
)) {
2775 off
+= reg
->var_off
.value
;
2776 err
= check_stack_write_fixed_off(env
, state
, off
, size
,
2777 value_regno
, insn_idx
);
2779 /* Variable offset stack reads need more conservative handling
2780 * than fixed offset ones.
2782 err
= check_stack_write_var_off(env
, state
,
2783 ptr_regno
, off
, size
,
2784 value_regno
, insn_idx
);
2789 static int check_map_access_type(struct bpf_verifier_env
*env
, u32 regno
,
2790 int off
, int size
, enum bpf_access_type type
)
2792 struct bpf_reg_state
*regs
= cur_regs(env
);
2793 struct bpf_map
*map
= regs
[regno
].map_ptr
;
2794 u32 cap
= bpf_map_flags_to_cap(map
);
2796 if (type
== BPF_WRITE
&& !(cap
& BPF_MAP_CAN_WRITE
)) {
2797 verbose(env
, "write into map forbidden, value_size=%d off=%d size=%d\n",
2798 map
->value_size
, off
, size
);
2802 if (type
== BPF_READ
&& !(cap
& BPF_MAP_CAN_READ
)) {
2803 verbose(env
, "read from map forbidden, value_size=%d off=%d size=%d\n",
2804 map
->value_size
, off
, size
);
2811 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
2812 static int __check_mem_access(struct bpf_verifier_env
*env
, int regno
,
2813 int off
, int size
, u32 mem_size
,
2814 bool zero_size_allowed
)
2816 bool size_ok
= size
> 0 || (size
== 0 && zero_size_allowed
);
2817 struct bpf_reg_state
*reg
;
2819 if (off
>= 0 && size_ok
&& (u64
)off
+ size
<= mem_size
)
2822 reg
= &cur_regs(env
)[regno
];
2823 switch (reg
->type
) {
2824 case PTR_TO_MAP_VALUE
:
2825 verbose(env
, "invalid access to map value, value_size=%d off=%d size=%d\n",
2826 mem_size
, off
, size
);
2829 case PTR_TO_PACKET_META
:
2830 case PTR_TO_PACKET_END
:
2831 verbose(env
, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
2832 off
, size
, regno
, reg
->id
, off
, mem_size
);
2836 verbose(env
, "invalid access to memory, mem_size=%u off=%d size=%d\n",
2837 mem_size
, off
, size
);
2843 /* check read/write into a memory region with possible variable offset */
2844 static int check_mem_region_access(struct bpf_verifier_env
*env
, u32 regno
,
2845 int off
, int size
, u32 mem_size
,
2846 bool zero_size_allowed
)
2848 struct bpf_verifier_state
*vstate
= env
->cur_state
;
2849 struct bpf_func_state
*state
= vstate
->frame
[vstate
->curframe
];
2850 struct bpf_reg_state
*reg
= &state
->regs
[regno
];
2853 /* We may have adjusted the register pointing to memory region, so we
2854 * need to try adding each of min_value and max_value to off
2855 * to make sure our theoretical access will be safe.
2857 if (env
->log
.level
& BPF_LOG_LEVEL
)
2858 print_verifier_state(env
, state
);
2860 /* The minimum value is only important with signed
2861 * comparisons where we can't assume the floor of a
2862 * value is 0. If we are using signed variables for our
2863 * index'es we need to make sure that whatever we use
2864 * will have a set floor within our range.
2866 if (reg
->smin_value
< 0 &&
2867 (reg
->smin_value
== S64_MIN
||
2868 (off
+ reg
->smin_value
!= (s64
)(s32
)(off
+ reg
->smin_value
)) ||
2869 reg
->smin_value
+ off
< 0)) {
2870 verbose(env
, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
2874 err
= __check_mem_access(env
, regno
, reg
->smin_value
+ off
, size
,
2875 mem_size
, zero_size_allowed
);
2877 verbose(env
, "R%d min value is outside of the allowed memory range\n",
2882 /* If we haven't set a max value then we need to bail since we can't be
2883 * sure we won't do bad things.
2884 * If reg->umax_value + off could overflow, treat that as unbounded too.
2886 if (reg
->umax_value
>= BPF_MAX_VAR_OFF
) {
2887 verbose(env
, "R%d unbounded memory access, make sure to bounds check any such access\n",
2891 err
= __check_mem_access(env
, regno
, reg
->umax_value
+ off
, size
,
2892 mem_size
, zero_size_allowed
);
2894 verbose(env
, "R%d max value is outside of the allowed memory range\n",
2902 /* check read/write into a map element with possible variable offset */
2903 static int check_map_access(struct bpf_verifier_env
*env
, u32 regno
,
2904 int off
, int size
, bool zero_size_allowed
)
2906 struct bpf_verifier_state
*vstate
= env
->cur_state
;
2907 struct bpf_func_state
*state
= vstate
->frame
[vstate
->curframe
];
2908 struct bpf_reg_state
*reg
= &state
->regs
[regno
];
2909 struct bpf_map
*map
= reg
->map_ptr
;
2912 err
= check_mem_region_access(env
, regno
, off
, size
, map
->value_size
,
2917 if (map_value_has_spin_lock(map
)) {
2918 u32 lock
= map
->spin_lock_off
;
2920 /* if any part of struct bpf_spin_lock can be touched by
2921 * load/store reject this program.
2922 * To check that [x1, x2) overlaps with [y1, y2)
2923 * it is sufficient to check x1 < y2 && y1 < x2.
2925 if (reg
->smin_value
+ off
< lock
+ sizeof(struct bpf_spin_lock
) &&
2926 lock
< reg
->umax_value
+ off
+ size
) {
2927 verbose(env
, "bpf_spin_lock cannot be accessed directly by load/store\n");
2934 #define MAX_PACKET_OFF 0xffff
2936 static enum bpf_prog_type
resolve_prog_type(struct bpf_prog
*prog
)
2938 return prog
->aux
->dst_prog
? prog
->aux
->dst_prog
->type
: prog
->type
;
2941 static bool may_access_direct_pkt_data(struct bpf_verifier_env
*env
,
2942 const struct bpf_call_arg_meta
*meta
,
2943 enum bpf_access_type t
)
2945 enum bpf_prog_type prog_type
= resolve_prog_type(env
->prog
);
2947 switch (prog_type
) {
2948 /* Program types only with direct read access go here! */
2949 case BPF_PROG_TYPE_LWT_IN
:
2950 case BPF_PROG_TYPE_LWT_OUT
:
2951 case BPF_PROG_TYPE_LWT_SEG6LOCAL
:
2952 case BPF_PROG_TYPE_SK_REUSEPORT
:
2953 case BPF_PROG_TYPE_FLOW_DISSECTOR
:
2954 case BPF_PROG_TYPE_CGROUP_SKB
:
2959 /* Program types with direct read + write access go here! */
2960 case BPF_PROG_TYPE_SCHED_CLS
:
2961 case BPF_PROG_TYPE_SCHED_ACT
:
2962 case BPF_PROG_TYPE_XDP
:
2963 case BPF_PROG_TYPE_LWT_XMIT
:
2964 case BPF_PROG_TYPE_SK_SKB
:
2965 case BPF_PROG_TYPE_SK_MSG
:
2967 return meta
->pkt_access
;
2969 env
->seen_direct_write
= true;
2972 case BPF_PROG_TYPE_CGROUP_SOCKOPT
:
2974 env
->seen_direct_write
= true;
2983 static int check_packet_access(struct bpf_verifier_env
*env
, u32 regno
, int off
,
2984 int size
, bool zero_size_allowed
)
2986 struct bpf_reg_state
*regs
= cur_regs(env
);
2987 struct bpf_reg_state
*reg
= ®s
[regno
];
2990 /* We may have added a variable offset to the packet pointer; but any
2991 * reg->range we have comes after that. We are only checking the fixed
2995 /* We don't allow negative numbers, because we aren't tracking enough
2996 * detail to prove they're safe.
2998 if (reg
->smin_value
< 0) {
2999 verbose(env
, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3004 err
= reg
->range
< 0 ? -EINVAL
:
3005 __check_mem_access(env
, regno
, off
, size
, reg
->range
,
3008 verbose(env
, "R%d offset is outside of the packet\n", regno
);
3012 /* __check_mem_access has made sure "off + size - 1" is within u16.
3013 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
3014 * otherwise find_good_pkt_pointers would have refused to set range info
3015 * that __check_mem_access would have rejected this pkt access.
3016 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
3018 env
->prog
->aux
->max_pkt_offset
=
3019 max_t(u32
, env
->prog
->aux
->max_pkt_offset
,
3020 off
+ reg
->umax_value
+ size
- 1);
3025 /* check access to 'struct bpf_context' fields. Supports fixed offsets only */
3026 static int check_ctx_access(struct bpf_verifier_env
*env
, int insn_idx
, int off
, int size
,
3027 enum bpf_access_type t
, enum bpf_reg_type
*reg_type
,
3028 struct btf
**btf
, u32
*btf_id
)
3030 struct bpf_insn_access_aux info
= {
3031 .reg_type
= *reg_type
,
3035 if (env
->ops
->is_valid_access
&&
3036 env
->ops
->is_valid_access(off
, size
, t
, env
->prog
, &info
)) {
3037 /* A non zero info.ctx_field_size indicates that this field is a
3038 * candidate for later verifier transformation to load the whole
3039 * field and then apply a mask when accessed with a narrower
3040 * access than actual ctx access size. A zero info.ctx_field_size
3041 * will only allow for whole field access and rejects any other
3042 * type of narrower access.
3044 *reg_type
= info
.reg_type
;
3046 if (*reg_type
== PTR_TO_BTF_ID
|| *reg_type
== PTR_TO_BTF_ID_OR_NULL
) {
3048 *btf_id
= info
.btf_id
;
3050 env
->insn_aux_data
[insn_idx
].ctx_field_size
= info
.ctx_field_size
;
3052 /* remember the offset of last byte accessed in ctx */
3053 if (env
->prog
->aux
->max_ctx_offset
< off
+ size
)
3054 env
->prog
->aux
->max_ctx_offset
= off
+ size
;
3058 verbose(env
, "invalid bpf_context access off=%d size=%d\n", off
, size
);
3062 static int check_flow_keys_access(struct bpf_verifier_env
*env
, int off
,
3065 if (size
< 0 || off
< 0 ||
3066 (u64
)off
+ size
> sizeof(struct bpf_flow_keys
)) {
3067 verbose(env
, "invalid access to flow keys off=%d size=%d\n",
3074 static int check_sock_access(struct bpf_verifier_env
*env
, int insn_idx
,
3075 u32 regno
, int off
, int size
,
3076 enum bpf_access_type t
)
3078 struct bpf_reg_state
*regs
= cur_regs(env
);
3079 struct bpf_reg_state
*reg
= ®s
[regno
];
3080 struct bpf_insn_access_aux info
= {};
3083 if (reg
->smin_value
< 0) {
3084 verbose(env
, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3089 switch (reg
->type
) {
3090 case PTR_TO_SOCK_COMMON
:
3091 valid
= bpf_sock_common_is_valid_access(off
, size
, t
, &info
);
3094 valid
= bpf_sock_is_valid_access(off
, size
, t
, &info
);
3096 case PTR_TO_TCP_SOCK
:
3097 valid
= bpf_tcp_sock_is_valid_access(off
, size
, t
, &info
);
3099 case PTR_TO_XDP_SOCK
:
3100 valid
= bpf_xdp_sock_is_valid_access(off
, size
, t
, &info
);
3108 env
->insn_aux_data
[insn_idx
].ctx_field_size
=
3109 info
.ctx_field_size
;
3113 verbose(env
, "R%d invalid %s access off=%d size=%d\n",
3114 regno
, reg_type_str
[reg
->type
], off
, size
);
3119 static bool is_pointer_value(struct bpf_verifier_env
*env
, int regno
)
3121 return __is_pointer_value(env
->allow_ptr_leaks
, reg_state(env
, regno
));
3124 static bool is_ctx_reg(struct bpf_verifier_env
*env
, int regno
)
3126 const struct bpf_reg_state
*reg
= reg_state(env
, regno
);
3128 return reg
->type
== PTR_TO_CTX
;
3131 static bool is_sk_reg(struct bpf_verifier_env
*env
, int regno
)
3133 const struct bpf_reg_state
*reg
= reg_state(env
, regno
);
3135 return type_is_sk_pointer(reg
->type
);
3138 static bool is_pkt_reg(struct bpf_verifier_env
*env
, int regno
)
3140 const struct bpf_reg_state
*reg
= reg_state(env
, regno
);
3142 return type_is_pkt_pointer(reg
->type
);
3145 static bool is_flow_key_reg(struct bpf_verifier_env
*env
, int regno
)
3147 const struct bpf_reg_state
*reg
= reg_state(env
, regno
);
3149 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
3150 return reg
->type
== PTR_TO_FLOW_KEYS
;
3153 static int check_pkt_ptr_alignment(struct bpf_verifier_env
*env
,
3154 const struct bpf_reg_state
*reg
,
3155 int off
, int size
, bool strict
)
3157 struct tnum reg_off
;
3160 /* Byte size accesses are always allowed. */
3161 if (!strict
|| size
== 1)
3164 /* For platforms that do not have a Kconfig enabling
3165 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
3166 * NET_IP_ALIGN is universally set to '2'. And on platforms
3167 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
3168 * to this code only in strict mode where we want to emulate
3169 * the NET_IP_ALIGN==2 checking. Therefore use an
3170 * unconditional IP align value of '2'.
3174 reg_off
= tnum_add(reg
->var_off
, tnum_const(ip_align
+ reg
->off
+ off
));
3175 if (!tnum_is_aligned(reg_off
, size
)) {
3178 tnum_strn(tn_buf
, sizeof(tn_buf
), reg
->var_off
);
3180 "misaligned packet access off %d+%s+%d+%d size %d\n",
3181 ip_align
, tn_buf
, reg
->off
, off
, size
);
3188 static int check_generic_ptr_alignment(struct bpf_verifier_env
*env
,
3189 const struct bpf_reg_state
*reg
,
3190 const char *pointer_desc
,
3191 int off
, int size
, bool strict
)
3193 struct tnum reg_off
;
3195 /* Byte size accesses are always allowed. */
3196 if (!strict
|| size
== 1)
3199 reg_off
= tnum_add(reg
->var_off
, tnum_const(reg
->off
+ off
));
3200 if (!tnum_is_aligned(reg_off
, size
)) {
3203 tnum_strn(tn_buf
, sizeof(tn_buf
), reg
->var_off
);
3204 verbose(env
, "misaligned %saccess off %s+%d+%d size %d\n",
3205 pointer_desc
, tn_buf
, reg
->off
, off
, size
);
3212 static int check_ptr_alignment(struct bpf_verifier_env
*env
,
3213 const struct bpf_reg_state
*reg
, int off
,
3214 int size
, bool strict_alignment_once
)
3216 bool strict
= env
->strict_alignment
|| strict_alignment_once
;
3217 const char *pointer_desc
= "";
3219 switch (reg
->type
) {
3221 case PTR_TO_PACKET_META
:
3222 /* Special case, because of NET_IP_ALIGN. Given metadata sits
3223 * right in front, treat it the very same way.
3225 return check_pkt_ptr_alignment(env
, reg
, off
, size
, strict
);
3226 case PTR_TO_FLOW_KEYS
:
3227 pointer_desc
= "flow keys ";
3229 case PTR_TO_MAP_VALUE
:
3230 pointer_desc
= "value ";
3233 pointer_desc
= "context ";
3236 pointer_desc
= "stack ";
3237 /* The stack spill tracking logic in check_stack_write_fixed_off()
3238 * and check_stack_read_fixed_off() relies on stack accesses being
3244 pointer_desc
= "sock ";
3246 case PTR_TO_SOCK_COMMON
:
3247 pointer_desc
= "sock_common ";
3249 case PTR_TO_TCP_SOCK
:
3250 pointer_desc
= "tcp_sock ";
3252 case PTR_TO_XDP_SOCK
:
3253 pointer_desc
= "xdp_sock ";
3258 return check_generic_ptr_alignment(env
, reg
, pointer_desc
, off
, size
,
3262 static int update_stack_depth(struct bpf_verifier_env
*env
,
3263 const struct bpf_func_state
*func
,
3266 u16 stack
= env
->subprog_info
[func
->subprogno
].stack_depth
;
3271 /* update known max for given subprogram */
3272 env
->subprog_info
[func
->subprogno
].stack_depth
= -off
;
3276 /* starting from main bpf function walk all instructions of the function
3277 * and recursively walk all callees that given function can call.
3278 * Ignore jump and exit insns.
3279 * Since recursion is prevented by check_cfg() this algorithm
3280 * only needs a local stack of MAX_CALL_FRAMES to remember callsites
3282 static int check_max_stack_depth(struct bpf_verifier_env
*env
)
3284 int depth
= 0, frame
= 0, idx
= 0, i
= 0, subprog_end
;
3285 struct bpf_subprog_info
*subprog
= env
->subprog_info
;
3286 struct bpf_insn
*insn
= env
->prog
->insnsi
;
3287 bool tail_call_reachable
= false;
3288 int ret_insn
[MAX_CALL_FRAMES
];
3289 int ret_prog
[MAX_CALL_FRAMES
];
3293 /* protect against potential stack overflow that might happen when
3294 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
3295 * depth for such case down to 256 so that the worst case scenario
3296 * would result in 8k stack size (32 which is tailcall limit * 256 =
3299 * To get the idea what might happen, see an example:
3300 * func1 -> sub rsp, 128
3301 * subfunc1 -> sub rsp, 256
3302 * tailcall1 -> add rsp, 256
3303 * func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
3304 * subfunc2 -> sub rsp, 64
3305 * subfunc22 -> sub rsp, 128
3306 * tailcall2 -> add rsp, 128
3307 * func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
3309 * tailcall will unwind the current stack frame but it will not get rid
3310 * of caller's stack as shown on the example above.
3312 if (idx
&& subprog
[idx
].has_tail_call
&& depth
>= 256) {
3314 "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
3318 /* round up to 32-bytes, since this is granularity
3319 * of interpreter stack size
3321 depth
+= round_up(max_t(u32
, subprog
[idx
].stack_depth
, 1), 32);
3322 if (depth
> MAX_BPF_STACK
) {
3323 verbose(env
, "combined stack size of %d calls is %d. Too large\n",
3328 subprog_end
= subprog
[idx
+ 1].start
;
3329 for (; i
< subprog_end
; i
++) {
3330 if (insn
[i
].code
!= (BPF_JMP
| BPF_CALL
))
3332 if (insn
[i
].src_reg
!= BPF_PSEUDO_CALL
)
3334 /* remember insn and function to return to */
3335 ret_insn
[frame
] = i
+ 1;
3336 ret_prog
[frame
] = idx
;
3338 /* find the callee */
3339 i
= i
+ insn
[i
].imm
+ 1;
3340 idx
= find_subprog(env
, i
);
3342 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
3347 if (subprog
[idx
].has_tail_call
)
3348 tail_call_reachable
= true;
3351 if (frame
>= MAX_CALL_FRAMES
) {
3352 verbose(env
, "the call stack of %d frames is too deep !\n",
3358 /* if tail call got detected across bpf2bpf calls then mark each of the
3359 * currently present subprog frames as tail call reachable subprogs;
3360 * this info will be utilized by JIT so that we will be preserving the
3361 * tail call counter throughout bpf2bpf calls combined with tailcalls
3363 if (tail_call_reachable
)
3364 for (j
= 0; j
< frame
; j
++)
3365 subprog
[ret_prog
[j
]].tail_call_reachable
= true;
3367 /* end of for() loop means the last insn of the 'subprog'
3368 * was reached. Doesn't matter whether it was JA or EXIT
3372 depth
-= round_up(max_t(u32
, subprog
[idx
].stack_depth
, 1), 32);
3374 i
= ret_insn
[frame
];
3375 idx
= ret_prog
[frame
];
3379 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
3380 static int get_callee_stack_depth(struct bpf_verifier_env
*env
,
3381 const struct bpf_insn
*insn
, int idx
)
3383 int start
= idx
+ insn
->imm
+ 1, subprog
;
3385 subprog
= find_subprog(env
, start
);
3387 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
3391 return env
->subprog_info
[subprog
].stack_depth
;
3395 int check_ctx_reg(struct bpf_verifier_env
*env
,
3396 const struct bpf_reg_state
*reg
, int regno
)
3398 /* Access to ctx or passing it to a helper is only allowed in
3399 * its original, unmodified form.
3403 verbose(env
, "dereference of modified ctx ptr R%d off=%d disallowed\n",
3408 if (!tnum_is_const(reg
->var_off
) || reg
->var_off
.value
) {
3411 tnum_strn(tn_buf
, sizeof(tn_buf
), reg
->var_off
);
3412 verbose(env
, "variable ctx access var_off=%s disallowed\n", tn_buf
);
3419 static int __check_buffer_access(struct bpf_verifier_env
*env
,
3420 const char *buf_info
,
3421 const struct bpf_reg_state
*reg
,
3422 int regno
, int off
, int size
)
3426 "R%d invalid %s buffer access: off=%d, size=%d\n",
3427 regno
, buf_info
, off
, size
);
3430 if (!tnum_is_const(reg
->var_off
) || reg
->var_off
.value
) {
3433 tnum_strn(tn_buf
, sizeof(tn_buf
), reg
->var_off
);
3435 "R%d invalid variable buffer offset: off=%d, var_off=%s\n",
3436 regno
, off
, tn_buf
);
3443 static int check_tp_buffer_access(struct bpf_verifier_env
*env
,
3444 const struct bpf_reg_state
*reg
,
3445 int regno
, int off
, int size
)
3449 err
= __check_buffer_access(env
, "tracepoint", reg
, regno
, off
, size
);
3453 if (off
+ size
> env
->prog
->aux
->max_tp_access
)
3454 env
->prog
->aux
->max_tp_access
= off
+ size
;
3459 static int check_buffer_access(struct bpf_verifier_env
*env
,
3460 const struct bpf_reg_state
*reg
,
3461 int regno
, int off
, int size
,
3462 bool zero_size_allowed
,
3463 const char *buf_info
,
3468 err
= __check_buffer_access(env
, buf_info
, reg
, regno
, off
, size
);
3472 if (off
+ size
> *max_access
)
3473 *max_access
= off
+ size
;
3478 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
3479 static void zext_32_to_64(struct bpf_reg_state
*reg
)
3481 reg
->var_off
= tnum_subreg(reg
->var_off
);
3482 __reg_assign_32_into_64(reg
);
3485 /* truncate register to smaller size (in bytes)
3486 * must be called with size < BPF_REG_SIZE
3488 static void coerce_reg_to_size(struct bpf_reg_state
*reg
, int size
)
3492 /* clear high bits in bit representation */
3493 reg
->var_off
= tnum_cast(reg
->var_off
, size
);
3495 /* fix arithmetic bounds */
3496 mask
= ((u64
)1 << (size
* 8)) - 1;
3497 if ((reg
->umin_value
& ~mask
) == (reg
->umax_value
& ~mask
)) {
3498 reg
->umin_value
&= mask
;
3499 reg
->umax_value
&= mask
;
3501 reg
->umin_value
= 0;
3502 reg
->umax_value
= mask
;
3504 reg
->smin_value
= reg
->umin_value
;
3505 reg
->smax_value
= reg
->umax_value
;
3507 /* If size is smaller than 32bit register the 32bit register
3508 * values are also truncated so we push 64-bit bounds into
3509 * 32-bit bounds. Above were truncated < 32-bits already.
3513 __reg_combine_64_into_32(reg
);
3516 static bool bpf_map_is_rdonly(const struct bpf_map
*map
)
3518 return (map
->map_flags
& BPF_F_RDONLY_PROG
) && map
->frozen
;
3521 static int bpf_map_direct_read(struct bpf_map
*map
, int off
, int size
, u64
*val
)
3527 err
= map
->ops
->map_direct_value_addr(map
, &addr
, off
);
3530 ptr
= (void *)(long)addr
+ off
;
3534 *val
= (u64
)*(u8
*)ptr
;
3537 *val
= (u64
)*(u16
*)ptr
;
3540 *val
= (u64
)*(u32
*)ptr
;
3551 static int check_ptr_to_btf_access(struct bpf_verifier_env
*env
,
3552 struct bpf_reg_state
*regs
,
3553 int regno
, int off
, int size
,
3554 enum bpf_access_type atype
,
3557 struct bpf_reg_state
*reg
= regs
+ regno
;
3558 const struct btf_type
*t
= btf_type_by_id(reg
->btf
, reg
->btf_id
);
3559 const char *tname
= btf_name_by_offset(reg
->btf
, t
->name_off
);
3565 "R%d is ptr_%s invalid negative access: off=%d\n",
3569 if (!tnum_is_const(reg
->var_off
) || reg
->var_off
.value
) {
3572 tnum_strn(tn_buf
, sizeof(tn_buf
), reg
->var_off
);
3574 "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
3575 regno
, tname
, off
, tn_buf
);
3579 if (env
->ops
->btf_struct_access
) {
3580 ret
= env
->ops
->btf_struct_access(&env
->log
, reg
->btf
, t
,
3581 off
, size
, atype
, &btf_id
);
3583 if (atype
!= BPF_READ
) {
3584 verbose(env
, "only read is supported\n");
3588 ret
= btf_struct_access(&env
->log
, reg
->btf
, t
, off
, size
,
3595 if (atype
== BPF_READ
&& value_regno
>= 0)
3596 mark_btf_ld_reg(env
, regs
, value_regno
, ret
, reg
->btf
, btf_id
);
3601 static int check_ptr_to_map_access(struct bpf_verifier_env
*env
,
3602 struct bpf_reg_state
*regs
,
3603 int regno
, int off
, int size
,
3604 enum bpf_access_type atype
,
3607 struct bpf_reg_state
*reg
= regs
+ regno
;
3608 struct bpf_map
*map
= reg
->map_ptr
;
3609 const struct btf_type
*t
;
3615 verbose(env
, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
3619 if (!map
->ops
->map_btf_id
|| !*map
->ops
->map_btf_id
) {
3620 verbose(env
, "map_ptr access not supported for map type %d\n",
3625 t
= btf_type_by_id(btf_vmlinux
, *map
->ops
->map_btf_id
);
3626 tname
= btf_name_by_offset(btf_vmlinux
, t
->name_off
);
3628 if (!env
->allow_ptr_to_map_access
) {
3630 "%s access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
3636 verbose(env
, "R%d is %s invalid negative access: off=%d\n",
3641 if (atype
!= BPF_READ
) {
3642 verbose(env
, "only read from %s is supported\n", tname
);
3646 ret
= btf_struct_access(&env
->log
, btf_vmlinux
, t
, off
, size
, atype
, &btf_id
);
3650 if (value_regno
>= 0)
3651 mark_btf_ld_reg(env
, regs
, value_regno
, ret
, btf_vmlinux
, btf_id
);
3656 /* Check that the stack access at the given offset is within bounds. The
3657 * maximum valid offset is -1.
3659 * The minimum valid offset is -MAX_BPF_STACK for writes, and
3660 * -state->allocated_stack for reads.
3662 static int check_stack_slot_within_bounds(int off
,
3663 struct bpf_func_state
*state
,
3664 enum bpf_access_type t
)
3669 min_valid_off
= -MAX_BPF_STACK
;
3671 min_valid_off
= -state
->allocated_stack
;
3673 if (off
< min_valid_off
|| off
> -1)
3678 /* Check that the stack access at 'regno + off' falls within the maximum stack
3681 * 'off' includes `regno->offset`, but not its dynamic part (if any).
3683 static int check_stack_access_within_bounds(
3684 struct bpf_verifier_env
*env
,
3685 int regno
, int off
, int access_size
,
3686 enum stack_access_src src
, enum bpf_access_type type
)
3688 struct bpf_reg_state
*regs
= cur_regs(env
);
3689 struct bpf_reg_state
*reg
= regs
+ regno
;
3690 struct bpf_func_state
*state
= func(env
, reg
);
3691 int min_off
, max_off
;
3695 if (src
== ACCESS_HELPER
)
3696 /* We don't know if helpers are reading or writing (or both). */
3697 err_extra
= " indirect access to";
3698 else if (type
== BPF_READ
)
3699 err_extra
= " read from";
3701 err_extra
= " write to";
3703 if (tnum_is_const(reg
->var_off
)) {
3704 min_off
= reg
->var_off
.value
+ off
;
3705 if (access_size
> 0)
3706 max_off
= min_off
+ access_size
- 1;
3710 if (reg
->smax_value
>= BPF_MAX_VAR_OFF
||
3711 reg
->smin_value
<= -BPF_MAX_VAR_OFF
) {
3712 verbose(env
, "invalid unbounded variable-offset%s stack R%d\n",
3716 min_off
= reg
->smin_value
+ off
;
3717 if (access_size
> 0)
3718 max_off
= reg
->smax_value
+ off
+ access_size
- 1;
3723 err
= check_stack_slot_within_bounds(min_off
, state
, type
);
3725 err
= check_stack_slot_within_bounds(max_off
, state
, type
);
3728 if (tnum_is_const(reg
->var_off
)) {
3729 verbose(env
, "invalid%s stack R%d off=%d size=%d\n",
3730 err_extra
, regno
, off
, access_size
);
3734 tnum_strn(tn_buf
, sizeof(tn_buf
), reg
->var_off
);
3735 verbose(env
, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
3736 err_extra
, regno
, tn_buf
, access_size
);
3742 /* check whether memory at (regno + off) is accessible for t = (read | write)
3743 * if t==write, value_regno is a register which value is stored into memory
3744 * if t==read, value_regno is a register which will receive the value from memory
3745 * if t==write && value_regno==-1, some unknown value is stored into memory
3746 * if t==read && value_regno==-1, don't care what we read from memory
3748 static int check_mem_access(struct bpf_verifier_env
*env
, int insn_idx
, u32 regno
,
3749 int off
, int bpf_size
, enum bpf_access_type t
,
3750 int value_regno
, bool strict_alignment_once
)
3752 struct bpf_reg_state
*regs
= cur_regs(env
);
3753 struct bpf_reg_state
*reg
= regs
+ regno
;
3754 struct bpf_func_state
*state
;
3757 size
= bpf_size_to_bytes(bpf_size
);
3761 /* alignment checks will add in reg->off themselves */
3762 err
= check_ptr_alignment(env
, reg
, off
, size
, strict_alignment_once
);
3766 /* for access checks, reg->off is just part of off */
3769 if (reg
->type
== PTR_TO_MAP_VALUE
) {
3770 if (t
== BPF_WRITE
&& value_regno
>= 0 &&
3771 is_pointer_value(env
, value_regno
)) {
3772 verbose(env
, "R%d leaks addr into map\n", value_regno
);
3775 err
= check_map_access_type(env
, regno
, off
, size
, t
);
3778 err
= check_map_access(env
, regno
, off
, size
, false);
3779 if (!err
&& t
== BPF_READ
&& value_regno
>= 0) {
3780 struct bpf_map
*map
= reg
->map_ptr
;
3782 /* if map is read-only, track its contents as scalars */
3783 if (tnum_is_const(reg
->var_off
) &&
3784 bpf_map_is_rdonly(map
) &&
3785 map
->ops
->map_direct_value_addr
) {
3786 int map_off
= off
+ reg
->var_off
.value
;
3789 err
= bpf_map_direct_read(map
, map_off
, size
,
3794 regs
[value_regno
].type
= SCALAR_VALUE
;
3795 __mark_reg_known(®s
[value_regno
], val
);
3797 mark_reg_unknown(env
, regs
, value_regno
);
3800 } else if (reg
->type
== PTR_TO_MEM
) {
3801 if (t
== BPF_WRITE
&& value_regno
>= 0 &&
3802 is_pointer_value(env
, value_regno
)) {
3803 verbose(env
, "R%d leaks addr into mem\n", value_regno
);
3806 err
= check_mem_region_access(env
, regno
, off
, size
,
3807 reg
->mem_size
, false);
3808 if (!err
&& t
== BPF_READ
&& value_regno
>= 0)
3809 mark_reg_unknown(env
, regs
, value_regno
);
3810 } else if (reg
->type
== PTR_TO_CTX
) {
3811 enum bpf_reg_type reg_type
= SCALAR_VALUE
;
3812 struct btf
*btf
= NULL
;
3815 if (t
== BPF_WRITE
&& value_regno
>= 0 &&
3816 is_pointer_value(env
, value_regno
)) {
3817 verbose(env
, "R%d leaks addr into ctx\n", value_regno
);
3821 err
= check_ctx_reg(env
, reg
, regno
);
3825 err
= check_ctx_access(env
, insn_idx
, off
, size
, t
, ®_type
, &btf
, &btf_id
);
3827 verbose_linfo(env
, insn_idx
, "; ");
3828 if (!err
&& t
== BPF_READ
&& value_regno
>= 0) {
3829 /* ctx access returns either a scalar, or a
3830 * PTR_TO_PACKET[_META,_END]. In the latter
3831 * case, we know the offset is zero.
3833 if (reg_type
== SCALAR_VALUE
) {
3834 mark_reg_unknown(env
, regs
, value_regno
);
3836 mark_reg_known_zero(env
, regs
,
3838 if (reg_type_may_be_null(reg_type
))
3839 regs
[value_regno
].id
= ++env
->id_gen
;
3840 /* A load of ctx field could have different
3841 * actual load size with the one encoded in the
3842 * insn. When the dst is PTR, it is for sure not
3845 regs
[value_regno
].subreg_def
= DEF_NOT_SUBREG
;
3846 if (reg_type
== PTR_TO_BTF_ID
||
3847 reg_type
== PTR_TO_BTF_ID_OR_NULL
) {
3848 regs
[value_regno
].btf
= btf
;
3849 regs
[value_regno
].btf_id
= btf_id
;
3852 regs
[value_regno
].type
= reg_type
;
3855 } else if (reg
->type
== PTR_TO_STACK
) {
3856 /* Basic bounds checks. */
3857 err
= check_stack_access_within_bounds(env
, regno
, off
, size
, ACCESS_DIRECT
, t
);
3861 state
= func(env
, reg
);
3862 err
= update_stack_depth(env
, state
, off
);
3867 err
= check_stack_read(env
, regno
, off
, size
,
3870 err
= check_stack_write(env
, regno
, off
, size
,
3871 value_regno
, insn_idx
);
3872 } else if (reg_is_pkt_pointer(reg
)) {
3873 if (t
== BPF_WRITE
&& !may_access_direct_pkt_data(env
, NULL
, t
)) {
3874 verbose(env
, "cannot write into packet\n");
3877 if (t
== BPF_WRITE
&& value_regno
>= 0 &&
3878 is_pointer_value(env
, value_regno
)) {
3879 verbose(env
, "R%d leaks addr into packet\n",
3883 err
= check_packet_access(env
, regno
, off
, size
, false);
3884 if (!err
&& t
== BPF_READ
&& value_regno
>= 0)
3885 mark_reg_unknown(env
, regs
, value_regno
);
3886 } else if (reg
->type
== PTR_TO_FLOW_KEYS
) {
3887 if (t
== BPF_WRITE
&& value_regno
>= 0 &&
3888 is_pointer_value(env
, value_regno
)) {
3889 verbose(env
, "R%d leaks addr into flow keys\n",
3894 err
= check_flow_keys_access(env
, off
, size
);
3895 if (!err
&& t
== BPF_READ
&& value_regno
>= 0)
3896 mark_reg_unknown(env
, regs
, value_regno
);
3897 } else if (type_is_sk_pointer(reg
->type
)) {
3898 if (t
== BPF_WRITE
) {
3899 verbose(env
, "R%d cannot write into %s\n",
3900 regno
, reg_type_str
[reg
->type
]);
3903 err
= check_sock_access(env
, insn_idx
, regno
, off
, size
, t
);
3904 if (!err
&& value_regno
>= 0)
3905 mark_reg_unknown(env
, regs
, value_regno
);
3906 } else if (reg
->type
== PTR_TO_TP_BUFFER
) {
3907 err
= check_tp_buffer_access(env
, reg
, regno
, off
, size
);
3908 if (!err
&& t
== BPF_READ
&& value_regno
>= 0)
3909 mark_reg_unknown(env
, regs
, value_regno
);
3910 } else if (reg
->type
== PTR_TO_BTF_ID
) {
3911 err
= check_ptr_to_btf_access(env
, regs
, regno
, off
, size
, t
,
3913 } else if (reg
->type
== CONST_PTR_TO_MAP
) {
3914 err
= check_ptr_to_map_access(env
, regs
, regno
, off
, size
, t
,
3916 } else if (reg
->type
== PTR_TO_RDONLY_BUF
) {
3917 if (t
== BPF_WRITE
) {
3918 verbose(env
, "R%d cannot write into %s\n",
3919 regno
, reg_type_str
[reg
->type
]);
3922 err
= check_buffer_access(env
, reg
, regno
, off
, size
, false,
3924 &env
->prog
->aux
->max_rdonly_access
);
3925 if (!err
&& value_regno
>= 0)
3926 mark_reg_unknown(env
, regs
, value_regno
);
3927 } else if (reg
->type
== PTR_TO_RDWR_BUF
) {
3928 err
= check_buffer_access(env
, reg
, regno
, off
, size
, false,
3930 &env
->prog
->aux
->max_rdwr_access
);
3931 if (!err
&& t
== BPF_READ
&& value_regno
>= 0)
3932 mark_reg_unknown(env
, regs
, value_regno
);
3934 verbose(env
, "R%d invalid mem access '%s'\n", regno
,
3935 reg_type_str
[reg
->type
]);
3939 if (!err
&& size
< BPF_REG_SIZE
&& value_regno
>= 0 && t
== BPF_READ
&&
3940 regs
[value_regno
].type
== SCALAR_VALUE
) {
3941 /* b/h/w load zero-extends, mark upper bits as known 0 */
3942 coerce_reg_to_size(®s
[value_regno
], size
);
3947 static int check_xadd(struct bpf_verifier_env
*env
, int insn_idx
, struct bpf_insn
*insn
)
3951 if ((BPF_SIZE(insn
->code
) != BPF_W
&& BPF_SIZE(insn
->code
) != BPF_DW
) ||
3953 verbose(env
, "BPF_XADD uses reserved fields\n");
3957 /* check src1 operand */
3958 err
= check_reg_arg(env
, insn
->src_reg
, SRC_OP
);
3962 /* check src2 operand */
3963 err
= check_reg_arg(env
, insn
->dst_reg
, SRC_OP
);
3967 if (is_pointer_value(env
, insn
->src_reg
)) {
3968 verbose(env
, "R%d leaks addr into mem\n", insn
->src_reg
);
3972 if (is_ctx_reg(env
, insn
->dst_reg
) ||
3973 is_pkt_reg(env
, insn
->dst_reg
) ||
3974 is_flow_key_reg(env
, insn
->dst_reg
) ||
3975 is_sk_reg(env
, insn
->dst_reg
)) {
3976 verbose(env
, "BPF_XADD stores into R%d %s is not allowed\n",
3978 reg_type_str
[reg_state(env
, insn
->dst_reg
)->type
]);
3982 /* check whether atomic_add can read the memory */
3983 err
= check_mem_access(env
, insn_idx
, insn
->dst_reg
, insn
->off
,
3984 BPF_SIZE(insn
->code
), BPF_READ
, -1, true);
3988 /* check whether atomic_add can write into the same memory */
3989 return check_mem_access(env
, insn_idx
, insn
->dst_reg
, insn
->off
,
3990 BPF_SIZE(insn
->code
), BPF_WRITE
, -1, true);
3993 /* When register 'regno' is used to read the stack (either directly or through
3994 * a helper function) make sure that it's within stack boundary and, depending
3995 * on the access type, that all elements of the stack are initialized.
3997 * 'off' includes 'regno->off', but not its dynamic part (if any).
3999 * All registers that have been spilled on the stack in the slots within the
4000 * read offsets are marked as read.
4002 static int check_stack_range_initialized(
4003 struct bpf_verifier_env
*env
, int regno
, int off
,
4004 int access_size
, bool zero_size_allowed
,
4005 enum stack_access_src type
, struct bpf_call_arg_meta
*meta
)
4007 struct bpf_reg_state
*reg
= reg_state(env
, regno
);
4008 struct bpf_func_state
*state
= func(env
, reg
);
4009 int err
, min_off
, max_off
, i
, j
, slot
, spi
;
4010 char *err_extra
= type
== ACCESS_HELPER
? " indirect" : "";
4011 enum bpf_access_type bounds_check_type
;
4012 /* Some accesses can write anything into the stack, others are
4015 bool clobber
= false;
4017 if (access_size
== 0 && !zero_size_allowed
) {
4018 verbose(env
, "invalid zero-sized read\n");
4022 if (type
== ACCESS_HELPER
) {
4023 /* The bounds checks for writes are more permissive than for
4024 * reads. However, if raw_mode is not set, we'll do extra
4027 bounds_check_type
= BPF_WRITE
;
4030 bounds_check_type
= BPF_READ
;
4032 err
= check_stack_access_within_bounds(env
, regno
, off
, access_size
,
4033 type
, bounds_check_type
);
4038 if (tnum_is_const(reg
->var_off
)) {
4039 min_off
= max_off
= reg
->var_off
.value
+ off
;
4041 /* Variable offset is prohibited for unprivileged mode for
4042 * simplicity since it requires corresponding support in
4043 * Spectre masking for stack ALU.
4044 * See also retrieve_ptr_limit().
4046 if (!env
->bypass_spec_v1
) {
4049 tnum_strn(tn_buf
, sizeof(tn_buf
), reg
->var_off
);
4050 verbose(env
, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
4051 regno
, err_extra
, tn_buf
);
4054 /* Only initialized buffer on stack is allowed to be accessed
4055 * with variable offset. With uninitialized buffer it's hard to
4056 * guarantee that whole memory is marked as initialized on
4057 * helper return since specific bounds are unknown what may
4058 * cause uninitialized stack leaking.
4060 if (meta
&& meta
->raw_mode
)
4063 min_off
= reg
->smin_value
+ off
;
4064 max_off
= reg
->smax_value
+ off
;
4067 if (meta
&& meta
->raw_mode
) {
4068 meta
->access_size
= access_size
;
4069 meta
->regno
= regno
;
4073 for (i
= min_off
; i
< max_off
+ access_size
; i
++) {
4077 spi
= slot
/ BPF_REG_SIZE
;
4078 if (state
->allocated_stack
<= slot
)
4080 stype
= &state
->stack
[spi
].slot_type
[slot
% BPF_REG_SIZE
];
4081 if (*stype
== STACK_MISC
)
4083 if (*stype
== STACK_ZERO
) {
4085 /* helper can write anything into the stack */
4086 *stype
= STACK_MISC
;
4091 if (state
->stack
[spi
].slot_type
[0] == STACK_SPILL
&&
4092 state
->stack
[spi
].spilled_ptr
.type
== PTR_TO_BTF_ID
)
4095 if (state
->stack
[spi
].slot_type
[0] == STACK_SPILL
&&
4096 (state
->stack
[spi
].spilled_ptr
.type
== SCALAR_VALUE
||
4097 env
->allow_ptr_leaks
)) {
4099 __mark_reg_unknown(env
, &state
->stack
[spi
].spilled_ptr
);
4100 for (j
= 0; j
< BPF_REG_SIZE
; j
++)
4101 state
->stack
[spi
].slot_type
[j
] = STACK_MISC
;
4107 if (tnum_is_const(reg
->var_off
)) {
4108 verbose(env
, "invalid%s read from stack R%d off %d+%d size %d\n",
4109 err_extra
, regno
, min_off
, i
- min_off
, access_size
);
4113 tnum_strn(tn_buf
, sizeof(tn_buf
), reg
->var_off
);
4114 verbose(env
, "invalid%s read from stack R%d var_off %s+%d size %d\n",
4115 err_extra
, regno
, tn_buf
, i
- min_off
, access_size
);
4119 /* reading any byte out of 8-byte 'spill_slot' will cause
4120 * the whole slot to be marked as 'read'
4122 mark_reg_read(env
, &state
->stack
[spi
].spilled_ptr
,
4123 state
->stack
[spi
].spilled_ptr
.parent
,
4126 return update_stack_depth(env
, state
, min_off
);
4129 static int check_helper_mem_access(struct bpf_verifier_env
*env
, int regno
,
4130 int access_size
, bool zero_size_allowed
,
4131 struct bpf_call_arg_meta
*meta
)
4133 struct bpf_reg_state
*regs
= cur_regs(env
), *reg
= ®s
[regno
];
4135 switch (reg
->type
) {
4137 case PTR_TO_PACKET_META
:
4138 return check_packet_access(env
, regno
, reg
->off
, access_size
,
4140 case PTR_TO_MAP_VALUE
:
4141 if (check_map_access_type(env
, regno
, reg
->off
, access_size
,
4142 meta
&& meta
->raw_mode
? BPF_WRITE
:
4145 return check_map_access(env
, regno
, reg
->off
, access_size
,
4148 return check_mem_region_access(env
, regno
, reg
->off
,
4149 access_size
, reg
->mem_size
,
4151 case PTR_TO_RDONLY_BUF
:
4152 if (meta
&& meta
->raw_mode
)
4154 return check_buffer_access(env
, reg
, regno
, reg
->off
,
4155 access_size
, zero_size_allowed
,
4157 &env
->prog
->aux
->max_rdonly_access
);
4158 case PTR_TO_RDWR_BUF
:
4159 return check_buffer_access(env
, reg
, regno
, reg
->off
,
4160 access_size
, zero_size_allowed
,
4162 &env
->prog
->aux
->max_rdwr_access
);
4164 return check_stack_range_initialized(
4166 regno
, reg
->off
, access_size
,
4167 zero_size_allowed
, ACCESS_HELPER
, meta
);
4168 default: /* scalar_value or invalid ptr */
4169 /* Allow zero-byte read from NULL, regardless of pointer type */
4170 if (zero_size_allowed
&& access_size
== 0 &&
4171 register_is_null(reg
))
4174 verbose(env
, "R%d type=%s expected=%s\n", regno
,
4175 reg_type_str
[reg
->type
],
4176 reg_type_str
[PTR_TO_STACK
]);
4181 /* Implementation details:
4182 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL
4183 * Two bpf_map_lookups (even with the same key) will have different reg->id.
4184 * For traditional PTR_TO_MAP_VALUE the verifier clears reg->id after
4185 * value_or_null->value transition, since the verifier only cares about
4186 * the range of access to valid map value pointer and doesn't care about actual
4187 * address of the map element.
4188 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
4189 * reg->id > 0 after value_or_null->value transition. By doing so
4190 * two bpf_map_lookups will be considered two different pointers that
4191 * point to different bpf_spin_locks.
4192 * The verifier allows taking only one bpf_spin_lock at a time to avoid
4194 * Since only one bpf_spin_lock is allowed the checks are simpler than
4195 * reg_is_refcounted() logic. The verifier needs to remember only
4196 * one spin_lock instead of array of acquired_refs.
4197 * cur_state->active_spin_lock remembers which map value element got locked
4198 * and clears it after bpf_spin_unlock.
4200 static int process_spin_lock(struct bpf_verifier_env
*env
, int regno
,
4203 struct bpf_reg_state
*regs
= cur_regs(env
), *reg
= ®s
[regno
];
4204 struct bpf_verifier_state
*cur
= env
->cur_state
;
4205 bool is_const
= tnum_is_const(reg
->var_off
);
4206 struct bpf_map
*map
= reg
->map_ptr
;
4207 u64 val
= reg
->var_off
.value
;
4211 "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
4217 "map '%s' has to have BTF in order to use bpf_spin_lock\n",
4221 if (!map_value_has_spin_lock(map
)) {
4222 if (map
->spin_lock_off
== -E2BIG
)
4224 "map '%s' has more than one 'struct bpf_spin_lock'\n",
4226 else if (map
->spin_lock_off
== -ENOENT
)
4228 "map '%s' doesn't have 'struct bpf_spin_lock'\n",
4232 "map '%s' is not a struct type or bpf_spin_lock is mangled\n",
4236 if (map
->spin_lock_off
!= val
+ reg
->off
) {
4237 verbose(env
, "off %lld doesn't point to 'struct bpf_spin_lock'\n",
4242 if (cur
->active_spin_lock
) {
4244 "Locking two bpf_spin_locks are not allowed\n");
4247 cur
->active_spin_lock
= reg
->id
;
4249 if (!cur
->active_spin_lock
) {
4250 verbose(env
, "bpf_spin_unlock without taking a lock\n");
4253 if (cur
->active_spin_lock
!= reg
->id
) {
4254 verbose(env
, "bpf_spin_unlock of different lock\n");
4257 cur
->active_spin_lock
= 0;
4262 static bool arg_type_is_mem_ptr(enum bpf_arg_type type
)
4264 return type
== ARG_PTR_TO_MEM
||
4265 type
== ARG_PTR_TO_MEM_OR_NULL
||
4266 type
== ARG_PTR_TO_UNINIT_MEM
;
4269 static bool arg_type_is_mem_size(enum bpf_arg_type type
)
4271 return type
== ARG_CONST_SIZE
||
4272 type
== ARG_CONST_SIZE_OR_ZERO
;
4275 static bool arg_type_is_alloc_size(enum bpf_arg_type type
)
4277 return type
== ARG_CONST_ALLOC_SIZE_OR_ZERO
;
4280 static bool arg_type_is_int_ptr(enum bpf_arg_type type
)
4282 return type
== ARG_PTR_TO_INT
||
4283 type
== ARG_PTR_TO_LONG
;
4286 static int int_ptr_type_to_size(enum bpf_arg_type type
)
4288 if (type
== ARG_PTR_TO_INT
)
4290 else if (type
== ARG_PTR_TO_LONG
)
4296 static int resolve_map_arg_type(struct bpf_verifier_env
*env
,
4297 const struct bpf_call_arg_meta
*meta
,
4298 enum bpf_arg_type
*arg_type
)
4300 if (!meta
->map_ptr
) {
4301 /* kernel subsystem misconfigured verifier */
4302 verbose(env
, "invalid map_ptr to access map->type\n");
4306 switch (meta
->map_ptr
->map_type
) {
4307 case BPF_MAP_TYPE_SOCKMAP
:
4308 case BPF_MAP_TYPE_SOCKHASH
:
4309 if (*arg_type
== ARG_PTR_TO_MAP_VALUE
) {
4310 *arg_type
= ARG_PTR_TO_BTF_ID_SOCK_COMMON
;
4312 verbose(env
, "invalid arg_type for sockmap/sockhash\n");
4323 struct bpf_reg_types
{
4324 const enum bpf_reg_type types
[10];
4328 static const struct bpf_reg_types map_key_value_types
= {
4337 static const struct bpf_reg_types sock_types
= {
4347 static const struct bpf_reg_types btf_id_sock_common_types
= {
4355 .btf_id
= &btf_sock_ids
[BTF_SOCK_TYPE_SOCK_COMMON
],
4359 static const struct bpf_reg_types mem_types
= {
4371 static const struct bpf_reg_types int_ptr_types
= {
4380 static const struct bpf_reg_types fullsock_types
= { .types
= { PTR_TO_SOCKET
} };
4381 static const struct bpf_reg_types scalar_types
= { .types
= { SCALAR_VALUE
} };
4382 static const struct bpf_reg_types context_types
= { .types
= { PTR_TO_CTX
} };
4383 static const struct bpf_reg_types alloc_mem_types
= { .types
= { PTR_TO_MEM
} };
4384 static const struct bpf_reg_types const_map_ptr_types
= { .types
= { CONST_PTR_TO_MAP
} };
4385 static const struct bpf_reg_types btf_ptr_types
= { .types
= { PTR_TO_BTF_ID
} };
4386 static const struct bpf_reg_types spin_lock_types
= { .types
= { PTR_TO_MAP_VALUE
} };
4387 static const struct bpf_reg_types percpu_btf_ptr_types
= { .types
= { PTR_TO_PERCPU_BTF_ID
} };
4389 static const struct bpf_reg_types
*compatible_reg_types
[__BPF_ARG_TYPE_MAX
] = {
4390 [ARG_PTR_TO_MAP_KEY
] = &map_key_value_types
,
4391 [ARG_PTR_TO_MAP_VALUE
] = &map_key_value_types
,
4392 [ARG_PTR_TO_UNINIT_MAP_VALUE
] = &map_key_value_types
,
4393 [ARG_PTR_TO_MAP_VALUE_OR_NULL
] = &map_key_value_types
,
4394 [ARG_CONST_SIZE
] = &scalar_types
,
4395 [ARG_CONST_SIZE_OR_ZERO
] = &scalar_types
,
4396 [ARG_CONST_ALLOC_SIZE_OR_ZERO
] = &scalar_types
,
4397 [ARG_CONST_MAP_PTR
] = &const_map_ptr_types
,
4398 [ARG_PTR_TO_CTX
] = &context_types
,
4399 [ARG_PTR_TO_CTX_OR_NULL
] = &context_types
,
4400 [ARG_PTR_TO_SOCK_COMMON
] = &sock_types
,
4402 [ARG_PTR_TO_BTF_ID_SOCK_COMMON
] = &btf_id_sock_common_types
,
4404 [ARG_PTR_TO_SOCKET
] = &fullsock_types
,
4405 [ARG_PTR_TO_SOCKET_OR_NULL
] = &fullsock_types
,
4406 [ARG_PTR_TO_BTF_ID
] = &btf_ptr_types
,
4407 [ARG_PTR_TO_SPIN_LOCK
] = &spin_lock_types
,
4408 [ARG_PTR_TO_MEM
] = &mem_types
,
4409 [ARG_PTR_TO_MEM_OR_NULL
] = &mem_types
,
4410 [ARG_PTR_TO_UNINIT_MEM
] = &mem_types
,
4411 [ARG_PTR_TO_ALLOC_MEM
] = &alloc_mem_types
,
4412 [ARG_PTR_TO_ALLOC_MEM_OR_NULL
] = &alloc_mem_types
,
4413 [ARG_PTR_TO_INT
] = &int_ptr_types
,
4414 [ARG_PTR_TO_LONG
] = &int_ptr_types
,
4415 [ARG_PTR_TO_PERCPU_BTF_ID
] = &percpu_btf_ptr_types
,
4418 static int check_reg_type(struct bpf_verifier_env
*env
, u32 regno
,
4419 enum bpf_arg_type arg_type
,
4420 const u32
*arg_btf_id
)
4422 struct bpf_reg_state
*regs
= cur_regs(env
), *reg
= ®s
[regno
];
4423 enum bpf_reg_type expected
, type
= reg
->type
;
4424 const struct bpf_reg_types
*compatible
;
4427 compatible
= compatible_reg_types
[arg_type
];
4429 verbose(env
, "verifier internal error: unsupported arg type %d\n", arg_type
);
4433 for (i
= 0; i
< ARRAY_SIZE(compatible
->types
); i
++) {
4434 expected
= compatible
->types
[i
];
4435 if (expected
== NOT_INIT
)
4438 if (type
== expected
)
4442 verbose(env
, "R%d type=%s expected=", regno
, reg_type_str
[type
]);
4443 for (j
= 0; j
+ 1 < i
; j
++)
4444 verbose(env
, "%s, ", reg_type_str
[compatible
->types
[j
]]);
4445 verbose(env
, "%s\n", reg_type_str
[compatible
->types
[j
]]);
4449 if (type
== PTR_TO_BTF_ID
) {
4451 if (!compatible
->btf_id
) {
4452 verbose(env
, "verifier internal error: missing arg compatible BTF ID\n");
4455 arg_btf_id
= compatible
->btf_id
;
4458 if (!btf_struct_ids_match(&env
->log
, reg
->btf
, reg
->btf_id
, reg
->off
,
4459 btf_vmlinux
, *arg_btf_id
)) {
4460 verbose(env
, "R%d is of type %s but %s is expected\n",
4461 regno
, kernel_type_name(reg
->btf
, reg
->btf_id
),
4462 kernel_type_name(btf_vmlinux
, *arg_btf_id
));
4466 if (!tnum_is_const(reg
->var_off
) || reg
->var_off
.value
) {
4467 verbose(env
, "R%d is a pointer to in-kernel struct with non-zero offset\n",
4476 static int check_func_arg(struct bpf_verifier_env
*env
, u32 arg
,
4477 struct bpf_call_arg_meta
*meta
,
4478 const struct bpf_func_proto
*fn
)
4480 u32 regno
= BPF_REG_1
+ arg
;
4481 struct bpf_reg_state
*regs
= cur_regs(env
), *reg
= ®s
[regno
];
4482 enum bpf_arg_type arg_type
= fn
->arg_type
[arg
];
4483 enum bpf_reg_type type
= reg
->type
;
4486 if (arg_type
== ARG_DONTCARE
)
4489 err
= check_reg_arg(env
, regno
, SRC_OP
);
4493 if (arg_type
== ARG_ANYTHING
) {
4494 if (is_pointer_value(env
, regno
)) {
4495 verbose(env
, "R%d leaks addr into helper function\n",
4502 if (type_is_pkt_pointer(type
) &&
4503 !may_access_direct_pkt_data(env
, meta
, BPF_READ
)) {
4504 verbose(env
, "helper access to the packet is not allowed\n");
4508 if (arg_type
== ARG_PTR_TO_MAP_VALUE
||
4509 arg_type
== ARG_PTR_TO_UNINIT_MAP_VALUE
||
4510 arg_type
== ARG_PTR_TO_MAP_VALUE_OR_NULL
) {
4511 err
= resolve_map_arg_type(env
, meta
, &arg_type
);
4516 if (register_is_null(reg
) && arg_type_may_be_null(arg_type
))
4517 /* A NULL register has a SCALAR_VALUE type, so skip
4520 goto skip_type_check
;
4522 err
= check_reg_type(env
, regno
, arg_type
, fn
->arg_btf_id
[arg
]);
4526 if (type
== PTR_TO_CTX
) {
4527 err
= check_ctx_reg(env
, reg
, regno
);
4533 if (reg
->ref_obj_id
) {
4534 if (meta
->ref_obj_id
) {
4535 verbose(env
, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
4536 regno
, reg
->ref_obj_id
,
4540 meta
->ref_obj_id
= reg
->ref_obj_id
;
4543 if (arg_type
== ARG_CONST_MAP_PTR
) {
4544 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
4545 meta
->map_ptr
= reg
->map_ptr
;
4546 } else if (arg_type
== ARG_PTR_TO_MAP_KEY
) {
4547 /* bpf_map_xxx(..., map_ptr, ..., key) call:
4548 * check that [key, key + map->key_size) are within
4549 * stack limits and initialized
4551 if (!meta
->map_ptr
) {
4552 /* in function declaration map_ptr must come before
4553 * map_key, so that it's verified and known before
4554 * we have to check map_key here. Otherwise it means
4555 * that kernel subsystem misconfigured verifier
4557 verbose(env
, "invalid map_ptr to access map->key\n");
4560 err
= check_helper_mem_access(env
, regno
,
4561 meta
->map_ptr
->key_size
, false,
4563 } else if (arg_type
== ARG_PTR_TO_MAP_VALUE
||
4564 (arg_type
== ARG_PTR_TO_MAP_VALUE_OR_NULL
&&
4565 !register_is_null(reg
)) ||
4566 arg_type
== ARG_PTR_TO_UNINIT_MAP_VALUE
) {
4567 /* bpf_map_xxx(..., map_ptr, ..., value) call:
4568 * check [value, value + map->value_size) validity
4570 if (!meta
->map_ptr
) {
4571 /* kernel subsystem misconfigured verifier */
4572 verbose(env
, "invalid map_ptr to access map->value\n");
4575 meta
->raw_mode
= (arg_type
== ARG_PTR_TO_UNINIT_MAP_VALUE
);
4576 err
= check_helper_mem_access(env
, regno
,
4577 meta
->map_ptr
->value_size
, false,
4579 } else if (arg_type
== ARG_PTR_TO_PERCPU_BTF_ID
) {
4581 verbose(env
, "Helper has invalid btf_id in R%d\n", regno
);
4584 meta
->ret_btf
= reg
->btf
;
4585 meta
->ret_btf_id
= reg
->btf_id
;
4586 } else if (arg_type
== ARG_PTR_TO_SPIN_LOCK
) {
4587 if (meta
->func_id
== BPF_FUNC_spin_lock
) {
4588 if (process_spin_lock(env
, regno
, true))
4590 } else if (meta
->func_id
== BPF_FUNC_spin_unlock
) {
4591 if (process_spin_lock(env
, regno
, false))
4594 verbose(env
, "verifier internal error\n");
4597 } else if (arg_type_is_mem_ptr(arg_type
)) {
4598 /* The access to this pointer is only checked when we hit the
4599 * next is_mem_size argument below.
4601 meta
->raw_mode
= (arg_type
== ARG_PTR_TO_UNINIT_MEM
);
4602 } else if (arg_type_is_mem_size(arg_type
)) {
4603 bool zero_size_allowed
= (arg_type
== ARG_CONST_SIZE_OR_ZERO
);
4605 /* This is used to refine r0 return value bounds for helpers
4606 * that enforce this value as an upper bound on return values.
4607 * See do_refine_retval_range() for helpers that can refine
4608 * the return value. C type of helper is u32 so we pull register
4609 * bound from umax_value however, if negative verifier errors
4610 * out. Only upper bounds can be learned because retval is an
4611 * int type and negative retvals are allowed.
4613 meta
->msize_max_value
= reg
->umax_value
;
4615 /* The register is SCALAR_VALUE; the access check
4616 * happens using its boundaries.
4618 if (!tnum_is_const(reg
->var_off
))
4619 /* For unprivileged variable accesses, disable raw
4620 * mode so that the program is required to
4621 * initialize all the memory that the helper could
4622 * just partially fill up.
4626 if (reg
->smin_value
< 0) {
4627 verbose(env
, "R%d min value is negative, either use unsigned or 'var &= const'\n",
4632 if (reg
->umin_value
== 0) {
4633 err
= check_helper_mem_access(env
, regno
- 1, 0,
4640 if (reg
->umax_value
>= BPF_MAX_VAR_SIZ
) {
4641 verbose(env
, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
4645 err
= check_helper_mem_access(env
, regno
- 1,
4647 zero_size_allowed
, meta
);
4649 err
= mark_chain_precision(env
, regno
);
4650 } else if (arg_type_is_alloc_size(arg_type
)) {
4651 if (!tnum_is_const(reg
->var_off
)) {
4652 verbose(env
, "R%d unbounded size, use 'var &= const' or 'if (var < const)'\n",
4656 meta
->mem_size
= reg
->var_off
.value
;
4657 } else if (arg_type_is_int_ptr(arg_type
)) {
4658 int size
= int_ptr_type_to_size(arg_type
);
4660 err
= check_helper_mem_access(env
, regno
, size
, false, meta
);
4663 err
= check_ptr_alignment(env
, reg
, 0, size
, true);
4669 static bool may_update_sockmap(struct bpf_verifier_env
*env
, int func_id
)
4671 enum bpf_attach_type eatype
= env
->prog
->expected_attach_type
;
4672 enum bpf_prog_type type
= resolve_prog_type(env
->prog
);
4674 if (func_id
!= BPF_FUNC_map_update_elem
)
4677 /* It's not possible to get access to a locked struct sock in these
4678 * contexts, so updating is safe.
4681 case BPF_PROG_TYPE_TRACING
:
4682 if (eatype
== BPF_TRACE_ITER
)
4685 case BPF_PROG_TYPE_SOCKET_FILTER
:
4686 case BPF_PROG_TYPE_SCHED_CLS
:
4687 case BPF_PROG_TYPE_SCHED_ACT
:
4688 case BPF_PROG_TYPE_XDP
:
4689 case BPF_PROG_TYPE_SK_REUSEPORT
:
4690 case BPF_PROG_TYPE_FLOW_DISSECTOR
:
4691 case BPF_PROG_TYPE_SK_LOOKUP
:
4697 verbose(env
, "cannot update sockmap in this context\n");
4701 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env
*env
)
4703 return env
->prog
->jit_requested
&& IS_ENABLED(CONFIG_X86_64
);
4706 static int check_map_func_compatibility(struct bpf_verifier_env
*env
,
4707 struct bpf_map
*map
, int func_id
)
4712 /* We need a two way check, first is from map perspective ... */
4713 switch (map
->map_type
) {
4714 case BPF_MAP_TYPE_PROG_ARRAY
:
4715 if (func_id
!= BPF_FUNC_tail_call
)
4718 case BPF_MAP_TYPE_PERF_EVENT_ARRAY
:
4719 if (func_id
!= BPF_FUNC_perf_event_read
&&
4720 func_id
!= BPF_FUNC_perf_event_output
&&
4721 func_id
!= BPF_FUNC_skb_output
&&
4722 func_id
!= BPF_FUNC_perf_event_read_value
&&
4723 func_id
!= BPF_FUNC_xdp_output
)
4726 case BPF_MAP_TYPE_RINGBUF
:
4727 if (func_id
!= BPF_FUNC_ringbuf_output
&&
4728 func_id
!= BPF_FUNC_ringbuf_reserve
&&
4729 func_id
!= BPF_FUNC_ringbuf_submit
&&
4730 func_id
!= BPF_FUNC_ringbuf_discard
&&
4731 func_id
!= BPF_FUNC_ringbuf_query
)
4734 case BPF_MAP_TYPE_STACK_TRACE
:
4735 if (func_id
!= BPF_FUNC_get_stackid
)
4738 case BPF_MAP_TYPE_CGROUP_ARRAY
:
4739 if (func_id
!= BPF_FUNC_skb_under_cgroup
&&
4740 func_id
!= BPF_FUNC_current_task_under_cgroup
)
4743 case BPF_MAP_TYPE_CGROUP_STORAGE
:
4744 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE
:
4745 if (func_id
!= BPF_FUNC_get_local_storage
)
4748 case BPF_MAP_TYPE_DEVMAP
:
4749 case BPF_MAP_TYPE_DEVMAP_HASH
:
4750 if (func_id
!= BPF_FUNC_redirect_map
&&
4751 func_id
!= BPF_FUNC_map_lookup_elem
)
4754 /* Restrict bpf side of cpumap and xskmap, open when use-cases
4757 case BPF_MAP_TYPE_CPUMAP
:
4758 if (func_id
!= BPF_FUNC_redirect_map
)
4761 case BPF_MAP_TYPE_XSKMAP
:
4762 if (func_id
!= BPF_FUNC_redirect_map
&&
4763 func_id
!= BPF_FUNC_map_lookup_elem
)
4766 case BPF_MAP_TYPE_ARRAY_OF_MAPS
:
4767 case BPF_MAP_TYPE_HASH_OF_MAPS
:
4768 if (func_id
!= BPF_FUNC_map_lookup_elem
)
4771 case BPF_MAP_TYPE_SOCKMAP
:
4772 if (func_id
!= BPF_FUNC_sk_redirect_map
&&
4773 func_id
!= BPF_FUNC_sock_map_update
&&
4774 func_id
!= BPF_FUNC_map_delete_elem
&&
4775 func_id
!= BPF_FUNC_msg_redirect_map
&&
4776 func_id
!= BPF_FUNC_sk_select_reuseport
&&
4777 func_id
!= BPF_FUNC_map_lookup_elem
&&
4778 !may_update_sockmap(env
, func_id
))
4781 case BPF_MAP_TYPE_SOCKHASH
:
4782 if (func_id
!= BPF_FUNC_sk_redirect_hash
&&
4783 func_id
!= BPF_FUNC_sock_hash_update
&&
4784 func_id
!= BPF_FUNC_map_delete_elem
&&
4785 func_id
!= BPF_FUNC_msg_redirect_hash
&&
4786 func_id
!= BPF_FUNC_sk_select_reuseport
&&
4787 func_id
!= BPF_FUNC_map_lookup_elem
&&
4788 !may_update_sockmap(env
, func_id
))
4791 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY
:
4792 if (func_id
!= BPF_FUNC_sk_select_reuseport
)
4795 case BPF_MAP_TYPE_QUEUE
:
4796 case BPF_MAP_TYPE_STACK
:
4797 if (func_id
!= BPF_FUNC_map_peek_elem
&&
4798 func_id
!= BPF_FUNC_map_pop_elem
&&
4799 func_id
!= BPF_FUNC_map_push_elem
)
4802 case BPF_MAP_TYPE_SK_STORAGE
:
4803 if (func_id
!= BPF_FUNC_sk_storage_get
&&
4804 func_id
!= BPF_FUNC_sk_storage_delete
)
4807 case BPF_MAP_TYPE_INODE_STORAGE
:
4808 if (func_id
!= BPF_FUNC_inode_storage_get
&&
4809 func_id
!= BPF_FUNC_inode_storage_delete
)
4812 case BPF_MAP_TYPE_TASK_STORAGE
:
4813 if (func_id
!= BPF_FUNC_task_storage_get
&&
4814 func_id
!= BPF_FUNC_task_storage_delete
)
4821 /* ... and second from the function itself. */
4823 case BPF_FUNC_tail_call
:
4824 if (map
->map_type
!= BPF_MAP_TYPE_PROG_ARRAY
)
4826 if (env
->subprog_cnt
> 1 && !allow_tail_call_in_subprogs(env
)) {
4827 verbose(env
, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
4831 case BPF_FUNC_perf_event_read
:
4832 case BPF_FUNC_perf_event_output
:
4833 case BPF_FUNC_perf_event_read_value
:
4834 case BPF_FUNC_skb_output
:
4835 case BPF_FUNC_xdp_output
:
4836 if (map
->map_type
!= BPF_MAP_TYPE_PERF_EVENT_ARRAY
)
4839 case BPF_FUNC_get_stackid
:
4840 if (map
->map_type
!= BPF_MAP_TYPE_STACK_TRACE
)
4843 case BPF_FUNC_current_task_under_cgroup
:
4844 case BPF_FUNC_skb_under_cgroup
:
4845 if (map
->map_type
!= BPF_MAP_TYPE_CGROUP_ARRAY
)
4848 case BPF_FUNC_redirect_map
:
4849 if (map
->map_type
!= BPF_MAP_TYPE_DEVMAP
&&
4850 map
->map_type
!= BPF_MAP_TYPE_DEVMAP_HASH
&&
4851 map
->map_type
!= BPF_MAP_TYPE_CPUMAP
&&
4852 map
->map_type
!= BPF_MAP_TYPE_XSKMAP
)
4855 case BPF_FUNC_sk_redirect_map
:
4856 case BPF_FUNC_msg_redirect_map
:
4857 case BPF_FUNC_sock_map_update
:
4858 if (map
->map_type
!= BPF_MAP_TYPE_SOCKMAP
)
4861 case BPF_FUNC_sk_redirect_hash
:
4862 case BPF_FUNC_msg_redirect_hash
:
4863 case BPF_FUNC_sock_hash_update
:
4864 if (map
->map_type
!= BPF_MAP_TYPE_SOCKHASH
)
4867 case BPF_FUNC_get_local_storage
:
4868 if (map
->map_type
!= BPF_MAP_TYPE_CGROUP_STORAGE
&&
4869 map
->map_type
!= BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE
)
4872 case BPF_FUNC_sk_select_reuseport
:
4873 if (map
->map_type
!= BPF_MAP_TYPE_REUSEPORT_SOCKARRAY
&&
4874 map
->map_type
!= BPF_MAP_TYPE_SOCKMAP
&&
4875 map
->map_type
!= BPF_MAP_TYPE_SOCKHASH
)
4878 case BPF_FUNC_map_peek_elem
:
4879 case BPF_FUNC_map_pop_elem
:
4880 case BPF_FUNC_map_push_elem
:
4881 if (map
->map_type
!= BPF_MAP_TYPE_QUEUE
&&
4882 map
->map_type
!= BPF_MAP_TYPE_STACK
)
4885 case BPF_FUNC_sk_storage_get
:
4886 case BPF_FUNC_sk_storage_delete
:
4887 if (map
->map_type
!= BPF_MAP_TYPE_SK_STORAGE
)
4890 case BPF_FUNC_inode_storage_get
:
4891 case BPF_FUNC_inode_storage_delete
:
4892 if (map
->map_type
!= BPF_MAP_TYPE_INODE_STORAGE
)
4895 case BPF_FUNC_task_storage_get
:
4896 case BPF_FUNC_task_storage_delete
:
4897 if (map
->map_type
!= BPF_MAP_TYPE_TASK_STORAGE
)
4906 verbose(env
, "cannot pass map_type %d into func %s#%d\n",
4907 map
->map_type
, func_id_name(func_id
), func_id
);
4911 static bool check_raw_mode_ok(const struct bpf_func_proto
*fn
)
4915 if (fn
->arg1_type
== ARG_PTR_TO_UNINIT_MEM
)
4917 if (fn
->arg2_type
== ARG_PTR_TO_UNINIT_MEM
)
4919 if (fn
->arg3_type
== ARG_PTR_TO_UNINIT_MEM
)
4921 if (fn
->arg4_type
== ARG_PTR_TO_UNINIT_MEM
)
4923 if (fn
->arg5_type
== ARG_PTR_TO_UNINIT_MEM
)
4926 /* We only support one arg being in raw mode at the moment,
4927 * which is sufficient for the helper functions we have
4933 static bool check_args_pair_invalid(enum bpf_arg_type arg_curr
,
4934 enum bpf_arg_type arg_next
)
4936 return (arg_type_is_mem_ptr(arg_curr
) &&
4937 !arg_type_is_mem_size(arg_next
)) ||
4938 (!arg_type_is_mem_ptr(arg_curr
) &&
4939 arg_type_is_mem_size(arg_next
));
4942 static bool check_arg_pair_ok(const struct bpf_func_proto
*fn
)
4944 /* bpf_xxx(..., buf, len) call will access 'len'
4945 * bytes from memory 'buf'. Both arg types need
4946 * to be paired, so make sure there's no buggy
4947 * helper function specification.
4949 if (arg_type_is_mem_size(fn
->arg1_type
) ||
4950 arg_type_is_mem_ptr(fn
->arg5_type
) ||
4951 check_args_pair_invalid(fn
->arg1_type
, fn
->arg2_type
) ||
4952 check_args_pair_invalid(fn
->arg2_type
, fn
->arg3_type
) ||
4953 check_args_pair_invalid(fn
->arg3_type
, fn
->arg4_type
) ||
4954 check_args_pair_invalid(fn
->arg4_type
, fn
->arg5_type
))
4960 static bool check_refcount_ok(const struct bpf_func_proto
*fn
, int func_id
)
4964 if (arg_type_may_be_refcounted(fn
->arg1_type
))
4966 if (arg_type_may_be_refcounted(fn
->arg2_type
))
4968 if (arg_type_may_be_refcounted(fn
->arg3_type
))
4970 if (arg_type_may_be_refcounted(fn
->arg4_type
))
4972 if (arg_type_may_be_refcounted(fn
->arg5_type
))
4975 /* A reference acquiring function cannot acquire
4976 * another refcounted ptr.
4978 if (may_be_acquire_function(func_id
) && count
)
4981 /* We only support one arg being unreferenced at the moment,
4982 * which is sufficient for the helper functions we have right now.
4987 static bool check_btf_id_ok(const struct bpf_func_proto
*fn
)
4991 for (i
= 0; i
< ARRAY_SIZE(fn
->arg_type
); i
++) {
4992 if (fn
->arg_type
[i
] == ARG_PTR_TO_BTF_ID
&& !fn
->arg_btf_id
[i
])
4995 if (fn
->arg_type
[i
] != ARG_PTR_TO_BTF_ID
&& fn
->arg_btf_id
[i
])
5002 static int check_func_proto(const struct bpf_func_proto
*fn
, int func_id
)
5004 return check_raw_mode_ok(fn
) &&
5005 check_arg_pair_ok(fn
) &&
5006 check_btf_id_ok(fn
) &&
5007 check_refcount_ok(fn
, func_id
) ? 0 : -EINVAL
;
5010 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
5011 * are now invalid, so turn them into unknown SCALAR_VALUE.
5013 static void __clear_all_pkt_pointers(struct bpf_verifier_env
*env
,
5014 struct bpf_func_state
*state
)
5016 struct bpf_reg_state
*regs
= state
->regs
, *reg
;
5019 for (i
= 0; i
< MAX_BPF_REG
; i
++)
5020 if (reg_is_pkt_pointer_any(®s
[i
]))
5021 mark_reg_unknown(env
, regs
, i
);
5023 bpf_for_each_spilled_reg(i
, state
, reg
) {
5026 if (reg_is_pkt_pointer_any(reg
))
5027 __mark_reg_unknown(env
, reg
);
5031 static void clear_all_pkt_pointers(struct bpf_verifier_env
*env
)
5033 struct bpf_verifier_state
*vstate
= env
->cur_state
;
5036 for (i
= 0; i
<= vstate
->curframe
; i
++)
5037 __clear_all_pkt_pointers(env
, vstate
->frame
[i
]);
5042 BEYOND_PKT_END
= -2,
5045 static void mark_pkt_end(struct bpf_verifier_state
*vstate
, int regn
, bool range_open
)
5047 struct bpf_func_state
*state
= vstate
->frame
[vstate
->curframe
];
5048 struct bpf_reg_state
*reg
= &state
->regs
[regn
];
5050 if (reg
->type
!= PTR_TO_PACKET
)
5051 /* PTR_TO_PACKET_META is not supported yet */
5054 /* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
5055 * How far beyond pkt_end it goes is unknown.
5056 * if (!range_open) it's the case of pkt >= pkt_end
5057 * if (range_open) it's the case of pkt > pkt_end
5058 * hence this pointer is at least 1 byte bigger than pkt_end
5061 reg
->range
= BEYOND_PKT_END
;
5063 reg
->range
= AT_PKT_END
;
5066 static void release_reg_references(struct bpf_verifier_env
*env
,
5067 struct bpf_func_state
*state
,
5070 struct bpf_reg_state
*regs
= state
->regs
, *reg
;
5073 for (i
= 0; i
< MAX_BPF_REG
; i
++)
5074 if (regs
[i
].ref_obj_id
== ref_obj_id
)
5075 mark_reg_unknown(env
, regs
, i
);
5077 bpf_for_each_spilled_reg(i
, state
, reg
) {
5080 if (reg
->ref_obj_id
== ref_obj_id
)
5081 __mark_reg_unknown(env
, reg
);
5085 /* The pointer with the specified id has released its reference to kernel
5086 * resources. Identify all copies of the same pointer and clear the reference.
5088 static int release_reference(struct bpf_verifier_env
*env
,
5091 struct bpf_verifier_state
*vstate
= env
->cur_state
;
5095 err
= release_reference_state(cur_func(env
), ref_obj_id
);
5099 for (i
= 0; i
<= vstate
->curframe
; i
++)
5100 release_reg_references(env
, vstate
->frame
[i
], ref_obj_id
);
5105 static void clear_caller_saved_regs(struct bpf_verifier_env
*env
,
5106 struct bpf_reg_state
*regs
)
5110 /* after the call registers r0 - r5 were scratched */
5111 for (i
= 0; i
< CALLER_SAVED_REGS
; i
++) {
5112 mark_reg_not_init(env
, regs
, caller_saved
[i
]);
5113 check_reg_arg(env
, caller_saved
[i
], DST_OP_NO_MARK
);
5117 static int check_func_call(struct bpf_verifier_env
*env
, struct bpf_insn
*insn
,
5120 struct bpf_verifier_state
*state
= env
->cur_state
;
5121 struct bpf_func_info_aux
*func_info_aux
;
5122 struct bpf_func_state
*caller
, *callee
;
5123 int i
, err
, subprog
, target_insn
;
5124 bool is_global
= false;
5126 if (state
->curframe
+ 1 >= MAX_CALL_FRAMES
) {
5127 verbose(env
, "the call stack of %d frames is too deep\n",
5128 state
->curframe
+ 2);
5132 target_insn
= *insn_idx
+ insn
->imm
;
5133 subprog
= find_subprog(env
, target_insn
+ 1);
5135 verbose(env
, "verifier bug. No program starts at insn %d\n",
5140 caller
= state
->frame
[state
->curframe
];
5141 if (state
->frame
[state
->curframe
+ 1]) {
5142 verbose(env
, "verifier bug. Frame %d already allocated\n",
5143 state
->curframe
+ 1);
5147 func_info_aux
= env
->prog
->aux
->func_info_aux
;
5149 is_global
= func_info_aux
[subprog
].linkage
== BTF_FUNC_GLOBAL
;
5150 err
= btf_check_func_arg_match(env
, subprog
, caller
->regs
);
5155 verbose(env
, "Caller passes invalid args into func#%d\n",
5159 if (env
->log
.level
& BPF_LOG_LEVEL
)
5161 "Func#%d is global and valid. Skipping.\n",
5163 clear_caller_saved_regs(env
, caller
->regs
);
5165 /* All global functions return a 64-bit SCALAR_VALUE */
5166 mark_reg_unknown(env
, caller
->regs
, BPF_REG_0
);
5167 caller
->regs
[BPF_REG_0
].subreg_def
= DEF_NOT_SUBREG
;
5169 /* continue with next insn after call */
5174 callee
= kzalloc(sizeof(*callee
), GFP_KERNEL
);
5177 state
->frame
[state
->curframe
+ 1] = callee
;
5179 /* callee cannot access r0, r6 - r9 for reading and has to write
5180 * into its own stack before reading from it.
5181 * callee can read/write into caller's stack
5183 init_func_state(env
, callee
,
5184 /* remember the callsite, it will be used by bpf_exit */
5185 *insn_idx
/* callsite */,
5186 state
->curframe
+ 1 /* frameno within this callchain */,
5187 subprog
/* subprog number within this prog */);
5189 /* Transfer references to the callee */
5190 err
= transfer_reference_state(callee
, caller
);
5194 /* copy r1 - r5 args that callee can access. The copy includes parent
5195 * pointers, which connects us up to the liveness chain
5197 for (i
= BPF_REG_1
; i
<= BPF_REG_5
; i
++)
5198 callee
->regs
[i
] = caller
->regs
[i
];
5200 clear_caller_saved_regs(env
, caller
->regs
);
5202 /* only increment it after check_reg_arg() finished */
5205 /* and go analyze first insn of the callee */
5206 *insn_idx
= target_insn
;
5208 if (env
->log
.level
& BPF_LOG_LEVEL
) {
5209 verbose(env
, "caller:\n");
5210 print_verifier_state(env
, caller
);
5211 verbose(env
, "callee:\n");
5212 print_verifier_state(env
, callee
);
5217 static int prepare_func_exit(struct bpf_verifier_env
*env
, int *insn_idx
)
5219 struct bpf_verifier_state
*state
= env
->cur_state
;
5220 struct bpf_func_state
*caller
, *callee
;
5221 struct bpf_reg_state
*r0
;
5224 callee
= state
->frame
[state
->curframe
];
5225 r0
= &callee
->regs
[BPF_REG_0
];
5226 if (r0
->type
== PTR_TO_STACK
) {
5227 /* technically it's ok to return caller's stack pointer
5228 * (or caller's caller's pointer) back to the caller,
5229 * since these pointers are valid. Only current stack
5230 * pointer will be invalid as soon as function exits,
5231 * but let's be conservative
5233 verbose(env
, "cannot return stack pointer to the caller\n");
5238 caller
= state
->frame
[state
->curframe
];
5239 /* return to the caller whatever r0 had in the callee */
5240 caller
->regs
[BPF_REG_0
] = *r0
;
5242 /* Transfer references to the caller */
5243 err
= transfer_reference_state(caller
, callee
);
5247 *insn_idx
= callee
->callsite
+ 1;
5248 if (env
->log
.level
& BPF_LOG_LEVEL
) {
5249 verbose(env
, "returning from callee:\n");
5250 print_verifier_state(env
, callee
);
5251 verbose(env
, "to caller at %d:\n", *insn_idx
);
5252 print_verifier_state(env
, caller
);
5254 /* clear everything in the callee */
5255 free_func_state(callee
);
5256 state
->frame
[state
->curframe
+ 1] = NULL
;
5260 static void do_refine_retval_range(struct bpf_reg_state
*regs
, int ret_type
,
5262 struct bpf_call_arg_meta
*meta
)
5264 struct bpf_reg_state
*ret_reg
= ®s
[BPF_REG_0
];
5266 if (ret_type
!= RET_INTEGER
||
5267 (func_id
!= BPF_FUNC_get_stack
&&
5268 func_id
!= BPF_FUNC_probe_read_str
&&
5269 func_id
!= BPF_FUNC_probe_read_kernel_str
&&
5270 func_id
!= BPF_FUNC_probe_read_user_str
))
5273 ret_reg
->smax_value
= meta
->msize_max_value
;
5274 ret_reg
->s32_max_value
= meta
->msize_max_value
;
5275 ret_reg
->smin_value
= -MAX_ERRNO
;
5276 ret_reg
->s32_min_value
= -MAX_ERRNO
;
5277 __reg_deduce_bounds(ret_reg
);
5278 __reg_bound_offset(ret_reg
);
5279 __update_reg_bounds(ret_reg
);
5283 record_func_map(struct bpf_verifier_env
*env
, struct bpf_call_arg_meta
*meta
,
5284 int func_id
, int insn_idx
)
5286 struct bpf_insn_aux_data
*aux
= &env
->insn_aux_data
[insn_idx
];
5287 struct bpf_map
*map
= meta
->map_ptr
;
5289 if (func_id
!= BPF_FUNC_tail_call
&&
5290 func_id
!= BPF_FUNC_map_lookup_elem
&&
5291 func_id
!= BPF_FUNC_map_update_elem
&&
5292 func_id
!= BPF_FUNC_map_delete_elem
&&
5293 func_id
!= BPF_FUNC_map_push_elem
&&
5294 func_id
!= BPF_FUNC_map_pop_elem
&&
5295 func_id
!= BPF_FUNC_map_peek_elem
)
5299 verbose(env
, "kernel subsystem misconfigured verifier\n");
5303 /* In case of read-only, some additional restrictions
5304 * need to be applied in order to prevent altering the
5305 * state of the map from program side.
5307 if ((map
->map_flags
& BPF_F_RDONLY_PROG
) &&
5308 (func_id
== BPF_FUNC_map_delete_elem
||
5309 func_id
== BPF_FUNC_map_update_elem
||
5310 func_id
== BPF_FUNC_map_push_elem
||
5311 func_id
== BPF_FUNC_map_pop_elem
)) {
5312 verbose(env
, "write into map forbidden\n");
5316 if (!BPF_MAP_PTR(aux
->map_ptr_state
))
5317 bpf_map_ptr_store(aux
, meta
->map_ptr
,
5318 !meta
->map_ptr
->bypass_spec_v1
);
5319 else if (BPF_MAP_PTR(aux
->map_ptr_state
) != meta
->map_ptr
)
5320 bpf_map_ptr_store(aux
, BPF_MAP_PTR_POISON
,
5321 !meta
->map_ptr
->bypass_spec_v1
);
5326 record_func_key(struct bpf_verifier_env
*env
, struct bpf_call_arg_meta
*meta
,
5327 int func_id
, int insn_idx
)
5329 struct bpf_insn_aux_data
*aux
= &env
->insn_aux_data
[insn_idx
];
5330 struct bpf_reg_state
*regs
= cur_regs(env
), *reg
;
5331 struct bpf_map
*map
= meta
->map_ptr
;
5336 if (func_id
!= BPF_FUNC_tail_call
)
5338 if (!map
|| map
->map_type
!= BPF_MAP_TYPE_PROG_ARRAY
) {
5339 verbose(env
, "kernel subsystem misconfigured verifier\n");
5343 range
= tnum_range(0, map
->max_entries
- 1);
5344 reg
= ®s
[BPF_REG_3
];
5346 if (!register_is_const(reg
) || !tnum_in(range
, reg
->var_off
)) {
5347 bpf_map_key_store(aux
, BPF_MAP_KEY_POISON
);
5351 err
= mark_chain_precision(env
, BPF_REG_3
);
5355 val
= reg
->var_off
.value
;
5356 if (bpf_map_key_unseen(aux
))
5357 bpf_map_key_store(aux
, val
);
5358 else if (!bpf_map_key_poisoned(aux
) &&
5359 bpf_map_key_immediate(aux
) != val
)
5360 bpf_map_key_store(aux
, BPF_MAP_KEY_POISON
);
5364 static int check_reference_leak(struct bpf_verifier_env
*env
)
5366 struct bpf_func_state
*state
= cur_func(env
);
5369 for (i
= 0; i
< state
->acquired_refs
; i
++) {
5370 verbose(env
, "Unreleased reference id=%d alloc_insn=%d\n",
5371 state
->refs
[i
].id
, state
->refs
[i
].insn_idx
);
5373 return state
->acquired_refs
? -EINVAL
: 0;
5376 static int check_helper_call(struct bpf_verifier_env
*env
, int func_id
, int insn_idx
)
5378 const struct bpf_func_proto
*fn
= NULL
;
5379 struct bpf_reg_state
*regs
;
5380 struct bpf_call_arg_meta meta
;
5384 /* find function prototype */
5385 if (func_id
< 0 || func_id
>= __BPF_FUNC_MAX_ID
) {
5386 verbose(env
, "invalid func %s#%d\n", func_id_name(func_id
),
5391 if (env
->ops
->get_func_proto
)
5392 fn
= env
->ops
->get_func_proto(func_id
, env
->prog
);
5394 verbose(env
, "unknown func %s#%d\n", func_id_name(func_id
),
5399 /* eBPF programs must be GPL compatible to use GPL-ed functions */
5400 if (!env
->prog
->gpl_compatible
&& fn
->gpl_only
) {
5401 verbose(env
, "cannot call GPL-restricted function from non-GPL compatible program\n");
5405 if (fn
->allowed
&& !fn
->allowed(env
->prog
)) {
5406 verbose(env
, "helper call is not allowed in probe\n");
5410 /* With LD_ABS/IND some JITs save/restore skb from r1. */
5411 changes_data
= bpf_helper_changes_pkt_data(fn
->func
);
5412 if (changes_data
&& fn
->arg1_type
!= ARG_PTR_TO_CTX
) {
5413 verbose(env
, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
5414 func_id_name(func_id
), func_id
);
5418 memset(&meta
, 0, sizeof(meta
));
5419 meta
.pkt_access
= fn
->pkt_access
;
5421 err
= check_func_proto(fn
, func_id
);
5423 verbose(env
, "kernel subsystem misconfigured func %s#%d\n",
5424 func_id_name(func_id
), func_id
);
5428 meta
.func_id
= func_id
;
5430 for (i
= 0; i
< 5; i
++) {
5431 err
= check_func_arg(env
, i
, &meta
, fn
);
5436 err
= record_func_map(env
, &meta
, func_id
, insn_idx
);
5440 err
= record_func_key(env
, &meta
, func_id
, insn_idx
);
5444 /* Mark slots with STACK_MISC in case of raw mode, stack offset
5445 * is inferred from register state.
5447 for (i
= 0; i
< meta
.access_size
; i
++) {
5448 err
= check_mem_access(env
, insn_idx
, meta
.regno
, i
, BPF_B
,
5449 BPF_WRITE
, -1, false);
5454 if (func_id
== BPF_FUNC_tail_call
) {
5455 err
= check_reference_leak(env
);
5457 verbose(env
, "tail_call would lead to reference leak\n");
5460 } else if (is_release_function(func_id
)) {
5461 err
= release_reference(env
, meta
.ref_obj_id
);
5463 verbose(env
, "func %s#%d reference has not been acquired before\n",
5464 func_id_name(func_id
), func_id
);
5469 regs
= cur_regs(env
);
5471 /* check that flags argument in get_local_storage(map, flags) is 0,
5472 * this is required because get_local_storage() can't return an error.
5474 if (func_id
== BPF_FUNC_get_local_storage
&&
5475 !register_is_null(®s
[BPF_REG_2
])) {
5476 verbose(env
, "get_local_storage() doesn't support non-zero flags\n");
5480 /* reset caller saved regs */
5481 for (i
= 0; i
< CALLER_SAVED_REGS
; i
++) {
5482 mark_reg_not_init(env
, regs
, caller_saved
[i
]);
5483 check_reg_arg(env
, caller_saved
[i
], DST_OP_NO_MARK
);
5486 /* helper call returns 64-bit value. */
5487 regs
[BPF_REG_0
].subreg_def
= DEF_NOT_SUBREG
;
5489 /* update return register (already marked as written above) */
5490 if (fn
->ret_type
== RET_INTEGER
) {
5491 /* sets type to SCALAR_VALUE */
5492 mark_reg_unknown(env
, regs
, BPF_REG_0
);
5493 } else if (fn
->ret_type
== RET_VOID
) {
5494 regs
[BPF_REG_0
].type
= NOT_INIT
;
5495 } else if (fn
->ret_type
== RET_PTR_TO_MAP_VALUE_OR_NULL
||
5496 fn
->ret_type
== RET_PTR_TO_MAP_VALUE
) {
5497 /* There is no offset yet applied, variable or fixed */
5498 mark_reg_known_zero(env
, regs
, BPF_REG_0
);
5499 /* remember map_ptr, so that check_map_access()
5500 * can check 'value_size' boundary of memory access
5501 * to map element returned from bpf_map_lookup_elem()
5503 if (meta
.map_ptr
== NULL
) {
5505 "kernel subsystem misconfigured verifier\n");
5508 regs
[BPF_REG_0
].map_ptr
= meta
.map_ptr
;
5509 if (fn
->ret_type
== RET_PTR_TO_MAP_VALUE
) {
5510 regs
[BPF_REG_0
].type
= PTR_TO_MAP_VALUE
;
5511 if (map_value_has_spin_lock(meta
.map_ptr
))
5512 regs
[BPF_REG_0
].id
= ++env
->id_gen
;
5514 regs
[BPF_REG_0
].type
= PTR_TO_MAP_VALUE_OR_NULL
;
5516 } else if (fn
->ret_type
== RET_PTR_TO_SOCKET_OR_NULL
) {
5517 mark_reg_known_zero(env
, regs
, BPF_REG_0
);
5518 regs
[BPF_REG_0
].type
= PTR_TO_SOCKET_OR_NULL
;
5519 } else if (fn
->ret_type
== RET_PTR_TO_SOCK_COMMON_OR_NULL
) {
5520 mark_reg_known_zero(env
, regs
, BPF_REG_0
);
5521 regs
[BPF_REG_0
].type
= PTR_TO_SOCK_COMMON_OR_NULL
;
5522 } else if (fn
->ret_type
== RET_PTR_TO_TCP_SOCK_OR_NULL
) {
5523 mark_reg_known_zero(env
, regs
, BPF_REG_0
);
5524 regs
[BPF_REG_0
].type
= PTR_TO_TCP_SOCK_OR_NULL
;
5525 } else if (fn
->ret_type
== RET_PTR_TO_ALLOC_MEM_OR_NULL
) {
5526 mark_reg_known_zero(env
, regs
, BPF_REG_0
);
5527 regs
[BPF_REG_0
].type
= PTR_TO_MEM_OR_NULL
;
5528 regs
[BPF_REG_0
].mem_size
= meta
.mem_size
;
5529 } else if (fn
->ret_type
== RET_PTR_TO_MEM_OR_BTF_ID_OR_NULL
||
5530 fn
->ret_type
== RET_PTR_TO_MEM_OR_BTF_ID
) {
5531 const struct btf_type
*t
;
5533 mark_reg_known_zero(env
, regs
, BPF_REG_0
);
5534 t
= btf_type_skip_modifiers(meta
.ret_btf
, meta
.ret_btf_id
, NULL
);
5535 if (!btf_type_is_struct(t
)) {
5537 const struct btf_type
*ret
;
5540 /* resolve the type size of ksym. */
5541 ret
= btf_resolve_size(meta
.ret_btf
, t
, &tsize
);
5543 tname
= btf_name_by_offset(meta
.ret_btf
, t
->name_off
);
5544 verbose(env
, "unable to resolve the size of type '%s': %ld\n",
5545 tname
, PTR_ERR(ret
));
5548 regs
[BPF_REG_0
].type
=
5549 fn
->ret_type
== RET_PTR_TO_MEM_OR_BTF_ID
?
5550 PTR_TO_MEM
: PTR_TO_MEM_OR_NULL
;
5551 regs
[BPF_REG_0
].mem_size
= tsize
;
5553 regs
[BPF_REG_0
].type
=
5554 fn
->ret_type
== RET_PTR_TO_MEM_OR_BTF_ID
?
5555 PTR_TO_BTF_ID
: PTR_TO_BTF_ID_OR_NULL
;
5556 regs
[BPF_REG_0
].btf
= meta
.ret_btf
;
5557 regs
[BPF_REG_0
].btf_id
= meta
.ret_btf_id
;
5559 } else if (fn
->ret_type
== RET_PTR_TO_BTF_ID_OR_NULL
||
5560 fn
->ret_type
== RET_PTR_TO_BTF_ID
) {
5563 mark_reg_known_zero(env
, regs
, BPF_REG_0
);
5564 regs
[BPF_REG_0
].type
= fn
->ret_type
== RET_PTR_TO_BTF_ID
?
5566 PTR_TO_BTF_ID_OR_NULL
;
5567 ret_btf_id
= *fn
->ret_btf_id
;
5568 if (ret_btf_id
== 0) {
5569 verbose(env
, "invalid return type %d of func %s#%d\n",
5570 fn
->ret_type
, func_id_name(func_id
), func_id
);
5573 /* current BPF helper definitions are only coming from
5574 * built-in code with type IDs from vmlinux BTF
5576 regs
[BPF_REG_0
].btf
= btf_vmlinux
;
5577 regs
[BPF_REG_0
].btf_id
= ret_btf_id
;
5579 verbose(env
, "unknown return type %d of func %s#%d\n",
5580 fn
->ret_type
, func_id_name(func_id
), func_id
);
5584 if (reg_type_may_be_null(regs
[BPF_REG_0
].type
))
5585 regs
[BPF_REG_0
].id
= ++env
->id_gen
;
5587 if (is_ptr_cast_function(func_id
)) {
5588 /* For release_reference() */
5589 regs
[BPF_REG_0
].ref_obj_id
= meta
.ref_obj_id
;
5590 } else if (is_acquire_function(func_id
, meta
.map_ptr
)) {
5591 int id
= acquire_reference_state(env
, insn_idx
);
5595 /* For mark_ptr_or_null_reg() */
5596 regs
[BPF_REG_0
].id
= id
;
5597 /* For release_reference() */
5598 regs
[BPF_REG_0
].ref_obj_id
= id
;
5601 do_refine_retval_range(regs
, fn
->ret_type
, func_id
, &meta
);
5603 err
= check_map_func_compatibility(env
, meta
.map_ptr
, func_id
);
5607 if ((func_id
== BPF_FUNC_get_stack
||
5608 func_id
== BPF_FUNC_get_task_stack
) &&
5609 !env
->prog
->has_callchain_buf
) {
5610 const char *err_str
;
5612 #ifdef CONFIG_PERF_EVENTS
5613 err
= get_callchain_buffers(sysctl_perf_event_max_stack
);
5614 err_str
= "cannot get callchain buffer for func %s#%d\n";
5617 err_str
= "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
5620 verbose(env
, err_str
, func_id_name(func_id
), func_id
);
5624 env
->prog
->has_callchain_buf
= true;
5627 if (func_id
== BPF_FUNC_get_stackid
|| func_id
== BPF_FUNC_get_stack
)
5628 env
->prog
->call_get_stack
= true;
5631 clear_all_pkt_pointers(env
);
5635 static bool signed_add_overflows(s64 a
, s64 b
)
5637 /* Do the add in u64, where overflow is well-defined */
5638 s64 res
= (s64
)((u64
)a
+ (u64
)b
);
5645 static bool signed_add32_overflows(s32 a
, s32 b
)
5647 /* Do the add in u32, where overflow is well-defined */
5648 s32 res
= (s32
)((u32
)a
+ (u32
)b
);
5655 static bool signed_sub_overflows(s64 a
, s64 b
)
5657 /* Do the sub in u64, where overflow is well-defined */
5658 s64 res
= (s64
)((u64
)a
- (u64
)b
);
5665 static bool signed_sub32_overflows(s32 a
, s32 b
)
5667 /* Do the sub in u32, where overflow is well-defined */
5668 s32 res
= (s32
)((u32
)a
- (u32
)b
);
5675 static bool check_reg_sane_offset(struct bpf_verifier_env
*env
,
5676 const struct bpf_reg_state
*reg
,
5677 enum bpf_reg_type type
)
5679 bool known
= tnum_is_const(reg
->var_off
);
5680 s64 val
= reg
->var_off
.value
;
5681 s64 smin
= reg
->smin_value
;
5683 if (known
&& (val
>= BPF_MAX_VAR_OFF
|| val
<= -BPF_MAX_VAR_OFF
)) {
5684 verbose(env
, "math between %s pointer and %lld is not allowed\n",
5685 reg_type_str
[type
], val
);
5689 if (reg
->off
>= BPF_MAX_VAR_OFF
|| reg
->off
<= -BPF_MAX_VAR_OFF
) {
5690 verbose(env
, "%s pointer offset %d is not allowed\n",
5691 reg_type_str
[type
], reg
->off
);
5695 if (smin
== S64_MIN
) {
5696 verbose(env
, "math between %s pointer and register with unbounded min value is not allowed\n",
5697 reg_type_str
[type
]);
5701 if (smin
>= BPF_MAX_VAR_OFF
|| smin
<= -BPF_MAX_VAR_OFF
) {
5702 verbose(env
, "value %lld makes %s pointer be out of bounds\n",
5703 smin
, reg_type_str
[type
]);
5710 static struct bpf_insn_aux_data
*cur_aux(struct bpf_verifier_env
*env
)
5712 return &env
->insn_aux_data
[env
->insn_idx
];
5723 static int retrieve_ptr_limit(const struct bpf_reg_state
*ptr_reg
,
5724 const struct bpf_reg_state
*off_reg
,
5725 u32
*alu_limit
, u8 opcode
)
5727 bool off_is_neg
= off_reg
->smin_value
< 0;
5728 bool mask_to_left
= (opcode
== BPF_ADD
&& off_is_neg
) ||
5729 (opcode
== BPF_SUB
&& !off_is_neg
);
5730 u32 max
= 0, ptr_limit
= 0;
5732 if (!tnum_is_const(off_reg
->var_off
) &&
5733 (off_reg
->smin_value
< 0) != (off_reg
->smax_value
< 0))
5734 return REASON_BOUNDS
;
5736 switch (ptr_reg
->type
) {
5738 /* Offset 0 is out-of-bounds, but acceptable start for the
5739 * left direction, see BPF_REG_FP. Also, unknown scalar
5740 * offset where we would need to deal with min/max bounds is
5741 * currently prohibited for unprivileged.
5743 max
= MAX_BPF_STACK
+ mask_to_left
;
5744 ptr_limit
= -(ptr_reg
->var_off
.value
+ ptr_reg
->off
);
5746 case PTR_TO_MAP_VALUE
:
5747 max
= ptr_reg
->map_ptr
->value_size
;
5748 ptr_limit
= (mask_to_left
?
5749 ptr_reg
->smin_value
:
5750 ptr_reg
->umax_value
) + ptr_reg
->off
;
5756 if (ptr_limit
>= max
)
5757 return REASON_LIMIT
;
5758 *alu_limit
= ptr_limit
;
5762 static bool can_skip_alu_sanitation(const struct bpf_verifier_env
*env
,
5763 const struct bpf_insn
*insn
)
5765 return env
->bypass_spec_v1
|| BPF_SRC(insn
->code
) == BPF_K
;
5768 static int update_alu_sanitation_state(struct bpf_insn_aux_data
*aux
,
5769 u32 alu_state
, u32 alu_limit
)
5771 /* If we arrived here from different branches with different
5772 * state or limits to sanitize, then this won't work.
5774 if (aux
->alu_state
&&
5775 (aux
->alu_state
!= alu_state
||
5776 aux
->alu_limit
!= alu_limit
))
5777 return REASON_PATHS
;
5779 /* Corresponding fixup done in fixup_bpf_calls(). */
5780 aux
->alu_state
= alu_state
;
5781 aux
->alu_limit
= alu_limit
;
5785 static int sanitize_val_alu(struct bpf_verifier_env
*env
,
5786 struct bpf_insn
*insn
)
5788 struct bpf_insn_aux_data
*aux
= cur_aux(env
);
5790 if (can_skip_alu_sanitation(env
, insn
))
5793 return update_alu_sanitation_state(aux
, BPF_ALU_NON_POINTER
, 0);
5796 static bool sanitize_needed(u8 opcode
)
5798 return opcode
== BPF_ADD
|| opcode
== BPF_SUB
;
5801 static int sanitize_ptr_alu(struct bpf_verifier_env
*env
,
5802 struct bpf_insn
*insn
,
5803 const struct bpf_reg_state
*ptr_reg
,
5804 const struct bpf_reg_state
*off_reg
,
5805 struct bpf_reg_state
*dst_reg
,
5806 struct bpf_insn_aux_data
*tmp_aux
,
5807 const bool commit_window
)
5809 struct bpf_insn_aux_data
*aux
= commit_window
? cur_aux(env
) : tmp_aux
;
5810 struct bpf_verifier_state
*vstate
= env
->cur_state
;
5811 bool off_is_imm
= tnum_is_const(off_reg
->var_off
);
5812 bool off_is_neg
= off_reg
->smin_value
< 0;
5813 bool ptr_is_dst_reg
= ptr_reg
== dst_reg
;
5814 u8 opcode
= BPF_OP(insn
->code
);
5815 u32 alu_state
, alu_limit
;
5816 struct bpf_reg_state tmp
;
5820 if (can_skip_alu_sanitation(env
, insn
))
5823 /* We already marked aux for masking from non-speculative
5824 * paths, thus we got here in the first place. We only care
5825 * to explore bad access from here.
5827 if (vstate
->speculative
)
5830 err
= retrieve_ptr_limit(ptr_reg
, off_reg
, &alu_limit
, opcode
);
5834 if (commit_window
) {
5835 /* In commit phase we narrow the masking window based on
5836 * the observed pointer move after the simulated operation.
5838 alu_state
= tmp_aux
->alu_state
;
5839 alu_limit
= abs(tmp_aux
->alu_limit
- alu_limit
);
5841 alu_state
= off_is_neg
? BPF_ALU_NEG_VALUE
: 0;
5842 alu_state
|= off_is_imm
? BPF_ALU_IMMEDIATE
: 0;
5843 alu_state
|= ptr_is_dst_reg
?
5844 BPF_ALU_SANITIZE_SRC
: BPF_ALU_SANITIZE_DST
;
5847 err
= update_alu_sanitation_state(aux
, alu_state
, alu_limit
);
5851 /* If we're in commit phase, we're done here given we already
5852 * pushed the truncated dst_reg into the speculative verification
5858 /* Simulate and find potential out-of-bounds access under
5859 * speculative execution from truncation as a result of
5860 * masking when off was not within expected range. If off
5861 * sits in dst, then we temporarily need to move ptr there
5862 * to simulate dst (== 0) +/-= ptr. Needed, for example,
5863 * for cases where we use K-based arithmetic in one direction
5864 * and truncated reg-based in the other in order to explore
5867 if (!ptr_is_dst_reg
) {
5869 *dst_reg
= *ptr_reg
;
5871 ret
= push_stack(env
, env
->insn_idx
+ 1, env
->insn_idx
, true);
5872 if (!ptr_is_dst_reg
&& ret
)
5874 return !ret
? REASON_STACK
: 0;
5877 static int sanitize_err(struct bpf_verifier_env
*env
,
5878 const struct bpf_insn
*insn
, int reason
,
5879 const struct bpf_reg_state
*off_reg
,
5880 const struct bpf_reg_state
*dst_reg
)
5882 static const char *err
= "pointer arithmetic with it prohibited for !root";
5883 const char *op
= BPF_OP(insn
->code
) == BPF_ADD
? "add" : "sub";
5884 u32 dst
= insn
->dst_reg
, src
= insn
->src_reg
;
5888 verbose(env
, "R%d has unknown scalar with mixed signed bounds, %s\n",
5889 off_reg
== dst_reg
? dst
: src
, err
);
5892 verbose(env
, "R%d has pointer with unsupported alu operation, %s\n",
5893 off_reg
== dst_reg
? src
: dst
, err
);
5896 verbose(env
, "R%d tried to %s from different maps, paths or scalars, %s\n",
5900 verbose(env
, "R%d tried to %s beyond pointer bounds, %s\n",
5904 verbose(env
, "R%d could not be pushed for speculative verification, %s\n",
5908 verbose(env
, "verifier internal error: unknown reason (%d)\n",
5916 /* check that stack access falls within stack limits and that 'reg' doesn't
5917 * have a variable offset.
5919 * Variable offset is prohibited for unprivileged mode for simplicity since it
5920 * requires corresponding support in Spectre masking for stack ALU. See also
5921 * retrieve_ptr_limit().
5924 * 'off' includes 'reg->off'.
5926 static int check_stack_access_for_ptr_arithmetic(
5927 struct bpf_verifier_env
*env
,
5929 const struct bpf_reg_state
*reg
,
5932 if (!tnum_is_const(reg
->var_off
)) {
5935 tnum_strn(tn_buf
, sizeof(tn_buf
), reg
->var_off
);
5936 verbose(env
, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
5937 regno
, tn_buf
, off
);
5941 if (off
>= 0 || off
< -MAX_BPF_STACK
) {
5942 verbose(env
, "R%d stack pointer arithmetic goes out of range, "
5943 "prohibited for !root; off=%d\n", regno
, off
);
5950 static int sanitize_check_bounds(struct bpf_verifier_env
*env
,
5951 const struct bpf_insn
*insn
,
5952 const struct bpf_reg_state
*dst_reg
)
5954 u32 dst
= insn
->dst_reg
;
5956 /* For unprivileged we require that resulting offset must be in bounds
5957 * in order to be able to sanitize access later on.
5959 if (env
->bypass_spec_v1
)
5962 switch (dst_reg
->type
) {
5964 if (check_stack_access_for_ptr_arithmetic(env
, dst
, dst_reg
,
5965 dst_reg
->off
+ dst_reg
->var_off
.value
))
5968 case PTR_TO_MAP_VALUE
:
5969 if (check_map_access(env
, dst
, dst_reg
->off
, 1, false)) {
5970 verbose(env
, "R%d pointer arithmetic of map value goes out of range, "
5971 "prohibited for !root\n", dst
);
5982 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
5983 * Caller should also handle BPF_MOV case separately.
5984 * If we return -EACCES, caller may want to try again treating pointer as a
5985 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks.
5987 static int adjust_ptr_min_max_vals(struct bpf_verifier_env
*env
,
5988 struct bpf_insn
*insn
,
5989 const struct bpf_reg_state
*ptr_reg
,
5990 const struct bpf_reg_state
*off_reg
)
5992 struct bpf_verifier_state
*vstate
= env
->cur_state
;
5993 struct bpf_func_state
*state
= vstate
->frame
[vstate
->curframe
];
5994 struct bpf_reg_state
*regs
= state
->regs
, *dst_reg
;
5995 bool known
= tnum_is_const(off_reg
->var_off
);
5996 s64 smin_val
= off_reg
->smin_value
, smax_val
= off_reg
->smax_value
,
5997 smin_ptr
= ptr_reg
->smin_value
, smax_ptr
= ptr_reg
->smax_value
;
5998 u64 umin_val
= off_reg
->umin_value
, umax_val
= off_reg
->umax_value
,
5999 umin_ptr
= ptr_reg
->umin_value
, umax_ptr
= ptr_reg
->umax_value
;
6000 struct bpf_insn_aux_data tmp_aux
= {};
6001 u8 opcode
= BPF_OP(insn
->code
);
6002 u32 dst
= insn
->dst_reg
;
6005 dst_reg
= ®s
[dst
];
6007 if ((known
&& (smin_val
!= smax_val
|| umin_val
!= umax_val
)) ||
6008 smin_val
> smax_val
|| umin_val
> umax_val
) {
6009 /* Taint dst register if offset had invalid bounds derived from
6010 * e.g. dead branches.
6012 __mark_reg_unknown(env
, dst_reg
);
6016 if (BPF_CLASS(insn
->code
) != BPF_ALU64
) {
6017 /* 32-bit ALU ops on pointers produce (meaningless) scalars */
6018 if (opcode
== BPF_SUB
&& env
->allow_ptr_leaks
) {
6019 __mark_reg_unknown(env
, dst_reg
);
6024 "R%d 32-bit pointer arithmetic prohibited\n",
6029 switch (ptr_reg
->type
) {
6030 case PTR_TO_MAP_VALUE_OR_NULL
:
6031 verbose(env
, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
6032 dst
, reg_type_str
[ptr_reg
->type
]);
6034 case CONST_PTR_TO_MAP
:
6035 /* smin_val represents the known value */
6036 if (known
&& smin_val
== 0 && opcode
== BPF_ADD
)
6039 case PTR_TO_PACKET_END
:
6041 case PTR_TO_SOCKET_OR_NULL
:
6042 case PTR_TO_SOCK_COMMON
:
6043 case PTR_TO_SOCK_COMMON_OR_NULL
:
6044 case PTR_TO_TCP_SOCK
:
6045 case PTR_TO_TCP_SOCK_OR_NULL
:
6046 case PTR_TO_XDP_SOCK
:
6047 verbose(env
, "R%d pointer arithmetic on %s prohibited\n",
6048 dst
, reg_type_str
[ptr_reg
->type
]);
6054 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
6055 * The id may be overwritten later if we create a new variable offset.
6057 dst_reg
->type
= ptr_reg
->type
;
6058 dst_reg
->id
= ptr_reg
->id
;
6060 if (!check_reg_sane_offset(env
, off_reg
, ptr_reg
->type
) ||
6061 !check_reg_sane_offset(env
, ptr_reg
, ptr_reg
->type
))
6064 /* pointer types do not carry 32-bit bounds at the moment. */
6065 __mark_reg32_unbounded(dst_reg
);
6067 if (sanitize_needed(opcode
)) {
6068 ret
= sanitize_ptr_alu(env
, insn
, ptr_reg
, off_reg
, dst_reg
,
6071 return sanitize_err(env
, insn
, ret
, off_reg
, dst_reg
);
6076 /* We can take a fixed offset as long as it doesn't overflow
6077 * the s32 'off' field
6079 if (known
&& (ptr_reg
->off
+ smin_val
==
6080 (s64
)(s32
)(ptr_reg
->off
+ smin_val
))) {
6081 /* pointer += K. Accumulate it into fixed offset */
6082 dst_reg
->smin_value
= smin_ptr
;
6083 dst_reg
->smax_value
= smax_ptr
;
6084 dst_reg
->umin_value
= umin_ptr
;
6085 dst_reg
->umax_value
= umax_ptr
;
6086 dst_reg
->var_off
= ptr_reg
->var_off
;
6087 dst_reg
->off
= ptr_reg
->off
+ smin_val
;
6088 dst_reg
->raw
= ptr_reg
->raw
;
6091 /* A new variable offset is created. Note that off_reg->off
6092 * == 0, since it's a scalar.
6093 * dst_reg gets the pointer type and since some positive
6094 * integer value was added to the pointer, give it a new 'id'
6095 * if it's a PTR_TO_PACKET.
6096 * this creates a new 'base' pointer, off_reg (variable) gets
6097 * added into the variable offset, and we copy the fixed offset
6100 if (signed_add_overflows(smin_ptr
, smin_val
) ||
6101 signed_add_overflows(smax_ptr
, smax_val
)) {
6102 dst_reg
->smin_value
= S64_MIN
;
6103 dst_reg
->smax_value
= S64_MAX
;
6105 dst_reg
->smin_value
= smin_ptr
+ smin_val
;
6106 dst_reg
->smax_value
= smax_ptr
+ smax_val
;
6108 if (umin_ptr
+ umin_val
< umin_ptr
||
6109 umax_ptr
+ umax_val
< umax_ptr
) {
6110 dst_reg
->umin_value
= 0;
6111 dst_reg
->umax_value
= U64_MAX
;
6113 dst_reg
->umin_value
= umin_ptr
+ umin_val
;
6114 dst_reg
->umax_value
= umax_ptr
+ umax_val
;
6116 dst_reg
->var_off
= tnum_add(ptr_reg
->var_off
, off_reg
->var_off
);
6117 dst_reg
->off
= ptr_reg
->off
;
6118 dst_reg
->raw
= ptr_reg
->raw
;
6119 if (reg_is_pkt_pointer(ptr_reg
)) {
6120 dst_reg
->id
= ++env
->id_gen
;
6121 /* something was added to pkt_ptr, set range to zero */
6122 memset(&dst_reg
->raw
, 0, sizeof(dst_reg
->raw
));
6126 if (dst_reg
== off_reg
) {
6127 /* scalar -= pointer. Creates an unknown scalar */
6128 verbose(env
, "R%d tried to subtract pointer from scalar\n",
6132 /* We don't allow subtraction from FP, because (according to
6133 * test_verifier.c test "invalid fp arithmetic", JITs might not
6134 * be able to deal with it.
6136 if (ptr_reg
->type
== PTR_TO_STACK
) {
6137 verbose(env
, "R%d subtraction from stack pointer prohibited\n",
6141 if (known
&& (ptr_reg
->off
- smin_val
==
6142 (s64
)(s32
)(ptr_reg
->off
- smin_val
))) {
6143 /* pointer -= K. Subtract it from fixed offset */
6144 dst_reg
->smin_value
= smin_ptr
;
6145 dst_reg
->smax_value
= smax_ptr
;
6146 dst_reg
->umin_value
= umin_ptr
;
6147 dst_reg
->umax_value
= umax_ptr
;
6148 dst_reg
->var_off
= ptr_reg
->var_off
;
6149 dst_reg
->id
= ptr_reg
->id
;
6150 dst_reg
->off
= ptr_reg
->off
- smin_val
;
6151 dst_reg
->raw
= ptr_reg
->raw
;
6154 /* A new variable offset is created. If the subtrahend is known
6155 * nonnegative, then any reg->range we had before is still good.
6157 if (signed_sub_overflows(smin_ptr
, smax_val
) ||
6158 signed_sub_overflows(smax_ptr
, smin_val
)) {
6159 /* Overflow possible, we know nothing */
6160 dst_reg
->smin_value
= S64_MIN
;
6161 dst_reg
->smax_value
= S64_MAX
;
6163 dst_reg
->smin_value
= smin_ptr
- smax_val
;
6164 dst_reg
->smax_value
= smax_ptr
- smin_val
;
6166 if (umin_ptr
< umax_val
) {
6167 /* Overflow possible, we know nothing */
6168 dst_reg
->umin_value
= 0;
6169 dst_reg
->umax_value
= U64_MAX
;
6171 /* Cannot overflow (as long as bounds are consistent) */
6172 dst_reg
->umin_value
= umin_ptr
- umax_val
;
6173 dst_reg
->umax_value
= umax_ptr
- umin_val
;
6175 dst_reg
->var_off
= tnum_sub(ptr_reg
->var_off
, off_reg
->var_off
);
6176 dst_reg
->off
= ptr_reg
->off
;
6177 dst_reg
->raw
= ptr_reg
->raw
;
6178 if (reg_is_pkt_pointer(ptr_reg
)) {
6179 dst_reg
->id
= ++env
->id_gen
;
6180 /* something was added to pkt_ptr, set range to zero */
6182 memset(&dst_reg
->raw
, 0, sizeof(dst_reg
->raw
));
6188 /* bitwise ops on pointers are troublesome, prohibit. */
6189 verbose(env
, "R%d bitwise operator %s on pointer prohibited\n",
6190 dst
, bpf_alu_string
[opcode
>> 4]);
6193 /* other operators (e.g. MUL,LSH) produce non-pointer results */
6194 verbose(env
, "R%d pointer arithmetic with %s operator prohibited\n",
6195 dst
, bpf_alu_string
[opcode
>> 4]);
6199 if (!check_reg_sane_offset(env
, dst_reg
, ptr_reg
->type
))
6202 __update_reg_bounds(dst_reg
);
6203 __reg_deduce_bounds(dst_reg
);
6204 __reg_bound_offset(dst_reg
);
6206 if (sanitize_check_bounds(env
, insn
, dst_reg
) < 0)
6208 if (sanitize_needed(opcode
)) {
6209 ret
= sanitize_ptr_alu(env
, insn
, dst_reg
, off_reg
, dst_reg
,
6212 return sanitize_err(env
, insn
, ret
, off_reg
, dst_reg
);
6218 static void scalar32_min_max_add(struct bpf_reg_state
*dst_reg
,
6219 struct bpf_reg_state
*src_reg
)
6221 s32 smin_val
= src_reg
->s32_min_value
;
6222 s32 smax_val
= src_reg
->s32_max_value
;
6223 u32 umin_val
= src_reg
->u32_min_value
;
6224 u32 umax_val
= src_reg
->u32_max_value
;
6226 if (signed_add32_overflows(dst_reg
->s32_min_value
, smin_val
) ||
6227 signed_add32_overflows(dst_reg
->s32_max_value
, smax_val
)) {
6228 dst_reg
->s32_min_value
= S32_MIN
;
6229 dst_reg
->s32_max_value
= S32_MAX
;
6231 dst_reg
->s32_min_value
+= smin_val
;
6232 dst_reg
->s32_max_value
+= smax_val
;
6234 if (dst_reg
->u32_min_value
+ umin_val
< umin_val
||
6235 dst_reg
->u32_max_value
+ umax_val
< umax_val
) {
6236 dst_reg
->u32_min_value
= 0;
6237 dst_reg
->u32_max_value
= U32_MAX
;
6239 dst_reg
->u32_min_value
+= umin_val
;
6240 dst_reg
->u32_max_value
+= umax_val
;
6244 static void scalar_min_max_add(struct bpf_reg_state
*dst_reg
,
6245 struct bpf_reg_state
*src_reg
)
6247 s64 smin_val
= src_reg
->smin_value
;
6248 s64 smax_val
= src_reg
->smax_value
;
6249 u64 umin_val
= src_reg
->umin_value
;
6250 u64 umax_val
= src_reg
->umax_value
;
6252 if (signed_add_overflows(dst_reg
->smin_value
, smin_val
) ||
6253 signed_add_overflows(dst_reg
->smax_value
, smax_val
)) {
6254 dst_reg
->smin_value
= S64_MIN
;
6255 dst_reg
->smax_value
= S64_MAX
;
6257 dst_reg
->smin_value
+= smin_val
;
6258 dst_reg
->smax_value
+= smax_val
;
6260 if (dst_reg
->umin_value
+ umin_val
< umin_val
||
6261 dst_reg
->umax_value
+ umax_val
< umax_val
) {
6262 dst_reg
->umin_value
= 0;
6263 dst_reg
->umax_value
= U64_MAX
;
6265 dst_reg
->umin_value
+= umin_val
;
6266 dst_reg
->umax_value
+= umax_val
;
6270 static void scalar32_min_max_sub(struct bpf_reg_state
*dst_reg
,
6271 struct bpf_reg_state
*src_reg
)
6273 s32 smin_val
= src_reg
->s32_min_value
;
6274 s32 smax_val
= src_reg
->s32_max_value
;
6275 u32 umin_val
= src_reg
->u32_min_value
;
6276 u32 umax_val
= src_reg
->u32_max_value
;
6278 if (signed_sub32_overflows(dst_reg
->s32_min_value
, smax_val
) ||
6279 signed_sub32_overflows(dst_reg
->s32_max_value
, smin_val
)) {
6280 /* Overflow possible, we know nothing */
6281 dst_reg
->s32_min_value
= S32_MIN
;
6282 dst_reg
->s32_max_value
= S32_MAX
;
6284 dst_reg
->s32_min_value
-= smax_val
;
6285 dst_reg
->s32_max_value
-= smin_val
;
6287 if (dst_reg
->u32_min_value
< umax_val
) {
6288 /* Overflow possible, we know nothing */
6289 dst_reg
->u32_min_value
= 0;
6290 dst_reg
->u32_max_value
= U32_MAX
;
6292 /* Cannot overflow (as long as bounds are consistent) */
6293 dst_reg
->u32_min_value
-= umax_val
;
6294 dst_reg
->u32_max_value
-= umin_val
;
6298 static void scalar_min_max_sub(struct bpf_reg_state
*dst_reg
,
6299 struct bpf_reg_state
*src_reg
)
6301 s64 smin_val
= src_reg
->smin_value
;
6302 s64 smax_val
= src_reg
->smax_value
;
6303 u64 umin_val
= src_reg
->umin_value
;
6304 u64 umax_val
= src_reg
->umax_value
;
6306 if (signed_sub_overflows(dst_reg
->smin_value
, smax_val
) ||
6307 signed_sub_overflows(dst_reg
->smax_value
, smin_val
)) {
6308 /* Overflow possible, we know nothing */
6309 dst_reg
->smin_value
= S64_MIN
;
6310 dst_reg
->smax_value
= S64_MAX
;
6312 dst_reg
->smin_value
-= smax_val
;
6313 dst_reg
->smax_value
-= smin_val
;
6315 if (dst_reg
->umin_value
< umax_val
) {
6316 /* Overflow possible, we know nothing */
6317 dst_reg
->umin_value
= 0;
6318 dst_reg
->umax_value
= U64_MAX
;
6320 /* Cannot overflow (as long as bounds are consistent) */
6321 dst_reg
->umin_value
-= umax_val
;
6322 dst_reg
->umax_value
-= umin_val
;
6326 static void scalar32_min_max_mul(struct bpf_reg_state
*dst_reg
,
6327 struct bpf_reg_state
*src_reg
)
6329 s32 smin_val
= src_reg
->s32_min_value
;
6330 u32 umin_val
= src_reg
->u32_min_value
;
6331 u32 umax_val
= src_reg
->u32_max_value
;
6333 if (smin_val
< 0 || dst_reg
->s32_min_value
< 0) {
6334 /* Ain't nobody got time to multiply that sign */
6335 __mark_reg32_unbounded(dst_reg
);
6338 /* Both values are positive, so we can work with unsigned and
6339 * copy the result to signed (unless it exceeds S32_MAX).
6341 if (umax_val
> U16_MAX
|| dst_reg
->u32_max_value
> U16_MAX
) {
6342 /* Potential overflow, we know nothing */
6343 __mark_reg32_unbounded(dst_reg
);
6346 dst_reg
->u32_min_value
*= umin_val
;
6347 dst_reg
->u32_max_value
*= umax_val
;
6348 if (dst_reg
->u32_max_value
> S32_MAX
) {
6349 /* Overflow possible, we know nothing */
6350 dst_reg
->s32_min_value
= S32_MIN
;
6351 dst_reg
->s32_max_value
= S32_MAX
;
6353 dst_reg
->s32_min_value
= dst_reg
->u32_min_value
;
6354 dst_reg
->s32_max_value
= dst_reg
->u32_max_value
;
6358 static void scalar_min_max_mul(struct bpf_reg_state
*dst_reg
,
6359 struct bpf_reg_state
*src_reg
)
6361 s64 smin_val
= src_reg
->smin_value
;
6362 u64 umin_val
= src_reg
->umin_value
;
6363 u64 umax_val
= src_reg
->umax_value
;
6365 if (smin_val
< 0 || dst_reg
->smin_value
< 0) {
6366 /* Ain't nobody got time to multiply that sign */
6367 __mark_reg64_unbounded(dst_reg
);
6370 /* Both values are positive, so we can work with unsigned and
6371 * copy the result to signed (unless it exceeds S64_MAX).
6373 if (umax_val
> U32_MAX
|| dst_reg
->umax_value
> U32_MAX
) {
6374 /* Potential overflow, we know nothing */
6375 __mark_reg64_unbounded(dst_reg
);
6378 dst_reg
->umin_value
*= umin_val
;
6379 dst_reg
->umax_value
*= umax_val
;
6380 if (dst_reg
->umax_value
> S64_MAX
) {
6381 /* Overflow possible, we know nothing */
6382 dst_reg
->smin_value
= S64_MIN
;
6383 dst_reg
->smax_value
= S64_MAX
;
6385 dst_reg
->smin_value
= dst_reg
->umin_value
;
6386 dst_reg
->smax_value
= dst_reg
->umax_value
;
6390 static void scalar32_min_max_and(struct bpf_reg_state
*dst_reg
,
6391 struct bpf_reg_state
*src_reg
)
6393 bool src_known
= tnum_subreg_is_const(src_reg
->var_off
);
6394 bool dst_known
= tnum_subreg_is_const(dst_reg
->var_off
);
6395 struct tnum var32_off
= tnum_subreg(dst_reg
->var_off
);
6396 s32 smin_val
= src_reg
->s32_min_value
;
6397 u32 umax_val
= src_reg
->u32_max_value
;
6399 if (src_known
&& dst_known
) {
6400 __mark_reg32_known(dst_reg
, var32_off
.value
);
6404 /* We get our minimum from the var_off, since that's inherently
6405 * bitwise. Our maximum is the minimum of the operands' maxima.
6407 dst_reg
->u32_min_value
= var32_off
.value
;
6408 dst_reg
->u32_max_value
= min(dst_reg
->u32_max_value
, umax_val
);
6409 if (dst_reg
->s32_min_value
< 0 || smin_val
< 0) {
6410 /* Lose signed bounds when ANDing negative numbers,
6411 * ain't nobody got time for that.
6413 dst_reg
->s32_min_value
= S32_MIN
;
6414 dst_reg
->s32_max_value
= S32_MAX
;
6416 /* ANDing two positives gives a positive, so safe to
6417 * cast result into s64.
6419 dst_reg
->s32_min_value
= dst_reg
->u32_min_value
;
6420 dst_reg
->s32_max_value
= dst_reg
->u32_max_value
;
6424 static void scalar_min_max_and(struct bpf_reg_state
*dst_reg
,
6425 struct bpf_reg_state
*src_reg
)
6427 bool src_known
= tnum_is_const(src_reg
->var_off
);
6428 bool dst_known
= tnum_is_const(dst_reg
->var_off
);
6429 s64 smin_val
= src_reg
->smin_value
;
6430 u64 umax_val
= src_reg
->umax_value
;
6432 if (src_known
&& dst_known
) {
6433 __mark_reg_known(dst_reg
, dst_reg
->var_off
.value
);
6437 /* We get our minimum from the var_off, since that's inherently
6438 * bitwise. Our maximum is the minimum of the operands' maxima.
6440 dst_reg
->umin_value
= dst_reg
->var_off
.value
;
6441 dst_reg
->umax_value
= min(dst_reg
->umax_value
, umax_val
);
6442 if (dst_reg
->smin_value
< 0 || smin_val
< 0) {
6443 /* Lose signed bounds when ANDing negative numbers,
6444 * ain't nobody got time for that.
6446 dst_reg
->smin_value
= S64_MIN
;
6447 dst_reg
->smax_value
= S64_MAX
;
6449 /* ANDing two positives gives a positive, so safe to
6450 * cast result into s64.
6452 dst_reg
->smin_value
= dst_reg
->umin_value
;
6453 dst_reg
->smax_value
= dst_reg
->umax_value
;
6455 /* We may learn something more from the var_off */
6456 __update_reg_bounds(dst_reg
);
6459 static void scalar32_min_max_or(struct bpf_reg_state
*dst_reg
,
6460 struct bpf_reg_state
*src_reg
)
6462 bool src_known
= tnum_subreg_is_const(src_reg
->var_off
);
6463 bool dst_known
= tnum_subreg_is_const(dst_reg
->var_off
);
6464 struct tnum var32_off
= tnum_subreg(dst_reg
->var_off
);
6465 s32 smin_val
= src_reg
->s32_min_value
;
6466 u32 umin_val
= src_reg
->u32_min_value
;
6468 if (src_known
&& dst_known
) {
6469 __mark_reg32_known(dst_reg
, var32_off
.value
);
6473 /* We get our maximum from the var_off, and our minimum is the
6474 * maximum of the operands' minima
6476 dst_reg
->u32_min_value
= max(dst_reg
->u32_min_value
, umin_val
);
6477 dst_reg
->u32_max_value
= var32_off
.value
| var32_off
.mask
;
6478 if (dst_reg
->s32_min_value
< 0 || smin_val
< 0) {
6479 /* Lose signed bounds when ORing negative numbers,
6480 * ain't nobody got time for that.
6482 dst_reg
->s32_min_value
= S32_MIN
;
6483 dst_reg
->s32_max_value
= S32_MAX
;
6485 /* ORing two positives gives a positive, so safe to
6486 * cast result into s64.
6488 dst_reg
->s32_min_value
= dst_reg
->u32_min_value
;
6489 dst_reg
->s32_max_value
= dst_reg
->u32_max_value
;
6493 static void scalar_min_max_or(struct bpf_reg_state
*dst_reg
,
6494 struct bpf_reg_state
*src_reg
)
6496 bool src_known
= tnum_is_const(src_reg
->var_off
);
6497 bool dst_known
= tnum_is_const(dst_reg
->var_off
);
6498 s64 smin_val
= src_reg
->smin_value
;
6499 u64 umin_val
= src_reg
->umin_value
;
6501 if (src_known
&& dst_known
) {
6502 __mark_reg_known(dst_reg
, dst_reg
->var_off
.value
);
6506 /* We get our maximum from the var_off, and our minimum is the
6507 * maximum of the operands' minima
6509 dst_reg
->umin_value
= max(dst_reg
->umin_value
, umin_val
);
6510 dst_reg
->umax_value
= dst_reg
->var_off
.value
| dst_reg
->var_off
.mask
;
6511 if (dst_reg
->smin_value
< 0 || smin_val
< 0) {
6512 /* Lose signed bounds when ORing negative numbers,
6513 * ain't nobody got time for that.
6515 dst_reg
->smin_value
= S64_MIN
;
6516 dst_reg
->smax_value
= S64_MAX
;
6518 /* ORing two positives gives a positive, so safe to
6519 * cast result into s64.
6521 dst_reg
->smin_value
= dst_reg
->umin_value
;
6522 dst_reg
->smax_value
= dst_reg
->umax_value
;
6524 /* We may learn something more from the var_off */
6525 __update_reg_bounds(dst_reg
);
6528 static void scalar32_min_max_xor(struct bpf_reg_state
*dst_reg
,
6529 struct bpf_reg_state
*src_reg
)
6531 bool src_known
= tnum_subreg_is_const(src_reg
->var_off
);
6532 bool dst_known
= tnum_subreg_is_const(dst_reg
->var_off
);
6533 struct tnum var32_off
= tnum_subreg(dst_reg
->var_off
);
6534 s32 smin_val
= src_reg
->s32_min_value
;
6536 if (src_known
&& dst_known
) {
6537 __mark_reg32_known(dst_reg
, var32_off
.value
);
6541 /* We get both minimum and maximum from the var32_off. */
6542 dst_reg
->u32_min_value
= var32_off
.value
;
6543 dst_reg
->u32_max_value
= var32_off
.value
| var32_off
.mask
;
6545 if (dst_reg
->s32_min_value
>= 0 && smin_val
>= 0) {
6546 /* XORing two positive sign numbers gives a positive,
6547 * so safe to cast u32 result into s32.
6549 dst_reg
->s32_min_value
= dst_reg
->u32_min_value
;
6550 dst_reg
->s32_max_value
= dst_reg
->u32_max_value
;
6552 dst_reg
->s32_min_value
= S32_MIN
;
6553 dst_reg
->s32_max_value
= S32_MAX
;
6557 static void scalar_min_max_xor(struct bpf_reg_state
*dst_reg
,
6558 struct bpf_reg_state
*src_reg
)
6560 bool src_known
= tnum_is_const(src_reg
->var_off
);
6561 bool dst_known
= tnum_is_const(dst_reg
->var_off
);
6562 s64 smin_val
= src_reg
->smin_value
;
6564 if (src_known
&& dst_known
) {
6565 /* dst_reg->var_off.value has been updated earlier */
6566 __mark_reg_known(dst_reg
, dst_reg
->var_off
.value
);
6570 /* We get both minimum and maximum from the var_off. */
6571 dst_reg
->umin_value
= dst_reg
->var_off
.value
;
6572 dst_reg
->umax_value
= dst_reg
->var_off
.value
| dst_reg
->var_off
.mask
;
6574 if (dst_reg
->smin_value
>= 0 && smin_val
>= 0) {
6575 /* XORing two positive sign numbers gives a positive,
6576 * so safe to cast u64 result into s64.
6578 dst_reg
->smin_value
= dst_reg
->umin_value
;
6579 dst_reg
->smax_value
= dst_reg
->umax_value
;
6581 dst_reg
->smin_value
= S64_MIN
;
6582 dst_reg
->smax_value
= S64_MAX
;
6585 __update_reg_bounds(dst_reg
);
6588 static void __scalar32_min_max_lsh(struct bpf_reg_state
*dst_reg
,
6589 u64 umin_val
, u64 umax_val
)
6591 /* We lose all sign bit information (except what we can pick
6594 dst_reg
->s32_min_value
= S32_MIN
;
6595 dst_reg
->s32_max_value
= S32_MAX
;
6596 /* If we might shift our top bit out, then we know nothing */
6597 if (umax_val
> 31 || dst_reg
->u32_max_value
> 1ULL << (31 - umax_val
)) {
6598 dst_reg
->u32_min_value
= 0;
6599 dst_reg
->u32_max_value
= U32_MAX
;
6601 dst_reg
->u32_min_value
<<= umin_val
;
6602 dst_reg
->u32_max_value
<<= umax_val
;
6606 static void scalar32_min_max_lsh(struct bpf_reg_state
*dst_reg
,
6607 struct bpf_reg_state
*src_reg
)
6609 u32 umax_val
= src_reg
->u32_max_value
;
6610 u32 umin_val
= src_reg
->u32_min_value
;
6611 /* u32 alu operation will zext upper bits */
6612 struct tnum subreg
= tnum_subreg(dst_reg
->var_off
);
6614 __scalar32_min_max_lsh(dst_reg
, umin_val
, umax_val
);
6615 dst_reg
->var_off
= tnum_subreg(tnum_lshift(subreg
, umin_val
));
6616 /* Not required but being careful mark reg64 bounds as unknown so
6617 * that we are forced to pick them up from tnum and zext later and
6618 * if some path skips this step we are still safe.
6620 __mark_reg64_unbounded(dst_reg
);
6621 __update_reg32_bounds(dst_reg
);
6624 static void __scalar64_min_max_lsh(struct bpf_reg_state
*dst_reg
,
6625 u64 umin_val
, u64 umax_val
)
6627 /* Special case <<32 because it is a common compiler pattern to sign
6628 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
6629 * positive we know this shift will also be positive so we can track
6630 * bounds correctly. Otherwise we lose all sign bit information except
6631 * what we can pick up from var_off. Perhaps we can generalize this
6632 * later to shifts of any length.
6634 if (umin_val
== 32 && umax_val
== 32 && dst_reg
->s32_max_value
>= 0)
6635 dst_reg
->smax_value
= (s64
)dst_reg
->s32_max_value
<< 32;
6637 dst_reg
->smax_value
= S64_MAX
;
6639 if (umin_val
== 32 && umax_val
== 32 && dst_reg
->s32_min_value
>= 0)
6640 dst_reg
->smin_value
= (s64
)dst_reg
->s32_min_value
<< 32;
6642 dst_reg
->smin_value
= S64_MIN
;
6644 /* If we might shift our top bit out, then we know nothing */
6645 if (dst_reg
->umax_value
> 1ULL << (63 - umax_val
)) {
6646 dst_reg
->umin_value
= 0;
6647 dst_reg
->umax_value
= U64_MAX
;
6649 dst_reg
->umin_value
<<= umin_val
;
6650 dst_reg
->umax_value
<<= umax_val
;
6654 static void scalar_min_max_lsh(struct bpf_reg_state
*dst_reg
,
6655 struct bpf_reg_state
*src_reg
)
6657 u64 umax_val
= src_reg
->umax_value
;
6658 u64 umin_val
= src_reg
->umin_value
;
6660 /* scalar64 calc uses 32bit unshifted bounds so must be called first */
6661 __scalar64_min_max_lsh(dst_reg
, umin_val
, umax_val
);
6662 __scalar32_min_max_lsh(dst_reg
, umin_val
, umax_val
);
6664 dst_reg
->var_off
= tnum_lshift(dst_reg
->var_off
, umin_val
);
6665 /* We may learn something more from the var_off */
6666 __update_reg_bounds(dst_reg
);
6669 static void scalar32_min_max_rsh(struct bpf_reg_state
*dst_reg
,
6670 struct bpf_reg_state
*src_reg
)
6672 struct tnum subreg
= tnum_subreg(dst_reg
->var_off
);
6673 u32 umax_val
= src_reg
->u32_max_value
;
6674 u32 umin_val
= src_reg
->u32_min_value
;
6676 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
6677 * be negative, then either:
6678 * 1) src_reg might be zero, so the sign bit of the result is
6679 * unknown, so we lose our signed bounds
6680 * 2) it's known negative, thus the unsigned bounds capture the
6682 * 3) the signed bounds cross zero, so they tell us nothing
6684 * If the value in dst_reg is known nonnegative, then again the
6685 * unsigned bounts capture the signed bounds.
6686 * Thus, in all cases it suffices to blow away our signed bounds
6687 * and rely on inferring new ones from the unsigned bounds and
6688 * var_off of the result.
6690 dst_reg
->s32_min_value
= S32_MIN
;
6691 dst_reg
->s32_max_value
= S32_MAX
;
6693 dst_reg
->var_off
= tnum_rshift(subreg
, umin_val
);
6694 dst_reg
->u32_min_value
>>= umax_val
;
6695 dst_reg
->u32_max_value
>>= umin_val
;
6697 __mark_reg64_unbounded(dst_reg
);
6698 __update_reg32_bounds(dst_reg
);
6701 static void scalar_min_max_rsh(struct bpf_reg_state
*dst_reg
,
6702 struct bpf_reg_state
*src_reg
)
6704 u64 umax_val
= src_reg
->umax_value
;
6705 u64 umin_val
= src_reg
->umin_value
;
6707 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
6708 * be negative, then either:
6709 * 1) src_reg might be zero, so the sign bit of the result is
6710 * unknown, so we lose our signed bounds
6711 * 2) it's known negative, thus the unsigned bounds capture the
6713 * 3) the signed bounds cross zero, so they tell us nothing
6715 * If the value in dst_reg is known nonnegative, then again the
6716 * unsigned bounts capture the signed bounds.
6717 * Thus, in all cases it suffices to blow away our signed bounds
6718 * and rely on inferring new ones from the unsigned bounds and
6719 * var_off of the result.
6721 dst_reg
->smin_value
= S64_MIN
;
6722 dst_reg
->smax_value
= S64_MAX
;
6723 dst_reg
->var_off
= tnum_rshift(dst_reg
->var_off
, umin_val
);
6724 dst_reg
->umin_value
>>= umax_val
;
6725 dst_reg
->umax_value
>>= umin_val
;
6727 /* Its not easy to operate on alu32 bounds here because it depends
6728 * on bits being shifted in. Take easy way out and mark unbounded
6729 * so we can recalculate later from tnum.
6731 __mark_reg32_unbounded(dst_reg
);
6732 __update_reg_bounds(dst_reg
);
6735 static void scalar32_min_max_arsh(struct bpf_reg_state
*dst_reg
,
6736 struct bpf_reg_state
*src_reg
)
6738 u64 umin_val
= src_reg
->u32_min_value
;
6740 /* Upon reaching here, src_known is true and
6741 * umax_val is equal to umin_val.
6743 dst_reg
->s32_min_value
= (u32
)(((s32
)dst_reg
->s32_min_value
) >> umin_val
);
6744 dst_reg
->s32_max_value
= (u32
)(((s32
)dst_reg
->s32_max_value
) >> umin_val
);
6746 dst_reg
->var_off
= tnum_arshift(tnum_subreg(dst_reg
->var_off
), umin_val
, 32);
6748 /* blow away the dst_reg umin_value/umax_value and rely on
6749 * dst_reg var_off to refine the result.
6751 dst_reg
->u32_min_value
= 0;
6752 dst_reg
->u32_max_value
= U32_MAX
;
6754 __mark_reg64_unbounded(dst_reg
);
6755 __update_reg32_bounds(dst_reg
);
6758 static void scalar_min_max_arsh(struct bpf_reg_state
*dst_reg
,
6759 struct bpf_reg_state
*src_reg
)
6761 u64 umin_val
= src_reg
->umin_value
;
6763 /* Upon reaching here, src_known is true and umax_val is equal
6766 dst_reg
->smin_value
>>= umin_val
;
6767 dst_reg
->smax_value
>>= umin_val
;
6769 dst_reg
->var_off
= tnum_arshift(dst_reg
->var_off
, umin_val
, 64);
6771 /* blow away the dst_reg umin_value/umax_value and rely on
6772 * dst_reg var_off to refine the result.
6774 dst_reg
->umin_value
= 0;
6775 dst_reg
->umax_value
= U64_MAX
;
6777 /* Its not easy to operate on alu32 bounds here because it depends
6778 * on bits being shifted in from upper 32-bits. Take easy way out
6779 * and mark unbounded so we can recalculate later from tnum.
6781 __mark_reg32_unbounded(dst_reg
);
6782 __update_reg_bounds(dst_reg
);
6785 /* WARNING: This function does calculations on 64-bit values, but the actual
6786 * execution may occur on 32-bit values. Therefore, things like bitshifts
6787 * need extra checks in the 32-bit case.
6789 static int adjust_scalar_min_max_vals(struct bpf_verifier_env
*env
,
6790 struct bpf_insn
*insn
,
6791 struct bpf_reg_state
*dst_reg
,
6792 struct bpf_reg_state src_reg
)
6794 struct bpf_reg_state
*regs
= cur_regs(env
);
6795 u8 opcode
= BPF_OP(insn
->code
);
6797 s64 smin_val
, smax_val
;
6798 u64 umin_val
, umax_val
;
6799 s32 s32_min_val
, s32_max_val
;
6800 u32 u32_min_val
, u32_max_val
;
6801 u64 insn_bitness
= (BPF_CLASS(insn
->code
) == BPF_ALU64
) ? 64 : 32;
6802 bool alu32
= (BPF_CLASS(insn
->code
) != BPF_ALU64
);
6805 smin_val
= src_reg
.smin_value
;
6806 smax_val
= src_reg
.smax_value
;
6807 umin_val
= src_reg
.umin_value
;
6808 umax_val
= src_reg
.umax_value
;
6810 s32_min_val
= src_reg
.s32_min_value
;
6811 s32_max_val
= src_reg
.s32_max_value
;
6812 u32_min_val
= src_reg
.u32_min_value
;
6813 u32_max_val
= src_reg
.u32_max_value
;
6816 src_known
= tnum_subreg_is_const(src_reg
.var_off
);
6818 (s32_min_val
!= s32_max_val
|| u32_min_val
!= u32_max_val
)) ||
6819 s32_min_val
> s32_max_val
|| u32_min_val
> u32_max_val
) {
6820 /* Taint dst register if offset had invalid bounds
6821 * derived from e.g. dead branches.
6823 __mark_reg_unknown(env
, dst_reg
);
6827 src_known
= tnum_is_const(src_reg
.var_off
);
6829 (smin_val
!= smax_val
|| umin_val
!= umax_val
)) ||
6830 smin_val
> smax_val
|| umin_val
> umax_val
) {
6831 /* Taint dst register if offset had invalid bounds
6832 * derived from e.g. dead branches.
6834 __mark_reg_unknown(env
, dst_reg
);
6840 opcode
!= BPF_ADD
&& opcode
!= BPF_SUB
&& opcode
!= BPF_AND
) {
6841 __mark_reg_unknown(env
, dst_reg
);
6845 if (sanitize_needed(opcode
)) {
6846 ret
= sanitize_val_alu(env
, insn
);
6848 return sanitize_err(env
, insn
, ret
, NULL
, NULL
);
6851 /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
6852 * There are two classes of instructions: The first class we track both
6853 * alu32 and alu64 sign/unsigned bounds independently this provides the
6854 * greatest amount of precision when alu operations are mixed with jmp32
6855 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
6856 * and BPF_OR. This is possible because these ops have fairly easy to
6857 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
6858 * See alu32 verifier tests for examples. The second class of
6859 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
6860 * with regards to tracking sign/unsigned bounds because the bits may
6861 * cross subreg boundaries in the alu64 case. When this happens we mark
6862 * the reg unbounded in the subreg bound space and use the resulting
6863 * tnum to calculate an approximation of the sign/unsigned bounds.
6867 scalar32_min_max_add(dst_reg
, &src_reg
);
6868 scalar_min_max_add(dst_reg
, &src_reg
);
6869 dst_reg
->var_off
= tnum_add(dst_reg
->var_off
, src_reg
.var_off
);
6872 scalar32_min_max_sub(dst_reg
, &src_reg
);
6873 scalar_min_max_sub(dst_reg
, &src_reg
);
6874 dst_reg
->var_off
= tnum_sub(dst_reg
->var_off
, src_reg
.var_off
);
6877 dst_reg
->var_off
= tnum_mul(dst_reg
->var_off
, src_reg
.var_off
);
6878 scalar32_min_max_mul(dst_reg
, &src_reg
);
6879 scalar_min_max_mul(dst_reg
, &src_reg
);
6882 dst_reg
->var_off
= tnum_and(dst_reg
->var_off
, src_reg
.var_off
);
6883 scalar32_min_max_and(dst_reg
, &src_reg
);
6884 scalar_min_max_and(dst_reg
, &src_reg
);
6887 dst_reg
->var_off
= tnum_or(dst_reg
->var_off
, src_reg
.var_off
);
6888 scalar32_min_max_or(dst_reg
, &src_reg
);
6889 scalar_min_max_or(dst_reg
, &src_reg
);
6892 dst_reg
->var_off
= tnum_xor(dst_reg
->var_off
, src_reg
.var_off
);
6893 scalar32_min_max_xor(dst_reg
, &src_reg
);
6894 scalar_min_max_xor(dst_reg
, &src_reg
);
6897 if (umax_val
>= insn_bitness
) {
6898 /* Shifts greater than 31 or 63 are undefined.
6899 * This includes shifts by a negative number.
6901 mark_reg_unknown(env
, regs
, insn
->dst_reg
);
6905 scalar32_min_max_lsh(dst_reg
, &src_reg
);
6907 scalar_min_max_lsh(dst_reg
, &src_reg
);
6910 if (umax_val
>= insn_bitness
) {
6911 /* Shifts greater than 31 or 63 are undefined.
6912 * This includes shifts by a negative number.
6914 mark_reg_unknown(env
, regs
, insn
->dst_reg
);
6918 scalar32_min_max_rsh(dst_reg
, &src_reg
);
6920 scalar_min_max_rsh(dst_reg
, &src_reg
);
6923 if (umax_val
>= insn_bitness
) {
6924 /* Shifts greater than 31 or 63 are undefined.
6925 * This includes shifts by a negative number.
6927 mark_reg_unknown(env
, regs
, insn
->dst_reg
);
6931 scalar32_min_max_arsh(dst_reg
, &src_reg
);
6933 scalar_min_max_arsh(dst_reg
, &src_reg
);
6936 mark_reg_unknown(env
, regs
, insn
->dst_reg
);
6940 /* ALU32 ops are zero extended into 64bit register */
6942 zext_32_to_64(dst_reg
);
6944 __update_reg_bounds(dst_reg
);
6945 __reg_deduce_bounds(dst_reg
);
6946 __reg_bound_offset(dst_reg
);
6950 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
6953 static int adjust_reg_min_max_vals(struct bpf_verifier_env
*env
,
6954 struct bpf_insn
*insn
)
6956 struct bpf_verifier_state
*vstate
= env
->cur_state
;
6957 struct bpf_func_state
*state
= vstate
->frame
[vstate
->curframe
];
6958 struct bpf_reg_state
*regs
= state
->regs
, *dst_reg
, *src_reg
;
6959 struct bpf_reg_state
*ptr_reg
= NULL
, off_reg
= {0};
6960 u8 opcode
= BPF_OP(insn
->code
);
6963 dst_reg
= ®s
[insn
->dst_reg
];
6965 if (dst_reg
->type
!= SCALAR_VALUE
)
6968 /* Make sure ID is cleared otherwise dst_reg min/max could be
6969 * incorrectly propagated into other registers by find_equal_scalars()
6972 if (BPF_SRC(insn
->code
) == BPF_X
) {
6973 src_reg
= ®s
[insn
->src_reg
];
6974 if (src_reg
->type
!= SCALAR_VALUE
) {
6975 if (dst_reg
->type
!= SCALAR_VALUE
) {
6976 /* Combining two pointers by any ALU op yields
6977 * an arbitrary scalar. Disallow all math except
6978 * pointer subtraction
6980 if (opcode
== BPF_SUB
&& env
->allow_ptr_leaks
) {
6981 mark_reg_unknown(env
, regs
, insn
->dst_reg
);
6984 verbose(env
, "R%d pointer %s pointer prohibited\n",
6986 bpf_alu_string
[opcode
>> 4]);
6989 /* scalar += pointer
6990 * This is legal, but we have to reverse our
6991 * src/dest handling in computing the range
6993 err
= mark_chain_precision(env
, insn
->dst_reg
);
6996 return adjust_ptr_min_max_vals(env
, insn
,
6999 } else if (ptr_reg
) {
7000 /* pointer += scalar */
7001 err
= mark_chain_precision(env
, insn
->src_reg
);
7004 return adjust_ptr_min_max_vals(env
, insn
,
7008 /* Pretend the src is a reg with a known value, since we only
7009 * need to be able to read from this state.
7011 off_reg
.type
= SCALAR_VALUE
;
7012 __mark_reg_known(&off_reg
, insn
->imm
);
7014 if (ptr_reg
) /* pointer += K */
7015 return adjust_ptr_min_max_vals(env
, insn
,
7019 /* Got here implies adding two SCALAR_VALUEs */
7020 if (WARN_ON_ONCE(ptr_reg
)) {
7021 print_verifier_state(env
, state
);
7022 verbose(env
, "verifier internal error: unexpected ptr_reg\n");
7025 if (WARN_ON(!src_reg
)) {
7026 print_verifier_state(env
, state
);
7027 verbose(env
, "verifier internal error: no src_reg\n");
7030 return adjust_scalar_min_max_vals(env
, insn
, dst_reg
, *src_reg
);
7033 /* check validity of 32-bit and 64-bit arithmetic operations */
7034 static int check_alu_op(struct bpf_verifier_env
*env
, struct bpf_insn
*insn
)
7036 struct bpf_reg_state
*regs
= cur_regs(env
);
7037 u8 opcode
= BPF_OP(insn
->code
);
7040 if (opcode
== BPF_END
|| opcode
== BPF_NEG
) {
7041 if (opcode
== BPF_NEG
) {
7042 if (BPF_SRC(insn
->code
) != 0 ||
7043 insn
->src_reg
!= BPF_REG_0
||
7044 insn
->off
!= 0 || insn
->imm
!= 0) {
7045 verbose(env
, "BPF_NEG uses reserved fields\n");
7049 if (insn
->src_reg
!= BPF_REG_0
|| insn
->off
!= 0 ||
7050 (insn
->imm
!= 16 && insn
->imm
!= 32 && insn
->imm
!= 64) ||
7051 BPF_CLASS(insn
->code
) == BPF_ALU64
) {
7052 verbose(env
, "BPF_END uses reserved fields\n");
7057 /* check src operand */
7058 err
= check_reg_arg(env
, insn
->dst_reg
, SRC_OP
);
7062 if (is_pointer_value(env
, insn
->dst_reg
)) {
7063 verbose(env
, "R%d pointer arithmetic prohibited\n",
7068 /* check dest operand */
7069 err
= check_reg_arg(env
, insn
->dst_reg
, DST_OP
);
7073 } else if (opcode
== BPF_MOV
) {
7075 if (BPF_SRC(insn
->code
) == BPF_X
) {
7076 if (insn
->imm
!= 0 || insn
->off
!= 0) {
7077 verbose(env
, "BPF_MOV uses reserved fields\n");
7081 /* check src operand */
7082 err
= check_reg_arg(env
, insn
->src_reg
, SRC_OP
);
7086 if (insn
->src_reg
!= BPF_REG_0
|| insn
->off
!= 0) {
7087 verbose(env
, "BPF_MOV uses reserved fields\n");
7092 /* check dest operand, mark as required later */
7093 err
= check_reg_arg(env
, insn
->dst_reg
, DST_OP_NO_MARK
);
7097 if (BPF_SRC(insn
->code
) == BPF_X
) {
7098 struct bpf_reg_state
*src_reg
= regs
+ insn
->src_reg
;
7099 struct bpf_reg_state
*dst_reg
= regs
+ insn
->dst_reg
;
7101 if (BPF_CLASS(insn
->code
) == BPF_ALU64
) {
7103 * copy register state to dest reg
7105 if (src_reg
->type
== SCALAR_VALUE
&& !src_reg
->id
)
7106 /* Assign src and dst registers the same ID
7107 * that will be used by find_equal_scalars()
7108 * to propagate min/max range.
7110 src_reg
->id
= ++env
->id_gen
;
7111 *dst_reg
= *src_reg
;
7112 dst_reg
->live
|= REG_LIVE_WRITTEN
;
7113 dst_reg
->subreg_def
= DEF_NOT_SUBREG
;
7116 if (is_pointer_value(env
, insn
->src_reg
)) {
7118 "R%d partial copy of pointer\n",
7121 } else if (src_reg
->type
== SCALAR_VALUE
) {
7122 *dst_reg
= *src_reg
;
7123 /* Make sure ID is cleared otherwise
7124 * dst_reg min/max could be incorrectly
7125 * propagated into src_reg by find_equal_scalars()
7128 dst_reg
->live
|= REG_LIVE_WRITTEN
;
7129 dst_reg
->subreg_def
= env
->insn_idx
+ 1;
7131 mark_reg_unknown(env
, regs
,
7134 zext_32_to_64(dst_reg
);
7138 * remember the value we stored into this reg
7140 /* clear any state __mark_reg_known doesn't set */
7141 mark_reg_unknown(env
, regs
, insn
->dst_reg
);
7142 regs
[insn
->dst_reg
].type
= SCALAR_VALUE
;
7143 if (BPF_CLASS(insn
->code
) == BPF_ALU64
) {
7144 __mark_reg_known(regs
+ insn
->dst_reg
,
7147 __mark_reg_known(regs
+ insn
->dst_reg
,
7152 } else if (opcode
> BPF_END
) {
7153 verbose(env
, "invalid BPF_ALU opcode %x\n", opcode
);
7156 } else { /* all other ALU ops: and, sub, xor, add, ... */
7158 if (BPF_SRC(insn
->code
) == BPF_X
) {
7159 if (insn
->imm
!= 0 || insn
->off
!= 0) {
7160 verbose(env
, "BPF_ALU uses reserved fields\n");
7163 /* check src1 operand */
7164 err
= check_reg_arg(env
, insn
->src_reg
, SRC_OP
);
7168 if (insn
->src_reg
!= BPF_REG_0
|| insn
->off
!= 0) {
7169 verbose(env
, "BPF_ALU uses reserved fields\n");
7174 /* check src2 operand */
7175 err
= check_reg_arg(env
, insn
->dst_reg
, SRC_OP
);
7179 if ((opcode
== BPF_MOD
|| opcode
== BPF_DIV
) &&
7180 BPF_SRC(insn
->code
) == BPF_K
&& insn
->imm
== 0) {
7181 verbose(env
, "div by zero\n");
7185 if ((opcode
== BPF_LSH
|| opcode
== BPF_RSH
||
7186 opcode
== BPF_ARSH
) && BPF_SRC(insn
->code
) == BPF_K
) {
7187 int size
= BPF_CLASS(insn
->code
) == BPF_ALU64
? 64 : 32;
7189 if (insn
->imm
< 0 || insn
->imm
>= size
) {
7190 verbose(env
, "invalid shift %d\n", insn
->imm
);
7195 /* check dest operand */
7196 err
= check_reg_arg(env
, insn
->dst_reg
, DST_OP_NO_MARK
);
7200 return adjust_reg_min_max_vals(env
, insn
);
7206 static void __find_good_pkt_pointers(struct bpf_func_state
*state
,
7207 struct bpf_reg_state
*dst_reg
,
7208 enum bpf_reg_type type
, int new_range
)
7210 struct bpf_reg_state
*reg
;
7213 for (i
= 0; i
< MAX_BPF_REG
; i
++) {
7214 reg
= &state
->regs
[i
];
7215 if (reg
->type
== type
&& reg
->id
== dst_reg
->id
)
7216 /* keep the maximum range already checked */
7217 reg
->range
= max(reg
->range
, new_range
);
7220 bpf_for_each_spilled_reg(i
, state
, reg
) {
7223 if (reg
->type
== type
&& reg
->id
== dst_reg
->id
)
7224 reg
->range
= max(reg
->range
, new_range
);
7228 static void find_good_pkt_pointers(struct bpf_verifier_state
*vstate
,
7229 struct bpf_reg_state
*dst_reg
,
7230 enum bpf_reg_type type
,
7231 bool range_right_open
)
7235 if (dst_reg
->off
< 0 ||
7236 (dst_reg
->off
== 0 && range_right_open
))
7237 /* This doesn't give us any range */
7240 if (dst_reg
->umax_value
> MAX_PACKET_OFF
||
7241 dst_reg
->umax_value
+ dst_reg
->off
> MAX_PACKET_OFF
)
7242 /* Risk of overflow. For instance, ptr + (1<<63) may be less
7243 * than pkt_end, but that's because it's also less than pkt.
7247 new_range
= dst_reg
->off
;
7248 if (range_right_open
)
7251 /* Examples for register markings:
7253 * pkt_data in dst register:
7257 * if (r2 > pkt_end) goto <handle exception>
7262 * if (r2 < pkt_end) goto <access okay>
7263 * <handle exception>
7266 * r2 == dst_reg, pkt_end == src_reg
7267 * r2=pkt(id=n,off=8,r=0)
7268 * r3=pkt(id=n,off=0,r=0)
7270 * pkt_data in src register:
7274 * if (pkt_end >= r2) goto <access okay>
7275 * <handle exception>
7279 * if (pkt_end <= r2) goto <handle exception>
7283 * pkt_end == dst_reg, r2 == src_reg
7284 * r2=pkt(id=n,off=8,r=0)
7285 * r3=pkt(id=n,off=0,r=0)
7287 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
7288 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
7289 * and [r3, r3 + 8-1) respectively is safe to access depending on
7293 /* If our ids match, then we must have the same max_value. And we
7294 * don't care about the other reg's fixed offset, since if it's too big
7295 * the range won't allow anything.
7296 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
7298 for (i
= 0; i
<= vstate
->curframe
; i
++)
7299 __find_good_pkt_pointers(vstate
->frame
[i
], dst_reg
, type
,
7303 static int is_branch32_taken(struct bpf_reg_state
*reg
, u32 val
, u8 opcode
)
7305 struct tnum subreg
= tnum_subreg(reg
->var_off
);
7306 s32 sval
= (s32
)val
;
7310 if (tnum_is_const(subreg
))
7311 return !!tnum_equals_const(subreg
, val
);
7314 if (tnum_is_const(subreg
))
7315 return !tnum_equals_const(subreg
, val
);
7318 if ((~subreg
.mask
& subreg
.value
) & val
)
7320 if (!((subreg
.mask
| subreg
.value
) & val
))
7324 if (reg
->u32_min_value
> val
)
7326 else if (reg
->u32_max_value
<= val
)
7330 if (reg
->s32_min_value
> sval
)
7332 else if (reg
->s32_max_value
<= sval
)
7336 if (reg
->u32_max_value
< val
)
7338 else if (reg
->u32_min_value
>= val
)
7342 if (reg
->s32_max_value
< sval
)
7344 else if (reg
->s32_min_value
>= sval
)
7348 if (reg
->u32_min_value
>= val
)
7350 else if (reg
->u32_max_value
< val
)
7354 if (reg
->s32_min_value
>= sval
)
7356 else if (reg
->s32_max_value
< sval
)
7360 if (reg
->u32_max_value
<= val
)
7362 else if (reg
->u32_min_value
> val
)
7366 if (reg
->s32_max_value
<= sval
)
7368 else if (reg
->s32_min_value
> sval
)
7377 static int is_branch64_taken(struct bpf_reg_state
*reg
, u64 val
, u8 opcode
)
7379 s64 sval
= (s64
)val
;
7383 if (tnum_is_const(reg
->var_off
))
7384 return !!tnum_equals_const(reg
->var_off
, val
);
7387 if (tnum_is_const(reg
->var_off
))
7388 return !tnum_equals_const(reg
->var_off
, val
);
7391 if ((~reg
->var_off
.mask
& reg
->var_off
.value
) & val
)
7393 if (!((reg
->var_off
.mask
| reg
->var_off
.value
) & val
))
7397 if (reg
->umin_value
> val
)
7399 else if (reg
->umax_value
<= val
)
7403 if (reg
->smin_value
> sval
)
7405 else if (reg
->smax_value
<= sval
)
7409 if (reg
->umax_value
< val
)
7411 else if (reg
->umin_value
>= val
)
7415 if (reg
->smax_value
< sval
)
7417 else if (reg
->smin_value
>= sval
)
7421 if (reg
->umin_value
>= val
)
7423 else if (reg
->umax_value
< val
)
7427 if (reg
->smin_value
>= sval
)
7429 else if (reg
->smax_value
< sval
)
7433 if (reg
->umax_value
<= val
)
7435 else if (reg
->umin_value
> val
)
7439 if (reg
->smax_value
<= sval
)
7441 else if (reg
->smin_value
> sval
)
7449 /* compute branch direction of the expression "if (reg opcode val) goto target;"
7451 * 1 - branch will be taken and "goto target" will be executed
7452 * 0 - branch will not be taken and fall-through to next insn
7453 * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
7456 static int is_branch_taken(struct bpf_reg_state
*reg
, u64 val
, u8 opcode
,
7459 if (__is_pointer_value(false, reg
)) {
7460 if (!reg_type_not_null(reg
->type
))
7463 /* If pointer is valid tests against zero will fail so we can
7464 * use this to direct branch taken.
7480 return is_branch32_taken(reg
, val
, opcode
);
7481 return is_branch64_taken(reg
, val
, opcode
);
7484 static int flip_opcode(u32 opcode
)
7486 /* How can we transform "a <op> b" into "b <op> a"? */
7487 static const u8 opcode_flip
[16] = {
7488 /* these stay the same */
7489 [BPF_JEQ
>> 4] = BPF_JEQ
,
7490 [BPF_JNE
>> 4] = BPF_JNE
,
7491 [BPF_JSET
>> 4] = BPF_JSET
,
7492 /* these swap "lesser" and "greater" (L and G in the opcodes) */
7493 [BPF_JGE
>> 4] = BPF_JLE
,
7494 [BPF_JGT
>> 4] = BPF_JLT
,
7495 [BPF_JLE
>> 4] = BPF_JGE
,
7496 [BPF_JLT
>> 4] = BPF_JGT
,
7497 [BPF_JSGE
>> 4] = BPF_JSLE
,
7498 [BPF_JSGT
>> 4] = BPF_JSLT
,
7499 [BPF_JSLE
>> 4] = BPF_JSGE
,
7500 [BPF_JSLT
>> 4] = BPF_JSGT
7502 return opcode_flip
[opcode
>> 4];
7505 static int is_pkt_ptr_branch_taken(struct bpf_reg_state
*dst_reg
,
7506 struct bpf_reg_state
*src_reg
,
7509 struct bpf_reg_state
*pkt
;
7511 if (src_reg
->type
== PTR_TO_PACKET_END
) {
7513 } else if (dst_reg
->type
== PTR_TO_PACKET_END
) {
7515 opcode
= flip_opcode(opcode
);
7520 if (pkt
->range
>= 0)
7525 /* pkt <= pkt_end */
7529 if (pkt
->range
== BEYOND_PKT_END
)
7530 /* pkt has at last one extra byte beyond pkt_end */
7531 return opcode
== BPF_JGT
;
7537 /* pkt >= pkt_end */
7538 if (pkt
->range
== BEYOND_PKT_END
|| pkt
->range
== AT_PKT_END
)
7539 return opcode
== BPF_JGE
;
7545 /* Adjusts the register min/max values in the case that the dst_reg is the
7546 * variable register that we are working on, and src_reg is a constant or we're
7547 * simply doing a BPF_K check.
7548 * In JEQ/JNE cases we also adjust the var_off values.
7550 static void reg_set_min_max(struct bpf_reg_state
*true_reg
,
7551 struct bpf_reg_state
*false_reg
,
7553 u8 opcode
, bool is_jmp32
)
7555 struct tnum false_32off
= tnum_subreg(false_reg
->var_off
);
7556 struct tnum false_64off
= false_reg
->var_off
;
7557 struct tnum true_32off
= tnum_subreg(true_reg
->var_off
);
7558 struct tnum true_64off
= true_reg
->var_off
;
7559 s64 sval
= (s64
)val
;
7560 s32 sval32
= (s32
)val32
;
7562 /* If the dst_reg is a pointer, we can't learn anything about its
7563 * variable offset from the compare (unless src_reg were a pointer into
7564 * the same object, but we don't bother with that.
7565 * Since false_reg and true_reg have the same type by construction, we
7566 * only need to check one of them for pointerness.
7568 if (__is_pointer_value(false, false_reg
))
7575 struct bpf_reg_state
*reg
=
7576 opcode
== BPF_JEQ
? true_reg
: false_reg
;
7578 /* JEQ/JNE comparison doesn't change the register equivalence.
7580 * if (r1 == 42) goto label;
7582 * label: // here both r1 and r2 are known to be 42.
7584 * Hence when marking register as known preserve it's ID.
7587 __mark_reg32_known(reg
, val32
);
7589 ___mark_reg_known(reg
, val
);
7594 false_32off
= tnum_and(false_32off
, tnum_const(~val32
));
7595 if (is_power_of_2(val32
))
7596 true_32off
= tnum_or(true_32off
,
7599 false_64off
= tnum_and(false_64off
, tnum_const(~val
));
7600 if (is_power_of_2(val
))
7601 true_64off
= tnum_or(true_64off
,
7609 u32 false_umax
= opcode
== BPF_JGT
? val32
: val32
- 1;
7610 u32 true_umin
= opcode
== BPF_JGT
? val32
+ 1 : val32
;
7612 false_reg
->u32_max_value
= min(false_reg
->u32_max_value
,
7614 true_reg
->u32_min_value
= max(true_reg
->u32_min_value
,
7617 u64 false_umax
= opcode
== BPF_JGT
? val
: val
- 1;
7618 u64 true_umin
= opcode
== BPF_JGT
? val
+ 1 : val
;
7620 false_reg
->umax_value
= min(false_reg
->umax_value
, false_umax
);
7621 true_reg
->umin_value
= max(true_reg
->umin_value
, true_umin
);
7629 s32 false_smax
= opcode
== BPF_JSGT
? sval32
: sval32
- 1;
7630 s32 true_smin
= opcode
== BPF_JSGT
? sval32
+ 1 : sval32
;
7632 false_reg
->s32_max_value
= min(false_reg
->s32_max_value
, false_smax
);
7633 true_reg
->s32_min_value
= max(true_reg
->s32_min_value
, true_smin
);
7635 s64 false_smax
= opcode
== BPF_JSGT
? sval
: sval
- 1;
7636 s64 true_smin
= opcode
== BPF_JSGT
? sval
+ 1 : sval
;
7638 false_reg
->smax_value
= min(false_reg
->smax_value
, false_smax
);
7639 true_reg
->smin_value
= max(true_reg
->smin_value
, true_smin
);
7647 u32 false_umin
= opcode
== BPF_JLT
? val32
: val32
+ 1;
7648 u32 true_umax
= opcode
== BPF_JLT
? val32
- 1 : val32
;
7650 false_reg
->u32_min_value
= max(false_reg
->u32_min_value
,
7652 true_reg
->u32_max_value
= min(true_reg
->u32_max_value
,
7655 u64 false_umin
= opcode
== BPF_JLT
? val
: val
+ 1;
7656 u64 true_umax
= opcode
== BPF_JLT
? val
- 1 : val
;
7658 false_reg
->umin_value
= max(false_reg
->umin_value
, false_umin
);
7659 true_reg
->umax_value
= min(true_reg
->umax_value
, true_umax
);
7667 s32 false_smin
= opcode
== BPF_JSLT
? sval32
: sval32
+ 1;
7668 s32 true_smax
= opcode
== BPF_JSLT
? sval32
- 1 : sval32
;
7670 false_reg
->s32_min_value
= max(false_reg
->s32_min_value
, false_smin
);
7671 true_reg
->s32_max_value
= min(true_reg
->s32_max_value
, true_smax
);
7673 s64 false_smin
= opcode
== BPF_JSLT
? sval
: sval
+ 1;
7674 s64 true_smax
= opcode
== BPF_JSLT
? sval
- 1 : sval
;
7676 false_reg
->smin_value
= max(false_reg
->smin_value
, false_smin
);
7677 true_reg
->smax_value
= min(true_reg
->smax_value
, true_smax
);
7686 false_reg
->var_off
= tnum_or(tnum_clear_subreg(false_64off
),
7687 tnum_subreg(false_32off
));
7688 true_reg
->var_off
= tnum_or(tnum_clear_subreg(true_64off
),
7689 tnum_subreg(true_32off
));
7690 __reg_combine_32_into_64(false_reg
);
7691 __reg_combine_32_into_64(true_reg
);
7693 false_reg
->var_off
= false_64off
;
7694 true_reg
->var_off
= true_64off
;
7695 __reg_combine_64_into_32(false_reg
);
7696 __reg_combine_64_into_32(true_reg
);
7700 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
7703 static void reg_set_min_max_inv(struct bpf_reg_state
*true_reg
,
7704 struct bpf_reg_state
*false_reg
,
7706 u8 opcode
, bool is_jmp32
)
7708 opcode
= flip_opcode(opcode
);
7709 /* This uses zero as "not present in table"; luckily the zero opcode,
7710 * BPF_JA, can't get here.
7713 reg_set_min_max(true_reg
, false_reg
, val
, val32
, opcode
, is_jmp32
);
7716 /* Regs are known to be equal, so intersect their min/max/var_off */
7717 static void __reg_combine_min_max(struct bpf_reg_state
*src_reg
,
7718 struct bpf_reg_state
*dst_reg
)
7720 src_reg
->umin_value
= dst_reg
->umin_value
= max(src_reg
->umin_value
,
7721 dst_reg
->umin_value
);
7722 src_reg
->umax_value
= dst_reg
->umax_value
= min(src_reg
->umax_value
,
7723 dst_reg
->umax_value
);
7724 src_reg
->smin_value
= dst_reg
->smin_value
= max(src_reg
->smin_value
,
7725 dst_reg
->smin_value
);
7726 src_reg
->smax_value
= dst_reg
->smax_value
= min(src_reg
->smax_value
,
7727 dst_reg
->smax_value
);
7728 src_reg
->var_off
= dst_reg
->var_off
= tnum_intersect(src_reg
->var_off
,
7730 /* We might have learned new bounds from the var_off. */
7731 __update_reg_bounds(src_reg
);
7732 __update_reg_bounds(dst_reg
);
7733 /* We might have learned something about the sign bit. */
7734 __reg_deduce_bounds(src_reg
);
7735 __reg_deduce_bounds(dst_reg
);
7736 /* We might have learned some bits from the bounds. */
7737 __reg_bound_offset(src_reg
);
7738 __reg_bound_offset(dst_reg
);
7739 /* Intersecting with the old var_off might have improved our bounds
7740 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
7741 * then new var_off is (0; 0x7f...fc) which improves our umax.
7743 __update_reg_bounds(src_reg
);
7744 __update_reg_bounds(dst_reg
);
7747 static void reg_combine_min_max(struct bpf_reg_state
*true_src
,
7748 struct bpf_reg_state
*true_dst
,
7749 struct bpf_reg_state
*false_src
,
7750 struct bpf_reg_state
*false_dst
,
7755 __reg_combine_min_max(true_src
, true_dst
);
7758 __reg_combine_min_max(false_src
, false_dst
);
7763 static void mark_ptr_or_null_reg(struct bpf_func_state
*state
,
7764 struct bpf_reg_state
*reg
, u32 id
,
7767 if (reg_type_may_be_null(reg
->type
) && reg
->id
== id
&&
7768 !WARN_ON_ONCE(!reg
->id
)) {
7769 /* Old offset (both fixed and variable parts) should
7770 * have been known-zero, because we don't allow pointer
7771 * arithmetic on pointers that might be NULL.
7773 if (WARN_ON_ONCE(reg
->smin_value
|| reg
->smax_value
||
7774 !tnum_equals_const(reg
->var_off
, 0) ||
7776 __mark_reg_known_zero(reg
);
7780 reg
->type
= SCALAR_VALUE
;
7781 } else if (reg
->type
== PTR_TO_MAP_VALUE_OR_NULL
) {
7782 const struct bpf_map
*map
= reg
->map_ptr
;
7784 if (map
->inner_map_meta
) {
7785 reg
->type
= CONST_PTR_TO_MAP
;
7786 reg
->map_ptr
= map
->inner_map_meta
;
7787 } else if (map
->map_type
== BPF_MAP_TYPE_XSKMAP
) {
7788 reg
->type
= PTR_TO_XDP_SOCK
;
7789 } else if (map
->map_type
== BPF_MAP_TYPE_SOCKMAP
||
7790 map
->map_type
== BPF_MAP_TYPE_SOCKHASH
) {
7791 reg
->type
= PTR_TO_SOCKET
;
7793 reg
->type
= PTR_TO_MAP_VALUE
;
7795 } else if (reg
->type
== PTR_TO_SOCKET_OR_NULL
) {
7796 reg
->type
= PTR_TO_SOCKET
;
7797 } else if (reg
->type
== PTR_TO_SOCK_COMMON_OR_NULL
) {
7798 reg
->type
= PTR_TO_SOCK_COMMON
;
7799 } else if (reg
->type
== PTR_TO_TCP_SOCK_OR_NULL
) {
7800 reg
->type
= PTR_TO_TCP_SOCK
;
7801 } else if (reg
->type
== PTR_TO_BTF_ID_OR_NULL
) {
7802 reg
->type
= PTR_TO_BTF_ID
;
7803 } else if (reg
->type
== PTR_TO_MEM_OR_NULL
) {
7804 reg
->type
= PTR_TO_MEM
;
7805 } else if (reg
->type
== PTR_TO_RDONLY_BUF_OR_NULL
) {
7806 reg
->type
= PTR_TO_RDONLY_BUF
;
7807 } else if (reg
->type
== PTR_TO_RDWR_BUF_OR_NULL
) {
7808 reg
->type
= PTR_TO_RDWR_BUF
;
7811 /* We don't need id and ref_obj_id from this point
7812 * onwards anymore, thus we should better reset it,
7813 * so that state pruning has chances to take effect.
7816 reg
->ref_obj_id
= 0;
7817 } else if (!reg_may_point_to_spin_lock(reg
)) {
7818 /* For not-NULL ptr, reg->ref_obj_id will be reset
7819 * in release_reg_references().
7821 * reg->id is still used by spin_lock ptr. Other
7822 * than spin_lock ptr type, reg->id can be reset.
7829 static void __mark_ptr_or_null_regs(struct bpf_func_state
*state
, u32 id
,
7832 struct bpf_reg_state
*reg
;
7835 for (i
= 0; i
< MAX_BPF_REG
; i
++)
7836 mark_ptr_or_null_reg(state
, &state
->regs
[i
], id
, is_null
);
7838 bpf_for_each_spilled_reg(i
, state
, reg
) {
7841 mark_ptr_or_null_reg(state
, reg
, id
, is_null
);
7845 /* The logic is similar to find_good_pkt_pointers(), both could eventually
7846 * be folded together at some point.
7848 static void mark_ptr_or_null_regs(struct bpf_verifier_state
*vstate
, u32 regno
,
7851 struct bpf_func_state
*state
= vstate
->frame
[vstate
->curframe
];
7852 struct bpf_reg_state
*regs
= state
->regs
;
7853 u32 ref_obj_id
= regs
[regno
].ref_obj_id
;
7854 u32 id
= regs
[regno
].id
;
7857 if (ref_obj_id
&& ref_obj_id
== id
&& is_null
)
7858 /* regs[regno] is in the " == NULL" branch.
7859 * No one could have freed the reference state before
7860 * doing the NULL check.
7862 WARN_ON_ONCE(release_reference_state(state
, id
));
7864 for (i
= 0; i
<= vstate
->curframe
; i
++)
7865 __mark_ptr_or_null_regs(vstate
->frame
[i
], id
, is_null
);
7868 static bool try_match_pkt_pointers(const struct bpf_insn
*insn
,
7869 struct bpf_reg_state
*dst_reg
,
7870 struct bpf_reg_state
*src_reg
,
7871 struct bpf_verifier_state
*this_branch
,
7872 struct bpf_verifier_state
*other_branch
)
7874 if (BPF_SRC(insn
->code
) != BPF_X
)
7877 /* Pointers are always 64-bit. */
7878 if (BPF_CLASS(insn
->code
) == BPF_JMP32
)
7881 switch (BPF_OP(insn
->code
)) {
7883 if ((dst_reg
->type
== PTR_TO_PACKET
&&
7884 src_reg
->type
== PTR_TO_PACKET_END
) ||
7885 (dst_reg
->type
== PTR_TO_PACKET_META
&&
7886 reg_is_init_pkt_pointer(src_reg
, PTR_TO_PACKET
))) {
7887 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
7888 find_good_pkt_pointers(this_branch
, dst_reg
,
7889 dst_reg
->type
, false);
7890 mark_pkt_end(other_branch
, insn
->dst_reg
, true);
7891 } else if ((dst_reg
->type
== PTR_TO_PACKET_END
&&
7892 src_reg
->type
== PTR_TO_PACKET
) ||
7893 (reg_is_init_pkt_pointer(dst_reg
, PTR_TO_PACKET
) &&
7894 src_reg
->type
== PTR_TO_PACKET_META
)) {
7895 /* pkt_end > pkt_data', pkt_data > pkt_meta' */
7896 find_good_pkt_pointers(other_branch
, src_reg
,
7897 src_reg
->type
, true);
7898 mark_pkt_end(this_branch
, insn
->src_reg
, false);
7904 if ((dst_reg
->type
== PTR_TO_PACKET
&&
7905 src_reg
->type
== PTR_TO_PACKET_END
) ||
7906 (dst_reg
->type
== PTR_TO_PACKET_META
&&
7907 reg_is_init_pkt_pointer(src_reg
, PTR_TO_PACKET
))) {
7908 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
7909 find_good_pkt_pointers(other_branch
, dst_reg
,
7910 dst_reg
->type
, true);
7911 mark_pkt_end(this_branch
, insn
->dst_reg
, false);
7912 } else if ((dst_reg
->type
== PTR_TO_PACKET_END
&&
7913 src_reg
->type
== PTR_TO_PACKET
) ||
7914 (reg_is_init_pkt_pointer(dst_reg
, PTR_TO_PACKET
) &&
7915 src_reg
->type
== PTR_TO_PACKET_META
)) {
7916 /* pkt_end < pkt_data', pkt_data > pkt_meta' */
7917 find_good_pkt_pointers(this_branch
, src_reg
,
7918 src_reg
->type
, false);
7919 mark_pkt_end(other_branch
, insn
->src_reg
, true);
7925 if ((dst_reg
->type
== PTR_TO_PACKET
&&
7926 src_reg
->type
== PTR_TO_PACKET_END
) ||
7927 (dst_reg
->type
== PTR_TO_PACKET_META
&&
7928 reg_is_init_pkt_pointer(src_reg
, PTR_TO_PACKET
))) {
7929 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
7930 find_good_pkt_pointers(this_branch
, dst_reg
,
7931 dst_reg
->type
, true);
7932 mark_pkt_end(other_branch
, insn
->dst_reg
, false);
7933 } else if ((dst_reg
->type
== PTR_TO_PACKET_END
&&
7934 src_reg
->type
== PTR_TO_PACKET
) ||
7935 (reg_is_init_pkt_pointer(dst_reg
, PTR_TO_PACKET
) &&
7936 src_reg
->type
== PTR_TO_PACKET_META
)) {
7937 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
7938 find_good_pkt_pointers(other_branch
, src_reg
,
7939 src_reg
->type
, false);
7940 mark_pkt_end(this_branch
, insn
->src_reg
, true);
7946 if ((dst_reg
->type
== PTR_TO_PACKET
&&
7947 src_reg
->type
== PTR_TO_PACKET_END
) ||
7948 (dst_reg
->type
== PTR_TO_PACKET_META
&&
7949 reg_is_init_pkt_pointer(src_reg
, PTR_TO_PACKET
))) {
7950 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
7951 find_good_pkt_pointers(other_branch
, dst_reg
,
7952 dst_reg
->type
, false);
7953 mark_pkt_end(this_branch
, insn
->dst_reg
, true);
7954 } else if ((dst_reg
->type
== PTR_TO_PACKET_END
&&
7955 src_reg
->type
== PTR_TO_PACKET
) ||
7956 (reg_is_init_pkt_pointer(dst_reg
, PTR_TO_PACKET
) &&
7957 src_reg
->type
== PTR_TO_PACKET_META
)) {
7958 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
7959 find_good_pkt_pointers(this_branch
, src_reg
,
7960 src_reg
->type
, true);
7961 mark_pkt_end(other_branch
, insn
->src_reg
, false);
7973 static void find_equal_scalars(struct bpf_verifier_state
*vstate
,
7974 struct bpf_reg_state
*known_reg
)
7976 struct bpf_func_state
*state
;
7977 struct bpf_reg_state
*reg
;
7980 for (i
= 0; i
<= vstate
->curframe
; i
++) {
7981 state
= vstate
->frame
[i
];
7982 for (j
= 0; j
< MAX_BPF_REG
; j
++) {
7983 reg
= &state
->regs
[j
];
7984 if (reg
->type
== SCALAR_VALUE
&& reg
->id
== known_reg
->id
)
7988 bpf_for_each_spilled_reg(j
, state
, reg
) {
7991 if (reg
->type
== SCALAR_VALUE
&& reg
->id
== known_reg
->id
)
7997 static int check_cond_jmp_op(struct bpf_verifier_env
*env
,
7998 struct bpf_insn
*insn
, int *insn_idx
)
8000 struct bpf_verifier_state
*this_branch
= env
->cur_state
;
8001 struct bpf_verifier_state
*other_branch
;
8002 struct bpf_reg_state
*regs
= this_branch
->frame
[this_branch
->curframe
]->regs
;
8003 struct bpf_reg_state
*dst_reg
, *other_branch_regs
, *src_reg
= NULL
;
8004 u8 opcode
= BPF_OP(insn
->code
);
8009 /* Only conditional jumps are expected to reach here. */
8010 if (opcode
== BPF_JA
|| opcode
> BPF_JSLE
) {
8011 verbose(env
, "invalid BPF_JMP/JMP32 opcode %x\n", opcode
);
8015 if (BPF_SRC(insn
->code
) == BPF_X
) {
8016 if (insn
->imm
!= 0) {
8017 verbose(env
, "BPF_JMP/JMP32 uses reserved fields\n");
8021 /* check src1 operand */
8022 err
= check_reg_arg(env
, insn
->src_reg
, SRC_OP
);
8026 if (is_pointer_value(env
, insn
->src_reg
)) {
8027 verbose(env
, "R%d pointer comparison prohibited\n",
8031 src_reg
= ®s
[insn
->src_reg
];
8033 if (insn
->src_reg
!= BPF_REG_0
) {
8034 verbose(env
, "BPF_JMP/JMP32 uses reserved fields\n");
8039 /* check src2 operand */
8040 err
= check_reg_arg(env
, insn
->dst_reg
, SRC_OP
);
8044 dst_reg
= ®s
[insn
->dst_reg
];
8045 is_jmp32
= BPF_CLASS(insn
->code
) == BPF_JMP32
;
8047 if (BPF_SRC(insn
->code
) == BPF_K
) {
8048 pred
= is_branch_taken(dst_reg
, insn
->imm
, opcode
, is_jmp32
);
8049 } else if (src_reg
->type
== SCALAR_VALUE
&&
8050 is_jmp32
&& tnum_is_const(tnum_subreg(src_reg
->var_off
))) {
8051 pred
= is_branch_taken(dst_reg
,
8052 tnum_subreg(src_reg
->var_off
).value
,
8055 } else if (src_reg
->type
== SCALAR_VALUE
&&
8056 !is_jmp32
&& tnum_is_const(src_reg
->var_off
)) {
8057 pred
= is_branch_taken(dst_reg
,
8058 src_reg
->var_off
.value
,
8061 } else if (reg_is_pkt_pointer_any(dst_reg
) &&
8062 reg_is_pkt_pointer_any(src_reg
) &&
8064 pred
= is_pkt_ptr_branch_taken(dst_reg
, src_reg
, opcode
);
8068 /* If we get here with a dst_reg pointer type it is because
8069 * above is_branch_taken() special cased the 0 comparison.
8071 if (!__is_pointer_value(false, dst_reg
))
8072 err
= mark_chain_precision(env
, insn
->dst_reg
);
8073 if (BPF_SRC(insn
->code
) == BPF_X
&& !err
&&
8074 !__is_pointer_value(false, src_reg
))
8075 err
= mark_chain_precision(env
, insn
->src_reg
);
8080 /* only follow the goto, ignore fall-through */
8081 *insn_idx
+= insn
->off
;
8083 } else if (pred
== 0) {
8084 /* only follow fall-through branch, since
8085 * that's where the program will go
8090 other_branch
= push_stack(env
, *insn_idx
+ insn
->off
+ 1, *insn_idx
,
8094 other_branch_regs
= other_branch
->frame
[other_branch
->curframe
]->regs
;
8096 /* detect if we are comparing against a constant value so we can adjust
8097 * our min/max values for our dst register.
8098 * this is only legit if both are scalars (or pointers to the same
8099 * object, I suppose, but we don't support that right now), because
8100 * otherwise the different base pointers mean the offsets aren't
8103 if (BPF_SRC(insn
->code
) == BPF_X
) {
8104 struct bpf_reg_state
*src_reg
= ®s
[insn
->src_reg
];
8106 if (dst_reg
->type
== SCALAR_VALUE
&&
8107 src_reg
->type
== SCALAR_VALUE
) {
8108 if (tnum_is_const(src_reg
->var_off
) ||
8110 tnum_is_const(tnum_subreg(src_reg
->var_off
))))
8111 reg_set_min_max(&other_branch_regs
[insn
->dst_reg
],
8113 src_reg
->var_off
.value
,
8114 tnum_subreg(src_reg
->var_off
).value
,
8116 else if (tnum_is_const(dst_reg
->var_off
) ||
8118 tnum_is_const(tnum_subreg(dst_reg
->var_off
))))
8119 reg_set_min_max_inv(&other_branch_regs
[insn
->src_reg
],
8121 dst_reg
->var_off
.value
,
8122 tnum_subreg(dst_reg
->var_off
).value
,
8124 else if (!is_jmp32
&&
8125 (opcode
== BPF_JEQ
|| opcode
== BPF_JNE
))
8126 /* Comparing for equality, we can combine knowledge */
8127 reg_combine_min_max(&other_branch_regs
[insn
->src_reg
],
8128 &other_branch_regs
[insn
->dst_reg
],
8129 src_reg
, dst_reg
, opcode
);
8131 !WARN_ON_ONCE(src_reg
->id
!= other_branch_regs
[insn
->src_reg
].id
)) {
8132 find_equal_scalars(this_branch
, src_reg
);
8133 find_equal_scalars(other_branch
, &other_branch_regs
[insn
->src_reg
]);
8137 } else if (dst_reg
->type
== SCALAR_VALUE
) {
8138 reg_set_min_max(&other_branch_regs
[insn
->dst_reg
],
8139 dst_reg
, insn
->imm
, (u32
)insn
->imm
,
8143 if (dst_reg
->type
== SCALAR_VALUE
&& dst_reg
->id
&&
8144 !WARN_ON_ONCE(dst_reg
->id
!= other_branch_regs
[insn
->dst_reg
].id
)) {
8145 find_equal_scalars(this_branch
, dst_reg
);
8146 find_equal_scalars(other_branch
, &other_branch_regs
[insn
->dst_reg
]);
8149 /* detect if R == 0 where R is returned from bpf_map_lookup_elem().
8150 * NOTE: these optimizations below are related with pointer comparison
8151 * which will never be JMP32.
8153 if (!is_jmp32
&& BPF_SRC(insn
->code
) == BPF_K
&&
8154 insn
->imm
== 0 && (opcode
== BPF_JEQ
|| opcode
== BPF_JNE
) &&
8155 reg_type_may_be_null(dst_reg
->type
)) {
8156 /* Mark all identical registers in each branch as either
8157 * safe or unknown depending R == 0 or R != 0 conditional.
8159 mark_ptr_or_null_regs(this_branch
, insn
->dst_reg
,
8161 mark_ptr_or_null_regs(other_branch
, insn
->dst_reg
,
8163 } else if (!try_match_pkt_pointers(insn
, dst_reg
, ®s
[insn
->src_reg
],
8164 this_branch
, other_branch
) &&
8165 is_pointer_value(env
, insn
->dst_reg
)) {
8166 verbose(env
, "R%d pointer comparison prohibited\n",
8170 if (env
->log
.level
& BPF_LOG_LEVEL
)
8171 print_verifier_state(env
, this_branch
->frame
[this_branch
->curframe
]);
8175 /* verify BPF_LD_IMM64 instruction */
8176 static int check_ld_imm(struct bpf_verifier_env
*env
, struct bpf_insn
*insn
)
8178 struct bpf_insn_aux_data
*aux
= cur_aux(env
);
8179 struct bpf_reg_state
*regs
= cur_regs(env
);
8180 struct bpf_reg_state
*dst_reg
;
8181 struct bpf_map
*map
;
8184 if (BPF_SIZE(insn
->code
) != BPF_DW
) {
8185 verbose(env
, "invalid BPF_LD_IMM insn\n");
8188 if (insn
->off
!= 0) {
8189 verbose(env
, "BPF_LD_IMM64 uses reserved fields\n");
8193 err
= check_reg_arg(env
, insn
->dst_reg
, DST_OP
);
8197 dst_reg
= ®s
[insn
->dst_reg
];
8198 if (insn
->src_reg
== 0) {
8199 u64 imm
= ((u64
)(insn
+ 1)->imm
<< 32) | (u32
)insn
->imm
;
8201 dst_reg
->type
= SCALAR_VALUE
;
8202 __mark_reg_known(®s
[insn
->dst_reg
], imm
);
8206 if (insn
->src_reg
== BPF_PSEUDO_BTF_ID
) {
8207 mark_reg_known_zero(env
, regs
, insn
->dst_reg
);
8209 dst_reg
->type
= aux
->btf_var
.reg_type
;
8210 switch (dst_reg
->type
) {
8212 dst_reg
->mem_size
= aux
->btf_var
.mem_size
;
8215 case PTR_TO_PERCPU_BTF_ID
:
8216 dst_reg
->btf
= aux
->btf_var
.btf
;
8217 dst_reg
->btf_id
= aux
->btf_var
.btf_id
;
8220 verbose(env
, "bpf verifier is misconfigured\n");
8226 map
= env
->used_maps
[aux
->map_index
];
8227 mark_reg_known_zero(env
, regs
, insn
->dst_reg
);
8228 dst_reg
->map_ptr
= map
;
8230 if (insn
->src_reg
== BPF_PSEUDO_MAP_VALUE
) {
8231 dst_reg
->type
= PTR_TO_MAP_VALUE
;
8232 dst_reg
->off
= aux
->map_off
;
8233 if (map_value_has_spin_lock(map
))
8234 dst_reg
->id
= ++env
->id_gen
;
8235 } else if (insn
->src_reg
== BPF_PSEUDO_MAP_FD
) {
8236 dst_reg
->type
= CONST_PTR_TO_MAP
;
8238 verbose(env
, "bpf verifier is misconfigured\n");
8245 static bool may_access_skb(enum bpf_prog_type type
)
8248 case BPF_PROG_TYPE_SOCKET_FILTER
:
8249 case BPF_PROG_TYPE_SCHED_CLS
:
8250 case BPF_PROG_TYPE_SCHED_ACT
:
8257 /* verify safety of LD_ABS|LD_IND instructions:
8258 * - they can only appear in the programs where ctx == skb
8259 * - since they are wrappers of function calls, they scratch R1-R5 registers,
8260 * preserve R6-R9, and store return value into R0
8263 * ctx == skb == R6 == CTX
8266 * SRC == any register
8267 * IMM == 32-bit immediate
8270 * R0 - 8/16/32-bit skb data converted to cpu endianness
8272 static int check_ld_abs(struct bpf_verifier_env
*env
, struct bpf_insn
*insn
)
8274 struct bpf_reg_state
*regs
= cur_regs(env
);
8275 static const int ctx_reg
= BPF_REG_6
;
8276 u8 mode
= BPF_MODE(insn
->code
);
8279 if (!may_access_skb(resolve_prog_type(env
->prog
))) {
8280 verbose(env
, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
8284 if (!env
->ops
->gen_ld_abs
) {
8285 verbose(env
, "bpf verifier is misconfigured\n");
8289 if (insn
->dst_reg
!= BPF_REG_0
|| insn
->off
!= 0 ||
8290 BPF_SIZE(insn
->code
) == BPF_DW
||
8291 (mode
== BPF_ABS
&& insn
->src_reg
!= BPF_REG_0
)) {
8292 verbose(env
, "BPF_LD_[ABS|IND] uses reserved fields\n");
8296 /* check whether implicit source operand (register R6) is readable */
8297 err
= check_reg_arg(env
, ctx_reg
, SRC_OP
);
8301 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
8302 * gen_ld_abs() may terminate the program at runtime, leading to
8305 err
= check_reference_leak(env
);
8307 verbose(env
, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
8311 if (env
->cur_state
->active_spin_lock
) {
8312 verbose(env
, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
8316 if (regs
[ctx_reg
].type
!= PTR_TO_CTX
) {
8318 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
8322 if (mode
== BPF_IND
) {
8323 /* check explicit source operand */
8324 err
= check_reg_arg(env
, insn
->src_reg
, SRC_OP
);
8329 err
= check_ctx_reg(env
, ®s
[ctx_reg
], ctx_reg
);
8333 /* reset caller saved regs to unreadable */
8334 for (i
= 0; i
< CALLER_SAVED_REGS
; i
++) {
8335 mark_reg_not_init(env
, regs
, caller_saved
[i
]);
8336 check_reg_arg(env
, caller_saved
[i
], DST_OP_NO_MARK
);
8339 /* mark destination R0 register as readable, since it contains
8340 * the value fetched from the packet.
8341 * Already marked as written above.
8343 mark_reg_unknown(env
, regs
, BPF_REG_0
);
8344 /* ld_abs load up to 32-bit skb data. */
8345 regs
[BPF_REG_0
].subreg_def
= env
->insn_idx
+ 1;
8349 static int check_return_code(struct bpf_verifier_env
*env
)
8351 struct tnum enforce_attach_type_range
= tnum_unknown
;
8352 const struct bpf_prog
*prog
= env
->prog
;
8353 struct bpf_reg_state
*reg
;
8354 struct tnum range
= tnum_range(0, 1);
8355 enum bpf_prog_type prog_type
= resolve_prog_type(env
->prog
);
8357 const bool is_subprog
= env
->cur_state
->frame
[0]->subprogno
;
8359 /* LSM and struct_ops func-ptr's return type could be "void" */
8361 (prog_type
== BPF_PROG_TYPE_STRUCT_OPS
||
8362 prog_type
== BPF_PROG_TYPE_LSM
) &&
8363 !prog
->aux
->attach_func_proto
->type
)
8366 /* eBPF calling convetion is such that R0 is used
8367 * to return the value from eBPF program.
8368 * Make sure that it's readable at this time
8369 * of bpf_exit, which means that program wrote
8370 * something into it earlier
8372 err
= check_reg_arg(env
, BPF_REG_0
, SRC_OP
);
8376 if (is_pointer_value(env
, BPF_REG_0
)) {
8377 verbose(env
, "R0 leaks addr as return value\n");
8381 reg
= cur_regs(env
) + BPF_REG_0
;
8383 if (reg
->type
!= SCALAR_VALUE
) {
8384 verbose(env
, "At subprogram exit the register R0 is not a scalar value (%s)\n",
8385 reg_type_str
[reg
->type
]);
8391 switch (prog_type
) {
8392 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR
:
8393 if (env
->prog
->expected_attach_type
== BPF_CGROUP_UDP4_RECVMSG
||
8394 env
->prog
->expected_attach_type
== BPF_CGROUP_UDP6_RECVMSG
||
8395 env
->prog
->expected_attach_type
== BPF_CGROUP_INET4_GETPEERNAME
||
8396 env
->prog
->expected_attach_type
== BPF_CGROUP_INET6_GETPEERNAME
||
8397 env
->prog
->expected_attach_type
== BPF_CGROUP_INET4_GETSOCKNAME
||
8398 env
->prog
->expected_attach_type
== BPF_CGROUP_INET6_GETSOCKNAME
)
8399 range
= tnum_range(1, 1);
8401 case BPF_PROG_TYPE_CGROUP_SKB
:
8402 if (env
->prog
->expected_attach_type
== BPF_CGROUP_INET_EGRESS
) {
8403 range
= tnum_range(0, 3);
8404 enforce_attach_type_range
= tnum_range(2, 3);
8407 case BPF_PROG_TYPE_CGROUP_SOCK
:
8408 case BPF_PROG_TYPE_SOCK_OPS
:
8409 case BPF_PROG_TYPE_CGROUP_DEVICE
:
8410 case BPF_PROG_TYPE_CGROUP_SYSCTL
:
8411 case BPF_PROG_TYPE_CGROUP_SOCKOPT
:
8413 case BPF_PROG_TYPE_RAW_TRACEPOINT
:
8414 if (!env
->prog
->aux
->attach_btf_id
)
8416 range
= tnum_const(0);
8418 case BPF_PROG_TYPE_TRACING
:
8419 switch (env
->prog
->expected_attach_type
) {
8420 case BPF_TRACE_FENTRY
:
8421 case BPF_TRACE_FEXIT
:
8422 range
= tnum_const(0);
8424 case BPF_TRACE_RAW_TP
:
8425 case BPF_MODIFY_RETURN
:
8427 case BPF_TRACE_ITER
:
8433 case BPF_PROG_TYPE_SK_LOOKUP
:
8434 range
= tnum_range(SK_DROP
, SK_PASS
);
8436 case BPF_PROG_TYPE_EXT
:
8437 /* freplace program can return anything as its return value
8438 * depends on the to-be-replaced kernel func or bpf program.
8444 if (reg
->type
!= SCALAR_VALUE
) {
8445 verbose(env
, "At program exit the register R0 is not a known value (%s)\n",
8446 reg_type_str
[reg
->type
]);
8450 if (!tnum_in(range
, reg
->var_off
)) {
8453 verbose(env
, "At program exit the register R0 ");
8454 if (!tnum_is_unknown(reg
->var_off
)) {
8455 tnum_strn(tn_buf
, sizeof(tn_buf
), reg
->var_off
);
8456 verbose(env
, "has value %s", tn_buf
);
8458 verbose(env
, "has unknown scalar value");
8460 tnum_strn(tn_buf
, sizeof(tn_buf
), range
);
8461 verbose(env
, " should have been in %s\n", tn_buf
);
8465 if (!tnum_is_unknown(enforce_attach_type_range
) &&
8466 tnum_in(enforce_attach_type_range
, reg
->var_off
))
8467 env
->prog
->enforce_expected_attach_type
= 1;
8471 /* non-recursive DFS pseudo code
8472 * 1 procedure DFS-iterative(G,v):
8473 * 2 label v as discovered
8474 * 3 let S be a stack
8476 * 5 while S is not empty
8478 * 7 if t is what we're looking for:
8480 * 9 for all edges e in G.adjacentEdges(t) do
8481 * 10 if edge e is already labelled
8482 * 11 continue with the next edge
8483 * 12 w <- G.adjacentVertex(t,e)
8484 * 13 if vertex w is not discovered and not explored
8485 * 14 label e as tree-edge
8486 * 15 label w as discovered
8489 * 18 else if vertex w is discovered
8490 * 19 label e as back-edge
8492 * 21 // vertex w is explored
8493 * 22 label e as forward- or cross-edge
8494 * 23 label t as explored
8499 * 0x11 - discovered and fall-through edge labelled
8500 * 0x12 - discovered and fall-through and branch edges labelled
8511 static u32
state_htab_size(struct bpf_verifier_env
*env
)
8513 return env
->prog
->len
;
8516 static struct bpf_verifier_state_list
**explored_state(
8517 struct bpf_verifier_env
*env
,
8520 struct bpf_verifier_state
*cur
= env
->cur_state
;
8521 struct bpf_func_state
*state
= cur
->frame
[cur
->curframe
];
8523 return &env
->explored_states
[(idx
^ state
->callsite
) % state_htab_size(env
)];
8526 static void init_explored_state(struct bpf_verifier_env
*env
, int idx
)
8528 env
->insn_aux_data
[idx
].prune_point
= true;
8536 /* t, w, e - match pseudo-code above:
8537 * t - index of current instruction
8538 * w - next instruction
8541 static int push_insn(int t
, int w
, int e
, struct bpf_verifier_env
*env
,
8544 int *insn_stack
= env
->cfg
.insn_stack
;
8545 int *insn_state
= env
->cfg
.insn_state
;
8547 if (e
== FALLTHROUGH
&& insn_state
[t
] >= (DISCOVERED
| FALLTHROUGH
))
8548 return DONE_EXPLORING
;
8550 if (e
== BRANCH
&& insn_state
[t
] >= (DISCOVERED
| BRANCH
))
8551 return DONE_EXPLORING
;
8553 if (w
< 0 || w
>= env
->prog
->len
) {
8554 verbose_linfo(env
, t
, "%d: ", t
);
8555 verbose(env
, "jump out of range from insn %d to %d\n", t
, w
);
8560 /* mark branch target for state pruning */
8561 init_explored_state(env
, w
);
8563 if (insn_state
[w
] == 0) {
8565 insn_state
[t
] = DISCOVERED
| e
;
8566 insn_state
[w
] = DISCOVERED
;
8567 if (env
->cfg
.cur_stack
>= env
->prog
->len
)
8569 insn_stack
[env
->cfg
.cur_stack
++] = w
;
8570 return KEEP_EXPLORING
;
8571 } else if ((insn_state
[w
] & 0xF0) == DISCOVERED
) {
8572 if (loop_ok
&& env
->bpf_capable
)
8573 return DONE_EXPLORING
;
8574 verbose_linfo(env
, t
, "%d: ", t
);
8575 verbose_linfo(env
, w
, "%d: ", w
);
8576 verbose(env
, "back-edge from insn %d to %d\n", t
, w
);
8578 } else if (insn_state
[w
] == EXPLORED
) {
8579 /* forward- or cross-edge */
8580 insn_state
[t
] = DISCOVERED
| e
;
8582 verbose(env
, "insn state internal bug\n");
8585 return DONE_EXPLORING
;
8588 /* Visits the instruction at index t and returns one of the following:
8589 * < 0 - an error occurred
8590 * DONE_EXPLORING - the instruction was fully explored
8591 * KEEP_EXPLORING - there is still work to be done before it is fully explored
8593 static int visit_insn(int t
, int insn_cnt
, struct bpf_verifier_env
*env
)
8595 struct bpf_insn
*insns
= env
->prog
->insnsi
;
8598 /* All non-branch instructions have a single fall-through edge. */
8599 if (BPF_CLASS(insns
[t
].code
) != BPF_JMP
&&
8600 BPF_CLASS(insns
[t
].code
) != BPF_JMP32
)
8601 return push_insn(t
, t
+ 1, FALLTHROUGH
, env
, false);
8603 switch (BPF_OP(insns
[t
].code
)) {
8605 return DONE_EXPLORING
;
8608 ret
= push_insn(t
, t
+ 1, FALLTHROUGH
, env
, false);
8612 if (t
+ 1 < insn_cnt
)
8613 init_explored_state(env
, t
+ 1);
8614 if (insns
[t
].src_reg
== BPF_PSEUDO_CALL
) {
8615 init_explored_state(env
, t
);
8616 ret
= push_insn(t
, t
+ insns
[t
].imm
+ 1, BRANCH
,
8622 if (BPF_SRC(insns
[t
].code
) != BPF_K
)
8625 /* unconditional jump with single edge */
8626 ret
= push_insn(t
, t
+ insns
[t
].off
+ 1, FALLTHROUGH
, env
,
8631 /* unconditional jmp is not a good pruning point,
8632 * but it's marked, since backtracking needs
8633 * to record jmp history in is_state_visited().
8635 init_explored_state(env
, t
+ insns
[t
].off
+ 1);
8636 /* tell verifier to check for equivalent states
8637 * after every call and jump
8639 if (t
+ 1 < insn_cnt
)
8640 init_explored_state(env
, t
+ 1);
8645 /* conditional jump with two edges */
8646 init_explored_state(env
, t
);
8647 ret
= push_insn(t
, t
+ 1, FALLTHROUGH
, env
, true);
8651 return push_insn(t
, t
+ insns
[t
].off
+ 1, BRANCH
, env
, true);
8655 /* non-recursive depth-first-search to detect loops in BPF program
8656 * loop == back-edge in directed graph
8658 static int check_cfg(struct bpf_verifier_env
*env
)
8660 int insn_cnt
= env
->prog
->len
;
8661 int *insn_stack
, *insn_state
;
8665 insn_state
= env
->cfg
.insn_state
= kvcalloc(insn_cnt
, sizeof(int), GFP_KERNEL
);
8669 insn_stack
= env
->cfg
.insn_stack
= kvcalloc(insn_cnt
, sizeof(int), GFP_KERNEL
);
8675 insn_state
[0] = DISCOVERED
; /* mark 1st insn as discovered */
8676 insn_stack
[0] = 0; /* 0 is the first instruction */
8677 env
->cfg
.cur_stack
= 1;
8679 while (env
->cfg
.cur_stack
> 0) {
8680 int t
= insn_stack
[env
->cfg
.cur_stack
- 1];
8682 ret
= visit_insn(t
, insn_cnt
, env
);
8684 case DONE_EXPLORING
:
8685 insn_state
[t
] = EXPLORED
;
8686 env
->cfg
.cur_stack
--;
8688 case KEEP_EXPLORING
:
8692 verbose(env
, "visit_insn internal bug\n");
8699 if (env
->cfg
.cur_stack
< 0) {
8700 verbose(env
, "pop stack internal bug\n");
8705 for (i
= 0; i
< insn_cnt
; i
++) {
8706 if (insn_state
[i
] != EXPLORED
) {
8707 verbose(env
, "unreachable insn %d\n", i
);
8712 ret
= 0; /* cfg looks good */
8717 env
->cfg
.insn_state
= env
->cfg
.insn_stack
= NULL
;
8721 static int check_abnormal_return(struct bpf_verifier_env
*env
)
8725 for (i
= 1; i
< env
->subprog_cnt
; i
++) {
8726 if (env
->subprog_info
[i
].has_ld_abs
) {
8727 verbose(env
, "LD_ABS is not allowed in subprogs without BTF\n");
8730 if (env
->subprog_info
[i
].has_tail_call
) {
8731 verbose(env
, "tail_call is not allowed in subprogs without BTF\n");
8738 /* The minimum supported BTF func info size */
8739 #define MIN_BPF_FUNCINFO_SIZE 8
8740 #define MAX_FUNCINFO_REC_SIZE 252
8742 static int check_btf_func(struct bpf_verifier_env
*env
,
8743 const union bpf_attr
*attr
,
8744 union bpf_attr __user
*uattr
)
8746 const struct btf_type
*type
, *func_proto
, *ret_type
;
8747 u32 i
, nfuncs
, urec_size
, min_size
;
8748 u32 krec_size
= sizeof(struct bpf_func_info
);
8749 struct bpf_func_info
*krecord
;
8750 struct bpf_func_info_aux
*info_aux
= NULL
;
8751 struct bpf_prog
*prog
;
8752 const struct btf
*btf
;
8753 void __user
*urecord
;
8754 u32 prev_offset
= 0;
8758 nfuncs
= attr
->func_info_cnt
;
8760 if (check_abnormal_return(env
))
8765 if (nfuncs
!= env
->subprog_cnt
) {
8766 verbose(env
, "number of funcs in func_info doesn't match number of subprogs\n");
8770 urec_size
= attr
->func_info_rec_size
;
8771 if (urec_size
< MIN_BPF_FUNCINFO_SIZE
||
8772 urec_size
> MAX_FUNCINFO_REC_SIZE
||
8773 urec_size
% sizeof(u32
)) {
8774 verbose(env
, "invalid func info rec size %u\n", urec_size
);
8779 btf
= prog
->aux
->btf
;
8781 urecord
= u64_to_user_ptr(attr
->func_info
);
8782 min_size
= min_t(u32
, krec_size
, urec_size
);
8784 krecord
= kvcalloc(nfuncs
, krec_size
, GFP_KERNEL
| __GFP_NOWARN
);
8787 info_aux
= kcalloc(nfuncs
, sizeof(*info_aux
), GFP_KERNEL
| __GFP_NOWARN
);
8791 for (i
= 0; i
< nfuncs
; i
++) {
8792 ret
= bpf_check_uarg_tail_zero(urecord
, krec_size
, urec_size
);
8794 if (ret
== -E2BIG
) {
8795 verbose(env
, "nonzero tailing record in func info");
8796 /* set the size kernel expects so loader can zero
8797 * out the rest of the record.
8799 if (put_user(min_size
, &uattr
->func_info_rec_size
))
8805 if (copy_from_user(&krecord
[i
], urecord
, min_size
)) {
8810 /* check insn_off */
8813 if (krecord
[i
].insn_off
) {
8815 "nonzero insn_off %u for the first func info record",
8816 krecord
[i
].insn_off
);
8819 } else if (krecord
[i
].insn_off
<= prev_offset
) {
8821 "same or smaller insn offset (%u) than previous func info record (%u)",
8822 krecord
[i
].insn_off
, prev_offset
);
8826 if (env
->subprog_info
[i
].start
!= krecord
[i
].insn_off
) {
8827 verbose(env
, "func_info BTF section doesn't match subprog layout in BPF program\n");
8832 type
= btf_type_by_id(btf
, krecord
[i
].type_id
);
8833 if (!type
|| !btf_type_is_func(type
)) {
8834 verbose(env
, "invalid type id %d in func info",
8835 krecord
[i
].type_id
);
8838 info_aux
[i
].linkage
= BTF_INFO_VLEN(type
->info
);
8840 func_proto
= btf_type_by_id(btf
, type
->type
);
8841 if (unlikely(!func_proto
|| !btf_type_is_func_proto(func_proto
)))
8842 /* btf_func_check() already verified it during BTF load */
8844 ret_type
= btf_type_skip_modifiers(btf
, func_proto
->type
, NULL
);
8846 btf_type_is_small_int(ret_type
) || btf_type_is_enum(ret_type
);
8847 if (i
&& !scalar_return
&& env
->subprog_info
[i
].has_ld_abs
) {
8848 verbose(env
, "LD_ABS is only allowed in functions that return 'int'.\n");
8851 if (i
&& !scalar_return
&& env
->subprog_info
[i
].has_tail_call
) {
8852 verbose(env
, "tail_call is only allowed in functions that return 'int'.\n");
8856 prev_offset
= krecord
[i
].insn_off
;
8857 urecord
+= urec_size
;
8860 prog
->aux
->func_info
= krecord
;
8861 prog
->aux
->func_info_cnt
= nfuncs
;
8862 prog
->aux
->func_info_aux
= info_aux
;
8871 static void adjust_btf_func(struct bpf_verifier_env
*env
)
8873 struct bpf_prog_aux
*aux
= env
->prog
->aux
;
8876 if (!aux
->func_info
)
8879 for (i
= 0; i
< env
->subprog_cnt
; i
++)
8880 aux
->func_info
[i
].insn_off
= env
->subprog_info
[i
].start
;
8883 #define MIN_BPF_LINEINFO_SIZE (offsetof(struct bpf_line_info, line_col) + \
8884 sizeof(((struct bpf_line_info *)(0))->line_col))
8885 #define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE
8887 static int check_btf_line(struct bpf_verifier_env
*env
,
8888 const union bpf_attr
*attr
,
8889 union bpf_attr __user
*uattr
)
8891 u32 i
, s
, nr_linfo
, ncopy
, expected_size
, rec_size
, prev_offset
= 0;
8892 struct bpf_subprog_info
*sub
;
8893 struct bpf_line_info
*linfo
;
8894 struct bpf_prog
*prog
;
8895 const struct btf
*btf
;
8896 void __user
*ulinfo
;
8899 nr_linfo
= attr
->line_info_cnt
;
8903 rec_size
= attr
->line_info_rec_size
;
8904 if (rec_size
< MIN_BPF_LINEINFO_SIZE
||
8905 rec_size
> MAX_LINEINFO_REC_SIZE
||
8906 rec_size
& (sizeof(u32
) - 1))
8909 /* Need to zero it in case the userspace may
8910 * pass in a smaller bpf_line_info object.
8912 linfo
= kvcalloc(nr_linfo
, sizeof(struct bpf_line_info
),
8913 GFP_KERNEL
| __GFP_NOWARN
);
8918 btf
= prog
->aux
->btf
;
8921 sub
= env
->subprog_info
;
8922 ulinfo
= u64_to_user_ptr(attr
->line_info
);
8923 expected_size
= sizeof(struct bpf_line_info
);
8924 ncopy
= min_t(u32
, expected_size
, rec_size
);
8925 for (i
= 0; i
< nr_linfo
; i
++) {
8926 err
= bpf_check_uarg_tail_zero(ulinfo
, expected_size
, rec_size
);
8928 if (err
== -E2BIG
) {
8929 verbose(env
, "nonzero tailing record in line_info");
8930 if (put_user(expected_size
,
8931 &uattr
->line_info_rec_size
))
8937 if (copy_from_user(&linfo
[i
], ulinfo
, ncopy
)) {
8943 * Check insn_off to ensure
8944 * 1) strictly increasing AND
8945 * 2) bounded by prog->len
8947 * The linfo[0].insn_off == 0 check logically falls into
8948 * the later "missing bpf_line_info for func..." case
8949 * because the first linfo[0].insn_off must be the
8950 * first sub also and the first sub must have
8951 * subprog_info[0].start == 0.
8953 if ((i
&& linfo
[i
].insn_off
<= prev_offset
) ||
8954 linfo
[i
].insn_off
>= prog
->len
) {
8955 verbose(env
, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
8956 i
, linfo
[i
].insn_off
, prev_offset
,
8962 if (!prog
->insnsi
[linfo
[i
].insn_off
].code
) {
8964 "Invalid insn code at line_info[%u].insn_off\n",
8970 if (!btf_name_by_offset(btf
, linfo
[i
].line_off
) ||
8971 !btf_name_by_offset(btf
, linfo
[i
].file_name_off
)) {
8972 verbose(env
, "Invalid line_info[%u].line_off or .file_name_off\n", i
);
8977 if (s
!= env
->subprog_cnt
) {
8978 if (linfo
[i
].insn_off
== sub
[s
].start
) {
8979 sub
[s
].linfo_idx
= i
;
8981 } else if (sub
[s
].start
< linfo
[i
].insn_off
) {
8982 verbose(env
, "missing bpf_line_info for func#%u\n", s
);
8988 prev_offset
= linfo
[i
].insn_off
;
8992 if (s
!= env
->subprog_cnt
) {
8993 verbose(env
, "missing bpf_line_info for %u funcs starting from func#%u\n",
8994 env
->subprog_cnt
- s
, s
);
8999 prog
->aux
->linfo
= linfo
;
9000 prog
->aux
->nr_linfo
= nr_linfo
;
9009 static int check_btf_info(struct bpf_verifier_env
*env
,
9010 const union bpf_attr
*attr
,
9011 union bpf_attr __user
*uattr
)
9016 if (!attr
->func_info_cnt
&& !attr
->line_info_cnt
) {
9017 if (check_abnormal_return(env
))
9022 btf
= btf_get_by_fd(attr
->prog_btf_fd
);
9024 return PTR_ERR(btf
);
9025 if (btf_is_kernel(btf
)) {
9029 env
->prog
->aux
->btf
= btf
;
9031 err
= check_btf_func(env
, attr
, uattr
);
9035 err
= check_btf_line(env
, attr
, uattr
);
9042 /* check %cur's range satisfies %old's */
9043 static bool range_within(struct bpf_reg_state
*old
,
9044 struct bpf_reg_state
*cur
)
9046 return old
->umin_value
<= cur
->umin_value
&&
9047 old
->umax_value
>= cur
->umax_value
&&
9048 old
->smin_value
<= cur
->smin_value
&&
9049 old
->smax_value
>= cur
->smax_value
&&
9050 old
->u32_min_value
<= cur
->u32_min_value
&&
9051 old
->u32_max_value
>= cur
->u32_max_value
&&
9052 old
->s32_min_value
<= cur
->s32_min_value
&&
9053 old
->s32_max_value
>= cur
->s32_max_value
;
9056 /* Maximum number of register states that can exist at once */
9057 #define ID_MAP_SIZE (MAX_BPF_REG + MAX_BPF_STACK / BPF_REG_SIZE)
9063 /* If in the old state two registers had the same id, then they need to have
9064 * the same id in the new state as well. But that id could be different from
9065 * the old state, so we need to track the mapping from old to new ids.
9066 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
9067 * regs with old id 5 must also have new id 9 for the new state to be safe. But
9068 * regs with a different old id could still have new id 9, we don't care about
9070 * So we look through our idmap to see if this old id has been seen before. If
9071 * so, we require the new id to match; otherwise, we add the id pair to the map.
9073 static bool check_ids(u32 old_id
, u32 cur_id
, struct idpair
*idmap
)
9077 for (i
= 0; i
< ID_MAP_SIZE
; i
++) {
9078 if (!idmap
[i
].old
) {
9079 /* Reached an empty slot; haven't seen this id before */
9080 idmap
[i
].old
= old_id
;
9081 idmap
[i
].cur
= cur_id
;
9084 if (idmap
[i
].old
== old_id
)
9085 return idmap
[i
].cur
== cur_id
;
9087 /* We ran out of idmap slots, which should be impossible */
9092 static void clean_func_state(struct bpf_verifier_env
*env
,
9093 struct bpf_func_state
*st
)
9095 enum bpf_reg_liveness live
;
9098 for (i
= 0; i
< BPF_REG_FP
; i
++) {
9099 live
= st
->regs
[i
].live
;
9100 /* liveness must not touch this register anymore */
9101 st
->regs
[i
].live
|= REG_LIVE_DONE
;
9102 if (!(live
& REG_LIVE_READ
))
9103 /* since the register is unused, clear its state
9104 * to make further comparison simpler
9106 __mark_reg_not_init(env
, &st
->regs
[i
]);
9109 for (i
= 0; i
< st
->allocated_stack
/ BPF_REG_SIZE
; i
++) {
9110 live
= st
->stack
[i
].spilled_ptr
.live
;
9111 /* liveness must not touch this stack slot anymore */
9112 st
->stack
[i
].spilled_ptr
.live
|= REG_LIVE_DONE
;
9113 if (!(live
& REG_LIVE_READ
)) {
9114 __mark_reg_not_init(env
, &st
->stack
[i
].spilled_ptr
);
9115 for (j
= 0; j
< BPF_REG_SIZE
; j
++)
9116 st
->stack
[i
].slot_type
[j
] = STACK_INVALID
;
9121 static void clean_verifier_state(struct bpf_verifier_env
*env
,
9122 struct bpf_verifier_state
*st
)
9126 if (st
->frame
[0]->regs
[0].live
& REG_LIVE_DONE
)
9127 /* all regs in this state in all frames were already marked */
9130 for (i
= 0; i
<= st
->curframe
; i
++)
9131 clean_func_state(env
, st
->frame
[i
]);
9134 /* the parentage chains form a tree.
9135 * the verifier states are added to state lists at given insn and
9136 * pushed into state stack for future exploration.
9137 * when the verifier reaches bpf_exit insn some of the verifer states
9138 * stored in the state lists have their final liveness state already,
9139 * but a lot of states will get revised from liveness point of view when
9140 * the verifier explores other branches.
9143 * 2: if r1 == 100 goto pc+1
9146 * when the verifier reaches exit insn the register r0 in the state list of
9147 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
9148 * of insn 2 and goes exploring further. At the insn 4 it will walk the
9149 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
9151 * Since the verifier pushes the branch states as it sees them while exploring
9152 * the program the condition of walking the branch instruction for the second
9153 * time means that all states below this branch were already explored and
9154 * their final liveness markes are already propagated.
9155 * Hence when the verifier completes the search of state list in is_state_visited()
9156 * we can call this clean_live_states() function to mark all liveness states
9157 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
9159 * This function also clears the registers and stack for states that !READ
9160 * to simplify state merging.
9162 * Important note here that walking the same branch instruction in the callee
9163 * doesn't meant that the states are DONE. The verifier has to compare
9166 static void clean_live_states(struct bpf_verifier_env
*env
, int insn
,
9167 struct bpf_verifier_state
*cur
)
9169 struct bpf_verifier_state_list
*sl
;
9172 sl
= *explored_state(env
, insn
);
9174 if (sl
->state
.branches
)
9176 if (sl
->state
.insn_idx
!= insn
||
9177 sl
->state
.curframe
!= cur
->curframe
)
9179 for (i
= 0; i
<= cur
->curframe
; i
++)
9180 if (sl
->state
.frame
[i
]->callsite
!= cur
->frame
[i
]->callsite
)
9182 clean_verifier_state(env
, &sl
->state
);
9188 /* Returns true if (rold safe implies rcur safe) */
9189 static bool regsafe(struct bpf_reg_state
*rold
, struct bpf_reg_state
*rcur
,
9190 struct idpair
*idmap
)
9194 if (!(rold
->live
& REG_LIVE_READ
))
9195 /* explored state didn't use this */
9198 equal
= memcmp(rold
, rcur
, offsetof(struct bpf_reg_state
, parent
)) == 0;
9200 if (rold
->type
== PTR_TO_STACK
)
9201 /* two stack pointers are equal only if they're pointing to
9202 * the same stack frame, since fp-8 in foo != fp-8 in bar
9204 return equal
&& rold
->frameno
== rcur
->frameno
;
9209 if (rold
->type
== NOT_INIT
)
9210 /* explored state can't have used this */
9212 if (rcur
->type
== NOT_INIT
)
9214 switch (rold
->type
) {
9216 if (rcur
->type
== SCALAR_VALUE
) {
9217 if (!rold
->precise
&& !rcur
->precise
)
9219 /* new val must satisfy old val knowledge */
9220 return range_within(rold
, rcur
) &&
9221 tnum_in(rold
->var_off
, rcur
->var_off
);
9223 /* We're trying to use a pointer in place of a scalar.
9224 * Even if the scalar was unbounded, this could lead to
9225 * pointer leaks because scalars are allowed to leak
9226 * while pointers are not. We could make this safe in
9227 * special cases if root is calling us, but it's
9228 * probably not worth the hassle.
9232 case PTR_TO_MAP_VALUE
:
9233 /* If the new min/max/var_off satisfy the old ones and
9234 * everything else matches, we are OK.
9235 * 'id' is not compared, since it's only used for maps with
9236 * bpf_spin_lock inside map element and in such cases if
9237 * the rest of the prog is valid for one map element then
9238 * it's valid for all map elements regardless of the key
9239 * used in bpf_map_lookup()
9241 return memcmp(rold
, rcur
, offsetof(struct bpf_reg_state
, id
)) == 0 &&
9242 range_within(rold
, rcur
) &&
9243 tnum_in(rold
->var_off
, rcur
->var_off
);
9244 case PTR_TO_MAP_VALUE_OR_NULL
:
9245 /* a PTR_TO_MAP_VALUE could be safe to use as a
9246 * PTR_TO_MAP_VALUE_OR_NULL into the same map.
9247 * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
9248 * checked, doing so could have affected others with the same
9249 * id, and we can't check for that because we lost the id when
9250 * we converted to a PTR_TO_MAP_VALUE.
9252 if (rcur
->type
!= PTR_TO_MAP_VALUE_OR_NULL
)
9254 if (memcmp(rold
, rcur
, offsetof(struct bpf_reg_state
, id
)))
9256 /* Check our ids match any regs they're supposed to */
9257 return check_ids(rold
->id
, rcur
->id
, idmap
);
9258 case PTR_TO_PACKET_META
:
9260 if (rcur
->type
!= rold
->type
)
9262 /* We must have at least as much range as the old ptr
9263 * did, so that any accesses which were safe before are
9264 * still safe. This is true even if old range < old off,
9265 * since someone could have accessed through (ptr - k), or
9266 * even done ptr -= k in a register, to get a safe access.
9268 if (rold
->range
> rcur
->range
)
9270 /* If the offsets don't match, we can't trust our alignment;
9271 * nor can we be sure that we won't fall out of range.
9273 if (rold
->off
!= rcur
->off
)
9275 /* id relations must be preserved */
9276 if (rold
->id
&& !check_ids(rold
->id
, rcur
->id
, idmap
))
9278 /* new val must satisfy old val knowledge */
9279 return range_within(rold
, rcur
) &&
9280 tnum_in(rold
->var_off
, rcur
->var_off
);
9282 case CONST_PTR_TO_MAP
:
9283 case PTR_TO_PACKET_END
:
9284 case PTR_TO_FLOW_KEYS
:
9286 case PTR_TO_SOCKET_OR_NULL
:
9287 case PTR_TO_SOCK_COMMON
:
9288 case PTR_TO_SOCK_COMMON_OR_NULL
:
9289 case PTR_TO_TCP_SOCK
:
9290 case PTR_TO_TCP_SOCK_OR_NULL
:
9291 case PTR_TO_XDP_SOCK
:
9292 /* Only valid matches are exact, which memcmp() above
9293 * would have accepted
9296 /* Don't know what's going on, just say it's not safe */
9300 /* Shouldn't get here; if we do, say it's not safe */
9305 static bool stacksafe(struct bpf_func_state
*old
,
9306 struct bpf_func_state
*cur
,
9307 struct idpair
*idmap
)
9311 /* walk slots of the explored stack and ignore any additional
9312 * slots in the current stack, since explored(safe) state
9315 for (i
= 0; i
< old
->allocated_stack
; i
++) {
9316 spi
= i
/ BPF_REG_SIZE
;
9318 if (!(old
->stack
[spi
].spilled_ptr
.live
& REG_LIVE_READ
)) {
9319 i
+= BPF_REG_SIZE
- 1;
9320 /* explored state didn't use this */
9324 if (old
->stack
[spi
].slot_type
[i
% BPF_REG_SIZE
] == STACK_INVALID
)
9327 /* explored stack has more populated slots than current stack
9328 * and these slots were used
9330 if (i
>= cur
->allocated_stack
)
9333 /* if old state was safe with misc data in the stack
9334 * it will be safe with zero-initialized stack.
9335 * The opposite is not true
9337 if (old
->stack
[spi
].slot_type
[i
% BPF_REG_SIZE
] == STACK_MISC
&&
9338 cur
->stack
[spi
].slot_type
[i
% BPF_REG_SIZE
] == STACK_ZERO
)
9340 if (old
->stack
[spi
].slot_type
[i
% BPF_REG_SIZE
] !=
9341 cur
->stack
[spi
].slot_type
[i
% BPF_REG_SIZE
])
9342 /* Ex: old explored (safe) state has STACK_SPILL in
9343 * this stack slot, but current has STACK_MISC ->
9344 * this verifier states are not equivalent,
9345 * return false to continue verification of this path
9348 if (i
% BPF_REG_SIZE
)
9350 if (old
->stack
[spi
].slot_type
[0] != STACK_SPILL
)
9352 if (!regsafe(&old
->stack
[spi
].spilled_ptr
,
9353 &cur
->stack
[spi
].spilled_ptr
,
9355 /* when explored and current stack slot are both storing
9356 * spilled registers, check that stored pointers types
9357 * are the same as well.
9358 * Ex: explored safe path could have stored
9359 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
9360 * but current path has stored:
9361 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
9362 * such verifier states are not equivalent.
9363 * return false to continue verification of this path
9370 static bool refsafe(struct bpf_func_state
*old
, struct bpf_func_state
*cur
)
9372 if (old
->acquired_refs
!= cur
->acquired_refs
)
9374 return !memcmp(old
->refs
, cur
->refs
,
9375 sizeof(*old
->refs
) * old
->acquired_refs
);
9378 /* compare two verifier states
9380 * all states stored in state_list are known to be valid, since
9381 * verifier reached 'bpf_exit' instruction through them
9383 * this function is called when verifier exploring different branches of
9384 * execution popped from the state stack. If it sees an old state that has
9385 * more strict register state and more strict stack state then this execution
9386 * branch doesn't need to be explored further, since verifier already
9387 * concluded that more strict state leads to valid finish.
9389 * Therefore two states are equivalent if register state is more conservative
9390 * and explored stack state is more conservative than the current one.
9393 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
9394 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
9396 * In other words if current stack state (one being explored) has more
9397 * valid slots than old one that already passed validation, it means
9398 * the verifier can stop exploring and conclude that current state is valid too
9400 * Similarly with registers. If explored state has register type as invalid
9401 * whereas register type in current state is meaningful, it means that
9402 * the current state will reach 'bpf_exit' instruction safely
9404 static bool func_states_equal(struct bpf_func_state
*old
,
9405 struct bpf_func_state
*cur
)
9407 struct idpair
*idmap
;
9411 idmap
= kcalloc(ID_MAP_SIZE
, sizeof(struct idpair
), GFP_KERNEL
);
9412 /* If we failed to allocate the idmap, just say it's not safe */
9416 for (i
= 0; i
< MAX_BPF_REG
; i
++) {
9417 if (!regsafe(&old
->regs
[i
], &cur
->regs
[i
], idmap
))
9421 if (!stacksafe(old
, cur
, idmap
))
9424 if (!refsafe(old
, cur
))
9432 static bool states_equal(struct bpf_verifier_env
*env
,
9433 struct bpf_verifier_state
*old
,
9434 struct bpf_verifier_state
*cur
)
9438 if (old
->curframe
!= cur
->curframe
)
9441 /* Verification state from speculative execution simulation
9442 * must never prune a non-speculative execution one.
9444 if (old
->speculative
&& !cur
->speculative
)
9447 if (old
->active_spin_lock
!= cur
->active_spin_lock
)
9450 /* for states to be equal callsites have to be the same
9451 * and all frame states need to be equivalent
9453 for (i
= 0; i
<= old
->curframe
; i
++) {
9454 if (old
->frame
[i
]->callsite
!= cur
->frame
[i
]->callsite
)
9456 if (!func_states_equal(old
->frame
[i
], cur
->frame
[i
]))
9462 /* Return 0 if no propagation happened. Return negative error code if error
9463 * happened. Otherwise, return the propagated bit.
9465 static int propagate_liveness_reg(struct bpf_verifier_env
*env
,
9466 struct bpf_reg_state
*reg
,
9467 struct bpf_reg_state
*parent_reg
)
9469 u8 parent_flag
= parent_reg
->live
& REG_LIVE_READ
;
9470 u8 flag
= reg
->live
& REG_LIVE_READ
;
9473 /* When comes here, read flags of PARENT_REG or REG could be any of
9474 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
9475 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
9477 if (parent_flag
== REG_LIVE_READ64
||
9478 /* Or if there is no read flag from REG. */
9480 /* Or if the read flag from REG is the same as PARENT_REG. */
9481 parent_flag
== flag
)
9484 err
= mark_reg_read(env
, reg
, parent_reg
, flag
);
9491 /* A write screens off any subsequent reads; but write marks come from the
9492 * straight-line code between a state and its parent. When we arrive at an
9493 * equivalent state (jump target or such) we didn't arrive by the straight-line
9494 * code, so read marks in the state must propagate to the parent regardless
9495 * of the state's write marks. That's what 'parent == state->parent' comparison
9496 * in mark_reg_read() is for.
9498 static int propagate_liveness(struct bpf_verifier_env
*env
,
9499 const struct bpf_verifier_state
*vstate
,
9500 struct bpf_verifier_state
*vparent
)
9502 struct bpf_reg_state
*state_reg
, *parent_reg
;
9503 struct bpf_func_state
*state
, *parent
;
9504 int i
, frame
, err
= 0;
9506 if (vparent
->curframe
!= vstate
->curframe
) {
9507 WARN(1, "propagate_live: parent frame %d current frame %d\n",
9508 vparent
->curframe
, vstate
->curframe
);
9511 /* Propagate read liveness of registers... */
9512 BUILD_BUG_ON(BPF_REG_FP
+ 1 != MAX_BPF_REG
);
9513 for (frame
= 0; frame
<= vstate
->curframe
; frame
++) {
9514 parent
= vparent
->frame
[frame
];
9515 state
= vstate
->frame
[frame
];
9516 parent_reg
= parent
->regs
;
9517 state_reg
= state
->regs
;
9518 /* We don't need to worry about FP liveness, it's read-only */
9519 for (i
= frame
< vstate
->curframe
? BPF_REG_6
: 0; i
< BPF_REG_FP
; i
++) {
9520 err
= propagate_liveness_reg(env
, &state_reg
[i
],
9524 if (err
== REG_LIVE_READ64
)
9525 mark_insn_zext(env
, &parent_reg
[i
]);
9528 /* Propagate stack slots. */
9529 for (i
= 0; i
< state
->allocated_stack
/ BPF_REG_SIZE
&&
9530 i
< parent
->allocated_stack
/ BPF_REG_SIZE
; i
++) {
9531 parent_reg
= &parent
->stack
[i
].spilled_ptr
;
9532 state_reg
= &state
->stack
[i
].spilled_ptr
;
9533 err
= propagate_liveness_reg(env
, state_reg
,
9542 /* find precise scalars in the previous equivalent state and
9543 * propagate them into the current state
9545 static int propagate_precision(struct bpf_verifier_env
*env
,
9546 const struct bpf_verifier_state
*old
)
9548 struct bpf_reg_state
*state_reg
;
9549 struct bpf_func_state
*state
;
9552 state
= old
->frame
[old
->curframe
];
9553 state_reg
= state
->regs
;
9554 for (i
= 0; i
< BPF_REG_FP
; i
++, state_reg
++) {
9555 if (state_reg
->type
!= SCALAR_VALUE
||
9556 !state_reg
->precise
)
9558 if (env
->log
.level
& BPF_LOG_LEVEL2
)
9559 verbose(env
, "propagating r%d\n", i
);
9560 err
= mark_chain_precision(env
, i
);
9565 for (i
= 0; i
< state
->allocated_stack
/ BPF_REG_SIZE
; i
++) {
9566 if (state
->stack
[i
].slot_type
[0] != STACK_SPILL
)
9568 state_reg
= &state
->stack
[i
].spilled_ptr
;
9569 if (state_reg
->type
!= SCALAR_VALUE
||
9570 !state_reg
->precise
)
9572 if (env
->log
.level
& BPF_LOG_LEVEL2
)
9573 verbose(env
, "propagating fp%d\n",
9574 (-i
- 1) * BPF_REG_SIZE
);
9575 err
= mark_chain_precision_stack(env
, i
);
9582 static bool states_maybe_looping(struct bpf_verifier_state
*old
,
9583 struct bpf_verifier_state
*cur
)
9585 struct bpf_func_state
*fold
, *fcur
;
9586 int i
, fr
= cur
->curframe
;
9588 if (old
->curframe
!= fr
)
9591 fold
= old
->frame
[fr
];
9592 fcur
= cur
->frame
[fr
];
9593 for (i
= 0; i
< MAX_BPF_REG
; i
++)
9594 if (memcmp(&fold
->regs
[i
], &fcur
->regs
[i
],
9595 offsetof(struct bpf_reg_state
, parent
)))
9601 static int is_state_visited(struct bpf_verifier_env
*env
, int insn_idx
)
9603 struct bpf_verifier_state_list
*new_sl
;
9604 struct bpf_verifier_state_list
*sl
, **pprev
;
9605 struct bpf_verifier_state
*cur
= env
->cur_state
, *new;
9606 int i
, j
, err
, states_cnt
= 0;
9607 bool add_new_state
= env
->test_state_freq
? true : false;
9609 cur
->last_insn_idx
= env
->prev_insn_idx
;
9610 if (!env
->insn_aux_data
[insn_idx
].prune_point
)
9611 /* this 'insn_idx' instruction wasn't marked, so we will not
9612 * be doing state search here
9616 /* bpf progs typically have pruning point every 4 instructions
9617 * http://vger.kernel.org/bpfconf2019.html#session-1
9618 * Do not add new state for future pruning if the verifier hasn't seen
9619 * at least 2 jumps and at least 8 instructions.
9620 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
9621 * In tests that amounts to up to 50% reduction into total verifier
9622 * memory consumption and 20% verifier time speedup.
9624 if (env
->jmps_processed
- env
->prev_jmps_processed
>= 2 &&
9625 env
->insn_processed
- env
->prev_insn_processed
>= 8)
9626 add_new_state
= true;
9628 pprev
= explored_state(env
, insn_idx
);
9631 clean_live_states(env
, insn_idx
, cur
);
9635 if (sl
->state
.insn_idx
!= insn_idx
)
9637 if (sl
->state
.branches
) {
9638 if (states_maybe_looping(&sl
->state
, cur
) &&
9639 states_equal(env
, &sl
->state
, cur
)) {
9640 verbose_linfo(env
, insn_idx
, "; ");
9641 verbose(env
, "infinite loop detected at insn %d\n", insn_idx
);
9644 /* if the verifier is processing a loop, avoid adding new state
9645 * too often, since different loop iterations have distinct
9646 * states and may not help future pruning.
9647 * This threshold shouldn't be too low to make sure that
9648 * a loop with large bound will be rejected quickly.
9649 * The most abusive loop will be:
9651 * if r1 < 1000000 goto pc-2
9652 * 1M insn_procssed limit / 100 == 10k peak states.
9653 * This threshold shouldn't be too high either, since states
9654 * at the end of the loop are likely to be useful in pruning.
9656 if (env
->jmps_processed
- env
->prev_jmps_processed
< 20 &&
9657 env
->insn_processed
- env
->prev_insn_processed
< 100)
9658 add_new_state
= false;
9661 if (states_equal(env
, &sl
->state
, cur
)) {
9663 /* reached equivalent register/stack state,
9665 * Registers read by the continuation are read by us.
9666 * If we have any write marks in env->cur_state, they
9667 * will prevent corresponding reads in the continuation
9668 * from reaching our parent (an explored_state). Our
9669 * own state will get the read marks recorded, but
9670 * they'll be immediately forgotten as we're pruning
9671 * this state and will pop a new one.
9673 err
= propagate_liveness(env
, &sl
->state
, cur
);
9675 /* if previous state reached the exit with precision and
9676 * current state is equivalent to it (except precsion marks)
9677 * the precision needs to be propagated back in
9678 * the current state.
9680 err
= err
? : push_jmp_history(env
, cur
);
9681 err
= err
? : propagate_precision(env
, &sl
->state
);
9687 /* when new state is not going to be added do not increase miss count.
9688 * Otherwise several loop iterations will remove the state
9689 * recorded earlier. The goal of these heuristics is to have
9690 * states from some iterations of the loop (some in the beginning
9691 * and some at the end) to help pruning.
9695 /* heuristic to determine whether this state is beneficial
9696 * to keep checking from state equivalence point of view.
9697 * Higher numbers increase max_states_per_insn and verification time,
9698 * but do not meaningfully decrease insn_processed.
9700 if (sl
->miss_cnt
> sl
->hit_cnt
* 3 + 3) {
9701 /* the state is unlikely to be useful. Remove it to
9702 * speed up verification
9705 if (sl
->state
.frame
[0]->regs
[0].live
& REG_LIVE_DONE
) {
9706 u32 br
= sl
->state
.branches
;
9709 "BUG live_done but branches_to_explore %d\n",
9711 free_verifier_state(&sl
->state
, false);
9715 /* cannot free this state, since parentage chain may
9716 * walk it later. Add it for free_list instead to
9717 * be freed at the end of verification
9719 sl
->next
= env
->free_list
;
9720 env
->free_list
= sl
;
9730 if (env
->max_states_per_insn
< states_cnt
)
9731 env
->max_states_per_insn
= states_cnt
;
9733 if (!env
->bpf_capable
&& states_cnt
> BPF_COMPLEXITY_LIMIT_STATES
)
9734 return push_jmp_history(env
, cur
);
9737 return push_jmp_history(env
, cur
);
9739 /* There were no equivalent states, remember the current one.
9740 * Technically the current state is not proven to be safe yet,
9741 * but it will either reach outer most bpf_exit (which means it's safe)
9742 * or it will be rejected. When there are no loops the verifier won't be
9743 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
9744 * again on the way to bpf_exit.
9745 * When looping the sl->state.branches will be > 0 and this state
9746 * will not be considered for equivalence until branches == 0.
9748 new_sl
= kzalloc(sizeof(struct bpf_verifier_state_list
), GFP_KERNEL
);
9751 env
->total_states
++;
9753 env
->prev_jmps_processed
= env
->jmps_processed
;
9754 env
->prev_insn_processed
= env
->insn_processed
;
9756 /* add new state to the head of linked list */
9757 new = &new_sl
->state
;
9758 err
= copy_verifier_state(new, cur
);
9760 free_verifier_state(new, false);
9764 new->insn_idx
= insn_idx
;
9765 WARN_ONCE(new->branches
!= 1,
9766 "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches
, insn_idx
);
9769 cur
->first_insn_idx
= insn_idx
;
9770 clear_jmp_history(cur
);
9771 new_sl
->next
= *explored_state(env
, insn_idx
);
9772 *explored_state(env
, insn_idx
) = new_sl
;
9773 /* connect new state to parentage chain. Current frame needs all
9774 * registers connected. Only r6 - r9 of the callers are alive (pushed
9775 * to the stack implicitly by JITs) so in callers' frames connect just
9776 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
9777 * the state of the call instruction (with WRITTEN set), and r0 comes
9778 * from callee with its full parentage chain, anyway.
9780 /* clear write marks in current state: the writes we did are not writes
9781 * our child did, so they don't screen off its reads from us.
9782 * (There are no read marks in current state, because reads always mark
9783 * their parent and current state never has children yet. Only
9784 * explored_states can get read marks.)
9786 for (j
= 0; j
<= cur
->curframe
; j
++) {
9787 for (i
= j
< cur
->curframe
? BPF_REG_6
: 0; i
< BPF_REG_FP
; i
++)
9788 cur
->frame
[j
]->regs
[i
].parent
= &new->frame
[j
]->regs
[i
];
9789 for (i
= 0; i
< BPF_REG_FP
; i
++)
9790 cur
->frame
[j
]->regs
[i
].live
= REG_LIVE_NONE
;
9793 /* all stack frames are accessible from callee, clear them all */
9794 for (j
= 0; j
<= cur
->curframe
; j
++) {
9795 struct bpf_func_state
*frame
= cur
->frame
[j
];
9796 struct bpf_func_state
*newframe
= new->frame
[j
];
9798 for (i
= 0; i
< frame
->allocated_stack
/ BPF_REG_SIZE
; i
++) {
9799 frame
->stack
[i
].spilled_ptr
.live
= REG_LIVE_NONE
;
9800 frame
->stack
[i
].spilled_ptr
.parent
=
9801 &newframe
->stack
[i
].spilled_ptr
;
9807 /* Return true if it's OK to have the same insn return a different type. */
9808 static bool reg_type_mismatch_ok(enum bpf_reg_type type
)
9813 case PTR_TO_SOCKET_OR_NULL
:
9814 case PTR_TO_SOCK_COMMON
:
9815 case PTR_TO_SOCK_COMMON_OR_NULL
:
9816 case PTR_TO_TCP_SOCK
:
9817 case PTR_TO_TCP_SOCK_OR_NULL
:
9818 case PTR_TO_XDP_SOCK
:
9820 case PTR_TO_BTF_ID_OR_NULL
:
9827 /* If an instruction was previously used with particular pointer types, then we
9828 * need to be careful to avoid cases such as the below, where it may be ok
9829 * for one branch accessing the pointer, but not ok for the other branch:
9834 * R1 = some_other_valid_ptr;
9837 * R2 = *(u32 *)(R1 + 0);
9839 static bool reg_type_mismatch(enum bpf_reg_type src
, enum bpf_reg_type prev
)
9841 return src
!= prev
&& (!reg_type_mismatch_ok(src
) ||
9842 !reg_type_mismatch_ok(prev
));
9845 static int do_check(struct bpf_verifier_env
*env
)
9847 bool pop_log
= !(env
->log
.level
& BPF_LOG_LEVEL2
);
9848 struct bpf_verifier_state
*state
= env
->cur_state
;
9849 struct bpf_insn
*insns
= env
->prog
->insnsi
;
9850 struct bpf_reg_state
*regs
;
9851 int insn_cnt
= env
->prog
->len
;
9852 bool do_print_state
= false;
9853 int prev_insn_idx
= -1;
9856 struct bpf_insn
*insn
;
9860 env
->prev_insn_idx
= prev_insn_idx
;
9861 if (env
->insn_idx
>= insn_cnt
) {
9862 verbose(env
, "invalid insn idx %d insn_cnt %d\n",
9863 env
->insn_idx
, insn_cnt
);
9867 insn
= &insns
[env
->insn_idx
];
9868 class = BPF_CLASS(insn
->code
);
9870 if (++env
->insn_processed
> BPF_COMPLEXITY_LIMIT_INSNS
) {
9872 "BPF program is too large. Processed %d insn\n",
9873 env
->insn_processed
);
9877 err
= is_state_visited(env
, env
->insn_idx
);
9881 /* found equivalent state, can prune the search */
9882 if (env
->log
.level
& BPF_LOG_LEVEL
) {
9884 verbose(env
, "\nfrom %d to %d%s: safe\n",
9885 env
->prev_insn_idx
, env
->insn_idx
,
9886 env
->cur_state
->speculative
?
9887 " (speculative execution)" : "");
9889 verbose(env
, "%d: safe\n", env
->insn_idx
);
9891 goto process_bpf_exit
;
9894 if (signal_pending(current
))
9900 if (env
->log
.level
& BPF_LOG_LEVEL2
||
9901 (env
->log
.level
& BPF_LOG_LEVEL
&& do_print_state
)) {
9902 if (env
->log
.level
& BPF_LOG_LEVEL2
)
9903 verbose(env
, "%d:", env
->insn_idx
);
9905 verbose(env
, "\nfrom %d to %d%s:",
9906 env
->prev_insn_idx
, env
->insn_idx
,
9907 env
->cur_state
->speculative
?
9908 " (speculative execution)" : "");
9909 print_verifier_state(env
, state
->frame
[state
->curframe
]);
9910 do_print_state
= false;
9913 if (env
->log
.level
& BPF_LOG_LEVEL
) {
9914 const struct bpf_insn_cbs cbs
= {
9915 .cb_print
= verbose
,
9916 .private_data
= env
,
9919 verbose_linfo(env
, env
->insn_idx
, "; ");
9920 verbose(env
, "%d: ", env
->insn_idx
);
9921 print_bpf_insn(&cbs
, insn
, env
->allow_ptr_leaks
);
9924 if (bpf_prog_is_dev_bound(env
->prog
->aux
)) {
9925 err
= bpf_prog_offload_verify_insn(env
, env
->insn_idx
,
9926 env
->prev_insn_idx
);
9931 regs
= cur_regs(env
);
9932 env
->insn_aux_data
[env
->insn_idx
].seen
= env
->pass_cnt
;
9933 prev_insn_idx
= env
->insn_idx
;
9935 if (class == BPF_ALU
|| class == BPF_ALU64
) {
9936 err
= check_alu_op(env
, insn
);
9940 } else if (class == BPF_LDX
) {
9941 enum bpf_reg_type
*prev_src_type
, src_reg_type
;
9943 /* check for reserved fields is already done */
9945 /* check src operand */
9946 err
= check_reg_arg(env
, insn
->src_reg
, SRC_OP
);
9950 err
= check_reg_arg(env
, insn
->dst_reg
, DST_OP_NO_MARK
);
9954 src_reg_type
= regs
[insn
->src_reg
].type
;
9956 /* check that memory (src_reg + off) is readable,
9957 * the state of dst_reg will be updated by this func
9959 err
= check_mem_access(env
, env
->insn_idx
, insn
->src_reg
,
9960 insn
->off
, BPF_SIZE(insn
->code
),
9961 BPF_READ
, insn
->dst_reg
, false);
9965 prev_src_type
= &env
->insn_aux_data
[env
->insn_idx
].ptr_type
;
9967 if (*prev_src_type
== NOT_INIT
) {
9969 * dst_reg = *(u32 *)(src_reg + off)
9970 * save type to validate intersecting paths
9972 *prev_src_type
= src_reg_type
;
9974 } else if (reg_type_mismatch(src_reg_type
, *prev_src_type
)) {
9975 /* ABuser program is trying to use the same insn
9976 * dst_reg = *(u32*) (src_reg + off)
9977 * with different pointer types:
9978 * src_reg == ctx in one branch and
9979 * src_reg == stack|map in some other branch.
9982 verbose(env
, "same insn cannot be used with different pointers\n");
9986 } else if (class == BPF_STX
) {
9987 enum bpf_reg_type
*prev_dst_type
, dst_reg_type
;
9989 if (BPF_MODE(insn
->code
) == BPF_XADD
) {
9990 err
= check_xadd(env
, env
->insn_idx
, insn
);
9997 /* check src1 operand */
9998 err
= check_reg_arg(env
, insn
->src_reg
, SRC_OP
);
10001 /* check src2 operand */
10002 err
= check_reg_arg(env
, insn
->dst_reg
, SRC_OP
);
10006 dst_reg_type
= regs
[insn
->dst_reg
].type
;
10008 /* check that memory (dst_reg + off) is writeable */
10009 err
= check_mem_access(env
, env
->insn_idx
, insn
->dst_reg
,
10010 insn
->off
, BPF_SIZE(insn
->code
),
10011 BPF_WRITE
, insn
->src_reg
, false);
10015 prev_dst_type
= &env
->insn_aux_data
[env
->insn_idx
].ptr_type
;
10017 if (*prev_dst_type
== NOT_INIT
) {
10018 *prev_dst_type
= dst_reg_type
;
10019 } else if (reg_type_mismatch(dst_reg_type
, *prev_dst_type
)) {
10020 verbose(env
, "same insn cannot be used with different pointers\n");
10024 } else if (class == BPF_ST
) {
10025 if (BPF_MODE(insn
->code
) != BPF_MEM
||
10026 insn
->src_reg
!= BPF_REG_0
) {
10027 verbose(env
, "BPF_ST uses reserved fields\n");
10030 /* check src operand */
10031 err
= check_reg_arg(env
, insn
->dst_reg
, SRC_OP
);
10035 if (is_ctx_reg(env
, insn
->dst_reg
)) {
10036 verbose(env
, "BPF_ST stores into R%d %s is not allowed\n",
10038 reg_type_str
[reg_state(env
, insn
->dst_reg
)->type
]);
10042 /* check that memory (dst_reg + off) is writeable */
10043 err
= check_mem_access(env
, env
->insn_idx
, insn
->dst_reg
,
10044 insn
->off
, BPF_SIZE(insn
->code
),
10045 BPF_WRITE
, -1, false);
10049 } else if (class == BPF_JMP
|| class == BPF_JMP32
) {
10050 u8 opcode
= BPF_OP(insn
->code
);
10052 env
->jmps_processed
++;
10053 if (opcode
== BPF_CALL
) {
10054 if (BPF_SRC(insn
->code
) != BPF_K
||
10056 (insn
->src_reg
!= BPF_REG_0
&&
10057 insn
->src_reg
!= BPF_PSEUDO_CALL
) ||
10058 insn
->dst_reg
!= BPF_REG_0
||
10059 class == BPF_JMP32
) {
10060 verbose(env
, "BPF_CALL uses reserved fields\n");
10064 if (env
->cur_state
->active_spin_lock
&&
10065 (insn
->src_reg
== BPF_PSEUDO_CALL
||
10066 insn
->imm
!= BPF_FUNC_spin_unlock
)) {
10067 verbose(env
, "function calls are not allowed while holding a lock\n");
10070 if (insn
->src_reg
== BPF_PSEUDO_CALL
)
10071 err
= check_func_call(env
, insn
, &env
->insn_idx
);
10073 err
= check_helper_call(env
, insn
->imm
, env
->insn_idx
);
10077 } else if (opcode
== BPF_JA
) {
10078 if (BPF_SRC(insn
->code
) != BPF_K
||
10080 insn
->src_reg
!= BPF_REG_0
||
10081 insn
->dst_reg
!= BPF_REG_0
||
10082 class == BPF_JMP32
) {
10083 verbose(env
, "BPF_JA uses reserved fields\n");
10087 env
->insn_idx
+= insn
->off
+ 1;
10090 } else if (opcode
== BPF_EXIT
) {
10091 if (BPF_SRC(insn
->code
) != BPF_K
||
10093 insn
->src_reg
!= BPF_REG_0
||
10094 insn
->dst_reg
!= BPF_REG_0
||
10095 class == BPF_JMP32
) {
10096 verbose(env
, "BPF_EXIT uses reserved fields\n");
10100 if (env
->cur_state
->active_spin_lock
) {
10101 verbose(env
, "bpf_spin_unlock is missing\n");
10105 if (state
->curframe
) {
10106 /* exit from nested function */
10107 err
= prepare_func_exit(env
, &env
->insn_idx
);
10110 do_print_state
= true;
10114 err
= check_reference_leak(env
);
10118 err
= check_return_code(env
);
10122 update_branch_counts(env
, env
->cur_state
);
10123 err
= pop_stack(env
, &prev_insn_idx
,
10124 &env
->insn_idx
, pop_log
);
10126 if (err
!= -ENOENT
)
10130 do_print_state
= true;
10134 err
= check_cond_jmp_op(env
, insn
, &env
->insn_idx
);
10138 } else if (class == BPF_LD
) {
10139 u8 mode
= BPF_MODE(insn
->code
);
10141 if (mode
== BPF_ABS
|| mode
== BPF_IND
) {
10142 err
= check_ld_abs(env
, insn
);
10146 } else if (mode
== BPF_IMM
) {
10147 err
= check_ld_imm(env
, insn
);
10152 env
->insn_aux_data
[env
->insn_idx
].seen
= env
->pass_cnt
;
10154 verbose(env
, "invalid BPF_LD mode\n");
10158 verbose(env
, "unknown insn class %d\n", class);
10168 /* replace pseudo btf_id with kernel symbol address */
10169 static int check_pseudo_btf_id(struct bpf_verifier_env
*env
,
10170 struct bpf_insn
*insn
,
10171 struct bpf_insn_aux_data
*aux
)
10173 const struct btf_var_secinfo
*vsi
;
10174 const struct btf_type
*datasec
;
10175 const struct btf_type
*t
;
10176 const char *sym_name
;
10177 bool percpu
= false;
10178 u32 type
, id
= insn
->imm
;
10183 if (!btf_vmlinux
) {
10184 verbose(env
, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
10188 if (insn
[1].imm
!= 0) {
10189 verbose(env
, "reserved field (insn[1].imm) is used in pseudo_btf_id ldimm64 insn.\n");
10193 t
= btf_type_by_id(btf_vmlinux
, id
);
10195 verbose(env
, "ldimm64 insn specifies invalid btf_id %d.\n", id
);
10199 if (!btf_type_is_var(t
)) {
10200 verbose(env
, "pseudo btf_id %d in ldimm64 isn't KIND_VAR.\n",
10205 sym_name
= btf_name_by_offset(btf_vmlinux
, t
->name_off
);
10206 addr
= kallsyms_lookup_name(sym_name
);
10208 verbose(env
, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
10213 datasec_id
= btf_find_by_name_kind(btf_vmlinux
, ".data..percpu",
10215 if (datasec_id
> 0) {
10216 datasec
= btf_type_by_id(btf_vmlinux
, datasec_id
);
10217 for_each_vsi(i
, datasec
, vsi
) {
10218 if (vsi
->type
== id
) {
10225 insn
[0].imm
= (u32
)addr
;
10226 insn
[1].imm
= addr
>> 32;
10229 t
= btf_type_skip_modifiers(btf_vmlinux
, type
, NULL
);
10231 aux
->btf_var
.reg_type
= PTR_TO_PERCPU_BTF_ID
;
10232 aux
->btf_var
.btf
= btf_vmlinux
;
10233 aux
->btf_var
.btf_id
= type
;
10234 } else if (!btf_type_is_struct(t
)) {
10235 const struct btf_type
*ret
;
10239 /* resolve the type size of ksym. */
10240 ret
= btf_resolve_size(btf_vmlinux
, t
, &tsize
);
10242 tname
= btf_name_by_offset(btf_vmlinux
, t
->name_off
);
10243 verbose(env
, "ldimm64 unable to resolve the size of type '%s': %ld\n",
10244 tname
, PTR_ERR(ret
));
10247 aux
->btf_var
.reg_type
= PTR_TO_MEM
;
10248 aux
->btf_var
.mem_size
= tsize
;
10250 aux
->btf_var
.reg_type
= PTR_TO_BTF_ID
;
10251 aux
->btf_var
.btf
= btf_vmlinux
;
10252 aux
->btf_var
.btf_id
= type
;
10257 static int check_map_prealloc(struct bpf_map
*map
)
10259 return (map
->map_type
!= BPF_MAP_TYPE_HASH
&&
10260 map
->map_type
!= BPF_MAP_TYPE_PERCPU_HASH
&&
10261 map
->map_type
!= BPF_MAP_TYPE_HASH_OF_MAPS
) ||
10262 !(map
->map_flags
& BPF_F_NO_PREALLOC
);
10265 static bool is_tracing_prog_type(enum bpf_prog_type type
)
10268 case BPF_PROG_TYPE_KPROBE
:
10269 case BPF_PROG_TYPE_TRACEPOINT
:
10270 case BPF_PROG_TYPE_PERF_EVENT
:
10271 case BPF_PROG_TYPE_RAW_TRACEPOINT
:
10278 static bool is_preallocated_map(struct bpf_map
*map
)
10280 if (!check_map_prealloc(map
))
10282 if (map
->inner_map_meta
&& !check_map_prealloc(map
->inner_map_meta
))
10287 static int check_map_prog_compatibility(struct bpf_verifier_env
*env
,
10288 struct bpf_map
*map
,
10289 struct bpf_prog
*prog
)
10292 enum bpf_prog_type prog_type
= resolve_prog_type(prog
);
10294 * Validate that trace type programs use preallocated hash maps.
10296 * For programs attached to PERF events this is mandatory as the
10297 * perf NMI can hit any arbitrary code sequence.
10299 * All other trace types using preallocated hash maps are unsafe as
10300 * well because tracepoint or kprobes can be inside locked regions
10301 * of the memory allocator or at a place where a recursion into the
10302 * memory allocator would see inconsistent state.
10304 * On RT enabled kernels run-time allocation of all trace type
10305 * programs is strictly prohibited due to lock type constraints. On
10306 * !RT kernels it is allowed for backwards compatibility reasons for
10307 * now, but warnings are emitted so developers are made aware of
10308 * the unsafety and can fix their programs before this is enforced.
10310 if (is_tracing_prog_type(prog_type
) && !is_preallocated_map(map
)) {
10311 if (prog_type
== BPF_PROG_TYPE_PERF_EVENT
) {
10312 verbose(env
, "perf_event programs can only use preallocated hash map\n");
10315 if (IS_ENABLED(CONFIG_PREEMPT_RT
)) {
10316 verbose(env
, "trace type programs can only use preallocated hash map\n");
10319 WARN_ONCE(1, "trace type BPF program uses run-time allocation\n");
10320 verbose(env
, "trace type programs with run-time allocated hash maps are unsafe. Switch to preallocated hash maps.\n");
10323 if (map_value_has_spin_lock(map
)) {
10324 if (prog_type
== BPF_PROG_TYPE_SOCKET_FILTER
) {
10325 verbose(env
, "socket filter progs cannot use bpf_spin_lock yet\n");
10329 if (is_tracing_prog_type(prog_type
)) {
10330 verbose(env
, "tracing progs cannot use bpf_spin_lock yet\n");
10334 if (prog
->aux
->sleepable
) {
10335 verbose(env
, "sleepable progs cannot use bpf_spin_lock yet\n");
10340 if ((bpf_prog_is_dev_bound(prog
->aux
) || bpf_map_is_dev_bound(map
)) &&
10341 !bpf_offload_prog_map_match(prog
, map
)) {
10342 verbose(env
, "offload device mismatch between prog and map\n");
10346 if (map
->map_type
== BPF_MAP_TYPE_STRUCT_OPS
) {
10347 verbose(env
, "bpf_struct_ops map cannot be used in prog\n");
10351 if (prog
->aux
->sleepable
)
10352 switch (map
->map_type
) {
10353 case BPF_MAP_TYPE_HASH
:
10354 case BPF_MAP_TYPE_LRU_HASH
:
10355 case BPF_MAP_TYPE_ARRAY
:
10356 if (!is_preallocated_map(map
)) {
10358 "Sleepable programs can only use preallocated hash maps\n");
10364 "Sleepable programs can only use array and hash maps\n");
10371 static bool bpf_map_is_cgroup_storage(struct bpf_map
*map
)
10373 return (map
->map_type
== BPF_MAP_TYPE_CGROUP_STORAGE
||
10374 map
->map_type
== BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE
);
10377 /* find and rewrite pseudo imm in ld_imm64 instructions:
10379 * 1. if it accesses map FD, replace it with actual map pointer.
10380 * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
10382 * NOTE: btf_vmlinux is required for converting pseudo btf_id.
10384 static int resolve_pseudo_ldimm64(struct bpf_verifier_env
*env
)
10386 struct bpf_insn
*insn
= env
->prog
->insnsi
;
10387 int insn_cnt
= env
->prog
->len
;
10390 err
= bpf_prog_calc_tag(env
->prog
);
10394 for (i
= 0; i
< insn_cnt
; i
++, insn
++) {
10395 if (BPF_CLASS(insn
->code
) == BPF_LDX
&&
10396 (BPF_MODE(insn
->code
) != BPF_MEM
|| insn
->imm
!= 0)) {
10397 verbose(env
, "BPF_LDX uses reserved fields\n");
10401 if (BPF_CLASS(insn
->code
) == BPF_STX
&&
10402 ((BPF_MODE(insn
->code
) != BPF_MEM
&&
10403 BPF_MODE(insn
->code
) != BPF_XADD
) || insn
->imm
!= 0)) {
10404 verbose(env
, "BPF_STX uses reserved fields\n");
10408 if (insn
[0].code
== (BPF_LD
| BPF_IMM
| BPF_DW
)) {
10409 struct bpf_insn_aux_data
*aux
;
10410 struct bpf_map
*map
;
10414 if (i
== insn_cnt
- 1 || insn
[1].code
!= 0 ||
10415 insn
[1].dst_reg
!= 0 || insn
[1].src_reg
!= 0 ||
10416 insn
[1].off
!= 0) {
10417 verbose(env
, "invalid bpf_ld_imm64 insn\n");
10421 if (insn
[0].src_reg
== 0)
10422 /* valid generic load 64-bit imm */
10425 if (insn
[0].src_reg
== BPF_PSEUDO_BTF_ID
) {
10426 aux
= &env
->insn_aux_data
[i
];
10427 err
= check_pseudo_btf_id(env
, insn
, aux
);
10433 /* In final convert_pseudo_ld_imm64() step, this is
10434 * converted into regular 64-bit imm load insn.
10436 if ((insn
[0].src_reg
!= BPF_PSEUDO_MAP_FD
&&
10437 insn
[0].src_reg
!= BPF_PSEUDO_MAP_VALUE
) ||
10438 (insn
[0].src_reg
== BPF_PSEUDO_MAP_FD
&&
10439 insn
[1].imm
!= 0)) {
10441 "unrecognized bpf_ld_imm64 insn\n");
10445 f
= fdget(insn
[0].imm
);
10446 map
= __bpf_map_get(f
);
10448 verbose(env
, "fd %d is not pointing to valid bpf_map\n",
10450 return PTR_ERR(map
);
10453 err
= check_map_prog_compatibility(env
, map
, env
->prog
);
10459 aux
= &env
->insn_aux_data
[i
];
10460 if (insn
->src_reg
== BPF_PSEUDO_MAP_FD
) {
10461 addr
= (unsigned long)map
;
10463 u32 off
= insn
[1].imm
;
10465 if (off
>= BPF_MAX_VAR_OFF
) {
10466 verbose(env
, "direct value offset of %u is not allowed\n", off
);
10471 if (!map
->ops
->map_direct_value_addr
) {
10472 verbose(env
, "no direct value access support for this map type\n");
10477 err
= map
->ops
->map_direct_value_addr(map
, &addr
, off
);
10479 verbose(env
, "invalid access to map value pointer, value_size=%u off=%u\n",
10480 map
->value_size
, off
);
10485 aux
->map_off
= off
;
10489 insn
[0].imm
= (u32
)addr
;
10490 insn
[1].imm
= addr
>> 32;
10492 /* check whether we recorded this map already */
10493 for (j
= 0; j
< env
->used_map_cnt
; j
++) {
10494 if (env
->used_maps
[j
] == map
) {
10495 aux
->map_index
= j
;
10501 if (env
->used_map_cnt
>= MAX_USED_MAPS
) {
10506 /* hold the map. If the program is rejected by verifier,
10507 * the map will be released by release_maps() or it
10508 * will be used by the valid program until it's unloaded
10509 * and all maps are released in free_used_maps()
10513 aux
->map_index
= env
->used_map_cnt
;
10514 env
->used_maps
[env
->used_map_cnt
++] = map
;
10516 if (bpf_map_is_cgroup_storage(map
) &&
10517 bpf_cgroup_storage_assign(env
->prog
->aux
, map
)) {
10518 verbose(env
, "only one cgroup storage of each type is allowed\n");
10530 /* Basic sanity check before we invest more work here. */
10531 if (!bpf_opcode_in_insntable(insn
->code
)) {
10532 verbose(env
, "unknown opcode %02x\n", insn
->code
);
10537 /* now all pseudo BPF_LD_IMM64 instructions load valid
10538 * 'struct bpf_map *' into a register instead of user map_fd.
10539 * These pointers will be used later by verifier to validate map access.
10544 /* drop refcnt of maps used by the rejected program */
10545 static void release_maps(struct bpf_verifier_env
*env
)
10547 __bpf_free_used_maps(env
->prog
->aux
, env
->used_maps
,
10548 env
->used_map_cnt
);
10551 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
10552 static void convert_pseudo_ld_imm64(struct bpf_verifier_env
*env
)
10554 struct bpf_insn
*insn
= env
->prog
->insnsi
;
10555 int insn_cnt
= env
->prog
->len
;
10558 for (i
= 0; i
< insn_cnt
; i
++, insn
++)
10559 if (insn
->code
== (BPF_LD
| BPF_IMM
| BPF_DW
))
10563 /* single env->prog->insni[off] instruction was replaced with the range
10564 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying
10565 * [0, off) and [off, end) to new locations, so the patched range stays zero
10567 static int adjust_insn_aux_data(struct bpf_verifier_env
*env
,
10568 struct bpf_prog
*new_prog
, u32 off
, u32 cnt
)
10570 struct bpf_insn_aux_data
*new_data
, *old_data
= env
->insn_aux_data
;
10571 struct bpf_insn
*insn
= new_prog
->insnsi
;
10575 /* aux info at OFF always needs adjustment, no matter fast path
10576 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
10577 * original insn at old prog.
10579 old_data
[off
].zext_dst
= insn_has_def32(env
, insn
+ off
+ cnt
- 1);
10583 prog_len
= new_prog
->len
;
10584 new_data
= vzalloc(array_size(prog_len
,
10585 sizeof(struct bpf_insn_aux_data
)));
10588 memcpy(new_data
, old_data
, sizeof(struct bpf_insn_aux_data
) * off
);
10589 memcpy(new_data
+ off
+ cnt
- 1, old_data
+ off
,
10590 sizeof(struct bpf_insn_aux_data
) * (prog_len
- off
- cnt
+ 1));
10591 for (i
= off
; i
< off
+ cnt
- 1; i
++) {
10592 new_data
[i
].seen
= env
->pass_cnt
;
10593 new_data
[i
].zext_dst
= insn_has_def32(env
, insn
+ i
);
10595 env
->insn_aux_data
= new_data
;
10600 static void adjust_subprog_starts(struct bpf_verifier_env
*env
, u32 off
, u32 len
)
10606 /* NOTE: fake 'exit' subprog should be updated as well. */
10607 for (i
= 0; i
<= env
->subprog_cnt
; i
++) {
10608 if (env
->subprog_info
[i
].start
<= off
)
10610 env
->subprog_info
[i
].start
+= len
- 1;
10614 static void adjust_poke_descs(struct bpf_prog
*prog
, u32 len
)
10616 struct bpf_jit_poke_descriptor
*tab
= prog
->aux
->poke_tab
;
10617 int i
, sz
= prog
->aux
->size_poke_tab
;
10618 struct bpf_jit_poke_descriptor
*desc
;
10620 for (i
= 0; i
< sz
; i
++) {
10622 desc
->insn_idx
+= len
- 1;
10626 static struct bpf_prog
*bpf_patch_insn_data(struct bpf_verifier_env
*env
, u32 off
,
10627 const struct bpf_insn
*patch
, u32 len
)
10629 struct bpf_prog
*new_prog
;
10631 new_prog
= bpf_patch_insn_single(env
->prog
, off
, patch
, len
);
10632 if (IS_ERR(new_prog
)) {
10633 if (PTR_ERR(new_prog
) == -ERANGE
)
10635 "insn %d cannot be patched due to 16-bit range\n",
10636 env
->insn_aux_data
[off
].orig_idx
);
10639 if (adjust_insn_aux_data(env
, new_prog
, off
, len
))
10641 adjust_subprog_starts(env
, off
, len
);
10642 adjust_poke_descs(new_prog
, len
);
10646 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env
*env
,
10651 /* find first prog starting at or after off (first to remove) */
10652 for (i
= 0; i
< env
->subprog_cnt
; i
++)
10653 if (env
->subprog_info
[i
].start
>= off
)
10655 /* find first prog starting at or after off + cnt (first to stay) */
10656 for (j
= i
; j
< env
->subprog_cnt
; j
++)
10657 if (env
->subprog_info
[j
].start
>= off
+ cnt
)
10659 /* if j doesn't start exactly at off + cnt, we are just removing
10660 * the front of previous prog
10662 if (env
->subprog_info
[j
].start
!= off
+ cnt
)
10666 struct bpf_prog_aux
*aux
= env
->prog
->aux
;
10669 /* move fake 'exit' subprog as well */
10670 move
= env
->subprog_cnt
+ 1 - j
;
10672 memmove(env
->subprog_info
+ i
,
10673 env
->subprog_info
+ j
,
10674 sizeof(*env
->subprog_info
) * move
);
10675 env
->subprog_cnt
-= j
- i
;
10677 /* remove func_info */
10678 if (aux
->func_info
) {
10679 move
= aux
->func_info_cnt
- j
;
10681 memmove(aux
->func_info
+ i
,
10682 aux
->func_info
+ j
,
10683 sizeof(*aux
->func_info
) * move
);
10684 aux
->func_info_cnt
-= j
- i
;
10685 /* func_info->insn_off is set after all code rewrites,
10686 * in adjust_btf_func() - no need to adjust
10690 /* convert i from "first prog to remove" to "first to adjust" */
10691 if (env
->subprog_info
[i
].start
== off
)
10695 /* update fake 'exit' subprog as well */
10696 for (; i
<= env
->subprog_cnt
; i
++)
10697 env
->subprog_info
[i
].start
-= cnt
;
10702 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env
*env
, u32 off
,
10705 struct bpf_prog
*prog
= env
->prog
;
10706 u32 i
, l_off
, l_cnt
, nr_linfo
;
10707 struct bpf_line_info
*linfo
;
10709 nr_linfo
= prog
->aux
->nr_linfo
;
10713 linfo
= prog
->aux
->linfo
;
10715 /* find first line info to remove, count lines to be removed */
10716 for (i
= 0; i
< nr_linfo
; i
++)
10717 if (linfo
[i
].insn_off
>= off
)
10722 for (; i
< nr_linfo
; i
++)
10723 if (linfo
[i
].insn_off
< off
+ cnt
)
10728 /* First live insn doesn't match first live linfo, it needs to "inherit"
10729 * last removed linfo. prog is already modified, so prog->len == off
10730 * means no live instructions after (tail of the program was removed).
10732 if (prog
->len
!= off
&& l_cnt
&&
10733 (i
== nr_linfo
|| linfo
[i
].insn_off
!= off
+ cnt
)) {
10735 linfo
[--i
].insn_off
= off
+ cnt
;
10738 /* remove the line info which refer to the removed instructions */
10740 memmove(linfo
+ l_off
, linfo
+ i
,
10741 sizeof(*linfo
) * (nr_linfo
- i
));
10743 prog
->aux
->nr_linfo
-= l_cnt
;
10744 nr_linfo
= prog
->aux
->nr_linfo
;
10747 /* pull all linfo[i].insn_off >= off + cnt in by cnt */
10748 for (i
= l_off
; i
< nr_linfo
; i
++)
10749 linfo
[i
].insn_off
-= cnt
;
10751 /* fix up all subprogs (incl. 'exit') which start >= off */
10752 for (i
= 0; i
<= env
->subprog_cnt
; i
++)
10753 if (env
->subprog_info
[i
].linfo_idx
> l_off
) {
10754 /* program may have started in the removed region but
10755 * may not be fully removed
10757 if (env
->subprog_info
[i
].linfo_idx
>= l_off
+ l_cnt
)
10758 env
->subprog_info
[i
].linfo_idx
-= l_cnt
;
10760 env
->subprog_info
[i
].linfo_idx
= l_off
;
10766 static int verifier_remove_insns(struct bpf_verifier_env
*env
, u32 off
, u32 cnt
)
10768 struct bpf_insn_aux_data
*aux_data
= env
->insn_aux_data
;
10769 unsigned int orig_prog_len
= env
->prog
->len
;
10772 if (bpf_prog_is_dev_bound(env
->prog
->aux
))
10773 bpf_prog_offload_remove_insns(env
, off
, cnt
);
10775 err
= bpf_remove_insns(env
->prog
, off
, cnt
);
10779 err
= adjust_subprog_starts_after_remove(env
, off
, cnt
);
10783 err
= bpf_adj_linfo_after_remove(env
, off
, cnt
);
10787 memmove(aux_data
+ off
, aux_data
+ off
+ cnt
,
10788 sizeof(*aux_data
) * (orig_prog_len
- off
- cnt
));
10793 /* The verifier does more data flow analysis than llvm and will not
10794 * explore branches that are dead at run time. Malicious programs can
10795 * have dead code too. Therefore replace all dead at-run-time code
10798 * Just nops are not optimal, e.g. if they would sit at the end of the
10799 * program and through another bug we would manage to jump there, then
10800 * we'd execute beyond program memory otherwise. Returning exception
10801 * code also wouldn't work since we can have subprogs where the dead
10802 * code could be located.
10804 static void sanitize_dead_code(struct bpf_verifier_env
*env
)
10806 struct bpf_insn_aux_data
*aux_data
= env
->insn_aux_data
;
10807 struct bpf_insn trap
= BPF_JMP_IMM(BPF_JA
, 0, 0, -1);
10808 struct bpf_insn
*insn
= env
->prog
->insnsi
;
10809 const int insn_cnt
= env
->prog
->len
;
10812 for (i
= 0; i
< insn_cnt
; i
++) {
10813 if (aux_data
[i
].seen
)
10815 memcpy(insn
+ i
, &trap
, sizeof(trap
));
10819 static bool insn_is_cond_jump(u8 code
)
10823 if (BPF_CLASS(code
) == BPF_JMP32
)
10826 if (BPF_CLASS(code
) != BPF_JMP
)
10830 return op
!= BPF_JA
&& op
!= BPF_EXIT
&& op
!= BPF_CALL
;
10833 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env
*env
)
10835 struct bpf_insn_aux_data
*aux_data
= env
->insn_aux_data
;
10836 struct bpf_insn ja
= BPF_JMP_IMM(BPF_JA
, 0, 0, 0);
10837 struct bpf_insn
*insn
= env
->prog
->insnsi
;
10838 const int insn_cnt
= env
->prog
->len
;
10841 for (i
= 0; i
< insn_cnt
; i
++, insn
++) {
10842 if (!insn_is_cond_jump(insn
->code
))
10845 if (!aux_data
[i
+ 1].seen
)
10846 ja
.off
= insn
->off
;
10847 else if (!aux_data
[i
+ 1 + insn
->off
].seen
)
10852 if (bpf_prog_is_dev_bound(env
->prog
->aux
))
10853 bpf_prog_offload_replace_insn(env
, i
, &ja
);
10855 memcpy(insn
, &ja
, sizeof(ja
));
10859 static int opt_remove_dead_code(struct bpf_verifier_env
*env
)
10861 struct bpf_insn_aux_data
*aux_data
= env
->insn_aux_data
;
10862 int insn_cnt
= env
->prog
->len
;
10865 for (i
= 0; i
< insn_cnt
; i
++) {
10869 while (i
+ j
< insn_cnt
&& !aux_data
[i
+ j
].seen
)
10874 err
= verifier_remove_insns(env
, i
, j
);
10877 insn_cnt
= env
->prog
->len
;
10883 static int opt_remove_nops(struct bpf_verifier_env
*env
)
10885 const struct bpf_insn ja
= BPF_JMP_IMM(BPF_JA
, 0, 0, 0);
10886 struct bpf_insn
*insn
= env
->prog
->insnsi
;
10887 int insn_cnt
= env
->prog
->len
;
10890 for (i
= 0; i
< insn_cnt
; i
++) {
10891 if (memcmp(&insn
[i
], &ja
, sizeof(ja
)))
10894 err
= verifier_remove_insns(env
, i
, 1);
10904 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env
*env
,
10905 const union bpf_attr
*attr
)
10907 struct bpf_insn
*patch
, zext_patch
[2], rnd_hi32_patch
[4];
10908 struct bpf_insn_aux_data
*aux
= env
->insn_aux_data
;
10909 int i
, patch_len
, delta
= 0, len
= env
->prog
->len
;
10910 struct bpf_insn
*insns
= env
->prog
->insnsi
;
10911 struct bpf_prog
*new_prog
;
10914 rnd_hi32
= attr
->prog_flags
& BPF_F_TEST_RND_HI32
;
10915 zext_patch
[1] = BPF_ZEXT_REG(0);
10916 rnd_hi32_patch
[1] = BPF_ALU64_IMM(BPF_MOV
, BPF_REG_AX
, 0);
10917 rnd_hi32_patch
[2] = BPF_ALU64_IMM(BPF_LSH
, BPF_REG_AX
, 32);
10918 rnd_hi32_patch
[3] = BPF_ALU64_REG(BPF_OR
, 0, BPF_REG_AX
);
10919 for (i
= 0; i
< len
; i
++) {
10920 int adj_idx
= i
+ delta
;
10921 struct bpf_insn insn
;
10923 insn
= insns
[adj_idx
];
10924 if (!aux
[adj_idx
].zext_dst
) {
10932 class = BPF_CLASS(code
);
10933 if (insn_no_def(&insn
))
10936 /* NOTE: arg "reg" (the fourth one) is only used for
10937 * BPF_STX which has been ruled out in above
10938 * check, it is safe to pass NULL here.
10940 if (is_reg64(env
, &insn
, insn
.dst_reg
, NULL
, DST_OP
)) {
10941 if (class == BPF_LD
&&
10942 BPF_MODE(code
) == BPF_IMM
)
10947 /* ctx load could be transformed into wider load. */
10948 if (class == BPF_LDX
&&
10949 aux
[adj_idx
].ptr_type
== PTR_TO_CTX
)
10952 imm_rnd
= get_random_int();
10953 rnd_hi32_patch
[0] = insn
;
10954 rnd_hi32_patch
[1].imm
= imm_rnd
;
10955 rnd_hi32_patch
[3].dst_reg
= insn
.dst_reg
;
10956 patch
= rnd_hi32_patch
;
10958 goto apply_patch_buffer
;
10961 if (!bpf_jit_needs_zext())
10964 zext_patch
[0] = insn
;
10965 zext_patch
[1].dst_reg
= insn
.dst_reg
;
10966 zext_patch
[1].src_reg
= insn
.dst_reg
;
10967 patch
= zext_patch
;
10969 apply_patch_buffer
:
10970 new_prog
= bpf_patch_insn_data(env
, adj_idx
, patch
, patch_len
);
10973 env
->prog
= new_prog
;
10974 insns
= new_prog
->insnsi
;
10975 aux
= env
->insn_aux_data
;
10976 delta
+= patch_len
- 1;
10982 /* convert load instructions that access fields of a context type into a
10983 * sequence of instructions that access fields of the underlying structure:
10984 * struct __sk_buff -> struct sk_buff
10985 * struct bpf_sock_ops -> struct sock
10987 static int convert_ctx_accesses(struct bpf_verifier_env
*env
)
10989 const struct bpf_verifier_ops
*ops
= env
->ops
;
10990 int i
, cnt
, size
, ctx_field_size
, delta
= 0;
10991 const int insn_cnt
= env
->prog
->len
;
10992 struct bpf_insn insn_buf
[16], *insn
;
10993 u32 target_size
, size_default
, off
;
10994 struct bpf_prog
*new_prog
;
10995 enum bpf_access_type type
;
10996 bool is_narrower_load
;
10998 if (ops
->gen_prologue
|| env
->seen_direct_write
) {
10999 if (!ops
->gen_prologue
) {
11000 verbose(env
, "bpf verifier is misconfigured\n");
11003 cnt
= ops
->gen_prologue(insn_buf
, env
->seen_direct_write
,
11005 if (cnt
>= ARRAY_SIZE(insn_buf
)) {
11006 verbose(env
, "bpf verifier is misconfigured\n");
11009 new_prog
= bpf_patch_insn_data(env
, 0, insn_buf
, cnt
);
11013 env
->prog
= new_prog
;
11018 if (bpf_prog_is_dev_bound(env
->prog
->aux
))
11021 insn
= env
->prog
->insnsi
+ delta
;
11023 for (i
= 0; i
< insn_cnt
; i
++, insn
++) {
11024 bpf_convert_ctx_access_t convert_ctx_access
;
11026 if (insn
->code
== (BPF_LDX
| BPF_MEM
| BPF_B
) ||
11027 insn
->code
== (BPF_LDX
| BPF_MEM
| BPF_H
) ||
11028 insn
->code
== (BPF_LDX
| BPF_MEM
| BPF_W
) ||
11029 insn
->code
== (BPF_LDX
| BPF_MEM
| BPF_DW
))
11031 else if (insn
->code
== (BPF_STX
| BPF_MEM
| BPF_B
) ||
11032 insn
->code
== (BPF_STX
| BPF_MEM
| BPF_H
) ||
11033 insn
->code
== (BPF_STX
| BPF_MEM
| BPF_W
) ||
11034 insn
->code
== (BPF_STX
| BPF_MEM
| BPF_DW
))
11039 if (type
== BPF_WRITE
&&
11040 env
->insn_aux_data
[i
+ delta
].sanitize_stack_off
) {
11041 struct bpf_insn patch
[] = {
11042 /* Sanitize suspicious stack slot with zero.
11043 * There are no memory dependencies for this store,
11044 * since it's only using frame pointer and immediate
11047 BPF_ST_MEM(BPF_DW
, BPF_REG_FP
,
11048 env
->insn_aux_data
[i
+ delta
].sanitize_stack_off
,
11050 /* the original STX instruction will immediately
11051 * overwrite the same stack slot with appropriate value
11056 cnt
= ARRAY_SIZE(patch
);
11057 new_prog
= bpf_patch_insn_data(env
, i
+ delta
, patch
, cnt
);
11062 env
->prog
= new_prog
;
11063 insn
= new_prog
->insnsi
+ i
+ delta
;
11067 switch (env
->insn_aux_data
[i
+ delta
].ptr_type
) {
11069 if (!ops
->convert_ctx_access
)
11071 convert_ctx_access
= ops
->convert_ctx_access
;
11073 case PTR_TO_SOCKET
:
11074 case PTR_TO_SOCK_COMMON
:
11075 convert_ctx_access
= bpf_sock_convert_ctx_access
;
11077 case PTR_TO_TCP_SOCK
:
11078 convert_ctx_access
= bpf_tcp_sock_convert_ctx_access
;
11080 case PTR_TO_XDP_SOCK
:
11081 convert_ctx_access
= bpf_xdp_sock_convert_ctx_access
;
11083 case PTR_TO_BTF_ID
:
11084 if (type
== BPF_READ
) {
11085 insn
->code
= BPF_LDX
| BPF_PROBE_MEM
|
11086 BPF_SIZE((insn
)->code
);
11087 env
->prog
->aux
->num_exentries
++;
11088 } else if (resolve_prog_type(env
->prog
) != BPF_PROG_TYPE_STRUCT_OPS
) {
11089 verbose(env
, "Writes through BTF pointers are not allowed\n");
11097 ctx_field_size
= env
->insn_aux_data
[i
+ delta
].ctx_field_size
;
11098 size
= BPF_LDST_BYTES(insn
);
11100 /* If the read access is a narrower load of the field,
11101 * convert to a 4/8-byte load, to minimum program type specific
11102 * convert_ctx_access changes. If conversion is successful,
11103 * we will apply proper mask to the result.
11105 is_narrower_load
= size
< ctx_field_size
;
11106 size_default
= bpf_ctx_off_adjust_machine(ctx_field_size
);
11108 if (is_narrower_load
) {
11111 if (type
== BPF_WRITE
) {
11112 verbose(env
, "bpf verifier narrow ctx access misconfigured\n");
11117 if (ctx_field_size
== 4)
11119 else if (ctx_field_size
== 8)
11120 size_code
= BPF_DW
;
11122 insn
->off
= off
& ~(size_default
- 1);
11123 insn
->code
= BPF_LDX
| BPF_MEM
| size_code
;
11127 cnt
= convert_ctx_access(type
, insn
, insn_buf
, env
->prog
,
11129 if (cnt
== 0 || cnt
>= ARRAY_SIZE(insn_buf
) ||
11130 (ctx_field_size
&& !target_size
)) {
11131 verbose(env
, "bpf verifier is misconfigured\n");
11135 if (is_narrower_load
&& size
< target_size
) {
11136 u8 shift
= bpf_ctx_narrow_access_offset(
11137 off
, size
, size_default
) * 8;
11138 if (ctx_field_size
<= 4) {
11140 insn_buf
[cnt
++] = BPF_ALU32_IMM(BPF_RSH
,
11143 insn_buf
[cnt
++] = BPF_ALU32_IMM(BPF_AND
, insn
->dst_reg
,
11144 (1 << size
* 8) - 1);
11147 insn_buf
[cnt
++] = BPF_ALU64_IMM(BPF_RSH
,
11150 insn_buf
[cnt
++] = BPF_ALU64_IMM(BPF_AND
, insn
->dst_reg
,
11151 (1ULL << size
* 8) - 1);
11155 new_prog
= bpf_patch_insn_data(env
, i
+ delta
, insn_buf
, cnt
);
11161 /* keep walking new program and skip insns we just inserted */
11162 env
->prog
= new_prog
;
11163 insn
= new_prog
->insnsi
+ i
+ delta
;
11169 static int jit_subprogs(struct bpf_verifier_env
*env
)
11171 struct bpf_prog
*prog
= env
->prog
, **func
, *tmp
;
11172 int i
, j
, subprog_start
, subprog_end
= 0, len
, subprog
;
11173 struct bpf_map
*map_ptr
;
11174 struct bpf_insn
*insn
;
11175 void *old_bpf_func
;
11176 int err
, num_exentries
;
11178 if (env
->subprog_cnt
<= 1)
11181 for (i
= 0, insn
= prog
->insnsi
; i
< prog
->len
; i
++, insn
++) {
11182 if (insn
->code
!= (BPF_JMP
| BPF_CALL
) ||
11183 insn
->src_reg
!= BPF_PSEUDO_CALL
)
11185 /* Upon error here we cannot fall back to interpreter but
11186 * need a hard reject of the program. Thus -EFAULT is
11187 * propagated in any case.
11189 subprog
= find_subprog(env
, i
+ insn
->imm
+ 1);
11191 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
11192 i
+ insn
->imm
+ 1);
11195 /* temporarily remember subprog id inside insn instead of
11196 * aux_data, since next loop will split up all insns into funcs
11198 insn
->off
= subprog
;
11199 /* remember original imm in case JIT fails and fallback
11200 * to interpreter will be needed
11202 env
->insn_aux_data
[i
].call_imm
= insn
->imm
;
11203 /* point imm to __bpf_call_base+1 from JITs point of view */
11207 err
= bpf_prog_alloc_jited_linfo(prog
);
11209 goto out_undo_insn
;
11212 func
= kcalloc(env
->subprog_cnt
, sizeof(prog
), GFP_KERNEL
);
11214 goto out_undo_insn
;
11216 for (i
= 0; i
< env
->subprog_cnt
; i
++) {
11217 subprog_start
= subprog_end
;
11218 subprog_end
= env
->subprog_info
[i
+ 1].start
;
11220 len
= subprog_end
- subprog_start
;
11221 /* BPF_PROG_RUN doesn't call subprogs directly,
11222 * hence main prog stats include the runtime of subprogs.
11223 * subprogs don't have IDs and not reachable via prog_get_next_id
11224 * func[i]->aux->stats will never be accessed and stays NULL
11226 func
[i
] = bpf_prog_alloc_no_stats(bpf_prog_size(len
), GFP_USER
);
11229 memcpy(func
[i
]->insnsi
, &prog
->insnsi
[subprog_start
],
11230 len
* sizeof(struct bpf_insn
));
11231 func
[i
]->type
= prog
->type
;
11232 func
[i
]->len
= len
;
11233 if (bpf_prog_calc_tag(func
[i
]))
11235 func
[i
]->is_func
= 1;
11236 func
[i
]->aux
->func_idx
= i
;
11237 /* the btf and func_info will be freed only at prog->aux */
11238 func
[i
]->aux
->btf
= prog
->aux
->btf
;
11239 func
[i
]->aux
->func_info
= prog
->aux
->func_info
;
11241 for (j
= 0; j
< prog
->aux
->size_poke_tab
; j
++) {
11242 u32 insn_idx
= prog
->aux
->poke_tab
[j
].insn_idx
;
11245 if (!(insn_idx
>= subprog_start
&&
11246 insn_idx
<= subprog_end
))
11249 ret
= bpf_jit_add_poke_descriptor(func
[i
],
11250 &prog
->aux
->poke_tab
[j
]);
11252 verbose(env
, "adding tail call poke descriptor failed\n");
11256 func
[i
]->insnsi
[insn_idx
- subprog_start
].imm
= ret
+ 1;
11258 map_ptr
= func
[i
]->aux
->poke_tab
[ret
].tail_call
.map
;
11259 ret
= map_ptr
->ops
->map_poke_track(map_ptr
, func
[i
]->aux
);
11261 verbose(env
, "tracking tail call prog failed\n");
11266 /* Use bpf_prog_F_tag to indicate functions in stack traces.
11267 * Long term would need debug info to populate names
11269 func
[i
]->aux
->name
[0] = 'F';
11270 func
[i
]->aux
->stack_depth
= env
->subprog_info
[i
].stack_depth
;
11271 func
[i
]->jit_requested
= 1;
11272 func
[i
]->aux
->linfo
= prog
->aux
->linfo
;
11273 func
[i
]->aux
->nr_linfo
= prog
->aux
->nr_linfo
;
11274 func
[i
]->aux
->jited_linfo
= prog
->aux
->jited_linfo
;
11275 func
[i
]->aux
->linfo_idx
= env
->subprog_info
[i
].linfo_idx
;
11277 insn
= func
[i
]->insnsi
;
11278 for (j
= 0; j
< func
[i
]->len
; j
++, insn
++) {
11279 if (BPF_CLASS(insn
->code
) == BPF_LDX
&&
11280 BPF_MODE(insn
->code
) == BPF_PROBE_MEM
)
11283 func
[i
]->aux
->num_exentries
= num_exentries
;
11284 func
[i
]->aux
->tail_call_reachable
= env
->subprog_info
[i
].tail_call_reachable
;
11285 func
[i
] = bpf_int_jit_compile(func
[i
]);
11286 if (!func
[i
]->jited
) {
11293 /* Untrack main program's aux structs so that during map_poke_run()
11294 * we will not stumble upon the unfilled poke descriptors; each
11295 * of the main program's poke descs got distributed across subprogs
11296 * and got tracked onto map, so we are sure that none of them will
11297 * be missed after the operation below
11299 for (i
= 0; i
< prog
->aux
->size_poke_tab
; i
++) {
11300 map_ptr
= prog
->aux
->poke_tab
[i
].tail_call
.map
;
11302 map_ptr
->ops
->map_poke_untrack(map_ptr
, prog
->aux
);
11305 /* at this point all bpf functions were successfully JITed
11306 * now populate all bpf_calls with correct addresses and
11307 * run last pass of JIT
11309 for (i
= 0; i
< env
->subprog_cnt
; i
++) {
11310 insn
= func
[i
]->insnsi
;
11311 for (j
= 0; j
< func
[i
]->len
; j
++, insn
++) {
11312 if (insn
->code
!= (BPF_JMP
| BPF_CALL
) ||
11313 insn
->src_reg
!= BPF_PSEUDO_CALL
)
11315 subprog
= insn
->off
;
11316 insn
->imm
= BPF_CAST_CALL(func
[subprog
]->bpf_func
) -
11320 /* we use the aux data to keep a list of the start addresses
11321 * of the JITed images for each function in the program
11323 * for some architectures, such as powerpc64, the imm field
11324 * might not be large enough to hold the offset of the start
11325 * address of the callee's JITed image from __bpf_call_base
11327 * in such cases, we can lookup the start address of a callee
11328 * by using its subprog id, available from the off field of
11329 * the call instruction, as an index for this list
11331 func
[i
]->aux
->func
= func
;
11332 func
[i
]->aux
->func_cnt
= env
->subprog_cnt
;
11334 for (i
= 0; i
< env
->subprog_cnt
; i
++) {
11335 old_bpf_func
= func
[i
]->bpf_func
;
11336 tmp
= bpf_int_jit_compile(func
[i
]);
11337 if (tmp
!= func
[i
] || func
[i
]->bpf_func
!= old_bpf_func
) {
11338 verbose(env
, "JIT doesn't support bpf-to-bpf calls\n");
11345 /* finally lock prog and jit images for all functions and
11346 * populate kallsysm
11348 for (i
= 0; i
< env
->subprog_cnt
; i
++) {
11349 bpf_prog_lock_ro(func
[i
]);
11350 bpf_prog_kallsyms_add(func
[i
]);
11353 /* Last step: make now unused interpreter insns from main
11354 * prog consistent for later dump requests, so they can
11355 * later look the same as if they were interpreted only.
11357 for (i
= 0, insn
= prog
->insnsi
; i
< prog
->len
; i
++, insn
++) {
11358 if (insn
->code
!= (BPF_JMP
| BPF_CALL
) ||
11359 insn
->src_reg
!= BPF_PSEUDO_CALL
)
11361 insn
->off
= env
->insn_aux_data
[i
].call_imm
;
11362 subprog
= find_subprog(env
, i
+ insn
->off
+ 1);
11363 insn
->imm
= subprog
;
11367 prog
->bpf_func
= func
[0]->bpf_func
;
11368 prog
->aux
->func
= func
;
11369 prog
->aux
->func_cnt
= env
->subprog_cnt
;
11370 bpf_prog_free_unused_jited_linfo(prog
);
11373 for (i
= 0; i
< env
->subprog_cnt
; i
++) {
11377 for (j
= 0; j
< func
[i
]->aux
->size_poke_tab
; j
++) {
11378 map_ptr
= func
[i
]->aux
->poke_tab
[j
].tail_call
.map
;
11379 map_ptr
->ops
->map_poke_untrack(map_ptr
, func
[i
]->aux
);
11381 bpf_jit_free(func
[i
]);
11385 /* cleanup main prog to be interpreted */
11386 prog
->jit_requested
= 0;
11387 for (i
= 0, insn
= prog
->insnsi
; i
< prog
->len
; i
++, insn
++) {
11388 if (insn
->code
!= (BPF_JMP
| BPF_CALL
) ||
11389 insn
->src_reg
!= BPF_PSEUDO_CALL
)
11392 insn
->imm
= env
->insn_aux_data
[i
].call_imm
;
11394 bpf_prog_free_jited_linfo(prog
);
11398 static int fixup_call_args(struct bpf_verifier_env
*env
)
11400 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
11401 struct bpf_prog
*prog
= env
->prog
;
11402 struct bpf_insn
*insn
= prog
->insnsi
;
11407 if (env
->prog
->jit_requested
&&
11408 !bpf_prog_is_dev_bound(env
->prog
->aux
)) {
11409 err
= jit_subprogs(env
);
11412 if (err
== -EFAULT
)
11415 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
11416 if (env
->subprog_cnt
> 1 && env
->prog
->aux
->tail_call_reachable
) {
11417 /* When JIT fails the progs with bpf2bpf calls and tail_calls
11418 * have to be rejected, since interpreter doesn't support them yet.
11420 verbose(env
, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
11423 for (i
= 0; i
< prog
->len
; i
++, insn
++) {
11424 if (insn
->code
!= (BPF_JMP
| BPF_CALL
) ||
11425 insn
->src_reg
!= BPF_PSEUDO_CALL
)
11427 depth
= get_callee_stack_depth(env
, insn
, i
);
11430 bpf_patch_call_args(insn
, depth
);
11437 /* fixup insn->imm field of bpf_call instructions
11438 * and inline eligible helpers as explicit sequence of BPF instructions
11440 * this function is called after eBPF program passed verification
11442 static int fixup_bpf_calls(struct bpf_verifier_env
*env
)
11444 struct bpf_prog
*prog
= env
->prog
;
11445 bool expect_blinding
= bpf_jit_blinding_enabled(prog
);
11446 struct bpf_insn
*insn
= prog
->insnsi
;
11447 const struct bpf_func_proto
*fn
;
11448 const int insn_cnt
= prog
->len
;
11449 const struct bpf_map_ops
*ops
;
11450 struct bpf_insn_aux_data
*aux
;
11451 struct bpf_insn insn_buf
[16];
11452 struct bpf_prog
*new_prog
;
11453 struct bpf_map
*map_ptr
;
11454 int i
, ret
, cnt
, delta
= 0;
11456 for (i
= 0; i
< insn_cnt
; i
++, insn
++) {
11457 if (insn
->code
== (BPF_ALU64
| BPF_MOD
| BPF_X
) ||
11458 insn
->code
== (BPF_ALU64
| BPF_DIV
| BPF_X
) ||
11459 insn
->code
== (BPF_ALU
| BPF_MOD
| BPF_X
) ||
11460 insn
->code
== (BPF_ALU
| BPF_DIV
| BPF_X
)) {
11461 bool is64
= BPF_CLASS(insn
->code
) == BPF_ALU64
;
11462 bool isdiv
= BPF_OP(insn
->code
) == BPF_DIV
;
11463 struct bpf_insn
*patchlet
;
11464 struct bpf_insn chk_and_div
[] = {
11465 /* [R,W]x div 0 -> 0 */
11466 BPF_RAW_INSN((is64
? BPF_JMP
: BPF_JMP32
) |
11467 BPF_JNE
| BPF_K
, insn
->src_reg
,
11469 BPF_ALU32_REG(BPF_XOR
, insn
->dst_reg
, insn
->dst_reg
),
11470 BPF_JMP_IMM(BPF_JA
, 0, 0, 1),
11473 struct bpf_insn chk_and_mod
[] = {
11474 /* [R,W]x mod 0 -> [R,W]x */
11475 BPF_RAW_INSN((is64
? BPF_JMP
: BPF_JMP32
) |
11476 BPF_JEQ
| BPF_K
, insn
->src_reg
,
11477 0, 1 + (is64
? 0 : 1), 0),
11479 BPF_JMP_IMM(BPF_JA
, 0, 0, 1),
11480 BPF_MOV32_REG(insn
->dst_reg
, insn
->dst_reg
),
11483 patchlet
= isdiv
? chk_and_div
: chk_and_mod
;
11484 cnt
= isdiv
? ARRAY_SIZE(chk_and_div
) :
11485 ARRAY_SIZE(chk_and_mod
) - (is64
? 2 : 0);
11487 new_prog
= bpf_patch_insn_data(env
, i
+ delta
, patchlet
, cnt
);
11492 env
->prog
= prog
= new_prog
;
11493 insn
= new_prog
->insnsi
+ i
+ delta
;
11497 if (BPF_CLASS(insn
->code
) == BPF_LD
&&
11498 (BPF_MODE(insn
->code
) == BPF_ABS
||
11499 BPF_MODE(insn
->code
) == BPF_IND
)) {
11500 cnt
= env
->ops
->gen_ld_abs(insn
, insn_buf
);
11501 if (cnt
== 0 || cnt
>= ARRAY_SIZE(insn_buf
)) {
11502 verbose(env
, "bpf verifier is misconfigured\n");
11506 new_prog
= bpf_patch_insn_data(env
, i
+ delta
, insn_buf
, cnt
);
11511 env
->prog
= prog
= new_prog
;
11512 insn
= new_prog
->insnsi
+ i
+ delta
;
11516 if (insn
->code
== (BPF_ALU64
| BPF_ADD
| BPF_X
) ||
11517 insn
->code
== (BPF_ALU64
| BPF_SUB
| BPF_X
)) {
11518 const u8 code_add
= BPF_ALU64
| BPF_ADD
| BPF_X
;
11519 const u8 code_sub
= BPF_ALU64
| BPF_SUB
| BPF_X
;
11520 struct bpf_insn insn_buf
[16];
11521 struct bpf_insn
*patch
= &insn_buf
[0];
11522 bool issrc
, isneg
, isimm
;
11525 aux
= &env
->insn_aux_data
[i
+ delta
];
11526 if (!aux
->alu_state
||
11527 aux
->alu_state
== BPF_ALU_NON_POINTER
)
11530 isneg
= aux
->alu_state
& BPF_ALU_NEG_VALUE
;
11531 issrc
= (aux
->alu_state
& BPF_ALU_SANITIZE
) ==
11532 BPF_ALU_SANITIZE_SRC
;
11533 isimm
= aux
->alu_state
& BPF_ALU_IMMEDIATE
;
11535 off_reg
= issrc
? insn
->src_reg
: insn
->dst_reg
;
11537 *patch
++ = BPF_MOV32_IMM(BPF_REG_AX
, aux
->alu_limit
);
11540 *patch
++ = BPF_ALU64_IMM(BPF_MUL
, off_reg
, -1);
11541 *patch
++ = BPF_MOV32_IMM(BPF_REG_AX
, aux
->alu_limit
);
11542 *patch
++ = BPF_ALU64_REG(BPF_SUB
, BPF_REG_AX
, off_reg
);
11543 *patch
++ = BPF_ALU64_REG(BPF_OR
, BPF_REG_AX
, off_reg
);
11544 *patch
++ = BPF_ALU64_IMM(BPF_NEG
, BPF_REG_AX
, 0);
11545 *patch
++ = BPF_ALU64_IMM(BPF_ARSH
, BPF_REG_AX
, 63);
11546 *patch
++ = BPF_ALU64_REG(BPF_AND
, BPF_REG_AX
, off_reg
);
11549 *patch
++ = BPF_MOV64_REG(insn
->dst_reg
, insn
->src_reg
);
11550 insn
->src_reg
= BPF_REG_AX
;
11552 insn
->code
= insn
->code
== code_add
?
11553 code_sub
: code_add
;
11555 if (issrc
&& isneg
&& !isimm
)
11556 *patch
++ = BPF_ALU64_IMM(BPF_MUL
, off_reg
, -1);
11557 cnt
= patch
- insn_buf
;
11559 new_prog
= bpf_patch_insn_data(env
, i
+ delta
, insn_buf
, cnt
);
11564 env
->prog
= prog
= new_prog
;
11565 insn
= new_prog
->insnsi
+ i
+ delta
;
11569 if (insn
->code
!= (BPF_JMP
| BPF_CALL
))
11571 if (insn
->src_reg
== BPF_PSEUDO_CALL
)
11574 if (insn
->imm
== BPF_FUNC_get_route_realm
)
11575 prog
->dst_needed
= 1;
11576 if (insn
->imm
== BPF_FUNC_get_prandom_u32
)
11577 bpf_user_rnd_init_once();
11578 if (insn
->imm
== BPF_FUNC_override_return
)
11579 prog
->kprobe_override
= 1;
11580 if (insn
->imm
== BPF_FUNC_tail_call
) {
11581 /* If we tail call into other programs, we
11582 * cannot make any assumptions since they can
11583 * be replaced dynamically during runtime in
11584 * the program array.
11586 prog
->cb_access
= 1;
11587 if (!allow_tail_call_in_subprogs(env
))
11588 prog
->aux
->stack_depth
= MAX_BPF_STACK
;
11589 prog
->aux
->max_pkt_offset
= MAX_PACKET_OFF
;
11591 /* mark bpf_tail_call as different opcode to avoid
11592 * conditional branch in the interpeter for every normal
11593 * call and to prevent accidental JITing by JIT compiler
11594 * that doesn't support bpf_tail_call yet
11597 insn
->code
= BPF_JMP
| BPF_TAIL_CALL
;
11599 aux
= &env
->insn_aux_data
[i
+ delta
];
11600 if (env
->bpf_capable
&& !expect_blinding
&&
11601 prog
->jit_requested
&&
11602 !bpf_map_key_poisoned(aux
) &&
11603 !bpf_map_ptr_poisoned(aux
) &&
11604 !bpf_map_ptr_unpriv(aux
)) {
11605 struct bpf_jit_poke_descriptor desc
= {
11606 .reason
= BPF_POKE_REASON_TAIL_CALL
,
11607 .tail_call
.map
= BPF_MAP_PTR(aux
->map_ptr_state
),
11608 .tail_call
.key
= bpf_map_key_immediate(aux
),
11609 .insn_idx
= i
+ delta
,
11612 ret
= bpf_jit_add_poke_descriptor(prog
, &desc
);
11614 verbose(env
, "adding tail call poke descriptor failed\n");
11618 insn
->imm
= ret
+ 1;
11622 if (!bpf_map_ptr_unpriv(aux
))
11625 /* instead of changing every JIT dealing with tail_call
11626 * emit two extra insns:
11627 * if (index >= max_entries) goto out;
11628 * index &= array->index_mask;
11629 * to avoid out-of-bounds cpu speculation
11631 if (bpf_map_ptr_poisoned(aux
)) {
11632 verbose(env
, "tail_call abusing map_ptr\n");
11636 map_ptr
= BPF_MAP_PTR(aux
->map_ptr_state
);
11637 insn_buf
[0] = BPF_JMP_IMM(BPF_JGE
, BPF_REG_3
,
11638 map_ptr
->max_entries
, 2);
11639 insn_buf
[1] = BPF_ALU32_IMM(BPF_AND
, BPF_REG_3
,
11640 container_of(map_ptr
,
11643 insn_buf
[2] = *insn
;
11645 new_prog
= bpf_patch_insn_data(env
, i
+ delta
, insn_buf
, cnt
);
11650 env
->prog
= prog
= new_prog
;
11651 insn
= new_prog
->insnsi
+ i
+ delta
;
11655 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
11656 * and other inlining handlers are currently limited to 64 bit
11659 if (prog
->jit_requested
&& BITS_PER_LONG
== 64 &&
11660 (insn
->imm
== BPF_FUNC_map_lookup_elem
||
11661 insn
->imm
== BPF_FUNC_map_update_elem
||
11662 insn
->imm
== BPF_FUNC_map_delete_elem
||
11663 insn
->imm
== BPF_FUNC_map_push_elem
||
11664 insn
->imm
== BPF_FUNC_map_pop_elem
||
11665 insn
->imm
== BPF_FUNC_map_peek_elem
)) {
11666 aux
= &env
->insn_aux_data
[i
+ delta
];
11667 if (bpf_map_ptr_poisoned(aux
))
11668 goto patch_call_imm
;
11670 map_ptr
= BPF_MAP_PTR(aux
->map_ptr_state
);
11671 ops
= map_ptr
->ops
;
11672 if (insn
->imm
== BPF_FUNC_map_lookup_elem
&&
11673 ops
->map_gen_lookup
) {
11674 cnt
= ops
->map_gen_lookup(map_ptr
, insn_buf
);
11675 if (cnt
== -EOPNOTSUPP
)
11676 goto patch_map_ops_generic
;
11677 if (cnt
<= 0 || cnt
>= ARRAY_SIZE(insn_buf
)) {
11678 verbose(env
, "bpf verifier is misconfigured\n");
11682 new_prog
= bpf_patch_insn_data(env
, i
+ delta
,
11688 env
->prog
= prog
= new_prog
;
11689 insn
= new_prog
->insnsi
+ i
+ delta
;
11693 BUILD_BUG_ON(!__same_type(ops
->map_lookup_elem
,
11694 (void *(*)(struct bpf_map
*map
, void *key
))NULL
));
11695 BUILD_BUG_ON(!__same_type(ops
->map_delete_elem
,
11696 (int (*)(struct bpf_map
*map
, void *key
))NULL
));
11697 BUILD_BUG_ON(!__same_type(ops
->map_update_elem
,
11698 (int (*)(struct bpf_map
*map
, void *key
, void *value
,
11700 BUILD_BUG_ON(!__same_type(ops
->map_push_elem
,
11701 (int (*)(struct bpf_map
*map
, void *value
,
11703 BUILD_BUG_ON(!__same_type(ops
->map_pop_elem
,
11704 (int (*)(struct bpf_map
*map
, void *value
))NULL
));
11705 BUILD_BUG_ON(!__same_type(ops
->map_peek_elem
,
11706 (int (*)(struct bpf_map
*map
, void *value
))NULL
));
11707 patch_map_ops_generic
:
11708 switch (insn
->imm
) {
11709 case BPF_FUNC_map_lookup_elem
:
11710 insn
->imm
= BPF_CAST_CALL(ops
->map_lookup_elem
) -
11713 case BPF_FUNC_map_update_elem
:
11714 insn
->imm
= BPF_CAST_CALL(ops
->map_update_elem
) -
11717 case BPF_FUNC_map_delete_elem
:
11718 insn
->imm
= BPF_CAST_CALL(ops
->map_delete_elem
) -
11721 case BPF_FUNC_map_push_elem
:
11722 insn
->imm
= BPF_CAST_CALL(ops
->map_push_elem
) -
11725 case BPF_FUNC_map_pop_elem
:
11726 insn
->imm
= BPF_CAST_CALL(ops
->map_pop_elem
) -
11729 case BPF_FUNC_map_peek_elem
:
11730 insn
->imm
= BPF_CAST_CALL(ops
->map_peek_elem
) -
11735 goto patch_call_imm
;
11738 if (prog
->jit_requested
&& BITS_PER_LONG
== 64 &&
11739 insn
->imm
== BPF_FUNC_jiffies64
) {
11740 struct bpf_insn ld_jiffies_addr
[2] = {
11741 BPF_LD_IMM64(BPF_REG_0
,
11742 (unsigned long)&jiffies
),
11745 insn_buf
[0] = ld_jiffies_addr
[0];
11746 insn_buf
[1] = ld_jiffies_addr
[1];
11747 insn_buf
[2] = BPF_LDX_MEM(BPF_DW
, BPF_REG_0
,
11751 new_prog
= bpf_patch_insn_data(env
, i
+ delta
, insn_buf
,
11757 env
->prog
= prog
= new_prog
;
11758 insn
= new_prog
->insnsi
+ i
+ delta
;
11763 fn
= env
->ops
->get_func_proto(insn
->imm
, env
->prog
);
11764 /* all functions that have prototype and verifier allowed
11765 * programs to call them, must be real in-kernel functions
11769 "kernel subsystem misconfigured func %s#%d\n",
11770 func_id_name(insn
->imm
), insn
->imm
);
11773 insn
->imm
= fn
->func
- __bpf_call_base
;
11776 /* Since poke tab is now finalized, publish aux to tracker. */
11777 for (i
= 0; i
< prog
->aux
->size_poke_tab
; i
++) {
11778 map_ptr
= prog
->aux
->poke_tab
[i
].tail_call
.map
;
11779 if (!map_ptr
->ops
->map_poke_track
||
11780 !map_ptr
->ops
->map_poke_untrack
||
11781 !map_ptr
->ops
->map_poke_run
) {
11782 verbose(env
, "bpf verifier is misconfigured\n");
11786 ret
= map_ptr
->ops
->map_poke_track(map_ptr
, prog
->aux
);
11788 verbose(env
, "tracking tail call prog failed\n");
11796 static void free_states(struct bpf_verifier_env
*env
)
11798 struct bpf_verifier_state_list
*sl
, *sln
;
11801 sl
= env
->free_list
;
11804 free_verifier_state(&sl
->state
, false);
11808 env
->free_list
= NULL
;
11810 if (!env
->explored_states
)
11813 for (i
= 0; i
< state_htab_size(env
); i
++) {
11814 sl
= env
->explored_states
[i
];
11818 free_verifier_state(&sl
->state
, false);
11822 env
->explored_states
[i
] = NULL
;
11826 /* The verifier is using insn_aux_data[] to store temporary data during
11827 * verification and to store information for passes that run after the
11828 * verification like dead code sanitization. do_check_common() for subprogram N
11829 * may analyze many other subprograms. sanitize_insn_aux_data() clears all
11830 * temporary data after do_check_common() finds that subprogram N cannot be
11831 * verified independently. pass_cnt counts the number of times
11832 * do_check_common() was run and insn->aux->seen tells the pass number
11833 * insn_aux_data was touched. These variables are compared to clear temporary
11834 * data from failed pass. For testing and experiments do_check_common() can be
11835 * run multiple times even when prior attempt to verify is unsuccessful.
11837 static void sanitize_insn_aux_data(struct bpf_verifier_env
*env
)
11839 struct bpf_insn
*insn
= env
->prog
->insnsi
;
11840 struct bpf_insn_aux_data
*aux
;
11843 for (i
= 0; i
< env
->prog
->len
; i
++) {
11844 class = BPF_CLASS(insn
[i
].code
);
11845 if (class != BPF_LDX
&& class != BPF_STX
)
11847 aux
= &env
->insn_aux_data
[i
];
11848 if (aux
->seen
!= env
->pass_cnt
)
11850 memset(aux
, 0, offsetof(typeof(*aux
), orig_idx
));
11854 static int do_check_common(struct bpf_verifier_env
*env
, int subprog
)
11856 bool pop_log
= !(env
->log
.level
& BPF_LOG_LEVEL2
);
11857 struct bpf_verifier_state
*state
;
11858 struct bpf_reg_state
*regs
;
11861 env
->prev_linfo
= NULL
;
11864 state
= kzalloc(sizeof(struct bpf_verifier_state
), GFP_KERNEL
);
11867 state
->curframe
= 0;
11868 state
->speculative
= false;
11869 state
->branches
= 1;
11870 state
->frame
[0] = kzalloc(sizeof(struct bpf_func_state
), GFP_KERNEL
);
11871 if (!state
->frame
[0]) {
11875 env
->cur_state
= state
;
11876 init_func_state(env
, state
->frame
[0],
11877 BPF_MAIN_FUNC
/* callsite */,
11881 regs
= state
->frame
[state
->curframe
]->regs
;
11882 if (subprog
|| env
->prog
->type
== BPF_PROG_TYPE_EXT
) {
11883 ret
= btf_prepare_func_args(env
, subprog
, regs
);
11886 for (i
= BPF_REG_1
; i
<= BPF_REG_5
; i
++) {
11887 if (regs
[i
].type
== PTR_TO_CTX
)
11888 mark_reg_known_zero(env
, regs
, i
);
11889 else if (regs
[i
].type
== SCALAR_VALUE
)
11890 mark_reg_unknown(env
, regs
, i
);
11893 /* 1st arg to a function */
11894 regs
[BPF_REG_1
].type
= PTR_TO_CTX
;
11895 mark_reg_known_zero(env
, regs
, BPF_REG_1
);
11896 ret
= btf_check_func_arg_match(env
, subprog
, regs
);
11897 if (ret
== -EFAULT
)
11898 /* unlikely verifier bug. abort.
11899 * ret == 0 and ret < 0 are sadly acceptable for
11900 * main() function due to backward compatibility.
11901 * Like socket filter program may be written as:
11902 * int bpf_prog(struct pt_regs *ctx)
11903 * and never dereference that ctx in the program.
11904 * 'struct pt_regs' is a type mismatch for socket
11905 * filter that should be using 'struct __sk_buff'.
11910 ret
= do_check(env
);
11912 /* check for NULL is necessary, since cur_state can be freed inside
11913 * do_check() under memory pressure.
11915 if (env
->cur_state
) {
11916 free_verifier_state(env
->cur_state
, true);
11917 env
->cur_state
= NULL
;
11919 while (!pop_stack(env
, NULL
, NULL
, false));
11920 if (!ret
&& pop_log
)
11921 bpf_vlog_reset(&env
->log
, 0);
11924 /* clean aux data in case subprog was rejected */
11925 sanitize_insn_aux_data(env
);
11929 /* Verify all global functions in a BPF program one by one based on their BTF.
11930 * All global functions must pass verification. Otherwise the whole program is rejected.
11941 * foo() will be verified first for R1=any_scalar_value. During verification it
11942 * will be assumed that bar() already verified successfully and call to bar()
11943 * from foo() will be checked for type match only. Later bar() will be verified
11944 * independently to check that it's safe for R1=any_scalar_value.
11946 static int do_check_subprogs(struct bpf_verifier_env
*env
)
11948 struct bpf_prog_aux
*aux
= env
->prog
->aux
;
11951 if (!aux
->func_info
)
11954 for (i
= 1; i
< env
->subprog_cnt
; i
++) {
11955 if (aux
->func_info_aux
[i
].linkage
!= BTF_FUNC_GLOBAL
)
11957 env
->insn_idx
= env
->subprog_info
[i
].start
;
11958 WARN_ON_ONCE(env
->insn_idx
== 0);
11959 ret
= do_check_common(env
, i
);
11962 } else if (env
->log
.level
& BPF_LOG_LEVEL
) {
11964 "Func#%d is safe for any args that match its prototype\n",
11971 static int do_check_main(struct bpf_verifier_env
*env
)
11976 ret
= do_check_common(env
, 0);
11978 env
->prog
->aux
->stack_depth
= env
->subprog_info
[0].stack_depth
;
11983 static void print_verification_stats(struct bpf_verifier_env
*env
)
11987 if (env
->log
.level
& BPF_LOG_STATS
) {
11988 verbose(env
, "verification time %lld usec\n",
11989 div_u64(env
->verification_time
, 1000));
11990 verbose(env
, "stack depth ");
11991 for (i
= 0; i
< env
->subprog_cnt
; i
++) {
11992 u32 depth
= env
->subprog_info
[i
].stack_depth
;
11994 verbose(env
, "%d", depth
);
11995 if (i
+ 1 < env
->subprog_cnt
)
11998 verbose(env
, "\n");
12000 verbose(env
, "processed %d insns (limit %d) max_states_per_insn %d "
12001 "total_states %d peak_states %d mark_read %d\n",
12002 env
->insn_processed
, BPF_COMPLEXITY_LIMIT_INSNS
,
12003 env
->max_states_per_insn
, env
->total_states
,
12004 env
->peak_states
, env
->longest_mark_read_walk
);
12007 static int check_struct_ops_btf_id(struct bpf_verifier_env
*env
)
12009 const struct btf_type
*t
, *func_proto
;
12010 const struct bpf_struct_ops
*st_ops
;
12011 const struct btf_member
*member
;
12012 struct bpf_prog
*prog
= env
->prog
;
12013 u32 btf_id
, member_idx
;
12016 if (!prog
->gpl_compatible
) {
12017 verbose(env
, "struct ops programs must have a GPL compatible license\n");
12021 btf_id
= prog
->aux
->attach_btf_id
;
12022 st_ops
= bpf_struct_ops_find(btf_id
);
12024 verbose(env
, "attach_btf_id %u is not a supported struct\n",
12030 member_idx
= prog
->expected_attach_type
;
12031 if (member_idx
>= btf_type_vlen(t
)) {
12032 verbose(env
, "attach to invalid member idx %u of struct %s\n",
12033 member_idx
, st_ops
->name
);
12037 member
= &btf_type_member(t
)[member_idx
];
12038 mname
= btf_name_by_offset(btf_vmlinux
, member
->name_off
);
12039 func_proto
= btf_type_resolve_func_ptr(btf_vmlinux
, member
->type
,
12042 verbose(env
, "attach to invalid member %s(@idx %u) of struct %s\n",
12043 mname
, member_idx
, st_ops
->name
);
12047 if (st_ops
->check_member
) {
12048 int err
= st_ops
->check_member(t
, member
);
12051 verbose(env
, "attach to unsupported member %s of struct %s\n",
12052 mname
, st_ops
->name
);
12057 prog
->aux
->attach_func_proto
= func_proto
;
12058 prog
->aux
->attach_func_name
= mname
;
12059 env
->ops
= st_ops
->verifier_ops
;
12063 #define SECURITY_PREFIX "security_"
12065 static int check_attach_modify_return(unsigned long addr
, const char *func_name
)
12067 if (within_error_injection_list(addr
) ||
12068 !strncmp(SECURITY_PREFIX
, func_name
, sizeof(SECURITY_PREFIX
) - 1))
12074 /* list of non-sleepable functions that are otherwise on
12075 * ALLOW_ERROR_INJECTION list
12077 BTF_SET_START(btf_non_sleepable_error_inject
)
12078 /* Three functions below can be called from sleepable and non-sleepable context.
12079 * Assume non-sleepable from bpf safety point of view.
12081 BTF_ID(func
, __add_to_page_cache_locked
)
12082 BTF_ID(func
, should_fail_alloc_page
)
12083 BTF_ID(func
, should_failslab
)
12084 BTF_SET_END(btf_non_sleepable_error_inject
)
12086 static int check_non_sleepable_error_inject(u32 btf_id
)
12088 return btf_id_set_contains(&btf_non_sleepable_error_inject
, btf_id
);
12091 int bpf_check_attach_target(struct bpf_verifier_log
*log
,
12092 const struct bpf_prog
*prog
,
12093 const struct bpf_prog
*tgt_prog
,
12095 struct bpf_attach_target_info
*tgt_info
)
12097 bool prog_extension
= prog
->type
== BPF_PROG_TYPE_EXT
;
12098 const char prefix
[] = "btf_trace_";
12099 int ret
= 0, subprog
= -1, i
;
12100 const struct btf_type
*t
;
12101 bool conservative
= true;
12107 bpf_log(log
, "Tracing programs must provide btf_id\n");
12110 btf
= tgt_prog
? tgt_prog
->aux
->btf
: prog
->aux
->attach_btf
;
12113 "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
12116 t
= btf_type_by_id(btf
, btf_id
);
12118 bpf_log(log
, "attach_btf_id %u is invalid\n", btf_id
);
12121 tname
= btf_name_by_offset(btf
, t
->name_off
);
12123 bpf_log(log
, "attach_btf_id %u doesn't have a name\n", btf_id
);
12127 struct bpf_prog_aux
*aux
= tgt_prog
->aux
;
12129 for (i
= 0; i
< aux
->func_info_cnt
; i
++)
12130 if (aux
->func_info
[i
].type_id
== btf_id
) {
12134 if (subprog
== -1) {
12135 bpf_log(log
, "Subprog %s doesn't exist\n", tname
);
12138 conservative
= aux
->func_info_aux
[subprog
].unreliable
;
12139 if (prog_extension
) {
12140 if (conservative
) {
12142 "Cannot replace static functions\n");
12145 if (!prog
->jit_requested
) {
12147 "Extension programs should be JITed\n");
12151 if (!tgt_prog
->jited
) {
12152 bpf_log(log
, "Can attach to only JITed progs\n");
12155 if (tgt_prog
->type
== prog
->type
) {
12156 /* Cannot fentry/fexit another fentry/fexit program.
12157 * Cannot attach program extension to another extension.
12158 * It's ok to attach fentry/fexit to extension program.
12160 bpf_log(log
, "Cannot recursively attach\n");
12163 if (tgt_prog
->type
== BPF_PROG_TYPE_TRACING
&&
12165 (tgt_prog
->expected_attach_type
== BPF_TRACE_FENTRY
||
12166 tgt_prog
->expected_attach_type
== BPF_TRACE_FEXIT
)) {
12167 /* Program extensions can extend all program types
12168 * except fentry/fexit. The reason is the following.
12169 * The fentry/fexit programs are used for performance
12170 * analysis, stats and can be attached to any program
12171 * type except themselves. When extension program is
12172 * replacing XDP function it is necessary to allow
12173 * performance analysis of all functions. Both original
12174 * XDP program and its program extension. Hence
12175 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
12176 * allowed. If extending of fentry/fexit was allowed it
12177 * would be possible to create long call chain
12178 * fentry->extension->fentry->extension beyond
12179 * reasonable stack size. Hence extending fentry is not
12182 bpf_log(log
, "Cannot extend fentry/fexit\n");
12186 if (prog_extension
) {
12187 bpf_log(log
, "Cannot replace kernel functions\n");
12192 switch (prog
->expected_attach_type
) {
12193 case BPF_TRACE_RAW_TP
:
12196 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
12199 if (!btf_type_is_typedef(t
)) {
12200 bpf_log(log
, "attach_btf_id %u is not a typedef\n",
12204 if (strncmp(prefix
, tname
, sizeof(prefix
) - 1)) {
12205 bpf_log(log
, "attach_btf_id %u points to wrong type name %s\n",
12209 tname
+= sizeof(prefix
) - 1;
12210 t
= btf_type_by_id(btf
, t
->type
);
12211 if (!btf_type_is_ptr(t
))
12212 /* should never happen in valid vmlinux build */
12214 t
= btf_type_by_id(btf
, t
->type
);
12215 if (!btf_type_is_func_proto(t
))
12216 /* should never happen in valid vmlinux build */
12220 case BPF_TRACE_ITER
:
12221 if (!btf_type_is_func(t
)) {
12222 bpf_log(log
, "attach_btf_id %u is not a function\n",
12226 t
= btf_type_by_id(btf
, t
->type
);
12227 if (!btf_type_is_func_proto(t
))
12229 ret
= btf_distill_func_proto(log
, btf
, t
, tname
, &tgt_info
->fmodel
);
12234 if (!prog_extension
)
12237 case BPF_MODIFY_RETURN
:
12239 case BPF_TRACE_FENTRY
:
12240 case BPF_TRACE_FEXIT
:
12241 if (!btf_type_is_func(t
)) {
12242 bpf_log(log
, "attach_btf_id %u is not a function\n",
12246 if (prog_extension
&&
12247 btf_check_type_match(log
, prog
, btf
, t
))
12249 t
= btf_type_by_id(btf
, t
->type
);
12250 if (!btf_type_is_func_proto(t
))
12253 if ((prog
->aux
->saved_dst_prog_type
|| prog
->aux
->saved_dst_attach_type
) &&
12254 (!tgt_prog
|| prog
->aux
->saved_dst_prog_type
!= tgt_prog
->type
||
12255 prog
->aux
->saved_dst_attach_type
!= tgt_prog
->expected_attach_type
))
12258 if (tgt_prog
&& conservative
)
12261 ret
= btf_distill_func_proto(log
, btf
, t
, tname
, &tgt_info
->fmodel
);
12267 addr
= (long) tgt_prog
->bpf_func
;
12269 addr
= (long) tgt_prog
->aux
->func
[subprog
]->bpf_func
;
12271 addr
= kallsyms_lookup_name(tname
);
12274 "The address of function %s cannot be found\n",
12280 if (prog
->aux
->sleepable
) {
12282 switch (prog
->type
) {
12283 case BPF_PROG_TYPE_TRACING
:
12284 /* fentry/fexit/fmod_ret progs can be sleepable only if they are
12285 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
12287 if (!check_non_sleepable_error_inject(btf_id
) &&
12288 within_error_injection_list(addr
))
12291 case BPF_PROG_TYPE_LSM
:
12292 /* LSM progs check that they are attached to bpf_lsm_*() funcs.
12293 * Only some of them are sleepable.
12295 if (bpf_lsm_is_sleepable_hook(btf_id
))
12302 bpf_log(log
, "%s is not sleepable\n", tname
);
12305 } else if (prog
->expected_attach_type
== BPF_MODIFY_RETURN
) {
12307 bpf_log(log
, "can't modify return codes of BPF programs\n");
12310 ret
= check_attach_modify_return(addr
, tname
);
12312 bpf_log(log
, "%s() is not modifiable\n", tname
);
12319 tgt_info
->tgt_addr
= addr
;
12320 tgt_info
->tgt_name
= tname
;
12321 tgt_info
->tgt_type
= t
;
12325 static int check_attach_btf_id(struct bpf_verifier_env
*env
)
12327 struct bpf_prog
*prog
= env
->prog
;
12328 struct bpf_prog
*tgt_prog
= prog
->aux
->dst_prog
;
12329 struct bpf_attach_target_info tgt_info
= {};
12330 u32 btf_id
= prog
->aux
->attach_btf_id
;
12331 struct bpf_trampoline
*tr
;
12335 if (prog
->aux
->sleepable
&& prog
->type
!= BPF_PROG_TYPE_TRACING
&&
12336 prog
->type
!= BPF_PROG_TYPE_LSM
) {
12337 verbose(env
, "Only fentry/fexit/fmod_ret and lsm programs can be sleepable\n");
12341 if (prog
->type
== BPF_PROG_TYPE_STRUCT_OPS
)
12342 return check_struct_ops_btf_id(env
);
12344 if (prog
->type
!= BPF_PROG_TYPE_TRACING
&&
12345 prog
->type
!= BPF_PROG_TYPE_LSM
&&
12346 prog
->type
!= BPF_PROG_TYPE_EXT
)
12349 ret
= bpf_check_attach_target(&env
->log
, prog
, tgt_prog
, btf_id
, &tgt_info
);
12353 if (tgt_prog
&& prog
->type
== BPF_PROG_TYPE_EXT
) {
12354 /* to make freplace equivalent to their targets, they need to
12355 * inherit env->ops and expected_attach_type for the rest of the
12358 env
->ops
= bpf_verifier_ops
[tgt_prog
->type
];
12359 prog
->expected_attach_type
= tgt_prog
->expected_attach_type
;
12362 /* store info about the attachment target that will be used later */
12363 prog
->aux
->attach_func_proto
= tgt_info
.tgt_type
;
12364 prog
->aux
->attach_func_name
= tgt_info
.tgt_name
;
12367 prog
->aux
->saved_dst_prog_type
= tgt_prog
->type
;
12368 prog
->aux
->saved_dst_attach_type
= tgt_prog
->expected_attach_type
;
12371 if (prog
->expected_attach_type
== BPF_TRACE_RAW_TP
) {
12372 prog
->aux
->attach_btf_trace
= true;
12374 } else if (prog
->expected_attach_type
== BPF_TRACE_ITER
) {
12375 if (!bpf_iter_prog_supported(prog
))
12380 if (prog
->type
== BPF_PROG_TYPE_LSM
) {
12381 ret
= bpf_lsm_verify_prog(&env
->log
, prog
);
12386 key
= bpf_trampoline_compute_key(tgt_prog
, prog
->aux
->attach_btf
, btf_id
);
12387 tr
= bpf_trampoline_get(key
, &tgt_info
);
12391 prog
->aux
->dst_trampoline
= tr
;
12395 struct btf
*bpf_get_btf_vmlinux(void)
12397 if (!btf_vmlinux
&& IS_ENABLED(CONFIG_DEBUG_INFO_BTF
)) {
12398 mutex_lock(&bpf_verifier_lock
);
12400 btf_vmlinux
= btf_parse_vmlinux();
12401 mutex_unlock(&bpf_verifier_lock
);
12403 return btf_vmlinux
;
12406 int bpf_check(struct bpf_prog
**prog
, union bpf_attr
*attr
,
12407 union bpf_attr __user
*uattr
)
12409 u64 start_time
= ktime_get_ns();
12410 struct bpf_verifier_env
*env
;
12411 struct bpf_verifier_log
*log
;
12412 int i
, len
, ret
= -EINVAL
;
12415 /* no program is valid */
12416 if (ARRAY_SIZE(bpf_verifier_ops
) == 0)
12419 /* 'struct bpf_verifier_env' can be global, but since it's not small,
12420 * allocate/free it every time bpf_check() is called
12422 env
= kzalloc(sizeof(struct bpf_verifier_env
), GFP_KERNEL
);
12427 len
= (*prog
)->len
;
12428 env
->insn_aux_data
=
12429 vzalloc(array_size(sizeof(struct bpf_insn_aux_data
), len
));
12431 if (!env
->insn_aux_data
)
12433 for (i
= 0; i
< len
; i
++)
12434 env
->insn_aux_data
[i
].orig_idx
= i
;
12436 env
->ops
= bpf_verifier_ops
[env
->prog
->type
];
12437 is_priv
= bpf_capable();
12439 bpf_get_btf_vmlinux();
12441 /* grab the mutex to protect few globals used by verifier */
12443 mutex_lock(&bpf_verifier_lock
);
12445 if (attr
->log_level
|| attr
->log_buf
|| attr
->log_size
) {
12446 /* user requested verbose verifier output
12447 * and supplied buffer to store the verification trace
12449 log
->level
= attr
->log_level
;
12450 log
->ubuf
= (char __user
*) (unsigned long) attr
->log_buf
;
12451 log
->len_total
= attr
->log_size
;
12454 /* log attributes have to be sane */
12455 if (log
->len_total
< 128 || log
->len_total
> UINT_MAX
>> 2 ||
12456 !log
->level
|| !log
->ubuf
|| log
->level
& ~BPF_LOG_MASK
)
12460 if (IS_ERR(btf_vmlinux
)) {
12461 /* Either gcc or pahole or kernel are broken. */
12462 verbose(env
, "in-kernel BTF is malformed\n");
12463 ret
= PTR_ERR(btf_vmlinux
);
12464 goto skip_full_check
;
12467 env
->strict_alignment
= !!(attr
->prog_flags
& BPF_F_STRICT_ALIGNMENT
);
12468 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS
))
12469 env
->strict_alignment
= true;
12470 if (attr
->prog_flags
& BPF_F_ANY_ALIGNMENT
)
12471 env
->strict_alignment
= false;
12473 env
->allow_ptr_leaks
= bpf_allow_ptr_leaks();
12474 env
->allow_uninit_stack
= bpf_allow_uninit_stack();
12475 env
->allow_ptr_to_map_access
= bpf_allow_ptr_to_map_access();
12476 env
->bypass_spec_v1
= bpf_bypass_spec_v1();
12477 env
->bypass_spec_v4
= bpf_bypass_spec_v4();
12478 env
->bpf_capable
= bpf_capable();
12481 env
->test_state_freq
= attr
->prog_flags
& BPF_F_TEST_STATE_FREQ
;
12483 if (bpf_prog_is_dev_bound(env
->prog
->aux
)) {
12484 ret
= bpf_prog_offload_verifier_prep(env
->prog
);
12486 goto skip_full_check
;
12489 env
->explored_states
= kvcalloc(state_htab_size(env
),
12490 sizeof(struct bpf_verifier_state_list
*),
12493 if (!env
->explored_states
)
12494 goto skip_full_check
;
12496 ret
= check_subprogs(env
);
12498 goto skip_full_check
;
12500 ret
= check_btf_info(env
, attr
, uattr
);
12502 goto skip_full_check
;
12504 ret
= check_attach_btf_id(env
);
12506 goto skip_full_check
;
12508 ret
= resolve_pseudo_ldimm64(env
);
12510 goto skip_full_check
;
12512 ret
= check_cfg(env
);
12514 goto skip_full_check
;
12516 ret
= do_check_subprogs(env
);
12517 ret
= ret
?: do_check_main(env
);
12519 if (ret
== 0 && bpf_prog_is_dev_bound(env
->prog
->aux
))
12520 ret
= bpf_prog_offload_finalize(env
);
12523 kvfree(env
->explored_states
);
12526 ret
= check_max_stack_depth(env
);
12528 /* instruction rewrites happen after this point */
12531 opt_hard_wire_dead_code_branches(env
);
12533 ret
= opt_remove_dead_code(env
);
12535 ret
= opt_remove_nops(env
);
12538 sanitize_dead_code(env
);
12542 /* program is valid, convert *(u32*)(ctx + off) accesses */
12543 ret
= convert_ctx_accesses(env
);
12546 ret
= fixup_bpf_calls(env
);
12548 /* do 32-bit optimization after insn patching has done so those patched
12549 * insns could be handled correctly.
12551 if (ret
== 0 && !bpf_prog_is_dev_bound(env
->prog
->aux
)) {
12552 ret
= opt_subreg_zext_lo32_rnd_hi32(env
, attr
);
12553 env
->prog
->aux
->verifier_zext
= bpf_jit_needs_zext() ? !ret
12558 ret
= fixup_call_args(env
);
12560 env
->verification_time
= ktime_get_ns() - start_time
;
12561 print_verification_stats(env
);
12563 if (log
->level
&& bpf_verifier_log_full(log
))
12565 if (log
->level
&& !log
->ubuf
) {
12567 goto err_release_maps
;
12570 if (ret
== 0 && env
->used_map_cnt
) {
12571 /* if program passed verifier, update used_maps in bpf_prog_info */
12572 env
->prog
->aux
->used_maps
= kmalloc_array(env
->used_map_cnt
,
12573 sizeof(env
->used_maps
[0]),
12576 if (!env
->prog
->aux
->used_maps
) {
12578 goto err_release_maps
;
12581 memcpy(env
->prog
->aux
->used_maps
, env
->used_maps
,
12582 sizeof(env
->used_maps
[0]) * env
->used_map_cnt
);
12583 env
->prog
->aux
->used_map_cnt
= env
->used_map_cnt
;
12585 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
12586 * bpf_ld_imm64 instructions
12588 convert_pseudo_ld_imm64(env
);
12592 adjust_btf_func(env
);
12595 if (!env
->prog
->aux
->used_maps
)
12596 /* if we didn't copy map pointers into bpf_prog_info, release
12597 * them now. Otherwise free_used_maps() will release them.
12601 /* extension progs temporarily inherit the attach_type of their targets
12602 for verification purposes, so set it back to zero before returning
12604 if (env
->prog
->type
== BPF_PROG_TYPE_EXT
)
12605 env
->prog
->expected_attach_type
= 0;
12610 mutex_unlock(&bpf_verifier_lock
);
12611 vfree(env
->insn_aux_data
);