]> git.proxmox.com Git - mirror_ubuntu-hirsute-kernel.git/blame - kernel/bpf/verifier.c
bpf: Remove unneeded break
[mirror_ubuntu-hirsute-kernel.git] / kernel / bpf / verifier.c
CommitLineData
5b497af4 1// SPDX-License-Identifier: GPL-2.0-only
51580e79 2/* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com
969bf05e 3 * Copyright (c) 2016 Facebook
fd978bf7 4 * Copyright (c) 2018 Covalent IO, Inc. http://covalent.io
51580e79 5 */
838e9690 6#include <uapi/linux/btf.h>
51580e79
AS
7#include <linux/kernel.h>
8#include <linux/types.h>
9#include <linux/slab.h>
10#include <linux/bpf.h>
838e9690 11#include <linux/btf.h>
58e2af8b 12#include <linux/bpf_verifier.h>
51580e79
AS
13#include <linux/filter.h>
14#include <net/netlink.h>
15#include <linux/file.h>
16#include <linux/vmalloc.h>
ebb676da 17#include <linux/stringify.h>
cc8b0b92
AS
18#include <linux/bsearch.h>
19#include <linux/sort.h>
c195651e 20#include <linux/perf_event.h>
d9762e84 21#include <linux/ctype.h>
6ba43b76 22#include <linux/error-injection.h>
9e4e01df 23#include <linux/bpf_lsm.h>
1e6c62a8 24#include <linux/btf_ids.h>
51580e79 25
f4ac7e0b
JK
26#include "disasm.h"
27
00176a34 28static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
91cc1a99 29#define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
00176a34
JK
30 [_id] = & _name ## _verifier_ops,
31#define BPF_MAP_TYPE(_id, _ops)
f2e10bff 32#define BPF_LINK_TYPE(_id, _name)
00176a34
JK
33#include <linux/bpf_types.h>
34#undef BPF_PROG_TYPE
35#undef BPF_MAP_TYPE
f2e10bff 36#undef BPF_LINK_TYPE
00176a34
JK
37};
38
51580e79
AS
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.
42 *
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
eba38a96 51 * analysis is limited to 64k insn, which may be hit even if total number of
51580e79
AS
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
54 *
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
58 * copied to R1.
59 *
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
65 *
66 * At the start of BPF program the register R1 contains a pointer to bpf_context
67 * and has type PTR_TO_CTX.
68 *
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.
78 *
f1174f77 79 * Most of the time the registers have SCALAR_VALUE type, which
51580e79 80 * means the register has some value, but it's not a valid pointer.
f1174f77 81 * (like pointer plus pointer becomes SCALAR_VALUE type)
51580e79
AS
82 *
83 * When verifier sees load or store instructions the type of base register
c64b7983
JS
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.
51580e79
AS
86 *
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.
89 *
90 * registers used to pass values to function calls are checked against
91 * function argument constraints.
92 *
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'
97 *
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,
102 *
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.
107 *
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)
110 * {
111 * struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
112 * void *key = (void *) (unsigned long) r2;
113 * void *value;
114 *
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.
118 * }
119 *
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
128 *
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.
136 *
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().
141 *
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.
fd978bf7
JS
144 *
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
147 * the BPF program:
148 * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET
149 *
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.
6acc9b43
JS
156 *
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.
51580e79
AS
162 */
163
17a52670 164/* verifier_state + insn_idx are pushed to stack when branch is encountered */
58e2af8b 165struct bpf_verifier_stack_elem {
17a52670
AS
166 /* verifer state is 'st'
167 * before processing instruction 'insn_idx'
168 * and after processing instruction 'prev_insn_idx'
169 */
58e2af8b 170 struct bpf_verifier_state st;
17a52670
AS
171 int insn_idx;
172 int prev_insn_idx;
58e2af8b 173 struct bpf_verifier_stack_elem *next;
6f8a57cc
AN
174 /* length of verifier log at the time this state was pushed on stack */
175 u32 log_pos;
cbd35700
AS
176};
177
b285fcb7 178#define BPF_COMPLEXITY_LIMIT_JMP_SEQ 8192
ceefbc96 179#define BPF_COMPLEXITY_LIMIT_STATES 64
07016151 180
d2e4c1e6
DB
181#define BPF_MAP_KEY_POISON (1ULL << 63)
182#define BPF_MAP_KEY_SEEN (1ULL << 62)
183
c93552c4
DB
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))
188
189static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux)
190{
d2e4c1e6 191 return BPF_MAP_PTR(aux->map_ptr_state) == BPF_MAP_PTR_POISON;
c93552c4
DB
192}
193
194static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux)
195{
d2e4c1e6 196 return aux->map_ptr_state & BPF_MAP_PTR_UNPRIV;
c93552c4
DB
197}
198
199static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
200 const struct bpf_map *map, bool unpriv)
201{
202 BUILD_BUG_ON((unsigned long)BPF_MAP_PTR_POISON & BPF_MAP_PTR_UNPRIV);
203 unpriv |= bpf_map_ptr_unpriv(aux);
d2e4c1e6
DB
204 aux->map_ptr_state = (unsigned long)map |
205 (unpriv ? BPF_MAP_PTR_UNPRIV : 0UL);
206}
207
208static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux)
209{
210 return aux->map_key_state & BPF_MAP_KEY_POISON;
211}
212
213static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux)
214{
215 return !(aux->map_key_state & BPF_MAP_KEY_SEEN);
216}
217
218static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux)
219{
220 return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON);
221}
222
223static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state)
224{
225 bool poisoned = bpf_map_key_poisoned(aux);
226
227 aux->map_key_state = state | BPF_MAP_KEY_SEEN |
228 (poisoned ? BPF_MAP_KEY_POISON : 0ULL);
c93552c4 229}
fad73a1a 230
33ff9823
DB
231struct bpf_call_arg_meta {
232 struct bpf_map *map_ptr;
435faee1 233 bool raw_mode;
36bbef52 234 bool pkt_access;
435faee1
DB
235 int regno;
236 int access_size;
457f4436 237 int mem_size;
10060503 238 u64 msize_max_value;
1b986589 239 int ref_obj_id;
d83525ca 240 int func_id;
eaa6bcb7
HL
241 u32 btf_id;
242 u32 ret_btf_id;
33ff9823
DB
243};
244
8580ac94
AS
245struct btf *btf_vmlinux;
246
cbd35700
AS
247static DEFINE_MUTEX(bpf_verifier_lock);
248
d9762e84
MKL
249static const struct bpf_line_info *
250find_linfo(const struct bpf_verifier_env *env, u32 insn_off)
251{
252 const struct bpf_line_info *linfo;
253 const struct bpf_prog *prog;
254 u32 i, nr_linfo;
255
256 prog = env->prog;
257 nr_linfo = prog->aux->nr_linfo;
258
259 if (!nr_linfo || insn_off >= prog->len)
260 return NULL;
261
262 linfo = prog->aux->linfo;
263 for (i = 1; i < nr_linfo; i++)
264 if (insn_off < linfo[i].insn_off)
265 break;
266
267 return &linfo[i - 1];
268}
269
77d2e05a
MKL
270void bpf_verifier_vlog(struct bpf_verifier_log *log, const char *fmt,
271 va_list args)
cbd35700 272{
a2a7d570 273 unsigned int n;
cbd35700 274
a2a7d570 275 n = vscnprintf(log->kbuf, BPF_VERIFIER_TMP_LOG_SIZE, fmt, args);
a2a7d570
JK
276
277 WARN_ONCE(n >= BPF_VERIFIER_TMP_LOG_SIZE - 1,
278 "verifier log line truncated - local buffer too short\n");
279
280 n = min(log->len_total - log->len_used - 1, n);
281 log->kbuf[n] = '\0';
282
8580ac94
AS
283 if (log->level == BPF_LOG_KERNEL) {
284 pr_err("BPF:%s\n", log->kbuf);
285 return;
286 }
a2a7d570
JK
287 if (!copy_to_user(log->ubuf + log->len_used, log->kbuf, n + 1))
288 log->len_used += n;
289 else
290 log->ubuf = NULL;
cbd35700 291}
abe08840 292
6f8a57cc
AN
293static void bpf_vlog_reset(struct bpf_verifier_log *log, u32 new_pos)
294{
295 char zero = 0;
296
297 if (!bpf_verifier_log_needed(log))
298 return;
299
300 log->len_used = new_pos;
301 if (put_user(zero, log->ubuf + new_pos))
302 log->ubuf = NULL;
303}
304
abe08840
JO
305/* log_level controls verbosity level of eBPF verifier.
306 * bpf_verifier_log_write() is used to dump the verification trace to the log,
307 * so the user can figure out what's wrong with the program
430e68d1 308 */
abe08840
JO
309__printf(2, 3) void bpf_verifier_log_write(struct bpf_verifier_env *env,
310 const char *fmt, ...)
311{
312 va_list args;
313
77d2e05a
MKL
314 if (!bpf_verifier_log_needed(&env->log))
315 return;
316
abe08840 317 va_start(args, fmt);
77d2e05a 318 bpf_verifier_vlog(&env->log, fmt, args);
abe08840
JO
319 va_end(args);
320}
321EXPORT_SYMBOL_GPL(bpf_verifier_log_write);
322
323__printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
324{
77d2e05a 325 struct bpf_verifier_env *env = private_data;
abe08840
JO
326 va_list args;
327
77d2e05a
MKL
328 if (!bpf_verifier_log_needed(&env->log))
329 return;
330
abe08840 331 va_start(args, fmt);
77d2e05a 332 bpf_verifier_vlog(&env->log, fmt, args);
abe08840
JO
333 va_end(args);
334}
cbd35700 335
9e15db66
AS
336__printf(2, 3) void bpf_log(struct bpf_verifier_log *log,
337 const char *fmt, ...)
338{
339 va_list args;
340
341 if (!bpf_verifier_log_needed(log))
342 return;
343
344 va_start(args, fmt);
345 bpf_verifier_vlog(log, fmt, args);
346 va_end(args);
347}
348
d9762e84
MKL
349static const char *ltrim(const char *s)
350{
351 while (isspace(*s))
352 s++;
353
354 return s;
355}
356
357__printf(3, 4) static void verbose_linfo(struct bpf_verifier_env *env,
358 u32 insn_off,
359 const char *prefix_fmt, ...)
360{
361 const struct bpf_line_info *linfo;
362
363 if (!bpf_verifier_log_needed(&env->log))
364 return;
365
366 linfo = find_linfo(env, insn_off);
367 if (!linfo || linfo == env->prev_linfo)
368 return;
369
370 if (prefix_fmt) {
371 va_list args;
372
373 va_start(args, prefix_fmt);
374 bpf_verifier_vlog(&env->log, prefix_fmt, args);
375 va_end(args);
376 }
377
378 verbose(env, "%s\n",
379 ltrim(btf_name_by_offset(env->prog->aux->btf,
380 linfo->line_off)));
381
382 env->prev_linfo = linfo;
383}
384
de8f3a83
DB
385static bool type_is_pkt_pointer(enum bpf_reg_type type)
386{
387 return type == PTR_TO_PACKET ||
388 type == PTR_TO_PACKET_META;
389}
390
46f8bc92
MKL
391static bool type_is_sk_pointer(enum bpf_reg_type type)
392{
393 return type == PTR_TO_SOCKET ||
655a51e5 394 type == PTR_TO_SOCK_COMMON ||
fada7fdc
JL
395 type == PTR_TO_TCP_SOCK ||
396 type == PTR_TO_XDP_SOCK;
46f8bc92
MKL
397}
398
cac616db
JF
399static bool reg_type_not_null(enum bpf_reg_type type)
400{
401 return type == PTR_TO_SOCKET ||
402 type == PTR_TO_TCP_SOCK ||
403 type == PTR_TO_MAP_VALUE ||
01c66c48 404 type == PTR_TO_SOCK_COMMON;
cac616db
JF
405}
406
840b9615
JS
407static bool reg_type_may_be_null(enum bpf_reg_type type)
408{
fd978bf7 409 return type == PTR_TO_MAP_VALUE_OR_NULL ||
46f8bc92 410 type == PTR_TO_SOCKET_OR_NULL ||
655a51e5 411 type == PTR_TO_SOCK_COMMON_OR_NULL ||
b121b341 412 type == PTR_TO_TCP_SOCK_OR_NULL ||
457f4436 413 type == PTR_TO_BTF_ID_OR_NULL ||
afbf21dc
YS
414 type == PTR_TO_MEM_OR_NULL ||
415 type == PTR_TO_RDONLY_BUF_OR_NULL ||
416 type == PTR_TO_RDWR_BUF_OR_NULL;
fd978bf7
JS
417}
418
d83525ca
AS
419static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
420{
421 return reg->type == PTR_TO_MAP_VALUE &&
422 map_value_has_spin_lock(reg->map_ptr);
423}
424
cba368c1
MKL
425static bool reg_type_may_be_refcounted_or_null(enum bpf_reg_type type)
426{
427 return type == PTR_TO_SOCKET ||
428 type == PTR_TO_SOCKET_OR_NULL ||
429 type == PTR_TO_TCP_SOCK ||
457f4436
AN
430 type == PTR_TO_TCP_SOCK_OR_NULL ||
431 type == PTR_TO_MEM ||
432 type == PTR_TO_MEM_OR_NULL;
cba368c1
MKL
433}
434
1b986589 435static bool arg_type_may_be_refcounted(enum bpf_arg_type type)
fd978bf7 436{
1b986589 437 return type == ARG_PTR_TO_SOCK_COMMON;
fd978bf7
JS
438}
439
fd1b0d60
LB
440static bool arg_type_may_be_null(enum bpf_arg_type type)
441{
442 return type == ARG_PTR_TO_MAP_VALUE_OR_NULL ||
443 type == ARG_PTR_TO_MEM_OR_NULL ||
444 type == ARG_PTR_TO_CTX_OR_NULL ||
445 type == ARG_PTR_TO_SOCKET_OR_NULL ||
446 type == ARG_PTR_TO_ALLOC_MEM_OR_NULL;
447}
448
fd978bf7
JS
449/* Determine whether the function releases some resources allocated by another
450 * function call. The first reference type argument will be assumed to be
451 * released by release_reference().
452 */
453static bool is_release_function(enum bpf_func_id func_id)
454{
457f4436
AN
455 return func_id == BPF_FUNC_sk_release ||
456 func_id == BPF_FUNC_ringbuf_submit ||
457 func_id == BPF_FUNC_ringbuf_discard;
840b9615
JS
458}
459
64d85290 460static bool may_be_acquire_function(enum bpf_func_id func_id)
46f8bc92
MKL
461{
462 return func_id == BPF_FUNC_sk_lookup_tcp ||
edbf8c01 463 func_id == BPF_FUNC_sk_lookup_udp ||
64d85290 464 func_id == BPF_FUNC_skc_lookup_tcp ||
457f4436
AN
465 func_id == BPF_FUNC_map_lookup_elem ||
466 func_id == BPF_FUNC_ringbuf_reserve;
64d85290
JS
467}
468
469static bool is_acquire_function(enum bpf_func_id func_id,
470 const struct bpf_map *map)
471{
472 enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
473
474 if (func_id == BPF_FUNC_sk_lookup_tcp ||
475 func_id == BPF_FUNC_sk_lookup_udp ||
457f4436
AN
476 func_id == BPF_FUNC_skc_lookup_tcp ||
477 func_id == BPF_FUNC_ringbuf_reserve)
64d85290
JS
478 return true;
479
480 if (func_id == BPF_FUNC_map_lookup_elem &&
481 (map_type == BPF_MAP_TYPE_SOCKMAP ||
482 map_type == BPF_MAP_TYPE_SOCKHASH))
483 return true;
484
485 return false;
46f8bc92
MKL
486}
487
1b986589
MKL
488static bool is_ptr_cast_function(enum bpf_func_id func_id)
489{
490 return func_id == BPF_FUNC_tcp_sock ||
1df8f55a
MKL
491 func_id == BPF_FUNC_sk_fullsock ||
492 func_id == BPF_FUNC_skc_to_tcp_sock ||
493 func_id == BPF_FUNC_skc_to_tcp6_sock ||
494 func_id == BPF_FUNC_skc_to_udp6_sock ||
495 func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
496 func_id == BPF_FUNC_skc_to_tcp_request_sock;
1b986589
MKL
497}
498
17a52670
AS
499/* string representation of 'enum bpf_reg_type' */
500static const char * const reg_type_str[] = {
501 [NOT_INIT] = "?",
f1174f77 502 [SCALAR_VALUE] = "inv",
17a52670
AS
503 [PTR_TO_CTX] = "ctx",
504 [CONST_PTR_TO_MAP] = "map_ptr",
505 [PTR_TO_MAP_VALUE] = "map_value",
506 [PTR_TO_MAP_VALUE_OR_NULL] = "map_value_or_null",
17a52670 507 [PTR_TO_STACK] = "fp",
969bf05e 508 [PTR_TO_PACKET] = "pkt",
de8f3a83 509 [PTR_TO_PACKET_META] = "pkt_meta",
969bf05e 510 [PTR_TO_PACKET_END] = "pkt_end",
d58e468b 511 [PTR_TO_FLOW_KEYS] = "flow_keys",
c64b7983
JS
512 [PTR_TO_SOCKET] = "sock",
513 [PTR_TO_SOCKET_OR_NULL] = "sock_or_null",
46f8bc92
MKL
514 [PTR_TO_SOCK_COMMON] = "sock_common",
515 [PTR_TO_SOCK_COMMON_OR_NULL] = "sock_common_or_null",
655a51e5
MKL
516 [PTR_TO_TCP_SOCK] = "tcp_sock",
517 [PTR_TO_TCP_SOCK_OR_NULL] = "tcp_sock_or_null",
9df1c28b 518 [PTR_TO_TP_BUFFER] = "tp_buffer",
fada7fdc 519 [PTR_TO_XDP_SOCK] = "xdp_sock",
9e15db66 520 [PTR_TO_BTF_ID] = "ptr_",
b121b341 521 [PTR_TO_BTF_ID_OR_NULL] = "ptr_or_null_",
eaa6bcb7 522 [PTR_TO_PERCPU_BTF_ID] = "percpu_ptr_",
457f4436
AN
523 [PTR_TO_MEM] = "mem",
524 [PTR_TO_MEM_OR_NULL] = "mem_or_null",
afbf21dc
YS
525 [PTR_TO_RDONLY_BUF] = "rdonly_buf",
526 [PTR_TO_RDONLY_BUF_OR_NULL] = "rdonly_buf_or_null",
527 [PTR_TO_RDWR_BUF] = "rdwr_buf",
528 [PTR_TO_RDWR_BUF_OR_NULL] = "rdwr_buf_or_null",
17a52670
AS
529};
530
8efea21d
EC
531static char slot_type_char[] = {
532 [STACK_INVALID] = '?',
533 [STACK_SPILL] = 'r',
534 [STACK_MISC] = 'm',
535 [STACK_ZERO] = '0',
536};
537
4e92024a
AS
538static void print_liveness(struct bpf_verifier_env *env,
539 enum bpf_reg_liveness live)
540{
9242b5f5 541 if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE))
4e92024a
AS
542 verbose(env, "_");
543 if (live & REG_LIVE_READ)
544 verbose(env, "r");
545 if (live & REG_LIVE_WRITTEN)
546 verbose(env, "w");
9242b5f5
AS
547 if (live & REG_LIVE_DONE)
548 verbose(env, "D");
4e92024a
AS
549}
550
f4d7e40a
AS
551static struct bpf_func_state *func(struct bpf_verifier_env *env,
552 const struct bpf_reg_state *reg)
553{
554 struct bpf_verifier_state *cur = env->cur_state;
555
556 return cur->frame[reg->frameno];
557}
558
9e15db66
AS
559const char *kernel_type_name(u32 id)
560{
561 return btf_name_by_offset(btf_vmlinux,
562 btf_type_by_id(btf_vmlinux, id)->name_off);
563}
564
61bd5218 565static void print_verifier_state(struct bpf_verifier_env *env,
f4d7e40a 566 const struct bpf_func_state *state)
17a52670 567{
f4d7e40a 568 const struct bpf_reg_state *reg;
17a52670
AS
569 enum bpf_reg_type t;
570 int i;
571
f4d7e40a
AS
572 if (state->frameno)
573 verbose(env, " frame%d:", state->frameno);
17a52670 574 for (i = 0; i < MAX_BPF_REG; i++) {
1a0dc1ac
AS
575 reg = &state->regs[i];
576 t = reg->type;
17a52670
AS
577 if (t == NOT_INIT)
578 continue;
4e92024a
AS
579 verbose(env, " R%d", i);
580 print_liveness(env, reg->live);
581 verbose(env, "=%s", reg_type_str[t]);
b5dc0163
AS
582 if (t == SCALAR_VALUE && reg->precise)
583 verbose(env, "P");
f1174f77
EC
584 if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
585 tnum_is_const(reg->var_off)) {
586 /* reg->off should be 0 for SCALAR_VALUE */
61bd5218 587 verbose(env, "%lld", reg->var_off.value + reg->off);
f1174f77 588 } else {
eaa6bcb7
HL
589 if (t == PTR_TO_BTF_ID ||
590 t == PTR_TO_BTF_ID_OR_NULL ||
591 t == PTR_TO_PERCPU_BTF_ID)
9e15db66 592 verbose(env, "%s", kernel_type_name(reg->btf_id));
cba368c1
MKL
593 verbose(env, "(id=%d", reg->id);
594 if (reg_type_may_be_refcounted_or_null(t))
595 verbose(env, ",ref_obj_id=%d", reg->ref_obj_id);
f1174f77 596 if (t != SCALAR_VALUE)
61bd5218 597 verbose(env, ",off=%d", reg->off);
de8f3a83 598 if (type_is_pkt_pointer(t))
61bd5218 599 verbose(env, ",r=%d", reg->range);
f1174f77
EC
600 else if (t == CONST_PTR_TO_MAP ||
601 t == PTR_TO_MAP_VALUE ||
602 t == PTR_TO_MAP_VALUE_OR_NULL)
61bd5218 603 verbose(env, ",ks=%d,vs=%d",
f1174f77
EC
604 reg->map_ptr->key_size,
605 reg->map_ptr->value_size);
7d1238f2
EC
606 if (tnum_is_const(reg->var_off)) {
607 /* Typically an immediate SCALAR_VALUE, but
608 * could be a pointer whose offset is too big
609 * for reg->off
610 */
61bd5218 611 verbose(env, ",imm=%llx", reg->var_off.value);
7d1238f2
EC
612 } else {
613 if (reg->smin_value != reg->umin_value &&
614 reg->smin_value != S64_MIN)
61bd5218 615 verbose(env, ",smin_value=%lld",
7d1238f2
EC
616 (long long)reg->smin_value);
617 if (reg->smax_value != reg->umax_value &&
618 reg->smax_value != S64_MAX)
61bd5218 619 verbose(env, ",smax_value=%lld",
7d1238f2
EC
620 (long long)reg->smax_value);
621 if (reg->umin_value != 0)
61bd5218 622 verbose(env, ",umin_value=%llu",
7d1238f2
EC
623 (unsigned long long)reg->umin_value);
624 if (reg->umax_value != U64_MAX)
61bd5218 625 verbose(env, ",umax_value=%llu",
7d1238f2
EC
626 (unsigned long long)reg->umax_value);
627 if (!tnum_is_unknown(reg->var_off)) {
628 char tn_buf[48];
f1174f77 629
7d1238f2 630 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
61bd5218 631 verbose(env, ",var_off=%s", tn_buf);
7d1238f2 632 }
3f50f132
JF
633 if (reg->s32_min_value != reg->smin_value &&
634 reg->s32_min_value != S32_MIN)
635 verbose(env, ",s32_min_value=%d",
636 (int)(reg->s32_min_value));
637 if (reg->s32_max_value != reg->smax_value &&
638 reg->s32_max_value != S32_MAX)
639 verbose(env, ",s32_max_value=%d",
640 (int)(reg->s32_max_value));
641 if (reg->u32_min_value != reg->umin_value &&
642 reg->u32_min_value != U32_MIN)
643 verbose(env, ",u32_min_value=%d",
644 (int)(reg->u32_min_value));
645 if (reg->u32_max_value != reg->umax_value &&
646 reg->u32_max_value != U32_MAX)
647 verbose(env, ",u32_max_value=%d",
648 (int)(reg->u32_max_value));
f1174f77 649 }
61bd5218 650 verbose(env, ")");
f1174f77 651 }
17a52670 652 }
638f5b90 653 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
8efea21d
EC
654 char types_buf[BPF_REG_SIZE + 1];
655 bool valid = false;
656 int j;
657
658 for (j = 0; j < BPF_REG_SIZE; j++) {
659 if (state->stack[i].slot_type[j] != STACK_INVALID)
660 valid = true;
661 types_buf[j] = slot_type_char[
662 state->stack[i].slot_type[j]];
663 }
664 types_buf[BPF_REG_SIZE] = 0;
665 if (!valid)
666 continue;
667 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
668 print_liveness(env, state->stack[i].spilled_ptr.live);
b5dc0163
AS
669 if (state->stack[i].slot_type[0] == STACK_SPILL) {
670 reg = &state->stack[i].spilled_ptr;
671 t = reg->type;
672 verbose(env, "=%s", reg_type_str[t]);
673 if (t == SCALAR_VALUE && reg->precise)
674 verbose(env, "P");
675 if (t == SCALAR_VALUE && tnum_is_const(reg->var_off))
676 verbose(env, "%lld", reg->var_off.value + reg->off);
677 } else {
8efea21d 678 verbose(env, "=%s", types_buf);
b5dc0163 679 }
17a52670 680 }
fd978bf7
JS
681 if (state->acquired_refs && state->refs[0].id) {
682 verbose(env, " refs=%d", state->refs[0].id);
683 for (i = 1; i < state->acquired_refs; i++)
684 if (state->refs[i].id)
685 verbose(env, ",%d", state->refs[i].id);
686 }
61bd5218 687 verbose(env, "\n");
17a52670
AS
688}
689
84dbf350
JS
690#define COPY_STATE_FN(NAME, COUNT, FIELD, SIZE) \
691static int copy_##NAME##_state(struct bpf_func_state *dst, \
692 const struct bpf_func_state *src) \
693{ \
694 if (!src->FIELD) \
695 return 0; \
696 if (WARN_ON_ONCE(dst->COUNT < src->COUNT)) { \
697 /* internal bug, make state invalid to reject the program */ \
698 memset(dst, 0, sizeof(*dst)); \
699 return -EFAULT; \
700 } \
701 memcpy(dst->FIELD, src->FIELD, \
702 sizeof(*src->FIELD) * (src->COUNT / SIZE)); \
703 return 0; \
638f5b90 704}
fd978bf7
JS
705/* copy_reference_state() */
706COPY_STATE_FN(reference, acquired_refs, refs, 1)
84dbf350
JS
707/* copy_stack_state() */
708COPY_STATE_FN(stack, allocated_stack, stack, BPF_REG_SIZE)
709#undef COPY_STATE_FN
710
711#define REALLOC_STATE_FN(NAME, COUNT, FIELD, SIZE) \
712static int realloc_##NAME##_state(struct bpf_func_state *state, int size, \
713 bool copy_old) \
714{ \
715 u32 old_size = state->COUNT; \
716 struct bpf_##NAME##_state *new_##FIELD; \
717 int slot = size / SIZE; \
718 \
719 if (size <= old_size || !size) { \
720 if (copy_old) \
721 return 0; \
722 state->COUNT = slot * SIZE; \
723 if (!size && old_size) { \
724 kfree(state->FIELD); \
725 state->FIELD = NULL; \
726 } \
727 return 0; \
728 } \
729 new_##FIELD = kmalloc_array(slot, sizeof(struct bpf_##NAME##_state), \
730 GFP_KERNEL); \
731 if (!new_##FIELD) \
732 return -ENOMEM; \
733 if (copy_old) { \
734 if (state->FIELD) \
735 memcpy(new_##FIELD, state->FIELD, \
736 sizeof(*new_##FIELD) * (old_size / SIZE)); \
737 memset(new_##FIELD + old_size / SIZE, 0, \
738 sizeof(*new_##FIELD) * (size - old_size) / SIZE); \
739 } \
740 state->COUNT = slot * SIZE; \
741 kfree(state->FIELD); \
742 state->FIELD = new_##FIELD; \
743 return 0; \
744}
fd978bf7
JS
745/* realloc_reference_state() */
746REALLOC_STATE_FN(reference, acquired_refs, refs, 1)
84dbf350
JS
747/* realloc_stack_state() */
748REALLOC_STATE_FN(stack, allocated_stack, stack, BPF_REG_SIZE)
749#undef REALLOC_STATE_FN
638f5b90
AS
750
751/* do_check() starts with zero-sized stack in struct bpf_verifier_state to
752 * make it consume minimal amount of memory. check_stack_write() access from
f4d7e40a 753 * the program calls into realloc_func_state() to grow the stack size.
84dbf350
JS
754 * Note there is a non-zero 'parent' pointer inside bpf_verifier_state
755 * which realloc_stack_state() copies over. It points to previous
756 * bpf_verifier_state which is never reallocated.
638f5b90 757 */
fd978bf7
JS
758static int realloc_func_state(struct bpf_func_state *state, int stack_size,
759 int refs_size, bool copy_old)
638f5b90 760{
fd978bf7
JS
761 int err = realloc_reference_state(state, refs_size, copy_old);
762 if (err)
763 return err;
764 return realloc_stack_state(state, stack_size, copy_old);
765}
766
767/* Acquire a pointer id from the env and update the state->refs to include
768 * this new pointer reference.
769 * On success, returns a valid pointer id to associate with the register
770 * On failure, returns a negative errno.
638f5b90 771 */
fd978bf7 772static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
638f5b90 773{
fd978bf7
JS
774 struct bpf_func_state *state = cur_func(env);
775 int new_ofs = state->acquired_refs;
776 int id, err;
777
778 err = realloc_reference_state(state, state->acquired_refs + 1, true);
779 if (err)
780 return err;
781 id = ++env->id_gen;
782 state->refs[new_ofs].id = id;
783 state->refs[new_ofs].insn_idx = insn_idx;
638f5b90 784
fd978bf7
JS
785 return id;
786}
787
788/* release function corresponding to acquire_reference_state(). Idempotent. */
46f8bc92 789static int release_reference_state(struct bpf_func_state *state, int ptr_id)
fd978bf7
JS
790{
791 int i, last_idx;
792
fd978bf7
JS
793 last_idx = state->acquired_refs - 1;
794 for (i = 0; i < state->acquired_refs; i++) {
795 if (state->refs[i].id == ptr_id) {
796 if (last_idx && i != last_idx)
797 memcpy(&state->refs[i], &state->refs[last_idx],
798 sizeof(*state->refs));
799 memset(&state->refs[last_idx], 0, sizeof(*state->refs));
800 state->acquired_refs--;
638f5b90 801 return 0;
638f5b90 802 }
638f5b90 803 }
46f8bc92 804 return -EINVAL;
fd978bf7
JS
805}
806
807static int transfer_reference_state(struct bpf_func_state *dst,
808 struct bpf_func_state *src)
809{
810 int err = realloc_reference_state(dst, src->acquired_refs, false);
811 if (err)
812 return err;
813 err = copy_reference_state(dst, src);
814 if (err)
815 return err;
638f5b90
AS
816 return 0;
817}
818
f4d7e40a
AS
819static void free_func_state(struct bpf_func_state *state)
820{
5896351e
AS
821 if (!state)
822 return;
fd978bf7 823 kfree(state->refs);
f4d7e40a
AS
824 kfree(state->stack);
825 kfree(state);
826}
827
b5dc0163
AS
828static void clear_jmp_history(struct bpf_verifier_state *state)
829{
830 kfree(state->jmp_history);
831 state->jmp_history = NULL;
832 state->jmp_history_cnt = 0;
833}
834
1969db47
AS
835static void free_verifier_state(struct bpf_verifier_state *state,
836 bool free_self)
638f5b90 837{
f4d7e40a
AS
838 int i;
839
840 for (i = 0; i <= state->curframe; i++) {
841 free_func_state(state->frame[i]);
842 state->frame[i] = NULL;
843 }
b5dc0163 844 clear_jmp_history(state);
1969db47
AS
845 if (free_self)
846 kfree(state);
638f5b90
AS
847}
848
849/* copy verifier state from src to dst growing dst stack space
850 * when necessary to accommodate larger src stack
851 */
f4d7e40a
AS
852static int copy_func_state(struct bpf_func_state *dst,
853 const struct bpf_func_state *src)
638f5b90
AS
854{
855 int err;
856
fd978bf7
JS
857 err = realloc_func_state(dst, src->allocated_stack, src->acquired_refs,
858 false);
859 if (err)
860 return err;
861 memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
862 err = copy_reference_state(dst, src);
638f5b90
AS
863 if (err)
864 return err;
638f5b90
AS
865 return copy_stack_state(dst, src);
866}
867
f4d7e40a
AS
868static int copy_verifier_state(struct bpf_verifier_state *dst_state,
869 const struct bpf_verifier_state *src)
870{
871 struct bpf_func_state *dst;
b5dc0163 872 u32 jmp_sz = sizeof(struct bpf_idx_pair) * src->jmp_history_cnt;
f4d7e40a
AS
873 int i, err;
874
b5dc0163
AS
875 if (dst_state->jmp_history_cnt < src->jmp_history_cnt) {
876 kfree(dst_state->jmp_history);
877 dst_state->jmp_history = kmalloc(jmp_sz, GFP_USER);
878 if (!dst_state->jmp_history)
879 return -ENOMEM;
880 }
881 memcpy(dst_state->jmp_history, src->jmp_history, jmp_sz);
882 dst_state->jmp_history_cnt = src->jmp_history_cnt;
883
f4d7e40a
AS
884 /* if dst has more stack frames then src frame, free them */
885 for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
886 free_func_state(dst_state->frame[i]);
887 dst_state->frame[i] = NULL;
888 }
979d63d5 889 dst_state->speculative = src->speculative;
f4d7e40a 890 dst_state->curframe = src->curframe;
d83525ca 891 dst_state->active_spin_lock = src->active_spin_lock;
2589726d
AS
892 dst_state->branches = src->branches;
893 dst_state->parent = src->parent;
b5dc0163
AS
894 dst_state->first_insn_idx = src->first_insn_idx;
895 dst_state->last_insn_idx = src->last_insn_idx;
f4d7e40a
AS
896 for (i = 0; i <= src->curframe; i++) {
897 dst = dst_state->frame[i];
898 if (!dst) {
899 dst = kzalloc(sizeof(*dst), GFP_KERNEL);
900 if (!dst)
901 return -ENOMEM;
902 dst_state->frame[i] = dst;
903 }
904 err = copy_func_state(dst, src->frame[i]);
905 if (err)
906 return err;
907 }
908 return 0;
909}
910
2589726d
AS
911static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
912{
913 while (st) {
914 u32 br = --st->branches;
915
916 /* WARN_ON(br > 1) technically makes sense here,
917 * but see comment in push_stack(), hence:
918 */
919 WARN_ONCE((int)br < 0,
920 "BUG update_branch_counts:branches_to_explore=%d\n",
921 br);
922 if (br)
923 break;
924 st = st->parent;
925 }
926}
927
638f5b90 928static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
6f8a57cc 929 int *insn_idx, bool pop_log)
638f5b90
AS
930{
931 struct bpf_verifier_state *cur = env->cur_state;
932 struct bpf_verifier_stack_elem *elem, *head = env->head;
933 int err;
17a52670
AS
934
935 if (env->head == NULL)
638f5b90 936 return -ENOENT;
17a52670 937
638f5b90
AS
938 if (cur) {
939 err = copy_verifier_state(cur, &head->st);
940 if (err)
941 return err;
942 }
6f8a57cc
AN
943 if (pop_log)
944 bpf_vlog_reset(&env->log, head->log_pos);
638f5b90
AS
945 if (insn_idx)
946 *insn_idx = head->insn_idx;
17a52670 947 if (prev_insn_idx)
638f5b90
AS
948 *prev_insn_idx = head->prev_insn_idx;
949 elem = head->next;
1969db47 950 free_verifier_state(&head->st, false);
638f5b90 951 kfree(head);
17a52670
AS
952 env->head = elem;
953 env->stack_size--;
638f5b90 954 return 0;
17a52670
AS
955}
956
58e2af8b 957static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
979d63d5
DB
958 int insn_idx, int prev_insn_idx,
959 bool speculative)
17a52670 960{
638f5b90 961 struct bpf_verifier_state *cur = env->cur_state;
58e2af8b 962 struct bpf_verifier_stack_elem *elem;
638f5b90 963 int err;
17a52670 964
638f5b90 965 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
17a52670
AS
966 if (!elem)
967 goto err;
968
17a52670
AS
969 elem->insn_idx = insn_idx;
970 elem->prev_insn_idx = prev_insn_idx;
971 elem->next = env->head;
6f8a57cc 972 elem->log_pos = env->log.len_used;
17a52670
AS
973 env->head = elem;
974 env->stack_size++;
1969db47
AS
975 err = copy_verifier_state(&elem->st, cur);
976 if (err)
977 goto err;
979d63d5 978 elem->st.speculative |= speculative;
b285fcb7
AS
979 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
980 verbose(env, "The sequence of %d jumps is too complex.\n",
981 env->stack_size);
17a52670
AS
982 goto err;
983 }
2589726d
AS
984 if (elem->st.parent) {
985 ++elem->st.parent->branches;
986 /* WARN_ON(branches > 2) technically makes sense here,
987 * but
988 * 1. speculative states will bump 'branches' for non-branch
989 * instructions
990 * 2. is_state_visited() heuristics may decide not to create
991 * a new state for a sequence of branches and all such current
992 * and cloned states will be pointing to a single parent state
993 * which might have large 'branches' count.
994 */
995 }
17a52670
AS
996 return &elem->st;
997err:
5896351e
AS
998 free_verifier_state(env->cur_state, true);
999 env->cur_state = NULL;
17a52670 1000 /* pop all elements and return */
6f8a57cc 1001 while (!pop_stack(env, NULL, NULL, false));
17a52670
AS
1002 return NULL;
1003}
1004
1005#define CALLER_SAVED_REGS 6
1006static const int caller_saved[CALLER_SAVED_REGS] = {
1007 BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
1008};
1009
f54c7898
DB
1010static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1011 struct bpf_reg_state *reg);
f1174f77 1012
e688c3db
AS
1013/* This helper doesn't clear reg->id */
1014static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
b03c9f9f 1015{
b03c9f9f
EC
1016 reg->var_off = tnum_const(imm);
1017 reg->smin_value = (s64)imm;
1018 reg->smax_value = (s64)imm;
1019 reg->umin_value = imm;
1020 reg->umax_value = imm;
3f50f132
JF
1021
1022 reg->s32_min_value = (s32)imm;
1023 reg->s32_max_value = (s32)imm;
1024 reg->u32_min_value = (u32)imm;
1025 reg->u32_max_value = (u32)imm;
1026}
1027
e688c3db
AS
1028/* Mark the unknown part of a register (variable offset or scalar value) as
1029 * known to have the value @imm.
1030 */
1031static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1032{
1033 /* Clear id, off, and union(map_ptr, range) */
1034 memset(((u8 *)reg) + sizeof(reg->type), 0,
1035 offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
1036 ___mark_reg_known(reg, imm);
1037}
1038
3f50f132
JF
1039static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1040{
1041 reg->var_off = tnum_const_subreg(reg->var_off, imm);
1042 reg->s32_min_value = (s32)imm;
1043 reg->s32_max_value = (s32)imm;
1044 reg->u32_min_value = (u32)imm;
1045 reg->u32_max_value = (u32)imm;
b03c9f9f
EC
1046}
1047
f1174f77
EC
1048/* Mark the 'variable offset' part of a register as zero. This should be
1049 * used only on registers holding a pointer type.
1050 */
1051static void __mark_reg_known_zero(struct bpf_reg_state *reg)
a9789ef9 1052{
b03c9f9f 1053 __mark_reg_known(reg, 0);
f1174f77 1054}
a9789ef9 1055
cc2b14d5
AS
1056static void __mark_reg_const_zero(struct bpf_reg_state *reg)
1057{
1058 __mark_reg_known(reg, 0);
cc2b14d5
AS
1059 reg->type = SCALAR_VALUE;
1060}
1061
61bd5218
JK
1062static void mark_reg_known_zero(struct bpf_verifier_env *env,
1063 struct bpf_reg_state *regs, u32 regno)
f1174f77
EC
1064{
1065 if (WARN_ON(regno >= MAX_BPF_REG)) {
61bd5218 1066 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
f1174f77
EC
1067 /* Something bad happened, let's kill all regs */
1068 for (regno = 0; regno < MAX_BPF_REG; regno++)
f54c7898 1069 __mark_reg_not_init(env, regs + regno);
f1174f77
EC
1070 return;
1071 }
1072 __mark_reg_known_zero(regs + regno);
1073}
1074
de8f3a83
DB
1075static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1076{
1077 return type_is_pkt_pointer(reg->type);
1078}
1079
1080static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
1081{
1082 return reg_is_pkt_pointer(reg) ||
1083 reg->type == PTR_TO_PACKET_END;
1084}
1085
1086/* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
1087static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
1088 enum bpf_reg_type which)
1089{
1090 /* The register can already have a range from prior markings.
1091 * This is fine as long as it hasn't been advanced from its
1092 * origin.
1093 */
1094 return reg->type == which &&
1095 reg->id == 0 &&
1096 reg->off == 0 &&
1097 tnum_equals_const(reg->var_off, 0);
1098}
1099
3f50f132
JF
1100/* Reset the min/max bounds of a register */
1101static void __mark_reg_unbounded(struct bpf_reg_state *reg)
1102{
1103 reg->smin_value = S64_MIN;
1104 reg->smax_value = S64_MAX;
1105 reg->umin_value = 0;
1106 reg->umax_value = U64_MAX;
1107
1108 reg->s32_min_value = S32_MIN;
1109 reg->s32_max_value = S32_MAX;
1110 reg->u32_min_value = 0;
1111 reg->u32_max_value = U32_MAX;
1112}
1113
1114static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
1115{
1116 reg->smin_value = S64_MIN;
1117 reg->smax_value = S64_MAX;
1118 reg->umin_value = 0;
1119 reg->umax_value = U64_MAX;
1120}
1121
1122static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
1123{
1124 reg->s32_min_value = S32_MIN;
1125 reg->s32_max_value = S32_MAX;
1126 reg->u32_min_value = 0;
1127 reg->u32_max_value = U32_MAX;
1128}
1129
1130static void __update_reg32_bounds(struct bpf_reg_state *reg)
1131{
1132 struct tnum var32_off = tnum_subreg(reg->var_off);
1133
1134 /* min signed is max(sign bit) | min(other bits) */
1135 reg->s32_min_value = max_t(s32, reg->s32_min_value,
1136 var32_off.value | (var32_off.mask & S32_MIN));
1137 /* max signed is min(sign bit) | max(other bits) */
1138 reg->s32_max_value = min_t(s32, reg->s32_max_value,
1139 var32_off.value | (var32_off.mask & S32_MAX));
1140 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
1141 reg->u32_max_value = min(reg->u32_max_value,
1142 (u32)(var32_off.value | var32_off.mask));
1143}
1144
1145static void __update_reg64_bounds(struct bpf_reg_state *reg)
b03c9f9f
EC
1146{
1147 /* min signed is max(sign bit) | min(other bits) */
1148 reg->smin_value = max_t(s64, reg->smin_value,
1149 reg->var_off.value | (reg->var_off.mask & S64_MIN));
1150 /* max signed is min(sign bit) | max(other bits) */
1151 reg->smax_value = min_t(s64, reg->smax_value,
1152 reg->var_off.value | (reg->var_off.mask & S64_MAX));
1153 reg->umin_value = max(reg->umin_value, reg->var_off.value);
1154 reg->umax_value = min(reg->umax_value,
1155 reg->var_off.value | reg->var_off.mask);
1156}
1157
3f50f132
JF
1158static void __update_reg_bounds(struct bpf_reg_state *reg)
1159{
1160 __update_reg32_bounds(reg);
1161 __update_reg64_bounds(reg);
1162}
1163
b03c9f9f 1164/* Uses signed min/max values to inform unsigned, and vice-versa */
3f50f132
JF
1165static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
1166{
1167 /* Learn sign from signed bounds.
1168 * If we cannot cross the sign boundary, then signed and unsigned bounds
1169 * are the same, so combine. This works even in the negative case, e.g.
1170 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1171 */
1172 if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) {
1173 reg->s32_min_value = reg->u32_min_value =
1174 max_t(u32, reg->s32_min_value, reg->u32_min_value);
1175 reg->s32_max_value = reg->u32_max_value =
1176 min_t(u32, reg->s32_max_value, reg->u32_max_value);
1177 return;
1178 }
1179 /* Learn sign from unsigned bounds. Signed bounds cross the sign
1180 * boundary, so we must be careful.
1181 */
1182 if ((s32)reg->u32_max_value >= 0) {
1183 /* Positive. We can't learn anything from the smin, but smax
1184 * is positive, hence safe.
1185 */
1186 reg->s32_min_value = reg->u32_min_value;
1187 reg->s32_max_value = reg->u32_max_value =
1188 min_t(u32, reg->s32_max_value, reg->u32_max_value);
1189 } else if ((s32)reg->u32_min_value < 0) {
1190 /* Negative. We can't learn anything from the smax, but smin
1191 * is negative, hence safe.
1192 */
1193 reg->s32_min_value = reg->u32_min_value =
1194 max_t(u32, reg->s32_min_value, reg->u32_min_value);
1195 reg->s32_max_value = reg->u32_max_value;
1196 }
1197}
1198
1199static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
b03c9f9f
EC
1200{
1201 /* Learn sign from signed bounds.
1202 * If we cannot cross the sign boundary, then signed and unsigned bounds
1203 * are the same, so combine. This works even in the negative case, e.g.
1204 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1205 */
1206 if (reg->smin_value >= 0 || reg->smax_value < 0) {
1207 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1208 reg->umin_value);
1209 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1210 reg->umax_value);
1211 return;
1212 }
1213 /* Learn sign from unsigned bounds. Signed bounds cross the sign
1214 * boundary, so we must be careful.
1215 */
1216 if ((s64)reg->umax_value >= 0) {
1217 /* Positive. We can't learn anything from the smin, but smax
1218 * is positive, hence safe.
1219 */
1220 reg->smin_value = reg->umin_value;
1221 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1222 reg->umax_value);
1223 } else if ((s64)reg->umin_value < 0) {
1224 /* Negative. We can't learn anything from the smax, but smin
1225 * is negative, hence safe.
1226 */
1227 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1228 reg->umin_value);
1229 reg->smax_value = reg->umax_value;
1230 }
1231}
1232
3f50f132
JF
1233static void __reg_deduce_bounds(struct bpf_reg_state *reg)
1234{
1235 __reg32_deduce_bounds(reg);
1236 __reg64_deduce_bounds(reg);
1237}
1238
b03c9f9f
EC
1239/* Attempts to improve var_off based on unsigned min/max information */
1240static void __reg_bound_offset(struct bpf_reg_state *reg)
1241{
3f50f132
JF
1242 struct tnum var64_off = tnum_intersect(reg->var_off,
1243 tnum_range(reg->umin_value,
1244 reg->umax_value));
1245 struct tnum var32_off = tnum_intersect(tnum_subreg(reg->var_off),
1246 tnum_range(reg->u32_min_value,
1247 reg->u32_max_value));
1248
1249 reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
b03c9f9f
EC
1250}
1251
3f50f132 1252static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
b03c9f9f 1253{
3f50f132
JF
1254 reg->umin_value = reg->u32_min_value;
1255 reg->umax_value = reg->u32_max_value;
1256 /* Attempt to pull 32-bit signed bounds into 64-bit bounds
1257 * but must be positive otherwise set to worse case bounds
1258 * and refine later from tnum.
1259 */
3a71dc36 1260 if (reg->s32_min_value >= 0 && reg->s32_max_value >= 0)
3f50f132
JF
1261 reg->smax_value = reg->s32_max_value;
1262 else
1263 reg->smax_value = U32_MAX;
3a71dc36
JF
1264 if (reg->s32_min_value >= 0)
1265 reg->smin_value = reg->s32_min_value;
1266 else
1267 reg->smin_value = 0;
3f50f132
JF
1268}
1269
1270static void __reg_combine_32_into_64(struct bpf_reg_state *reg)
1271{
1272 /* special case when 64-bit register has upper 32-bit register
1273 * zeroed. Typically happens after zext or <<32, >>32 sequence
1274 * allowing us to use 32-bit bounds directly,
1275 */
1276 if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) {
1277 __reg_assign_32_into_64(reg);
1278 } else {
1279 /* Otherwise the best we can do is push lower 32bit known and
1280 * unknown bits into register (var_off set from jmp logic)
1281 * then learn as much as possible from the 64-bit tnum
1282 * known and unknown bits. The previous smin/smax bounds are
1283 * invalid here because of jmp32 compare so mark them unknown
1284 * so they do not impact tnum bounds calculation.
1285 */
1286 __mark_reg64_unbounded(reg);
1287 __update_reg_bounds(reg);
1288 }
1289
1290 /* Intersecting with the old var_off might have improved our bounds
1291 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1292 * then new var_off is (0; 0x7f...fc) which improves our umax.
1293 */
1294 __reg_deduce_bounds(reg);
1295 __reg_bound_offset(reg);
1296 __update_reg_bounds(reg);
1297}
1298
1299static bool __reg64_bound_s32(s64 a)
1300{
1301 if (a > S32_MIN && a < S32_MAX)
1302 return true;
1303 return false;
1304}
1305
1306static bool __reg64_bound_u32(u64 a)
1307{
1308 if (a > U32_MIN && a < U32_MAX)
1309 return true;
1310 return false;
1311}
1312
1313static void __reg_combine_64_into_32(struct bpf_reg_state *reg)
1314{
1315 __mark_reg32_unbounded(reg);
1316
1317 if (__reg64_bound_s32(reg->smin_value))
1318 reg->s32_min_value = (s32)reg->smin_value;
1319 if (__reg64_bound_s32(reg->smax_value))
1320 reg->s32_max_value = (s32)reg->smax_value;
1321 if (__reg64_bound_u32(reg->umin_value))
1322 reg->u32_min_value = (u32)reg->umin_value;
1323 if (__reg64_bound_u32(reg->umax_value))
1324 reg->u32_max_value = (u32)reg->umax_value;
1325
1326 /* Intersecting with the old var_off might have improved our bounds
1327 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1328 * then new var_off is (0; 0x7f...fc) which improves our umax.
1329 */
1330 __reg_deduce_bounds(reg);
1331 __reg_bound_offset(reg);
1332 __update_reg_bounds(reg);
b03c9f9f
EC
1333}
1334
f1174f77 1335/* Mark a register as having a completely unknown (scalar) value. */
f54c7898
DB
1336static void __mark_reg_unknown(const struct bpf_verifier_env *env,
1337 struct bpf_reg_state *reg)
f1174f77 1338{
a9c676bc
AS
1339 /*
1340 * Clear type, id, off, and union(map_ptr, range) and
1341 * padding between 'type' and union
1342 */
1343 memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
f1174f77 1344 reg->type = SCALAR_VALUE;
f1174f77 1345 reg->var_off = tnum_unknown;
f4d7e40a 1346 reg->frameno = 0;
2c78ee89 1347 reg->precise = env->subprog_cnt > 1 || !env->bpf_capable;
b03c9f9f 1348 __mark_reg_unbounded(reg);
f1174f77
EC
1349}
1350
61bd5218
JK
1351static void mark_reg_unknown(struct bpf_verifier_env *env,
1352 struct bpf_reg_state *regs, u32 regno)
f1174f77
EC
1353{
1354 if (WARN_ON(regno >= MAX_BPF_REG)) {
61bd5218 1355 verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
19ceb417
AS
1356 /* Something bad happened, let's kill all regs except FP */
1357 for (regno = 0; regno < BPF_REG_FP; regno++)
f54c7898 1358 __mark_reg_not_init(env, regs + regno);
f1174f77
EC
1359 return;
1360 }
f54c7898 1361 __mark_reg_unknown(env, regs + regno);
f1174f77
EC
1362}
1363
f54c7898
DB
1364static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1365 struct bpf_reg_state *reg)
f1174f77 1366{
f54c7898 1367 __mark_reg_unknown(env, reg);
f1174f77
EC
1368 reg->type = NOT_INIT;
1369}
1370
61bd5218
JK
1371static void mark_reg_not_init(struct bpf_verifier_env *env,
1372 struct bpf_reg_state *regs, u32 regno)
f1174f77
EC
1373{
1374 if (WARN_ON(regno >= MAX_BPF_REG)) {
61bd5218 1375 verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
19ceb417
AS
1376 /* Something bad happened, let's kill all regs except FP */
1377 for (regno = 0; regno < BPF_REG_FP; regno++)
f54c7898 1378 __mark_reg_not_init(env, regs + regno);
f1174f77
EC
1379 return;
1380 }
f54c7898 1381 __mark_reg_not_init(env, regs + regno);
a9789ef9
DB
1382}
1383
41c48f3a
AI
1384static void mark_btf_ld_reg(struct bpf_verifier_env *env,
1385 struct bpf_reg_state *regs, u32 regno,
1386 enum bpf_reg_type reg_type, u32 btf_id)
1387{
1388 if (reg_type == SCALAR_VALUE) {
1389 mark_reg_unknown(env, regs, regno);
1390 return;
1391 }
1392 mark_reg_known_zero(env, regs, regno);
1393 regs[regno].type = PTR_TO_BTF_ID;
1394 regs[regno].btf_id = btf_id;
1395}
1396
5327ed3d 1397#define DEF_NOT_SUBREG (0)
61bd5218 1398static void init_reg_state(struct bpf_verifier_env *env,
f4d7e40a 1399 struct bpf_func_state *state)
17a52670 1400{
f4d7e40a 1401 struct bpf_reg_state *regs = state->regs;
17a52670
AS
1402 int i;
1403
dc503a8a 1404 for (i = 0; i < MAX_BPF_REG; i++) {
61bd5218 1405 mark_reg_not_init(env, regs, i);
dc503a8a 1406 regs[i].live = REG_LIVE_NONE;
679c782d 1407 regs[i].parent = NULL;
5327ed3d 1408 regs[i].subreg_def = DEF_NOT_SUBREG;
dc503a8a 1409 }
17a52670
AS
1410
1411 /* frame pointer */
f1174f77 1412 regs[BPF_REG_FP].type = PTR_TO_STACK;
61bd5218 1413 mark_reg_known_zero(env, regs, BPF_REG_FP);
f4d7e40a 1414 regs[BPF_REG_FP].frameno = state->frameno;
6760bf2d
DB
1415}
1416
f4d7e40a
AS
1417#define BPF_MAIN_FUNC (-1)
1418static void init_func_state(struct bpf_verifier_env *env,
1419 struct bpf_func_state *state,
1420 int callsite, int frameno, int subprogno)
1421{
1422 state->callsite = callsite;
1423 state->frameno = frameno;
1424 state->subprogno = subprogno;
1425 init_reg_state(env, state);
1426}
1427
17a52670
AS
1428enum reg_arg_type {
1429 SRC_OP, /* register is used as source operand */
1430 DST_OP, /* register is used as destination operand */
1431 DST_OP_NO_MARK /* same as above, check only, don't mark */
1432};
1433
cc8b0b92
AS
1434static int cmp_subprogs(const void *a, const void *b)
1435{
9c8105bd
JW
1436 return ((struct bpf_subprog_info *)a)->start -
1437 ((struct bpf_subprog_info *)b)->start;
cc8b0b92
AS
1438}
1439
1440static int find_subprog(struct bpf_verifier_env *env, int off)
1441{
9c8105bd 1442 struct bpf_subprog_info *p;
cc8b0b92 1443
9c8105bd
JW
1444 p = bsearch(&off, env->subprog_info, env->subprog_cnt,
1445 sizeof(env->subprog_info[0]), cmp_subprogs);
cc8b0b92
AS
1446 if (!p)
1447 return -ENOENT;
9c8105bd 1448 return p - env->subprog_info;
cc8b0b92
AS
1449
1450}
1451
1452static int add_subprog(struct bpf_verifier_env *env, int off)
1453{
1454 int insn_cnt = env->prog->len;
1455 int ret;
1456
1457 if (off >= insn_cnt || off < 0) {
1458 verbose(env, "call to invalid destination\n");
1459 return -EINVAL;
1460 }
1461 ret = find_subprog(env, off);
1462 if (ret >= 0)
1463 return 0;
4cb3d99c 1464 if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
cc8b0b92
AS
1465 verbose(env, "too many subprograms\n");
1466 return -E2BIG;
1467 }
9c8105bd
JW
1468 env->subprog_info[env->subprog_cnt++].start = off;
1469 sort(env->subprog_info, env->subprog_cnt,
1470 sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
cc8b0b92
AS
1471 return 0;
1472}
1473
1474static int check_subprogs(struct bpf_verifier_env *env)
1475{
1476 int i, ret, subprog_start, subprog_end, off, cur_subprog = 0;
9c8105bd 1477 struct bpf_subprog_info *subprog = env->subprog_info;
cc8b0b92
AS
1478 struct bpf_insn *insn = env->prog->insnsi;
1479 int insn_cnt = env->prog->len;
1480
f910cefa
JW
1481 /* Add entry function. */
1482 ret = add_subprog(env, 0);
1483 if (ret < 0)
1484 return ret;
1485
cc8b0b92
AS
1486 /* determine subprog starts. The end is one before the next starts */
1487 for (i = 0; i < insn_cnt; i++) {
1488 if (insn[i].code != (BPF_JMP | BPF_CALL))
1489 continue;
1490 if (insn[i].src_reg != BPF_PSEUDO_CALL)
1491 continue;
2c78ee89
AS
1492 if (!env->bpf_capable) {
1493 verbose(env,
1494 "function calls to other bpf functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
cc8b0b92
AS
1495 return -EPERM;
1496 }
cc8b0b92
AS
1497 ret = add_subprog(env, i + insn[i].imm + 1);
1498 if (ret < 0)
1499 return ret;
1500 }
1501
4cb3d99c
JW
1502 /* Add a fake 'exit' subprog which could simplify subprog iteration
1503 * logic. 'subprog_cnt' should not be increased.
1504 */
1505 subprog[env->subprog_cnt].start = insn_cnt;
1506
06ee7115 1507 if (env->log.level & BPF_LOG_LEVEL2)
cc8b0b92 1508 for (i = 0; i < env->subprog_cnt; i++)
9c8105bd 1509 verbose(env, "func#%d @%d\n", i, subprog[i].start);
cc8b0b92
AS
1510
1511 /* now check that all jumps are within the same subprog */
4cb3d99c
JW
1512 subprog_start = subprog[cur_subprog].start;
1513 subprog_end = subprog[cur_subprog + 1].start;
cc8b0b92
AS
1514 for (i = 0; i < insn_cnt; i++) {
1515 u8 code = insn[i].code;
1516
7f6e4312
MF
1517 if (code == (BPF_JMP | BPF_CALL) &&
1518 insn[i].imm == BPF_FUNC_tail_call &&
1519 insn[i].src_reg != BPF_PSEUDO_CALL)
1520 subprog[cur_subprog].has_tail_call = true;
09b28d76
AS
1521 if (BPF_CLASS(code) == BPF_LD &&
1522 (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
1523 subprog[cur_subprog].has_ld_abs = true;
092ed096 1524 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
cc8b0b92
AS
1525 goto next;
1526 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
1527 goto next;
1528 off = i + insn[i].off + 1;
1529 if (off < subprog_start || off >= subprog_end) {
1530 verbose(env, "jump out of range from insn %d to %d\n", i, off);
1531 return -EINVAL;
1532 }
1533next:
1534 if (i == subprog_end - 1) {
1535 /* to avoid fall-through from one subprog into another
1536 * the last insn of the subprog should be either exit
1537 * or unconditional jump back
1538 */
1539 if (code != (BPF_JMP | BPF_EXIT) &&
1540 code != (BPF_JMP | BPF_JA)) {
1541 verbose(env, "last insn is not an exit or jmp\n");
1542 return -EINVAL;
1543 }
1544 subprog_start = subprog_end;
4cb3d99c
JW
1545 cur_subprog++;
1546 if (cur_subprog < env->subprog_cnt)
9c8105bd 1547 subprog_end = subprog[cur_subprog + 1].start;
cc8b0b92
AS
1548 }
1549 }
1550 return 0;
1551}
1552
679c782d
EC
1553/* Parentage chain of this register (or stack slot) should take care of all
1554 * issues like callee-saved registers, stack slot allocation time, etc.
1555 */
f4d7e40a 1556static int mark_reg_read(struct bpf_verifier_env *env,
679c782d 1557 const struct bpf_reg_state *state,
5327ed3d 1558 struct bpf_reg_state *parent, u8 flag)
f4d7e40a
AS
1559{
1560 bool writes = parent == state->parent; /* Observe write marks */
06ee7115 1561 int cnt = 0;
dc503a8a
EC
1562
1563 while (parent) {
1564 /* if read wasn't screened by an earlier write ... */
679c782d 1565 if (writes && state->live & REG_LIVE_WRITTEN)
dc503a8a 1566 break;
9242b5f5
AS
1567 if (parent->live & REG_LIVE_DONE) {
1568 verbose(env, "verifier BUG type %s var_off %lld off %d\n",
1569 reg_type_str[parent->type],
1570 parent->var_off.value, parent->off);
1571 return -EFAULT;
1572 }
5327ed3d
JW
1573 /* The first condition is more likely to be true than the
1574 * second, checked it first.
1575 */
1576 if ((parent->live & REG_LIVE_READ) == flag ||
1577 parent->live & REG_LIVE_READ64)
25af32da
AS
1578 /* The parentage chain never changes and
1579 * this parent was already marked as LIVE_READ.
1580 * There is no need to keep walking the chain again and
1581 * keep re-marking all parents as LIVE_READ.
1582 * This case happens when the same register is read
1583 * multiple times without writes into it in-between.
5327ed3d
JW
1584 * Also, if parent has the stronger REG_LIVE_READ64 set,
1585 * then no need to set the weak REG_LIVE_READ32.
25af32da
AS
1586 */
1587 break;
dc503a8a 1588 /* ... then we depend on parent's value */
5327ed3d
JW
1589 parent->live |= flag;
1590 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
1591 if (flag == REG_LIVE_READ64)
1592 parent->live &= ~REG_LIVE_READ32;
dc503a8a
EC
1593 state = parent;
1594 parent = state->parent;
f4d7e40a 1595 writes = true;
06ee7115 1596 cnt++;
dc503a8a 1597 }
06ee7115
AS
1598
1599 if (env->longest_mark_read_walk < cnt)
1600 env->longest_mark_read_walk = cnt;
f4d7e40a 1601 return 0;
dc503a8a
EC
1602}
1603
5327ed3d
JW
1604/* This function is supposed to be used by the following 32-bit optimization
1605 * code only. It returns TRUE if the source or destination register operates
1606 * on 64-bit, otherwise return FALSE.
1607 */
1608static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
1609 u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
1610{
1611 u8 code, class, op;
1612
1613 code = insn->code;
1614 class = BPF_CLASS(code);
1615 op = BPF_OP(code);
1616 if (class == BPF_JMP) {
1617 /* BPF_EXIT for "main" will reach here. Return TRUE
1618 * conservatively.
1619 */
1620 if (op == BPF_EXIT)
1621 return true;
1622 if (op == BPF_CALL) {
1623 /* BPF to BPF call will reach here because of marking
1624 * caller saved clobber with DST_OP_NO_MARK for which we
1625 * don't care the register def because they are anyway
1626 * marked as NOT_INIT already.
1627 */
1628 if (insn->src_reg == BPF_PSEUDO_CALL)
1629 return false;
1630 /* Helper call will reach here because of arg type
1631 * check, conservatively return TRUE.
1632 */
1633 if (t == SRC_OP)
1634 return true;
1635
1636 return false;
1637 }
1638 }
1639
1640 if (class == BPF_ALU64 || class == BPF_JMP ||
1641 /* BPF_END always use BPF_ALU class. */
1642 (class == BPF_ALU && op == BPF_END && insn->imm == 64))
1643 return true;
1644
1645 if (class == BPF_ALU || class == BPF_JMP32)
1646 return false;
1647
1648 if (class == BPF_LDX) {
1649 if (t != SRC_OP)
1650 return BPF_SIZE(code) == BPF_DW;
1651 /* LDX source must be ptr. */
1652 return true;
1653 }
1654
1655 if (class == BPF_STX) {
1656 if (reg->type != SCALAR_VALUE)
1657 return true;
1658 return BPF_SIZE(code) == BPF_DW;
1659 }
1660
1661 if (class == BPF_LD) {
1662 u8 mode = BPF_MODE(code);
1663
1664 /* LD_IMM64 */
1665 if (mode == BPF_IMM)
1666 return true;
1667
1668 /* Both LD_IND and LD_ABS return 32-bit data. */
1669 if (t != SRC_OP)
1670 return false;
1671
1672 /* Implicit ctx ptr. */
1673 if (regno == BPF_REG_6)
1674 return true;
1675
1676 /* Explicit source could be any width. */
1677 return true;
1678 }
1679
1680 if (class == BPF_ST)
1681 /* The only source register for BPF_ST is a ptr. */
1682 return true;
1683
1684 /* Conservatively return true at default. */
1685 return true;
1686}
1687
b325fbca
JW
1688/* Return TRUE if INSN doesn't have explicit value define. */
1689static bool insn_no_def(struct bpf_insn *insn)
1690{
1691 u8 class = BPF_CLASS(insn->code);
1692
1693 return (class == BPF_JMP || class == BPF_JMP32 ||
1694 class == BPF_STX || class == BPF_ST);
1695}
1696
1697/* Return TRUE if INSN has defined any 32-bit value explicitly. */
1698static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
1699{
1700 if (insn_no_def(insn))
1701 return false;
1702
1703 return !is_reg64(env, insn, insn->dst_reg, NULL, DST_OP);
1704}
1705
5327ed3d
JW
1706static void mark_insn_zext(struct bpf_verifier_env *env,
1707 struct bpf_reg_state *reg)
1708{
1709 s32 def_idx = reg->subreg_def;
1710
1711 if (def_idx == DEF_NOT_SUBREG)
1712 return;
1713
1714 env->insn_aux_data[def_idx - 1].zext_dst = true;
1715 /* The dst will be zero extended, so won't be sub-register anymore. */
1716 reg->subreg_def = DEF_NOT_SUBREG;
1717}
1718
dc503a8a 1719static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
17a52670
AS
1720 enum reg_arg_type t)
1721{
f4d7e40a
AS
1722 struct bpf_verifier_state *vstate = env->cur_state;
1723 struct bpf_func_state *state = vstate->frame[vstate->curframe];
5327ed3d 1724 struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
c342dc10 1725 struct bpf_reg_state *reg, *regs = state->regs;
5327ed3d 1726 bool rw64;
dc503a8a 1727
17a52670 1728 if (regno >= MAX_BPF_REG) {
61bd5218 1729 verbose(env, "R%d is invalid\n", regno);
17a52670
AS
1730 return -EINVAL;
1731 }
1732
c342dc10 1733 reg = &regs[regno];
5327ed3d 1734 rw64 = is_reg64(env, insn, regno, reg, t);
17a52670
AS
1735 if (t == SRC_OP) {
1736 /* check whether register used as source operand can be read */
c342dc10 1737 if (reg->type == NOT_INIT) {
61bd5218 1738 verbose(env, "R%d !read_ok\n", regno);
17a52670
AS
1739 return -EACCES;
1740 }
679c782d 1741 /* We don't need to worry about FP liveness because it's read-only */
c342dc10
JW
1742 if (regno == BPF_REG_FP)
1743 return 0;
1744
5327ed3d
JW
1745 if (rw64)
1746 mark_insn_zext(env, reg);
1747
1748 return mark_reg_read(env, reg, reg->parent,
1749 rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
17a52670
AS
1750 } else {
1751 /* check whether register used as dest operand can be written to */
1752 if (regno == BPF_REG_FP) {
61bd5218 1753 verbose(env, "frame pointer is read only\n");
17a52670
AS
1754 return -EACCES;
1755 }
c342dc10 1756 reg->live |= REG_LIVE_WRITTEN;
5327ed3d 1757 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
17a52670 1758 if (t == DST_OP)
61bd5218 1759 mark_reg_unknown(env, regs, regno);
17a52670
AS
1760 }
1761 return 0;
1762}
1763
b5dc0163
AS
1764/* for any branch, call, exit record the history of jmps in the given state */
1765static int push_jmp_history(struct bpf_verifier_env *env,
1766 struct bpf_verifier_state *cur)
1767{
1768 u32 cnt = cur->jmp_history_cnt;
1769 struct bpf_idx_pair *p;
1770
1771 cnt++;
1772 p = krealloc(cur->jmp_history, cnt * sizeof(*p), GFP_USER);
1773 if (!p)
1774 return -ENOMEM;
1775 p[cnt - 1].idx = env->insn_idx;
1776 p[cnt - 1].prev_idx = env->prev_insn_idx;
1777 cur->jmp_history = p;
1778 cur->jmp_history_cnt = cnt;
1779 return 0;
1780}
1781
1782/* Backtrack one insn at a time. If idx is not at the top of recorded
1783 * history then previous instruction came from straight line execution.
1784 */
1785static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
1786 u32 *history)
1787{
1788 u32 cnt = *history;
1789
1790 if (cnt && st->jmp_history[cnt - 1].idx == i) {
1791 i = st->jmp_history[cnt - 1].prev_idx;
1792 (*history)--;
1793 } else {
1794 i--;
1795 }
1796 return i;
1797}
1798
1799/* For given verifier state backtrack_insn() is called from the last insn to
1800 * the first insn. Its purpose is to compute a bitmask of registers and
1801 * stack slots that needs precision in the parent verifier state.
1802 */
1803static int backtrack_insn(struct bpf_verifier_env *env, int idx,
1804 u32 *reg_mask, u64 *stack_mask)
1805{
1806 const struct bpf_insn_cbs cbs = {
1807 .cb_print = verbose,
1808 .private_data = env,
1809 };
1810 struct bpf_insn *insn = env->prog->insnsi + idx;
1811 u8 class = BPF_CLASS(insn->code);
1812 u8 opcode = BPF_OP(insn->code);
1813 u8 mode = BPF_MODE(insn->code);
1814 u32 dreg = 1u << insn->dst_reg;
1815 u32 sreg = 1u << insn->src_reg;
1816 u32 spi;
1817
1818 if (insn->code == 0)
1819 return 0;
1820 if (env->log.level & BPF_LOG_LEVEL) {
1821 verbose(env, "regs=%x stack=%llx before ", *reg_mask, *stack_mask);
1822 verbose(env, "%d: ", idx);
1823 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
1824 }
1825
1826 if (class == BPF_ALU || class == BPF_ALU64) {
1827 if (!(*reg_mask & dreg))
1828 return 0;
1829 if (opcode == BPF_MOV) {
1830 if (BPF_SRC(insn->code) == BPF_X) {
1831 /* dreg = sreg
1832 * dreg needs precision after this insn
1833 * sreg needs precision before this insn
1834 */
1835 *reg_mask &= ~dreg;
1836 *reg_mask |= sreg;
1837 } else {
1838 /* dreg = K
1839 * dreg needs precision after this insn.
1840 * Corresponding register is already marked
1841 * as precise=true in this verifier state.
1842 * No further markings in parent are necessary
1843 */
1844 *reg_mask &= ~dreg;
1845 }
1846 } else {
1847 if (BPF_SRC(insn->code) == BPF_X) {
1848 /* dreg += sreg
1849 * both dreg and sreg need precision
1850 * before this insn
1851 */
1852 *reg_mask |= sreg;
1853 } /* else dreg += K
1854 * dreg still needs precision before this insn
1855 */
1856 }
1857 } else if (class == BPF_LDX) {
1858 if (!(*reg_mask & dreg))
1859 return 0;
1860 *reg_mask &= ~dreg;
1861
1862 /* scalars can only be spilled into stack w/o losing precision.
1863 * Load from any other memory can be zero extended.
1864 * The desire to keep that precision is already indicated
1865 * by 'precise' mark in corresponding register of this state.
1866 * No further tracking necessary.
1867 */
1868 if (insn->src_reg != BPF_REG_FP)
1869 return 0;
1870 if (BPF_SIZE(insn->code) != BPF_DW)
1871 return 0;
1872
1873 /* dreg = *(u64 *)[fp - off] was a fill from the stack.
1874 * that [fp - off] slot contains scalar that needs to be
1875 * tracked with precision
1876 */
1877 spi = (-insn->off - 1) / BPF_REG_SIZE;
1878 if (spi >= 64) {
1879 verbose(env, "BUG spi %d\n", spi);
1880 WARN_ONCE(1, "verifier backtracking bug");
1881 return -EFAULT;
1882 }
1883 *stack_mask |= 1ull << spi;
b3b50f05 1884 } else if (class == BPF_STX || class == BPF_ST) {
b5dc0163 1885 if (*reg_mask & dreg)
b3b50f05 1886 /* stx & st shouldn't be using _scalar_ dst_reg
b5dc0163
AS
1887 * to access memory. It means backtracking
1888 * encountered a case of pointer subtraction.
1889 */
1890 return -ENOTSUPP;
1891 /* scalars can only be spilled into stack */
1892 if (insn->dst_reg != BPF_REG_FP)
1893 return 0;
1894 if (BPF_SIZE(insn->code) != BPF_DW)
1895 return 0;
1896 spi = (-insn->off - 1) / BPF_REG_SIZE;
1897 if (spi >= 64) {
1898 verbose(env, "BUG spi %d\n", spi);
1899 WARN_ONCE(1, "verifier backtracking bug");
1900 return -EFAULT;
1901 }
1902 if (!(*stack_mask & (1ull << spi)))
1903 return 0;
1904 *stack_mask &= ~(1ull << spi);
b3b50f05
AN
1905 if (class == BPF_STX)
1906 *reg_mask |= sreg;
b5dc0163
AS
1907 } else if (class == BPF_JMP || class == BPF_JMP32) {
1908 if (opcode == BPF_CALL) {
1909 if (insn->src_reg == BPF_PSEUDO_CALL)
1910 return -ENOTSUPP;
1911 /* regular helper call sets R0 */
1912 *reg_mask &= ~1;
1913 if (*reg_mask & 0x3f) {
1914 /* if backtracing was looking for registers R1-R5
1915 * they should have been found already.
1916 */
1917 verbose(env, "BUG regs %x\n", *reg_mask);
1918 WARN_ONCE(1, "verifier backtracking bug");
1919 return -EFAULT;
1920 }
1921 } else if (opcode == BPF_EXIT) {
1922 return -ENOTSUPP;
1923 }
1924 } else if (class == BPF_LD) {
1925 if (!(*reg_mask & dreg))
1926 return 0;
1927 *reg_mask &= ~dreg;
1928 /* It's ld_imm64 or ld_abs or ld_ind.
1929 * For ld_imm64 no further tracking of precision
1930 * into parent is necessary
1931 */
1932 if (mode == BPF_IND || mode == BPF_ABS)
1933 /* to be analyzed */
1934 return -ENOTSUPP;
b5dc0163
AS
1935 }
1936 return 0;
1937}
1938
1939/* the scalar precision tracking algorithm:
1940 * . at the start all registers have precise=false.
1941 * . scalar ranges are tracked as normal through alu and jmp insns.
1942 * . once precise value of the scalar register is used in:
1943 * . ptr + scalar alu
1944 * . if (scalar cond K|scalar)
1945 * . helper_call(.., scalar, ...) where ARG_CONST is expected
1946 * backtrack through the verifier states and mark all registers and
1947 * stack slots with spilled constants that these scalar regisers
1948 * should be precise.
1949 * . during state pruning two registers (or spilled stack slots)
1950 * are equivalent if both are not precise.
1951 *
1952 * Note the verifier cannot simply walk register parentage chain,
1953 * since many different registers and stack slots could have been
1954 * used to compute single precise scalar.
1955 *
1956 * The approach of starting with precise=true for all registers and then
1957 * backtrack to mark a register as not precise when the verifier detects
1958 * that program doesn't care about specific value (e.g., when helper
1959 * takes register as ARG_ANYTHING parameter) is not safe.
1960 *
1961 * It's ok to walk single parentage chain of the verifier states.
1962 * It's possible that this backtracking will go all the way till 1st insn.
1963 * All other branches will be explored for needing precision later.
1964 *
1965 * The backtracking needs to deal with cases like:
1966 * 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)
1967 * r9 -= r8
1968 * r5 = r9
1969 * if r5 > 0x79f goto pc+7
1970 * R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
1971 * r5 += 1
1972 * ...
1973 * call bpf_perf_event_output#25
1974 * where .arg5_type = ARG_CONST_SIZE_OR_ZERO
1975 *
1976 * and this case:
1977 * r6 = 1
1978 * call foo // uses callee's r6 inside to compute r0
1979 * r0 += r6
1980 * if r0 == 0 goto
1981 *
1982 * to track above reg_mask/stack_mask needs to be independent for each frame.
1983 *
1984 * Also if parent's curframe > frame where backtracking started,
1985 * the verifier need to mark registers in both frames, otherwise callees
1986 * may incorrectly prune callers. This is similar to
1987 * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
1988 *
1989 * For now backtracking falls back into conservative marking.
1990 */
1991static void mark_all_scalars_precise(struct bpf_verifier_env *env,
1992 struct bpf_verifier_state *st)
1993{
1994 struct bpf_func_state *func;
1995 struct bpf_reg_state *reg;
1996 int i, j;
1997
1998 /* big hammer: mark all scalars precise in this path.
1999 * pop_stack may still get !precise scalars.
2000 */
2001 for (; st; st = st->parent)
2002 for (i = 0; i <= st->curframe; i++) {
2003 func = st->frame[i];
2004 for (j = 0; j < BPF_REG_FP; j++) {
2005 reg = &func->regs[j];
2006 if (reg->type != SCALAR_VALUE)
2007 continue;
2008 reg->precise = true;
2009 }
2010 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
2011 if (func->stack[j].slot_type[0] != STACK_SPILL)
2012 continue;
2013 reg = &func->stack[j].spilled_ptr;
2014 if (reg->type != SCALAR_VALUE)
2015 continue;
2016 reg->precise = true;
2017 }
2018 }
2019}
2020
a3ce685d
AS
2021static int __mark_chain_precision(struct bpf_verifier_env *env, int regno,
2022 int spi)
b5dc0163
AS
2023{
2024 struct bpf_verifier_state *st = env->cur_state;
2025 int first_idx = st->first_insn_idx;
2026 int last_idx = env->insn_idx;
2027 struct bpf_func_state *func;
2028 struct bpf_reg_state *reg;
a3ce685d
AS
2029 u32 reg_mask = regno >= 0 ? 1u << regno : 0;
2030 u64 stack_mask = spi >= 0 ? 1ull << spi : 0;
b5dc0163 2031 bool skip_first = true;
a3ce685d 2032 bool new_marks = false;
b5dc0163
AS
2033 int i, err;
2034
2c78ee89 2035 if (!env->bpf_capable)
b5dc0163
AS
2036 return 0;
2037
2038 func = st->frame[st->curframe];
a3ce685d
AS
2039 if (regno >= 0) {
2040 reg = &func->regs[regno];
2041 if (reg->type != SCALAR_VALUE) {
2042 WARN_ONCE(1, "backtracing misuse");
2043 return -EFAULT;
2044 }
2045 if (!reg->precise)
2046 new_marks = true;
2047 else
2048 reg_mask = 0;
2049 reg->precise = true;
b5dc0163 2050 }
b5dc0163 2051
a3ce685d
AS
2052 while (spi >= 0) {
2053 if (func->stack[spi].slot_type[0] != STACK_SPILL) {
2054 stack_mask = 0;
2055 break;
2056 }
2057 reg = &func->stack[spi].spilled_ptr;
2058 if (reg->type != SCALAR_VALUE) {
2059 stack_mask = 0;
2060 break;
2061 }
2062 if (!reg->precise)
2063 new_marks = true;
2064 else
2065 stack_mask = 0;
2066 reg->precise = true;
2067 break;
2068 }
2069
2070 if (!new_marks)
2071 return 0;
2072 if (!reg_mask && !stack_mask)
2073 return 0;
b5dc0163
AS
2074 for (;;) {
2075 DECLARE_BITMAP(mask, 64);
b5dc0163
AS
2076 u32 history = st->jmp_history_cnt;
2077
2078 if (env->log.level & BPF_LOG_LEVEL)
2079 verbose(env, "last_idx %d first_idx %d\n", last_idx, first_idx);
2080 for (i = last_idx;;) {
2081 if (skip_first) {
2082 err = 0;
2083 skip_first = false;
2084 } else {
2085 err = backtrack_insn(env, i, &reg_mask, &stack_mask);
2086 }
2087 if (err == -ENOTSUPP) {
2088 mark_all_scalars_precise(env, st);
2089 return 0;
2090 } else if (err) {
2091 return err;
2092 }
2093 if (!reg_mask && !stack_mask)
2094 /* Found assignment(s) into tracked register in this state.
2095 * Since this state is already marked, just return.
2096 * Nothing to be tracked further in the parent state.
2097 */
2098 return 0;
2099 if (i == first_idx)
2100 break;
2101 i = get_prev_insn_idx(st, i, &history);
2102 if (i >= env->prog->len) {
2103 /* This can happen if backtracking reached insn 0
2104 * and there are still reg_mask or stack_mask
2105 * to backtrack.
2106 * It means the backtracking missed the spot where
2107 * particular register was initialized with a constant.
2108 */
2109 verbose(env, "BUG backtracking idx %d\n", i);
2110 WARN_ONCE(1, "verifier backtracking bug");
2111 return -EFAULT;
2112 }
2113 }
2114 st = st->parent;
2115 if (!st)
2116 break;
2117
a3ce685d 2118 new_marks = false;
b5dc0163
AS
2119 func = st->frame[st->curframe];
2120 bitmap_from_u64(mask, reg_mask);
2121 for_each_set_bit(i, mask, 32) {
2122 reg = &func->regs[i];
a3ce685d
AS
2123 if (reg->type != SCALAR_VALUE) {
2124 reg_mask &= ~(1u << i);
b5dc0163 2125 continue;
a3ce685d 2126 }
b5dc0163
AS
2127 if (!reg->precise)
2128 new_marks = true;
2129 reg->precise = true;
2130 }
2131
2132 bitmap_from_u64(mask, stack_mask);
2133 for_each_set_bit(i, mask, 64) {
2134 if (i >= func->allocated_stack / BPF_REG_SIZE) {
2339cd6c
AS
2135 /* the sequence of instructions:
2136 * 2: (bf) r3 = r10
2137 * 3: (7b) *(u64 *)(r3 -8) = r0
2138 * 4: (79) r4 = *(u64 *)(r10 -8)
2139 * doesn't contain jmps. It's backtracked
2140 * as a single block.
2141 * During backtracking insn 3 is not recognized as
2142 * stack access, so at the end of backtracking
2143 * stack slot fp-8 is still marked in stack_mask.
2144 * However the parent state may not have accessed
2145 * fp-8 and it's "unallocated" stack space.
2146 * In such case fallback to conservative.
b5dc0163 2147 */
2339cd6c
AS
2148 mark_all_scalars_precise(env, st);
2149 return 0;
b5dc0163
AS
2150 }
2151
a3ce685d
AS
2152 if (func->stack[i].slot_type[0] != STACK_SPILL) {
2153 stack_mask &= ~(1ull << i);
b5dc0163 2154 continue;
a3ce685d 2155 }
b5dc0163 2156 reg = &func->stack[i].spilled_ptr;
a3ce685d
AS
2157 if (reg->type != SCALAR_VALUE) {
2158 stack_mask &= ~(1ull << i);
b5dc0163 2159 continue;
a3ce685d 2160 }
b5dc0163
AS
2161 if (!reg->precise)
2162 new_marks = true;
2163 reg->precise = true;
2164 }
2165 if (env->log.level & BPF_LOG_LEVEL) {
2166 print_verifier_state(env, func);
2167 verbose(env, "parent %s regs=%x stack=%llx marks\n",
2168 new_marks ? "didn't have" : "already had",
2169 reg_mask, stack_mask);
2170 }
2171
a3ce685d
AS
2172 if (!reg_mask && !stack_mask)
2173 break;
b5dc0163
AS
2174 if (!new_marks)
2175 break;
2176
2177 last_idx = st->last_insn_idx;
2178 first_idx = st->first_insn_idx;
2179 }
2180 return 0;
2181}
2182
a3ce685d
AS
2183static int mark_chain_precision(struct bpf_verifier_env *env, int regno)
2184{
2185 return __mark_chain_precision(env, regno, -1);
2186}
2187
2188static int mark_chain_precision_stack(struct bpf_verifier_env *env, int spi)
2189{
2190 return __mark_chain_precision(env, -1, spi);
2191}
b5dc0163 2192
1be7f75d
AS
2193static bool is_spillable_regtype(enum bpf_reg_type type)
2194{
2195 switch (type) {
2196 case PTR_TO_MAP_VALUE:
2197 case PTR_TO_MAP_VALUE_OR_NULL:
2198 case PTR_TO_STACK:
2199 case PTR_TO_CTX:
969bf05e 2200 case PTR_TO_PACKET:
de8f3a83 2201 case PTR_TO_PACKET_META:
969bf05e 2202 case PTR_TO_PACKET_END:
d58e468b 2203 case PTR_TO_FLOW_KEYS:
1be7f75d 2204 case CONST_PTR_TO_MAP:
c64b7983
JS
2205 case PTR_TO_SOCKET:
2206 case PTR_TO_SOCKET_OR_NULL:
46f8bc92
MKL
2207 case PTR_TO_SOCK_COMMON:
2208 case PTR_TO_SOCK_COMMON_OR_NULL:
655a51e5
MKL
2209 case PTR_TO_TCP_SOCK:
2210 case PTR_TO_TCP_SOCK_OR_NULL:
fada7fdc 2211 case PTR_TO_XDP_SOCK:
65726b5b 2212 case PTR_TO_BTF_ID:
b121b341 2213 case PTR_TO_BTF_ID_OR_NULL:
afbf21dc
YS
2214 case PTR_TO_RDONLY_BUF:
2215 case PTR_TO_RDONLY_BUF_OR_NULL:
2216 case PTR_TO_RDWR_BUF:
2217 case PTR_TO_RDWR_BUF_OR_NULL:
eaa6bcb7 2218 case PTR_TO_PERCPU_BTF_ID:
1be7f75d
AS
2219 return true;
2220 default:
2221 return false;
2222 }
2223}
2224
cc2b14d5
AS
2225/* Does this register contain a constant zero? */
2226static bool register_is_null(struct bpf_reg_state *reg)
2227{
2228 return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
2229}
2230
f7cf25b2
AS
2231static bool register_is_const(struct bpf_reg_state *reg)
2232{
2233 return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
2234}
2235
5689d49b
YS
2236static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
2237{
2238 return tnum_is_unknown(reg->var_off) &&
2239 reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
2240 reg->umin_value == 0 && reg->umax_value == U64_MAX &&
2241 reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
2242 reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
2243}
2244
2245static bool register_is_bounded(struct bpf_reg_state *reg)
2246{
2247 return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
2248}
2249
6e7e63cb
JH
2250static bool __is_pointer_value(bool allow_ptr_leaks,
2251 const struct bpf_reg_state *reg)
2252{
2253 if (allow_ptr_leaks)
2254 return false;
2255
2256 return reg->type != SCALAR_VALUE;
2257}
2258
f7cf25b2
AS
2259static void save_register_state(struct bpf_func_state *state,
2260 int spi, struct bpf_reg_state *reg)
2261{
2262 int i;
2263
2264 state->stack[spi].spilled_ptr = *reg;
2265 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
2266
2267 for (i = 0; i < BPF_REG_SIZE; i++)
2268 state->stack[spi].slot_type[i] = STACK_SPILL;
2269}
2270
17a52670
AS
2271/* check_stack_read/write functions track spill/fill of registers,
2272 * stack boundary and alignment are checked in check_mem_access()
2273 */
61bd5218 2274static int check_stack_write(struct bpf_verifier_env *env,
f4d7e40a 2275 struct bpf_func_state *state, /* func where register points to */
af86ca4e 2276 int off, int size, int value_regno, int insn_idx)
17a52670 2277{
f4d7e40a 2278 struct bpf_func_state *cur; /* state of the current function */
638f5b90 2279 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
b5dc0163 2280 u32 dst_reg = env->prog->insnsi[insn_idx].dst_reg;
f7cf25b2 2281 struct bpf_reg_state *reg = NULL;
638f5b90 2282
f4d7e40a 2283 err = realloc_func_state(state, round_up(slot + 1, BPF_REG_SIZE),
fd978bf7 2284 state->acquired_refs, true);
638f5b90
AS
2285 if (err)
2286 return err;
9c399760
AS
2287 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
2288 * so it's aligned access and [off, off + size) are within stack limits
2289 */
638f5b90
AS
2290 if (!env->allow_ptr_leaks &&
2291 state->stack[spi].slot_type[0] == STACK_SPILL &&
2292 size != BPF_REG_SIZE) {
2293 verbose(env, "attempt to corrupt spilled pointer on stack\n");
2294 return -EACCES;
2295 }
17a52670 2296
f4d7e40a 2297 cur = env->cur_state->frame[env->cur_state->curframe];
f7cf25b2
AS
2298 if (value_regno >= 0)
2299 reg = &cur->regs[value_regno];
17a52670 2300
5689d49b 2301 if (reg && size == BPF_REG_SIZE && register_is_bounded(reg) &&
2c78ee89 2302 !register_is_null(reg) && env->bpf_capable) {
b5dc0163
AS
2303 if (dst_reg != BPF_REG_FP) {
2304 /* The backtracking logic can only recognize explicit
2305 * stack slot address like [fp - 8]. Other spill of
2306 * scalar via different register has to be conervative.
2307 * Backtrack from here and mark all registers as precise
2308 * that contributed into 'reg' being a constant.
2309 */
2310 err = mark_chain_precision(env, value_regno);
2311 if (err)
2312 return err;
2313 }
f7cf25b2
AS
2314 save_register_state(state, spi, reg);
2315 } else if (reg && is_spillable_regtype(reg->type)) {
17a52670 2316 /* register containing pointer is being spilled into stack */
9c399760 2317 if (size != BPF_REG_SIZE) {
f7cf25b2 2318 verbose_linfo(env, insn_idx, "; ");
61bd5218 2319 verbose(env, "invalid size of register spill\n");
17a52670
AS
2320 return -EACCES;
2321 }
2322
f7cf25b2 2323 if (state != cur && reg->type == PTR_TO_STACK) {
f4d7e40a
AS
2324 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
2325 return -EINVAL;
2326 }
2327
2c78ee89 2328 if (!env->bypass_spec_v4) {
f7cf25b2 2329 bool sanitize = false;
17a52670 2330
f7cf25b2
AS
2331 if (state->stack[spi].slot_type[0] == STACK_SPILL &&
2332 register_is_const(&state->stack[spi].spilled_ptr))
2333 sanitize = true;
2334 for (i = 0; i < BPF_REG_SIZE; i++)
2335 if (state->stack[spi].slot_type[i] == STACK_MISC) {
2336 sanitize = true;
2337 break;
2338 }
2339 if (sanitize) {
af86ca4e
AS
2340 int *poff = &env->insn_aux_data[insn_idx].sanitize_stack_off;
2341 int soff = (-spi - 1) * BPF_REG_SIZE;
2342
2343 /* detected reuse of integer stack slot with a pointer
2344 * which means either llvm is reusing stack slot or
2345 * an attacker is trying to exploit CVE-2018-3639
2346 * (speculative store bypass)
2347 * Have to sanitize that slot with preemptive
2348 * store of zero.
2349 */
2350 if (*poff && *poff != soff) {
2351 /* disallow programs where single insn stores
2352 * into two different stack slots, since verifier
2353 * cannot sanitize them
2354 */
2355 verbose(env,
2356 "insn %d cannot access two stack slots fp%d and fp%d",
2357 insn_idx, *poff, soff);
2358 return -EINVAL;
2359 }
2360 *poff = soff;
2361 }
af86ca4e 2362 }
f7cf25b2 2363 save_register_state(state, spi, reg);
9c399760 2364 } else {
cc2b14d5
AS
2365 u8 type = STACK_MISC;
2366
679c782d
EC
2367 /* regular write of data into stack destroys any spilled ptr */
2368 state->stack[spi].spilled_ptr.type = NOT_INIT;
0bae2d4d
JW
2369 /* Mark slots as STACK_MISC if they belonged to spilled ptr. */
2370 if (state->stack[spi].slot_type[0] == STACK_SPILL)
2371 for (i = 0; i < BPF_REG_SIZE; i++)
2372 state->stack[spi].slot_type[i] = STACK_MISC;
9c399760 2373
cc2b14d5
AS
2374 /* only mark the slot as written if all 8 bytes were written
2375 * otherwise read propagation may incorrectly stop too soon
2376 * when stack slots are partially written.
2377 * This heuristic means that read propagation will be
2378 * conservative, since it will add reg_live_read marks
2379 * to stack slots all the way to first state when programs
2380 * writes+reads less than 8 bytes
2381 */
2382 if (size == BPF_REG_SIZE)
2383 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
2384
2385 /* when we zero initialize stack slots mark them as such */
b5dc0163
AS
2386 if (reg && register_is_null(reg)) {
2387 /* backtracking doesn't work for STACK_ZERO yet. */
2388 err = mark_chain_precision(env, value_regno);
2389 if (err)
2390 return err;
cc2b14d5 2391 type = STACK_ZERO;
b5dc0163 2392 }
cc2b14d5 2393
0bae2d4d 2394 /* Mark slots affected by this stack write. */
9c399760 2395 for (i = 0; i < size; i++)
638f5b90 2396 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
cc2b14d5 2397 type;
17a52670
AS
2398 }
2399 return 0;
2400}
2401
61bd5218 2402static int check_stack_read(struct bpf_verifier_env *env,
f4d7e40a
AS
2403 struct bpf_func_state *reg_state /* func where register points to */,
2404 int off, int size, int value_regno)
17a52670 2405{
f4d7e40a
AS
2406 struct bpf_verifier_state *vstate = env->cur_state;
2407 struct bpf_func_state *state = vstate->frame[vstate->curframe];
638f5b90 2408 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
f7cf25b2 2409 struct bpf_reg_state *reg;
638f5b90 2410 u8 *stype;
17a52670 2411
f4d7e40a 2412 if (reg_state->allocated_stack <= slot) {
638f5b90
AS
2413 verbose(env, "invalid read from stack off %d+0 size %d\n",
2414 off, size);
2415 return -EACCES;
2416 }
f4d7e40a 2417 stype = reg_state->stack[spi].slot_type;
f7cf25b2 2418 reg = &reg_state->stack[spi].spilled_ptr;
17a52670 2419
638f5b90 2420 if (stype[0] == STACK_SPILL) {
9c399760 2421 if (size != BPF_REG_SIZE) {
f7cf25b2
AS
2422 if (reg->type != SCALAR_VALUE) {
2423 verbose_linfo(env, env->insn_idx, "; ");
2424 verbose(env, "invalid size of register fill\n");
2425 return -EACCES;
2426 }
2427 if (value_regno >= 0) {
2428 mark_reg_unknown(env, state->regs, value_regno);
2429 state->regs[value_regno].live |= REG_LIVE_WRITTEN;
2430 }
2431 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
2432 return 0;
17a52670 2433 }
9c399760 2434 for (i = 1; i < BPF_REG_SIZE; i++) {
638f5b90 2435 if (stype[(slot - i) % BPF_REG_SIZE] != STACK_SPILL) {
61bd5218 2436 verbose(env, "corrupted spill memory\n");
17a52670
AS
2437 return -EACCES;
2438 }
2439 }
2440
dc503a8a 2441 if (value_regno >= 0) {
17a52670 2442 /* restore register state from stack */
f7cf25b2 2443 state->regs[value_regno] = *reg;
2f18f62e
AS
2444 /* mark reg as written since spilled pointer state likely
2445 * has its liveness marks cleared by is_state_visited()
2446 * which resets stack/reg liveness for state transitions
2447 */
2448 state->regs[value_regno].live |= REG_LIVE_WRITTEN;
6e7e63cb
JH
2449 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
2450 /* If value_regno==-1, the caller is asking us whether
2451 * it is acceptable to use this value as a SCALAR_VALUE
2452 * (e.g. for XADD).
2453 * We must not allow unprivileged callers to do that
2454 * with spilled pointers.
2455 */
2456 verbose(env, "leaking pointer from stack off %d\n",
2457 off);
2458 return -EACCES;
dc503a8a 2459 }
f7cf25b2 2460 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
17a52670 2461 } else {
cc2b14d5
AS
2462 int zeros = 0;
2463
17a52670 2464 for (i = 0; i < size; i++) {
cc2b14d5
AS
2465 if (stype[(slot - i) % BPF_REG_SIZE] == STACK_MISC)
2466 continue;
2467 if (stype[(slot - i) % BPF_REG_SIZE] == STACK_ZERO) {
2468 zeros++;
2469 continue;
17a52670 2470 }
cc2b14d5
AS
2471 verbose(env, "invalid read from stack off %d+%d size %d\n",
2472 off, i, size);
2473 return -EACCES;
2474 }
f7cf25b2 2475 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
cc2b14d5
AS
2476 if (value_regno >= 0) {
2477 if (zeros == size) {
2478 /* any size read into register is zero extended,
2479 * so the whole register == const_zero
2480 */
2481 __mark_reg_const_zero(&state->regs[value_regno]);
b5dc0163
AS
2482 /* backtracking doesn't support STACK_ZERO yet,
2483 * so mark it precise here, so that later
2484 * backtracking can stop here.
2485 * Backtracking may not need this if this register
2486 * doesn't participate in pointer adjustment.
2487 * Forward propagation of precise flag is not
2488 * necessary either. This mark is only to stop
2489 * backtracking. Any register that contributed
2490 * to const 0 was marked precise before spill.
2491 */
2492 state->regs[value_regno].precise = true;
cc2b14d5
AS
2493 } else {
2494 /* have read misc data from the stack */
2495 mark_reg_unknown(env, state->regs, value_regno);
2496 }
2497 state->regs[value_regno].live |= REG_LIVE_WRITTEN;
17a52670 2498 }
17a52670 2499 }
f7cf25b2 2500 return 0;
17a52670
AS
2501}
2502
e4298d25
DB
2503static int check_stack_access(struct bpf_verifier_env *env,
2504 const struct bpf_reg_state *reg,
2505 int off, int size)
2506{
2507 /* Stack accesses must be at a fixed offset, so that we
2508 * can determine what type of data were returned. See
2509 * check_stack_read().
2510 */
2511 if (!tnum_is_const(reg->var_off)) {
2512 char tn_buf[48];
2513
2514 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
1fbd20f8 2515 verbose(env, "variable stack access var_off=%s off=%d size=%d\n",
e4298d25
DB
2516 tn_buf, off, size);
2517 return -EACCES;
2518 }
2519
2520 if (off >= 0 || off < -MAX_BPF_STACK) {
2521 verbose(env, "invalid stack off=%d size=%d\n", off, size);
2522 return -EACCES;
2523 }
2524
2525 return 0;
2526}
2527
591fe988
DB
2528static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
2529 int off, int size, enum bpf_access_type type)
2530{
2531 struct bpf_reg_state *regs = cur_regs(env);
2532 struct bpf_map *map = regs[regno].map_ptr;
2533 u32 cap = bpf_map_flags_to_cap(map);
2534
2535 if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
2536 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
2537 map->value_size, off, size);
2538 return -EACCES;
2539 }
2540
2541 if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
2542 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
2543 map->value_size, off, size);
2544 return -EACCES;
2545 }
2546
2547 return 0;
2548}
2549
457f4436
AN
2550/* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
2551static int __check_mem_access(struct bpf_verifier_env *env, int regno,
2552 int off, int size, u32 mem_size,
2553 bool zero_size_allowed)
17a52670 2554{
457f4436
AN
2555 bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
2556 struct bpf_reg_state *reg;
2557
2558 if (off >= 0 && size_ok && (u64)off + size <= mem_size)
2559 return 0;
17a52670 2560
457f4436
AN
2561 reg = &cur_regs(env)[regno];
2562 switch (reg->type) {
2563 case PTR_TO_MAP_VALUE:
61bd5218 2564 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
457f4436
AN
2565 mem_size, off, size);
2566 break;
2567 case PTR_TO_PACKET:
2568 case PTR_TO_PACKET_META:
2569 case PTR_TO_PACKET_END:
2570 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
2571 off, size, regno, reg->id, off, mem_size);
2572 break;
2573 case PTR_TO_MEM:
2574 default:
2575 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
2576 mem_size, off, size);
17a52670 2577 }
457f4436
AN
2578
2579 return -EACCES;
17a52670
AS
2580}
2581
457f4436
AN
2582/* check read/write into a memory region with possible variable offset */
2583static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
2584 int off, int size, u32 mem_size,
2585 bool zero_size_allowed)
dbcfe5f7 2586{
f4d7e40a
AS
2587 struct bpf_verifier_state *vstate = env->cur_state;
2588 struct bpf_func_state *state = vstate->frame[vstate->curframe];
dbcfe5f7
GB
2589 struct bpf_reg_state *reg = &state->regs[regno];
2590 int err;
2591
457f4436 2592 /* We may have adjusted the register pointing to memory region, so we
f1174f77
EC
2593 * need to try adding each of min_value and max_value to off
2594 * to make sure our theoretical access will be safe.
dbcfe5f7 2595 */
06ee7115 2596 if (env->log.level & BPF_LOG_LEVEL)
61bd5218 2597 print_verifier_state(env, state);
b7137c4e 2598
dbcfe5f7
GB
2599 /* The minimum value is only important with signed
2600 * comparisons where we can't assume the floor of a
2601 * value is 0. If we are using signed variables for our
2602 * index'es we need to make sure that whatever we use
2603 * will have a set floor within our range.
2604 */
b7137c4e
DB
2605 if (reg->smin_value < 0 &&
2606 (reg->smin_value == S64_MIN ||
2607 (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
2608 reg->smin_value + off < 0)) {
61bd5218 2609 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
dbcfe5f7
GB
2610 regno);
2611 return -EACCES;
2612 }
457f4436
AN
2613 err = __check_mem_access(env, regno, reg->smin_value + off, size,
2614 mem_size, zero_size_allowed);
dbcfe5f7 2615 if (err) {
457f4436 2616 verbose(env, "R%d min value is outside of the allowed memory range\n",
61bd5218 2617 regno);
dbcfe5f7
GB
2618 return err;
2619 }
2620
b03c9f9f
EC
2621 /* If we haven't set a max value then we need to bail since we can't be
2622 * sure we won't do bad things.
2623 * If reg->umax_value + off could overflow, treat that as unbounded too.
dbcfe5f7 2624 */
b03c9f9f 2625 if (reg->umax_value >= BPF_MAX_VAR_OFF) {
457f4436 2626 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
dbcfe5f7
GB
2627 regno);
2628 return -EACCES;
2629 }
457f4436
AN
2630 err = __check_mem_access(env, regno, reg->umax_value + off, size,
2631 mem_size, zero_size_allowed);
2632 if (err) {
2633 verbose(env, "R%d max value is outside of the allowed memory range\n",
61bd5218 2634 regno);
457f4436
AN
2635 return err;
2636 }
2637
2638 return 0;
2639}
d83525ca 2640
457f4436
AN
2641/* check read/write into a map element with possible variable offset */
2642static int check_map_access(struct bpf_verifier_env *env, u32 regno,
2643 int off, int size, bool zero_size_allowed)
2644{
2645 struct bpf_verifier_state *vstate = env->cur_state;
2646 struct bpf_func_state *state = vstate->frame[vstate->curframe];
2647 struct bpf_reg_state *reg = &state->regs[regno];
2648 struct bpf_map *map = reg->map_ptr;
2649 int err;
2650
2651 err = check_mem_region_access(env, regno, off, size, map->value_size,
2652 zero_size_allowed);
2653 if (err)
2654 return err;
2655
2656 if (map_value_has_spin_lock(map)) {
2657 u32 lock = map->spin_lock_off;
d83525ca
AS
2658
2659 /* if any part of struct bpf_spin_lock can be touched by
2660 * load/store reject this program.
2661 * To check that [x1, x2) overlaps with [y1, y2)
2662 * it is sufficient to check x1 < y2 && y1 < x2.
2663 */
2664 if (reg->smin_value + off < lock + sizeof(struct bpf_spin_lock) &&
2665 lock < reg->umax_value + off + size) {
2666 verbose(env, "bpf_spin_lock cannot be accessed directly by load/store\n");
2667 return -EACCES;
2668 }
2669 }
f1174f77 2670 return err;
dbcfe5f7
GB
2671}
2672
969bf05e
AS
2673#define MAX_PACKET_OFF 0xffff
2674
7e40781c
UP
2675static enum bpf_prog_type resolve_prog_type(struct bpf_prog *prog)
2676{
3aac1ead 2677 return prog->aux->dst_prog ? prog->aux->dst_prog->type : prog->type;
7e40781c
UP
2678}
2679
58e2af8b 2680static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
3a0af8fd
TG
2681 const struct bpf_call_arg_meta *meta,
2682 enum bpf_access_type t)
4acf6c0b 2683{
7e40781c
UP
2684 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
2685
2686 switch (prog_type) {
5d66fa7d 2687 /* Program types only with direct read access go here! */
3a0af8fd
TG
2688 case BPF_PROG_TYPE_LWT_IN:
2689 case BPF_PROG_TYPE_LWT_OUT:
004d4b27 2690 case BPF_PROG_TYPE_LWT_SEG6LOCAL:
2dbb9b9e 2691 case BPF_PROG_TYPE_SK_REUSEPORT:
5d66fa7d 2692 case BPF_PROG_TYPE_FLOW_DISSECTOR:
d5563d36 2693 case BPF_PROG_TYPE_CGROUP_SKB:
3a0af8fd
TG
2694 if (t == BPF_WRITE)
2695 return false;
8731745e 2696 fallthrough;
5d66fa7d
DB
2697
2698 /* Program types with direct read + write access go here! */
36bbef52
DB
2699 case BPF_PROG_TYPE_SCHED_CLS:
2700 case BPF_PROG_TYPE_SCHED_ACT:
4acf6c0b 2701 case BPF_PROG_TYPE_XDP:
3a0af8fd 2702 case BPF_PROG_TYPE_LWT_XMIT:
8a31db56 2703 case BPF_PROG_TYPE_SK_SKB:
4f738adb 2704 case BPF_PROG_TYPE_SK_MSG:
36bbef52
DB
2705 if (meta)
2706 return meta->pkt_access;
2707
2708 env->seen_direct_write = true;
4acf6c0b 2709 return true;
0d01da6a
SF
2710
2711 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
2712 if (t == BPF_WRITE)
2713 env->seen_direct_write = true;
2714
2715 return true;
2716
4acf6c0b
BB
2717 default:
2718 return false;
2719 }
2720}
2721
f1174f77 2722static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
9fd29c08 2723 int size, bool zero_size_allowed)
f1174f77 2724{
638f5b90 2725 struct bpf_reg_state *regs = cur_regs(env);
f1174f77
EC
2726 struct bpf_reg_state *reg = &regs[regno];
2727 int err;
2728
2729 /* We may have added a variable offset to the packet pointer; but any
2730 * reg->range we have comes after that. We are only checking the fixed
2731 * offset.
2732 */
2733
2734 /* We don't allow negative numbers, because we aren't tracking enough
2735 * detail to prove they're safe.
2736 */
b03c9f9f 2737 if (reg->smin_value < 0) {
61bd5218 2738 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
f1174f77
EC
2739 regno);
2740 return -EACCES;
2741 }
457f4436
AN
2742 err = __check_mem_access(env, regno, off, size, reg->range,
2743 zero_size_allowed);
f1174f77 2744 if (err) {
61bd5218 2745 verbose(env, "R%d offset is outside of the packet\n", regno);
f1174f77
EC
2746 return err;
2747 }
e647815a 2748
457f4436 2749 /* __check_mem_access has made sure "off + size - 1" is within u16.
e647815a
JW
2750 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
2751 * otherwise find_good_pkt_pointers would have refused to set range info
457f4436 2752 * that __check_mem_access would have rejected this pkt access.
e647815a
JW
2753 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
2754 */
2755 env->prog->aux->max_pkt_offset =
2756 max_t(u32, env->prog->aux->max_pkt_offset,
2757 off + reg->umax_value + size - 1);
2758
f1174f77
EC
2759 return err;
2760}
2761
2762/* check access to 'struct bpf_context' fields. Supports fixed offsets only */
31fd8581 2763static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
9e15db66
AS
2764 enum bpf_access_type t, enum bpf_reg_type *reg_type,
2765 u32 *btf_id)
17a52670 2766{
f96da094
DB
2767 struct bpf_insn_access_aux info = {
2768 .reg_type = *reg_type,
9e15db66 2769 .log = &env->log,
f96da094 2770 };
31fd8581 2771
4f9218aa 2772 if (env->ops->is_valid_access &&
5e43f899 2773 env->ops->is_valid_access(off, size, t, env->prog, &info)) {
f96da094
DB
2774 /* A non zero info.ctx_field_size indicates that this field is a
2775 * candidate for later verifier transformation to load the whole
2776 * field and then apply a mask when accessed with a narrower
2777 * access than actual ctx access size. A zero info.ctx_field_size
2778 * will only allow for whole field access and rejects any other
2779 * type of narrower access.
31fd8581 2780 */
23994631 2781 *reg_type = info.reg_type;
31fd8581 2782
b121b341 2783 if (*reg_type == PTR_TO_BTF_ID || *reg_type == PTR_TO_BTF_ID_OR_NULL)
9e15db66
AS
2784 *btf_id = info.btf_id;
2785 else
2786 env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
32bbe007
AS
2787 /* remember the offset of last byte accessed in ctx */
2788 if (env->prog->aux->max_ctx_offset < off + size)
2789 env->prog->aux->max_ctx_offset = off + size;
17a52670 2790 return 0;
32bbe007 2791 }
17a52670 2792
61bd5218 2793 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
17a52670
AS
2794 return -EACCES;
2795}
2796
d58e468b
PP
2797static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
2798 int size)
2799{
2800 if (size < 0 || off < 0 ||
2801 (u64)off + size > sizeof(struct bpf_flow_keys)) {
2802 verbose(env, "invalid access to flow keys off=%d size=%d\n",
2803 off, size);
2804 return -EACCES;
2805 }
2806 return 0;
2807}
2808
5f456649
MKL
2809static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
2810 u32 regno, int off, int size,
2811 enum bpf_access_type t)
c64b7983
JS
2812{
2813 struct bpf_reg_state *regs = cur_regs(env);
2814 struct bpf_reg_state *reg = &regs[regno];
5f456649 2815 struct bpf_insn_access_aux info = {};
46f8bc92 2816 bool valid;
c64b7983
JS
2817
2818 if (reg->smin_value < 0) {
2819 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
2820 regno);
2821 return -EACCES;
2822 }
2823
46f8bc92
MKL
2824 switch (reg->type) {
2825 case PTR_TO_SOCK_COMMON:
2826 valid = bpf_sock_common_is_valid_access(off, size, t, &info);
2827 break;
2828 case PTR_TO_SOCKET:
2829 valid = bpf_sock_is_valid_access(off, size, t, &info);
2830 break;
655a51e5
MKL
2831 case PTR_TO_TCP_SOCK:
2832 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
2833 break;
fada7fdc
JL
2834 case PTR_TO_XDP_SOCK:
2835 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
2836 break;
46f8bc92
MKL
2837 default:
2838 valid = false;
c64b7983
JS
2839 }
2840
5f456649 2841
46f8bc92
MKL
2842 if (valid) {
2843 env->insn_aux_data[insn_idx].ctx_field_size =
2844 info.ctx_field_size;
2845 return 0;
2846 }
2847
2848 verbose(env, "R%d invalid %s access off=%d size=%d\n",
2849 regno, reg_type_str[reg->type], off, size);
2850
2851 return -EACCES;
c64b7983
JS
2852}
2853
2a159c6f
DB
2854static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
2855{
2856 return cur_regs(env) + regno;
2857}
2858
4cabc5b1
DB
2859static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
2860{
2a159c6f 2861 return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
4cabc5b1
DB
2862}
2863
f37a8cb8
DB
2864static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
2865{
2a159c6f 2866 const struct bpf_reg_state *reg = reg_state(env, regno);
f37a8cb8 2867
46f8bc92
MKL
2868 return reg->type == PTR_TO_CTX;
2869}
2870
2871static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
2872{
2873 const struct bpf_reg_state *reg = reg_state(env, regno);
2874
2875 return type_is_sk_pointer(reg->type);
f37a8cb8
DB
2876}
2877
ca369602
DB
2878static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
2879{
2a159c6f 2880 const struct bpf_reg_state *reg = reg_state(env, regno);
ca369602
DB
2881
2882 return type_is_pkt_pointer(reg->type);
2883}
2884
4b5defde
DB
2885static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
2886{
2887 const struct bpf_reg_state *reg = reg_state(env, regno);
2888
2889 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
2890 return reg->type == PTR_TO_FLOW_KEYS;
2891}
2892
61bd5218
JK
2893static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
2894 const struct bpf_reg_state *reg,
d1174416 2895 int off, int size, bool strict)
969bf05e 2896{
f1174f77 2897 struct tnum reg_off;
e07b98d9 2898 int ip_align;
d1174416
DM
2899
2900 /* Byte size accesses are always allowed. */
2901 if (!strict || size == 1)
2902 return 0;
2903
e4eda884
DM
2904 /* For platforms that do not have a Kconfig enabling
2905 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
2906 * NET_IP_ALIGN is universally set to '2'. And on platforms
2907 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
2908 * to this code only in strict mode where we want to emulate
2909 * the NET_IP_ALIGN==2 checking. Therefore use an
2910 * unconditional IP align value of '2'.
e07b98d9 2911 */
e4eda884 2912 ip_align = 2;
f1174f77
EC
2913
2914 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
2915 if (!tnum_is_aligned(reg_off, size)) {
2916 char tn_buf[48];
2917
2918 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
61bd5218
JK
2919 verbose(env,
2920 "misaligned packet access off %d+%s+%d+%d size %d\n",
f1174f77 2921 ip_align, tn_buf, reg->off, off, size);
969bf05e
AS
2922 return -EACCES;
2923 }
79adffcd 2924
969bf05e
AS
2925 return 0;
2926}
2927
61bd5218
JK
2928static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
2929 const struct bpf_reg_state *reg,
f1174f77
EC
2930 const char *pointer_desc,
2931 int off, int size, bool strict)
79adffcd 2932{
f1174f77
EC
2933 struct tnum reg_off;
2934
2935 /* Byte size accesses are always allowed. */
2936 if (!strict || size == 1)
2937 return 0;
2938
2939 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
2940 if (!tnum_is_aligned(reg_off, size)) {
2941 char tn_buf[48];
2942
2943 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
61bd5218 2944 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
f1174f77 2945 pointer_desc, tn_buf, reg->off, off, size);
79adffcd
DB
2946 return -EACCES;
2947 }
2948
969bf05e
AS
2949 return 0;
2950}
2951
e07b98d9 2952static int check_ptr_alignment(struct bpf_verifier_env *env,
ca369602
DB
2953 const struct bpf_reg_state *reg, int off,
2954 int size, bool strict_alignment_once)
79adffcd 2955{
ca369602 2956 bool strict = env->strict_alignment || strict_alignment_once;
f1174f77 2957 const char *pointer_desc = "";
d1174416 2958
79adffcd
DB
2959 switch (reg->type) {
2960 case PTR_TO_PACKET:
de8f3a83
DB
2961 case PTR_TO_PACKET_META:
2962 /* Special case, because of NET_IP_ALIGN. Given metadata sits
2963 * right in front, treat it the very same way.
2964 */
61bd5218 2965 return check_pkt_ptr_alignment(env, reg, off, size, strict);
d58e468b
PP
2966 case PTR_TO_FLOW_KEYS:
2967 pointer_desc = "flow keys ";
2968 break;
f1174f77
EC
2969 case PTR_TO_MAP_VALUE:
2970 pointer_desc = "value ";
2971 break;
2972 case PTR_TO_CTX:
2973 pointer_desc = "context ";
2974 break;
2975 case PTR_TO_STACK:
2976 pointer_desc = "stack ";
a5ec6ae1
JH
2977 /* The stack spill tracking logic in check_stack_write()
2978 * and check_stack_read() relies on stack accesses being
2979 * aligned.
2980 */
2981 strict = true;
f1174f77 2982 break;
c64b7983
JS
2983 case PTR_TO_SOCKET:
2984 pointer_desc = "sock ";
2985 break;
46f8bc92
MKL
2986 case PTR_TO_SOCK_COMMON:
2987 pointer_desc = "sock_common ";
2988 break;
655a51e5
MKL
2989 case PTR_TO_TCP_SOCK:
2990 pointer_desc = "tcp_sock ";
2991 break;
fada7fdc
JL
2992 case PTR_TO_XDP_SOCK:
2993 pointer_desc = "xdp_sock ";
2994 break;
79adffcd 2995 default:
f1174f77 2996 break;
79adffcd 2997 }
61bd5218
JK
2998 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
2999 strict);
79adffcd
DB
3000}
3001
f4d7e40a
AS
3002static int update_stack_depth(struct bpf_verifier_env *env,
3003 const struct bpf_func_state *func,
3004 int off)
3005{
9c8105bd 3006 u16 stack = env->subprog_info[func->subprogno].stack_depth;
f4d7e40a
AS
3007
3008 if (stack >= -off)
3009 return 0;
3010
3011 /* update known max for given subprogram */
9c8105bd 3012 env->subprog_info[func->subprogno].stack_depth = -off;
70a87ffe
AS
3013 return 0;
3014}
f4d7e40a 3015
70a87ffe
AS
3016/* starting from main bpf function walk all instructions of the function
3017 * and recursively walk all callees that given function can call.
3018 * Ignore jump and exit insns.
3019 * Since recursion is prevented by check_cfg() this algorithm
3020 * only needs a local stack of MAX_CALL_FRAMES to remember callsites
3021 */
3022static int check_max_stack_depth(struct bpf_verifier_env *env)
3023{
9c8105bd
JW
3024 int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
3025 struct bpf_subprog_info *subprog = env->subprog_info;
70a87ffe 3026 struct bpf_insn *insn = env->prog->insnsi;
ebf7d1f5 3027 bool tail_call_reachable = false;
70a87ffe
AS
3028 int ret_insn[MAX_CALL_FRAMES];
3029 int ret_prog[MAX_CALL_FRAMES];
ebf7d1f5 3030 int j;
f4d7e40a 3031
70a87ffe 3032process_func:
7f6e4312
MF
3033 /* protect against potential stack overflow that might happen when
3034 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
3035 * depth for such case down to 256 so that the worst case scenario
3036 * would result in 8k stack size (32 which is tailcall limit * 256 =
3037 * 8k).
3038 *
3039 * To get the idea what might happen, see an example:
3040 * func1 -> sub rsp, 128
3041 * subfunc1 -> sub rsp, 256
3042 * tailcall1 -> add rsp, 256
3043 * func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
3044 * subfunc2 -> sub rsp, 64
3045 * subfunc22 -> sub rsp, 128
3046 * tailcall2 -> add rsp, 128
3047 * func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
3048 *
3049 * tailcall will unwind the current stack frame but it will not get rid
3050 * of caller's stack as shown on the example above.
3051 */
3052 if (idx && subprog[idx].has_tail_call && depth >= 256) {
3053 verbose(env,
3054 "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
3055 depth);
3056 return -EACCES;
3057 }
70a87ffe
AS
3058 /* round up to 32-bytes, since this is granularity
3059 * of interpreter stack size
3060 */
9c8105bd 3061 depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
70a87ffe 3062 if (depth > MAX_BPF_STACK) {
f4d7e40a 3063 verbose(env, "combined stack size of %d calls is %d. Too large\n",
70a87ffe 3064 frame + 1, depth);
f4d7e40a
AS
3065 return -EACCES;
3066 }
70a87ffe 3067continue_func:
4cb3d99c 3068 subprog_end = subprog[idx + 1].start;
70a87ffe
AS
3069 for (; i < subprog_end; i++) {
3070 if (insn[i].code != (BPF_JMP | BPF_CALL))
3071 continue;
3072 if (insn[i].src_reg != BPF_PSEUDO_CALL)
3073 continue;
3074 /* remember insn and function to return to */
3075 ret_insn[frame] = i + 1;
9c8105bd 3076 ret_prog[frame] = idx;
70a87ffe
AS
3077
3078 /* find the callee */
3079 i = i + insn[i].imm + 1;
9c8105bd
JW
3080 idx = find_subprog(env, i);
3081 if (idx < 0) {
70a87ffe
AS
3082 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
3083 i);
3084 return -EFAULT;
3085 }
ebf7d1f5
MF
3086
3087 if (subprog[idx].has_tail_call)
3088 tail_call_reachable = true;
3089
70a87ffe
AS
3090 frame++;
3091 if (frame >= MAX_CALL_FRAMES) {
927cb781
PC
3092 verbose(env, "the call stack of %d frames is too deep !\n",
3093 frame);
3094 return -E2BIG;
70a87ffe
AS
3095 }
3096 goto process_func;
3097 }
ebf7d1f5
MF
3098 /* if tail call got detected across bpf2bpf calls then mark each of the
3099 * currently present subprog frames as tail call reachable subprogs;
3100 * this info will be utilized by JIT so that we will be preserving the
3101 * tail call counter throughout bpf2bpf calls combined with tailcalls
3102 */
3103 if (tail_call_reachable)
3104 for (j = 0; j < frame; j++)
3105 subprog[ret_prog[j]].tail_call_reachable = true;
3106
70a87ffe
AS
3107 /* end of for() loop means the last insn of the 'subprog'
3108 * was reached. Doesn't matter whether it was JA or EXIT
3109 */
3110 if (frame == 0)
3111 return 0;
9c8105bd 3112 depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
70a87ffe
AS
3113 frame--;
3114 i = ret_insn[frame];
9c8105bd 3115 idx = ret_prog[frame];
70a87ffe 3116 goto continue_func;
f4d7e40a
AS
3117}
3118
19d28fbd 3119#ifndef CONFIG_BPF_JIT_ALWAYS_ON
1ea47e01
AS
3120static int get_callee_stack_depth(struct bpf_verifier_env *env,
3121 const struct bpf_insn *insn, int idx)
3122{
3123 int start = idx + insn->imm + 1, subprog;
3124
3125 subprog = find_subprog(env, start);
3126 if (subprog < 0) {
3127 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
3128 start);
3129 return -EFAULT;
3130 }
9c8105bd 3131 return env->subprog_info[subprog].stack_depth;
1ea47e01 3132}
19d28fbd 3133#endif
1ea47e01 3134
51c39bb1
AS
3135int check_ctx_reg(struct bpf_verifier_env *env,
3136 const struct bpf_reg_state *reg, int regno)
58990d1f
DB
3137{
3138 /* Access to ctx or passing it to a helper is only allowed in
3139 * its original, unmodified form.
3140 */
3141
3142 if (reg->off) {
3143 verbose(env, "dereference of modified ctx ptr R%d off=%d disallowed\n",
3144 regno, reg->off);
3145 return -EACCES;
3146 }
3147
3148 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3149 char tn_buf[48];
3150
3151 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3152 verbose(env, "variable ctx access var_off=%s disallowed\n", tn_buf);
3153 return -EACCES;
3154 }
3155
3156 return 0;
3157}
3158
afbf21dc
YS
3159static int __check_buffer_access(struct bpf_verifier_env *env,
3160 const char *buf_info,
3161 const struct bpf_reg_state *reg,
3162 int regno, int off, int size)
9df1c28b
MM
3163{
3164 if (off < 0) {
3165 verbose(env,
4fc00b79 3166 "R%d invalid %s buffer access: off=%d, size=%d\n",
afbf21dc 3167 regno, buf_info, off, size);
9df1c28b
MM
3168 return -EACCES;
3169 }
3170 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3171 char tn_buf[48];
3172
3173 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3174 verbose(env,
4fc00b79 3175 "R%d invalid variable buffer offset: off=%d, var_off=%s\n",
9df1c28b
MM
3176 regno, off, tn_buf);
3177 return -EACCES;
3178 }
afbf21dc
YS
3179
3180 return 0;
3181}
3182
3183static int check_tp_buffer_access(struct bpf_verifier_env *env,
3184 const struct bpf_reg_state *reg,
3185 int regno, int off, int size)
3186{
3187 int err;
3188
3189 err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
3190 if (err)
3191 return err;
3192
9df1c28b
MM
3193 if (off + size > env->prog->aux->max_tp_access)
3194 env->prog->aux->max_tp_access = off + size;
3195
3196 return 0;
3197}
3198
afbf21dc
YS
3199static int check_buffer_access(struct bpf_verifier_env *env,
3200 const struct bpf_reg_state *reg,
3201 int regno, int off, int size,
3202 bool zero_size_allowed,
3203 const char *buf_info,
3204 u32 *max_access)
3205{
3206 int err;
3207
3208 err = __check_buffer_access(env, buf_info, reg, regno, off, size);
3209 if (err)
3210 return err;
3211
3212 if (off + size > *max_access)
3213 *max_access = off + size;
3214
3215 return 0;
3216}
3217
3f50f132
JF
3218/* BPF architecture zero extends alu32 ops into 64-bit registesr */
3219static void zext_32_to_64(struct bpf_reg_state *reg)
3220{
3221 reg->var_off = tnum_subreg(reg->var_off);
3222 __reg_assign_32_into_64(reg);
3223}
9df1c28b 3224
0c17d1d2
JH
3225/* truncate register to smaller size (in bytes)
3226 * must be called with size < BPF_REG_SIZE
3227 */
3228static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
3229{
3230 u64 mask;
3231
3232 /* clear high bits in bit representation */
3233 reg->var_off = tnum_cast(reg->var_off, size);
3234
3235 /* fix arithmetic bounds */
3236 mask = ((u64)1 << (size * 8)) - 1;
3237 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
3238 reg->umin_value &= mask;
3239 reg->umax_value &= mask;
3240 } else {
3241 reg->umin_value = 0;
3242 reg->umax_value = mask;
3243 }
3244 reg->smin_value = reg->umin_value;
3245 reg->smax_value = reg->umax_value;
3f50f132
JF
3246
3247 /* If size is smaller than 32bit register the 32bit register
3248 * values are also truncated so we push 64-bit bounds into
3249 * 32-bit bounds. Above were truncated < 32-bits already.
3250 */
3251 if (size >= 4)
3252 return;
3253 __reg_combine_64_into_32(reg);
0c17d1d2
JH
3254}
3255
a23740ec
AN
3256static bool bpf_map_is_rdonly(const struct bpf_map *map)
3257{
3258 return (map->map_flags & BPF_F_RDONLY_PROG) && map->frozen;
3259}
3260
3261static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val)
3262{
3263 void *ptr;
3264 u64 addr;
3265 int err;
3266
3267 err = map->ops->map_direct_value_addr(map, &addr, off);
3268 if (err)
3269 return err;
2dedd7d2 3270 ptr = (void *)(long)addr + off;
a23740ec
AN
3271
3272 switch (size) {
3273 case sizeof(u8):
3274 *val = (u64)*(u8 *)ptr;
3275 break;
3276 case sizeof(u16):
3277 *val = (u64)*(u16 *)ptr;
3278 break;
3279 case sizeof(u32):
3280 *val = (u64)*(u32 *)ptr;
3281 break;
3282 case sizeof(u64):
3283 *val = *(u64 *)ptr;
3284 break;
3285 default:
3286 return -EINVAL;
3287 }
3288 return 0;
3289}
3290
9e15db66
AS
3291static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
3292 struct bpf_reg_state *regs,
3293 int regno, int off, int size,
3294 enum bpf_access_type atype,
3295 int value_regno)
3296{
3297 struct bpf_reg_state *reg = regs + regno;
3298 const struct btf_type *t = btf_type_by_id(btf_vmlinux, reg->btf_id);
3299 const char *tname = btf_name_by_offset(btf_vmlinux, t->name_off);
3300 u32 btf_id;
3301 int ret;
3302
9e15db66
AS
3303 if (off < 0) {
3304 verbose(env,
3305 "R%d is ptr_%s invalid negative access: off=%d\n",
3306 regno, tname, off);
3307 return -EACCES;
3308 }
3309 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3310 char tn_buf[48];
3311
3312 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3313 verbose(env,
3314 "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
3315 regno, tname, off, tn_buf);
3316 return -EACCES;
3317 }
3318
27ae7997
MKL
3319 if (env->ops->btf_struct_access) {
3320 ret = env->ops->btf_struct_access(&env->log, t, off, size,
3321 atype, &btf_id);
3322 } else {
3323 if (atype != BPF_READ) {
3324 verbose(env, "only read is supported\n");
3325 return -EACCES;
3326 }
3327
3328 ret = btf_struct_access(&env->log, t, off, size, atype,
3329 &btf_id);
3330 }
3331
9e15db66
AS
3332 if (ret < 0)
3333 return ret;
3334
41c48f3a
AI
3335 if (atype == BPF_READ && value_regno >= 0)
3336 mark_btf_ld_reg(env, regs, value_regno, ret, btf_id);
3337
3338 return 0;
3339}
3340
3341static int check_ptr_to_map_access(struct bpf_verifier_env *env,
3342 struct bpf_reg_state *regs,
3343 int regno, int off, int size,
3344 enum bpf_access_type atype,
3345 int value_regno)
3346{
3347 struct bpf_reg_state *reg = regs + regno;
3348 struct bpf_map *map = reg->map_ptr;
3349 const struct btf_type *t;
3350 const char *tname;
3351 u32 btf_id;
3352 int ret;
3353
3354 if (!btf_vmlinux) {
3355 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
3356 return -ENOTSUPP;
3357 }
3358
3359 if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
3360 verbose(env, "map_ptr access not supported for map type %d\n",
3361 map->map_type);
3362 return -ENOTSUPP;
3363 }
3364
3365 t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
3366 tname = btf_name_by_offset(btf_vmlinux, t->name_off);
3367
3368 if (!env->allow_ptr_to_map_access) {
3369 verbose(env,
3370 "%s access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
3371 tname);
3372 return -EPERM;
9e15db66 3373 }
27ae7997 3374
41c48f3a
AI
3375 if (off < 0) {
3376 verbose(env, "R%d is %s invalid negative access: off=%d\n",
3377 regno, tname, off);
3378 return -EACCES;
3379 }
3380
3381 if (atype != BPF_READ) {
3382 verbose(env, "only read from %s is supported\n", tname);
3383 return -EACCES;
3384 }
3385
3386 ret = btf_struct_access(&env->log, t, off, size, atype, &btf_id);
3387 if (ret < 0)
3388 return ret;
3389
3390 if (value_regno >= 0)
3391 mark_btf_ld_reg(env, regs, value_regno, ret, btf_id);
3392
9e15db66
AS
3393 return 0;
3394}
3395
41c48f3a 3396
17a52670
AS
3397/* check whether memory at (regno + off) is accessible for t = (read | write)
3398 * if t==write, value_regno is a register which value is stored into memory
3399 * if t==read, value_regno is a register which will receive the value from memory
3400 * if t==write && value_regno==-1, some unknown value is stored into memory
3401 * if t==read && value_regno==-1, don't care what we read from memory
3402 */
ca369602
DB
3403static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
3404 int off, int bpf_size, enum bpf_access_type t,
3405 int value_regno, bool strict_alignment_once)
17a52670 3406{
638f5b90
AS
3407 struct bpf_reg_state *regs = cur_regs(env);
3408 struct bpf_reg_state *reg = regs + regno;
f4d7e40a 3409 struct bpf_func_state *state;
17a52670
AS
3410 int size, err = 0;
3411
3412 size = bpf_size_to_bytes(bpf_size);
3413 if (size < 0)
3414 return size;
3415
f1174f77 3416 /* alignment checks will add in reg->off themselves */
ca369602 3417 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
969bf05e
AS
3418 if (err)
3419 return err;
17a52670 3420
f1174f77
EC
3421 /* for access checks, reg->off is just part of off */
3422 off += reg->off;
3423
3424 if (reg->type == PTR_TO_MAP_VALUE) {
1be7f75d
AS
3425 if (t == BPF_WRITE && value_regno >= 0 &&
3426 is_pointer_value(env, value_regno)) {
61bd5218 3427 verbose(env, "R%d leaks addr into map\n", value_regno);
1be7f75d
AS
3428 return -EACCES;
3429 }
591fe988
DB
3430 err = check_map_access_type(env, regno, off, size, t);
3431 if (err)
3432 return err;
9fd29c08 3433 err = check_map_access(env, regno, off, size, false);
a23740ec
AN
3434 if (!err && t == BPF_READ && value_regno >= 0) {
3435 struct bpf_map *map = reg->map_ptr;
3436
3437 /* if map is read-only, track its contents as scalars */
3438 if (tnum_is_const(reg->var_off) &&
3439 bpf_map_is_rdonly(map) &&
3440 map->ops->map_direct_value_addr) {
3441 int map_off = off + reg->var_off.value;
3442 u64 val = 0;
3443
3444 err = bpf_map_direct_read(map, map_off, size,
3445 &val);
3446 if (err)
3447 return err;
3448
3449 regs[value_regno].type = SCALAR_VALUE;
3450 __mark_reg_known(&regs[value_regno], val);
3451 } else {
3452 mark_reg_unknown(env, regs, value_regno);
3453 }
3454 }
457f4436
AN
3455 } else if (reg->type == PTR_TO_MEM) {
3456 if (t == BPF_WRITE && value_regno >= 0 &&
3457 is_pointer_value(env, value_regno)) {
3458 verbose(env, "R%d leaks addr into mem\n", value_regno);
3459 return -EACCES;
3460 }
3461 err = check_mem_region_access(env, regno, off, size,
3462 reg->mem_size, false);
3463 if (!err && t == BPF_READ && value_regno >= 0)
3464 mark_reg_unknown(env, regs, value_regno);
1a0dc1ac 3465 } else if (reg->type == PTR_TO_CTX) {
f1174f77 3466 enum bpf_reg_type reg_type = SCALAR_VALUE;
9e15db66 3467 u32 btf_id = 0;
19de99f7 3468
1be7f75d
AS
3469 if (t == BPF_WRITE && value_regno >= 0 &&
3470 is_pointer_value(env, value_regno)) {
61bd5218 3471 verbose(env, "R%d leaks addr into ctx\n", value_regno);
1be7f75d
AS
3472 return -EACCES;
3473 }
f1174f77 3474
58990d1f
DB
3475 err = check_ctx_reg(env, reg, regno);
3476 if (err < 0)
3477 return err;
3478
9e15db66
AS
3479 err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf_id);
3480 if (err)
3481 verbose_linfo(env, insn_idx, "; ");
969bf05e 3482 if (!err && t == BPF_READ && value_regno >= 0) {
f1174f77 3483 /* ctx access returns either a scalar, or a
de8f3a83
DB
3484 * PTR_TO_PACKET[_META,_END]. In the latter
3485 * case, we know the offset is zero.
f1174f77 3486 */
46f8bc92 3487 if (reg_type == SCALAR_VALUE) {
638f5b90 3488 mark_reg_unknown(env, regs, value_regno);
46f8bc92 3489 } else {
638f5b90 3490 mark_reg_known_zero(env, regs,
61bd5218 3491 value_regno);
46f8bc92
MKL
3492 if (reg_type_may_be_null(reg_type))
3493 regs[value_regno].id = ++env->id_gen;
5327ed3d
JW
3494 /* A load of ctx field could have different
3495 * actual load size with the one encoded in the
3496 * insn. When the dst is PTR, it is for sure not
3497 * a sub-register.
3498 */
3499 regs[value_regno].subreg_def = DEF_NOT_SUBREG;
b121b341
YS
3500 if (reg_type == PTR_TO_BTF_ID ||
3501 reg_type == PTR_TO_BTF_ID_OR_NULL)
9e15db66 3502 regs[value_regno].btf_id = btf_id;
46f8bc92 3503 }
638f5b90 3504 regs[value_regno].type = reg_type;
969bf05e 3505 }
17a52670 3506
f1174f77 3507 } else if (reg->type == PTR_TO_STACK) {
f1174f77 3508 off += reg->var_off.value;
e4298d25
DB
3509 err = check_stack_access(env, reg, off, size);
3510 if (err)
3511 return err;
8726679a 3512
f4d7e40a
AS
3513 state = func(env, reg);
3514 err = update_stack_depth(env, state, off);
3515 if (err)
3516 return err;
8726679a 3517
638f5b90 3518 if (t == BPF_WRITE)
61bd5218 3519 err = check_stack_write(env, state, off, size,
af86ca4e 3520 value_regno, insn_idx);
638f5b90 3521 else
61bd5218
JK
3522 err = check_stack_read(env, state, off, size,
3523 value_regno);
de8f3a83 3524 } else if (reg_is_pkt_pointer(reg)) {
3a0af8fd 3525 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
61bd5218 3526 verbose(env, "cannot write into packet\n");
969bf05e
AS
3527 return -EACCES;
3528 }
4acf6c0b
BB
3529 if (t == BPF_WRITE && value_regno >= 0 &&
3530 is_pointer_value(env, value_regno)) {
61bd5218
JK
3531 verbose(env, "R%d leaks addr into packet\n",
3532 value_regno);
4acf6c0b
BB
3533 return -EACCES;
3534 }
9fd29c08 3535 err = check_packet_access(env, regno, off, size, false);
969bf05e 3536 if (!err && t == BPF_READ && value_regno >= 0)
638f5b90 3537 mark_reg_unknown(env, regs, value_regno);
d58e468b
PP
3538 } else if (reg->type == PTR_TO_FLOW_KEYS) {
3539 if (t == BPF_WRITE && value_regno >= 0 &&
3540 is_pointer_value(env, value_regno)) {
3541 verbose(env, "R%d leaks addr into flow keys\n",
3542 value_regno);
3543 return -EACCES;
3544 }
3545
3546 err = check_flow_keys_access(env, off, size);
3547 if (!err && t == BPF_READ && value_regno >= 0)
3548 mark_reg_unknown(env, regs, value_regno);
46f8bc92 3549 } else if (type_is_sk_pointer(reg->type)) {
c64b7983 3550 if (t == BPF_WRITE) {
46f8bc92
MKL
3551 verbose(env, "R%d cannot write into %s\n",
3552 regno, reg_type_str[reg->type]);
c64b7983
JS
3553 return -EACCES;
3554 }
5f456649 3555 err = check_sock_access(env, insn_idx, regno, off, size, t);
c64b7983
JS
3556 if (!err && value_regno >= 0)
3557 mark_reg_unknown(env, regs, value_regno);
9df1c28b
MM
3558 } else if (reg->type == PTR_TO_TP_BUFFER) {
3559 err = check_tp_buffer_access(env, reg, regno, off, size);
3560 if (!err && t == BPF_READ && value_regno >= 0)
3561 mark_reg_unknown(env, regs, value_regno);
9e15db66
AS
3562 } else if (reg->type == PTR_TO_BTF_ID) {
3563 err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
3564 value_regno);
41c48f3a
AI
3565 } else if (reg->type == CONST_PTR_TO_MAP) {
3566 err = check_ptr_to_map_access(env, regs, regno, off, size, t,
3567 value_regno);
afbf21dc
YS
3568 } else if (reg->type == PTR_TO_RDONLY_BUF) {
3569 if (t == BPF_WRITE) {
3570 verbose(env, "R%d cannot write into %s\n",
3571 regno, reg_type_str[reg->type]);
3572 return -EACCES;
3573 }
f6dfbe31
CIK
3574 err = check_buffer_access(env, reg, regno, off, size, false,
3575 "rdonly",
afbf21dc
YS
3576 &env->prog->aux->max_rdonly_access);
3577 if (!err && value_regno >= 0)
3578 mark_reg_unknown(env, regs, value_regno);
3579 } else if (reg->type == PTR_TO_RDWR_BUF) {
f6dfbe31
CIK
3580 err = check_buffer_access(env, reg, regno, off, size, false,
3581 "rdwr",
afbf21dc
YS
3582 &env->prog->aux->max_rdwr_access);
3583 if (!err && t == BPF_READ && value_regno >= 0)
3584 mark_reg_unknown(env, regs, value_regno);
17a52670 3585 } else {
61bd5218
JK
3586 verbose(env, "R%d invalid mem access '%s'\n", regno,
3587 reg_type_str[reg->type]);
17a52670
AS
3588 return -EACCES;
3589 }
969bf05e 3590
f1174f77 3591 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
638f5b90 3592 regs[value_regno].type == SCALAR_VALUE) {
f1174f77 3593 /* b/h/w load zero-extends, mark upper bits as known 0 */
0c17d1d2 3594 coerce_reg_to_size(&regs[value_regno], size);
969bf05e 3595 }
17a52670
AS
3596 return err;
3597}
3598
31fd8581 3599static int check_xadd(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
17a52670 3600{
17a52670
AS
3601 int err;
3602
3603 if ((BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) ||
3604 insn->imm != 0) {
61bd5218 3605 verbose(env, "BPF_XADD uses reserved fields\n");
17a52670
AS
3606 return -EINVAL;
3607 }
3608
3609 /* check src1 operand */
dc503a8a 3610 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17a52670
AS
3611 if (err)
3612 return err;
3613
3614 /* check src2 operand */
dc503a8a 3615 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17a52670
AS
3616 if (err)
3617 return err;
3618
6bdf6abc 3619 if (is_pointer_value(env, insn->src_reg)) {
61bd5218 3620 verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
6bdf6abc
DB
3621 return -EACCES;
3622 }
3623
ca369602 3624 if (is_ctx_reg(env, insn->dst_reg) ||
4b5defde 3625 is_pkt_reg(env, insn->dst_reg) ||
46f8bc92
MKL
3626 is_flow_key_reg(env, insn->dst_reg) ||
3627 is_sk_reg(env, insn->dst_reg)) {
ca369602 3628 verbose(env, "BPF_XADD stores into R%d %s is not allowed\n",
2a159c6f
DB
3629 insn->dst_reg,
3630 reg_type_str[reg_state(env, insn->dst_reg)->type]);
f37a8cb8
DB
3631 return -EACCES;
3632 }
3633
17a52670 3634 /* check whether atomic_add can read the memory */
31fd8581 3635 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
ca369602 3636 BPF_SIZE(insn->code), BPF_READ, -1, true);
17a52670
AS
3637 if (err)
3638 return err;
3639
3640 /* check whether atomic_add can write into the same memory */
31fd8581 3641 return check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
ca369602 3642 BPF_SIZE(insn->code), BPF_WRITE, -1, true);
17a52670
AS
3643}
3644
2011fccf
AI
3645static int __check_stack_boundary(struct bpf_verifier_env *env, u32 regno,
3646 int off, int access_size,
3647 bool zero_size_allowed)
3648{
3649 struct bpf_reg_state *reg = reg_state(env, regno);
3650
3651 if (off >= 0 || off < -MAX_BPF_STACK || off + access_size > 0 ||
3652 access_size < 0 || (access_size == 0 && !zero_size_allowed)) {
3653 if (tnum_is_const(reg->var_off)) {
3654 verbose(env, "invalid stack type R%d off=%d access_size=%d\n",
3655 regno, off, access_size);
3656 } else {
3657 char tn_buf[48];
3658
3659 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3660 verbose(env, "invalid stack type R%d var_off=%s access_size=%d\n",
3661 regno, tn_buf, access_size);
3662 }
3663 return -EACCES;
3664 }
3665 return 0;
3666}
3667
17a52670
AS
3668/* when register 'regno' is passed into function that will read 'access_size'
3669 * bytes from that pointer, make sure that it's within stack boundary
f1174f77
EC
3670 * and all elements of stack are initialized.
3671 * Unlike most pointer bounds-checking functions, this one doesn't take an
3672 * 'off' argument, so it has to add in reg->off itself.
17a52670 3673 */
58e2af8b 3674static int check_stack_boundary(struct bpf_verifier_env *env, int regno,
435faee1
DB
3675 int access_size, bool zero_size_allowed,
3676 struct bpf_call_arg_meta *meta)
17a52670 3677{
2a159c6f 3678 struct bpf_reg_state *reg = reg_state(env, regno);
f4d7e40a 3679 struct bpf_func_state *state = func(env, reg);
f7cf25b2 3680 int err, min_off, max_off, i, j, slot, spi;
17a52670 3681
2011fccf
AI
3682 if (tnum_is_const(reg->var_off)) {
3683 min_off = max_off = reg->var_off.value + reg->off;
3684 err = __check_stack_boundary(env, regno, min_off, access_size,
3685 zero_size_allowed);
3686 if (err)
3687 return err;
3688 } else {
088ec26d
AI
3689 /* Variable offset is prohibited for unprivileged mode for
3690 * simplicity since it requires corresponding support in
3691 * Spectre masking for stack ALU.
3692 * See also retrieve_ptr_limit().
3693 */
2c78ee89 3694 if (!env->bypass_spec_v1) {
088ec26d 3695 char tn_buf[48];
f1174f77 3696
088ec26d
AI
3697 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3698 verbose(env, "R%d indirect variable offset stack access prohibited for !root, var_off=%s\n",
3699 regno, tn_buf);
3700 return -EACCES;
3701 }
f2bcd05e
AI
3702 /* Only initialized buffer on stack is allowed to be accessed
3703 * with variable offset. With uninitialized buffer it's hard to
3704 * guarantee that whole memory is marked as initialized on
3705 * helper return since specific bounds are unknown what may
3706 * cause uninitialized stack leaking.
3707 */
3708 if (meta && meta->raw_mode)
3709 meta = NULL;
3710
107c26a7
AI
3711 if (reg->smax_value >= BPF_MAX_VAR_OFF ||
3712 reg->smax_value <= -BPF_MAX_VAR_OFF) {
3713 verbose(env, "R%d unbounded indirect variable offset stack access\n",
3714 regno);
3715 return -EACCES;
3716 }
2011fccf 3717 min_off = reg->smin_value + reg->off;
107c26a7 3718 max_off = reg->smax_value + reg->off;
2011fccf
AI
3719 err = __check_stack_boundary(env, regno, min_off, access_size,
3720 zero_size_allowed);
107c26a7
AI
3721 if (err) {
3722 verbose(env, "R%d min value is outside of stack bound\n",
3723 regno);
2011fccf 3724 return err;
107c26a7 3725 }
2011fccf
AI
3726 err = __check_stack_boundary(env, regno, max_off, access_size,
3727 zero_size_allowed);
107c26a7
AI
3728 if (err) {
3729 verbose(env, "R%d max value is outside of stack bound\n",
3730 regno);
2011fccf 3731 return err;
107c26a7 3732 }
17a52670
AS
3733 }
3734
435faee1
DB
3735 if (meta && meta->raw_mode) {
3736 meta->access_size = access_size;
3737 meta->regno = regno;
3738 return 0;
3739 }
3740
2011fccf 3741 for (i = min_off; i < max_off + access_size; i++) {
cc2b14d5
AS
3742 u8 *stype;
3743
2011fccf 3744 slot = -i - 1;
638f5b90 3745 spi = slot / BPF_REG_SIZE;
cc2b14d5
AS
3746 if (state->allocated_stack <= slot)
3747 goto err;
3748 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
3749 if (*stype == STACK_MISC)
3750 goto mark;
3751 if (*stype == STACK_ZERO) {
3752 /* helper can write anything into the stack */
3753 *stype = STACK_MISC;
3754 goto mark;
17a52670 3755 }
1d68f22b
YS
3756
3757 if (state->stack[spi].slot_type[0] == STACK_SPILL &&
3758 state->stack[spi].spilled_ptr.type == PTR_TO_BTF_ID)
3759 goto mark;
3760
f7cf25b2
AS
3761 if (state->stack[spi].slot_type[0] == STACK_SPILL &&
3762 state->stack[spi].spilled_ptr.type == SCALAR_VALUE) {
f54c7898 3763 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
f7cf25b2
AS
3764 for (j = 0; j < BPF_REG_SIZE; j++)
3765 state->stack[spi].slot_type[j] = STACK_MISC;
3766 goto mark;
3767 }
3768
cc2b14d5 3769err:
2011fccf
AI
3770 if (tnum_is_const(reg->var_off)) {
3771 verbose(env, "invalid indirect read from stack off %d+%d size %d\n",
3772 min_off, i - min_off, access_size);
3773 } else {
3774 char tn_buf[48];
3775
3776 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3777 verbose(env, "invalid indirect read from stack var_off %s+%d size %d\n",
3778 tn_buf, i - min_off, access_size);
3779 }
cc2b14d5
AS
3780 return -EACCES;
3781mark:
3782 /* reading any byte out of 8-byte 'spill_slot' will cause
3783 * the whole slot to be marked as 'read'
3784 */
679c782d 3785 mark_reg_read(env, &state->stack[spi].spilled_ptr,
5327ed3d
JW
3786 state->stack[spi].spilled_ptr.parent,
3787 REG_LIVE_READ64);
17a52670 3788 }
2011fccf 3789 return update_stack_depth(env, state, min_off);
17a52670
AS
3790}
3791
06c1c049
GB
3792static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
3793 int access_size, bool zero_size_allowed,
3794 struct bpf_call_arg_meta *meta)
3795{
638f5b90 3796 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
06c1c049 3797
f1174f77 3798 switch (reg->type) {
06c1c049 3799 case PTR_TO_PACKET:
de8f3a83 3800 case PTR_TO_PACKET_META:
9fd29c08
YS
3801 return check_packet_access(env, regno, reg->off, access_size,
3802 zero_size_allowed);
06c1c049 3803 case PTR_TO_MAP_VALUE:
591fe988
DB
3804 if (check_map_access_type(env, regno, reg->off, access_size,
3805 meta && meta->raw_mode ? BPF_WRITE :
3806 BPF_READ))
3807 return -EACCES;
9fd29c08
YS
3808 return check_map_access(env, regno, reg->off, access_size,
3809 zero_size_allowed);
457f4436
AN
3810 case PTR_TO_MEM:
3811 return check_mem_region_access(env, regno, reg->off,
3812 access_size, reg->mem_size,
3813 zero_size_allowed);
afbf21dc
YS
3814 case PTR_TO_RDONLY_BUF:
3815 if (meta && meta->raw_mode)
3816 return -EACCES;
3817 return check_buffer_access(env, reg, regno, reg->off,
3818 access_size, zero_size_allowed,
3819 "rdonly",
3820 &env->prog->aux->max_rdonly_access);
3821 case PTR_TO_RDWR_BUF:
3822 return check_buffer_access(env, reg, regno, reg->off,
3823 access_size, zero_size_allowed,
3824 "rdwr",
3825 &env->prog->aux->max_rdwr_access);
0d004c02 3826 case PTR_TO_STACK:
06c1c049
GB
3827 return check_stack_boundary(env, regno, access_size,
3828 zero_size_allowed, meta);
0d004c02
LB
3829 default: /* scalar_value or invalid ptr */
3830 /* Allow zero-byte read from NULL, regardless of pointer type */
3831 if (zero_size_allowed && access_size == 0 &&
3832 register_is_null(reg))
3833 return 0;
3834
3835 verbose(env, "R%d type=%s expected=%s\n", regno,
3836 reg_type_str[reg->type],
3837 reg_type_str[PTR_TO_STACK]);
3838 return -EACCES;
06c1c049
GB
3839 }
3840}
3841
d83525ca
AS
3842/* Implementation details:
3843 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL
3844 * Two bpf_map_lookups (even with the same key) will have different reg->id.
3845 * For traditional PTR_TO_MAP_VALUE the verifier clears reg->id after
3846 * value_or_null->value transition, since the verifier only cares about
3847 * the range of access to valid map value pointer and doesn't care about actual
3848 * address of the map element.
3849 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
3850 * reg->id > 0 after value_or_null->value transition. By doing so
3851 * two bpf_map_lookups will be considered two different pointers that
3852 * point to different bpf_spin_locks.
3853 * The verifier allows taking only one bpf_spin_lock at a time to avoid
3854 * dead-locks.
3855 * Since only one bpf_spin_lock is allowed the checks are simpler than
3856 * reg_is_refcounted() logic. The verifier needs to remember only
3857 * one spin_lock instead of array of acquired_refs.
3858 * cur_state->active_spin_lock remembers which map value element got locked
3859 * and clears it after bpf_spin_unlock.
3860 */
3861static int process_spin_lock(struct bpf_verifier_env *env, int regno,
3862 bool is_lock)
3863{
3864 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
3865 struct bpf_verifier_state *cur = env->cur_state;
3866 bool is_const = tnum_is_const(reg->var_off);
3867 struct bpf_map *map = reg->map_ptr;
3868 u64 val = reg->var_off.value;
3869
d83525ca
AS
3870 if (!is_const) {
3871 verbose(env,
3872 "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
3873 regno);
3874 return -EINVAL;
3875 }
3876 if (!map->btf) {
3877 verbose(env,
3878 "map '%s' has to have BTF in order to use bpf_spin_lock\n",
3879 map->name);
3880 return -EINVAL;
3881 }
3882 if (!map_value_has_spin_lock(map)) {
3883 if (map->spin_lock_off == -E2BIG)
3884 verbose(env,
3885 "map '%s' has more than one 'struct bpf_spin_lock'\n",
3886 map->name);
3887 else if (map->spin_lock_off == -ENOENT)
3888 verbose(env,
3889 "map '%s' doesn't have 'struct bpf_spin_lock'\n",
3890 map->name);
3891 else
3892 verbose(env,
3893 "map '%s' is not a struct type or bpf_spin_lock is mangled\n",
3894 map->name);
3895 return -EINVAL;
3896 }
3897 if (map->spin_lock_off != val + reg->off) {
3898 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock'\n",
3899 val + reg->off);
3900 return -EINVAL;
3901 }
3902 if (is_lock) {
3903 if (cur->active_spin_lock) {
3904 verbose(env,
3905 "Locking two bpf_spin_locks are not allowed\n");
3906 return -EINVAL;
3907 }
3908 cur->active_spin_lock = reg->id;
3909 } else {
3910 if (!cur->active_spin_lock) {
3911 verbose(env, "bpf_spin_unlock without taking a lock\n");
3912 return -EINVAL;
3913 }
3914 if (cur->active_spin_lock != reg->id) {
3915 verbose(env, "bpf_spin_unlock of different lock\n");
3916 return -EINVAL;
3917 }
3918 cur->active_spin_lock = 0;
3919 }
3920 return 0;
3921}
3922
90133415
DB
3923static bool arg_type_is_mem_ptr(enum bpf_arg_type type)
3924{
3925 return type == ARG_PTR_TO_MEM ||
3926 type == ARG_PTR_TO_MEM_OR_NULL ||
3927 type == ARG_PTR_TO_UNINIT_MEM;
3928}
3929
3930static bool arg_type_is_mem_size(enum bpf_arg_type type)
3931{
3932 return type == ARG_CONST_SIZE ||
3933 type == ARG_CONST_SIZE_OR_ZERO;
3934}
3935
457f4436
AN
3936static bool arg_type_is_alloc_size(enum bpf_arg_type type)
3937{
3938 return type == ARG_CONST_ALLOC_SIZE_OR_ZERO;
3939}
3940
57c3bb72
AI
3941static bool arg_type_is_int_ptr(enum bpf_arg_type type)
3942{
3943 return type == ARG_PTR_TO_INT ||
3944 type == ARG_PTR_TO_LONG;
3945}
3946
3947static int int_ptr_type_to_size(enum bpf_arg_type type)
3948{
3949 if (type == ARG_PTR_TO_INT)
3950 return sizeof(u32);
3951 else if (type == ARG_PTR_TO_LONG)
3952 return sizeof(u64);
3953
3954 return -EINVAL;
3955}
3956
912f442c
LB
3957static int resolve_map_arg_type(struct bpf_verifier_env *env,
3958 const struct bpf_call_arg_meta *meta,
3959 enum bpf_arg_type *arg_type)
3960{
3961 if (!meta->map_ptr) {
3962 /* kernel subsystem misconfigured verifier */
3963 verbose(env, "invalid map_ptr to access map->type\n");
3964 return -EACCES;
3965 }
3966
3967 switch (meta->map_ptr->map_type) {
3968 case BPF_MAP_TYPE_SOCKMAP:
3969 case BPF_MAP_TYPE_SOCKHASH:
3970 if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
6550f2dd 3971 *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
912f442c
LB
3972 } else {
3973 verbose(env, "invalid arg_type for sockmap/sockhash\n");
3974 return -EINVAL;
3975 }
3976 break;
3977
3978 default:
3979 break;
3980 }
3981 return 0;
3982}
3983
f79e7ea5
LB
3984struct bpf_reg_types {
3985 const enum bpf_reg_type types[10];
1df8f55a 3986 u32 *btf_id;
f79e7ea5
LB
3987};
3988
3989static const struct bpf_reg_types map_key_value_types = {
3990 .types = {
3991 PTR_TO_STACK,
3992 PTR_TO_PACKET,
3993 PTR_TO_PACKET_META,
3994 PTR_TO_MAP_VALUE,
3995 },
3996};
3997
3998static const struct bpf_reg_types sock_types = {
3999 .types = {
4000 PTR_TO_SOCK_COMMON,
4001 PTR_TO_SOCKET,
4002 PTR_TO_TCP_SOCK,
4003 PTR_TO_XDP_SOCK,
4004 },
4005};
4006
49a2a4d4 4007#ifdef CONFIG_NET
1df8f55a
MKL
4008static const struct bpf_reg_types btf_id_sock_common_types = {
4009 .types = {
4010 PTR_TO_SOCK_COMMON,
4011 PTR_TO_SOCKET,
4012 PTR_TO_TCP_SOCK,
4013 PTR_TO_XDP_SOCK,
4014 PTR_TO_BTF_ID,
4015 },
4016 .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
4017};
49a2a4d4 4018#endif
1df8f55a 4019
f79e7ea5
LB
4020static const struct bpf_reg_types mem_types = {
4021 .types = {
4022 PTR_TO_STACK,
4023 PTR_TO_PACKET,
4024 PTR_TO_PACKET_META,
4025 PTR_TO_MAP_VALUE,
4026 PTR_TO_MEM,
4027 PTR_TO_RDONLY_BUF,
4028 PTR_TO_RDWR_BUF,
4029 },
4030};
4031
4032static const struct bpf_reg_types int_ptr_types = {
4033 .types = {
4034 PTR_TO_STACK,
4035 PTR_TO_PACKET,
4036 PTR_TO_PACKET_META,
4037 PTR_TO_MAP_VALUE,
4038 },
4039};
4040
4041static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
4042static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
4043static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
4044static const struct bpf_reg_types alloc_mem_types = { .types = { PTR_TO_MEM } };
4045static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
4046static const struct bpf_reg_types btf_ptr_types = { .types = { PTR_TO_BTF_ID } };
4047static const struct bpf_reg_types spin_lock_types = { .types = { PTR_TO_MAP_VALUE } };
eaa6bcb7 4048static const struct bpf_reg_types percpu_btf_ptr_types = { .types = { PTR_TO_PERCPU_BTF_ID } };
f79e7ea5 4049
0789e13b 4050static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
f79e7ea5
LB
4051 [ARG_PTR_TO_MAP_KEY] = &map_key_value_types,
4052 [ARG_PTR_TO_MAP_VALUE] = &map_key_value_types,
4053 [ARG_PTR_TO_UNINIT_MAP_VALUE] = &map_key_value_types,
4054 [ARG_PTR_TO_MAP_VALUE_OR_NULL] = &map_key_value_types,
4055 [ARG_CONST_SIZE] = &scalar_types,
4056 [ARG_CONST_SIZE_OR_ZERO] = &scalar_types,
4057 [ARG_CONST_ALLOC_SIZE_OR_ZERO] = &scalar_types,
4058 [ARG_CONST_MAP_PTR] = &const_map_ptr_types,
4059 [ARG_PTR_TO_CTX] = &context_types,
4060 [ARG_PTR_TO_CTX_OR_NULL] = &context_types,
4061 [ARG_PTR_TO_SOCK_COMMON] = &sock_types,
49a2a4d4 4062#ifdef CONFIG_NET
1df8f55a 4063 [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types,
49a2a4d4 4064#endif
f79e7ea5
LB
4065 [ARG_PTR_TO_SOCKET] = &fullsock_types,
4066 [ARG_PTR_TO_SOCKET_OR_NULL] = &fullsock_types,
4067 [ARG_PTR_TO_BTF_ID] = &btf_ptr_types,
4068 [ARG_PTR_TO_SPIN_LOCK] = &spin_lock_types,
4069 [ARG_PTR_TO_MEM] = &mem_types,
4070 [ARG_PTR_TO_MEM_OR_NULL] = &mem_types,
4071 [ARG_PTR_TO_UNINIT_MEM] = &mem_types,
4072 [ARG_PTR_TO_ALLOC_MEM] = &alloc_mem_types,
4073 [ARG_PTR_TO_ALLOC_MEM_OR_NULL] = &alloc_mem_types,
4074 [ARG_PTR_TO_INT] = &int_ptr_types,
4075 [ARG_PTR_TO_LONG] = &int_ptr_types,
eaa6bcb7 4076 [ARG_PTR_TO_PERCPU_BTF_ID] = &percpu_btf_ptr_types,
f79e7ea5
LB
4077};
4078
4079static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
a968d5e2
MKL
4080 enum bpf_arg_type arg_type,
4081 const u32 *arg_btf_id)
f79e7ea5
LB
4082{
4083 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4084 enum bpf_reg_type expected, type = reg->type;
a968d5e2 4085 const struct bpf_reg_types *compatible;
f79e7ea5
LB
4086 int i, j;
4087
a968d5e2
MKL
4088 compatible = compatible_reg_types[arg_type];
4089 if (!compatible) {
4090 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
4091 return -EFAULT;
4092 }
4093
f79e7ea5
LB
4094 for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
4095 expected = compatible->types[i];
4096 if (expected == NOT_INIT)
4097 break;
4098
4099 if (type == expected)
a968d5e2 4100 goto found;
f79e7ea5
LB
4101 }
4102
4103 verbose(env, "R%d type=%s expected=", regno, reg_type_str[type]);
4104 for (j = 0; j + 1 < i; j++)
4105 verbose(env, "%s, ", reg_type_str[compatible->types[j]]);
4106 verbose(env, "%s\n", reg_type_str[compatible->types[j]]);
4107 return -EACCES;
a968d5e2
MKL
4108
4109found:
4110 if (type == PTR_TO_BTF_ID) {
1df8f55a
MKL
4111 if (!arg_btf_id) {
4112 if (!compatible->btf_id) {
4113 verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
4114 return -EFAULT;
4115 }
4116 arg_btf_id = compatible->btf_id;
4117 }
4118
a968d5e2
MKL
4119 if (!btf_struct_ids_match(&env->log, reg->off, reg->btf_id,
4120 *arg_btf_id)) {
4121 verbose(env, "R%d is of type %s but %s is expected\n",
4122 regno, kernel_type_name(reg->btf_id),
4123 kernel_type_name(*arg_btf_id));
4124 return -EACCES;
4125 }
4126
4127 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4128 verbose(env, "R%d is a pointer to in-kernel struct with non-zero offset\n",
4129 regno);
4130 return -EACCES;
4131 }
4132 }
4133
4134 return 0;
f79e7ea5
LB
4135}
4136
af7ec138
YS
4137static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
4138 struct bpf_call_arg_meta *meta,
4139 const struct bpf_func_proto *fn)
17a52670 4140{
af7ec138 4141 u32 regno = BPF_REG_1 + arg;
638f5b90 4142 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
af7ec138 4143 enum bpf_arg_type arg_type = fn->arg_type[arg];
f79e7ea5 4144 enum bpf_reg_type type = reg->type;
17a52670
AS
4145 int err = 0;
4146
80f1d68c 4147 if (arg_type == ARG_DONTCARE)
17a52670
AS
4148 return 0;
4149
dc503a8a
EC
4150 err = check_reg_arg(env, regno, SRC_OP);
4151 if (err)
4152 return err;
17a52670 4153
1be7f75d
AS
4154 if (arg_type == ARG_ANYTHING) {
4155 if (is_pointer_value(env, regno)) {
61bd5218
JK
4156 verbose(env, "R%d leaks addr into helper function\n",
4157 regno);
1be7f75d
AS
4158 return -EACCES;
4159 }
80f1d68c 4160 return 0;
1be7f75d 4161 }
80f1d68c 4162
de8f3a83 4163 if (type_is_pkt_pointer(type) &&
3a0af8fd 4164 !may_access_direct_pkt_data(env, meta, BPF_READ)) {
61bd5218 4165 verbose(env, "helper access to the packet is not allowed\n");
6841de8b
AS
4166 return -EACCES;
4167 }
4168
912f442c
LB
4169 if (arg_type == ARG_PTR_TO_MAP_VALUE ||
4170 arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE ||
4171 arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL) {
4172 err = resolve_map_arg_type(env, meta, &arg_type);
4173 if (err)
4174 return err;
4175 }
4176
fd1b0d60
LB
4177 if (register_is_null(reg) && arg_type_may_be_null(arg_type))
4178 /* A NULL register has a SCALAR_VALUE type, so skip
4179 * type checking.
4180 */
4181 goto skip_type_check;
4182
a968d5e2 4183 err = check_reg_type(env, regno, arg_type, fn->arg_btf_id[arg]);
f79e7ea5
LB
4184 if (err)
4185 return err;
4186
a968d5e2 4187 if (type == PTR_TO_CTX) {
feec7040
LB
4188 err = check_ctx_reg(env, reg, regno);
4189 if (err < 0)
4190 return err;
d7b9454a
LB
4191 }
4192
fd1b0d60 4193skip_type_check:
02f7c958 4194 if (reg->ref_obj_id) {
457f4436
AN
4195 if (meta->ref_obj_id) {
4196 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
4197 regno, reg->ref_obj_id,
4198 meta->ref_obj_id);
4199 return -EFAULT;
4200 }
4201 meta->ref_obj_id = reg->ref_obj_id;
17a52670
AS
4202 }
4203
17a52670
AS
4204 if (arg_type == ARG_CONST_MAP_PTR) {
4205 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
33ff9823 4206 meta->map_ptr = reg->map_ptr;
17a52670
AS
4207 } else if (arg_type == ARG_PTR_TO_MAP_KEY) {
4208 /* bpf_map_xxx(..., map_ptr, ..., key) call:
4209 * check that [key, key + map->key_size) are within
4210 * stack limits and initialized
4211 */
33ff9823 4212 if (!meta->map_ptr) {
17a52670
AS
4213 /* in function declaration map_ptr must come before
4214 * map_key, so that it's verified and known before
4215 * we have to check map_key here. Otherwise it means
4216 * that kernel subsystem misconfigured verifier
4217 */
61bd5218 4218 verbose(env, "invalid map_ptr to access map->key\n");
17a52670
AS
4219 return -EACCES;
4220 }
d71962f3
PC
4221 err = check_helper_mem_access(env, regno,
4222 meta->map_ptr->key_size, false,
4223 NULL);
2ea864c5 4224 } else if (arg_type == ARG_PTR_TO_MAP_VALUE ||
6ac99e8f
MKL
4225 (arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL &&
4226 !register_is_null(reg)) ||
2ea864c5 4227 arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE) {
17a52670
AS
4228 /* bpf_map_xxx(..., map_ptr, ..., value) call:
4229 * check [value, value + map->value_size) validity
4230 */
33ff9823 4231 if (!meta->map_ptr) {
17a52670 4232 /* kernel subsystem misconfigured verifier */
61bd5218 4233 verbose(env, "invalid map_ptr to access map->value\n");
17a52670
AS
4234 return -EACCES;
4235 }
2ea864c5 4236 meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE);
d71962f3
PC
4237 err = check_helper_mem_access(env, regno,
4238 meta->map_ptr->value_size, false,
2ea864c5 4239 meta);
eaa6bcb7
HL
4240 } else if (arg_type == ARG_PTR_TO_PERCPU_BTF_ID) {
4241 if (!reg->btf_id) {
4242 verbose(env, "Helper has invalid btf_id in R%d\n", regno);
4243 return -EACCES;
4244 }
4245 meta->ret_btf_id = reg->btf_id;
c18f0b6a
LB
4246 } else if (arg_type == ARG_PTR_TO_SPIN_LOCK) {
4247 if (meta->func_id == BPF_FUNC_spin_lock) {
4248 if (process_spin_lock(env, regno, true))
4249 return -EACCES;
4250 } else if (meta->func_id == BPF_FUNC_spin_unlock) {
4251 if (process_spin_lock(env, regno, false))
4252 return -EACCES;
4253 } else {
4254 verbose(env, "verifier internal error\n");
4255 return -EFAULT;
4256 }
a2bbe7cc
LB
4257 } else if (arg_type_is_mem_ptr(arg_type)) {
4258 /* The access to this pointer is only checked when we hit the
4259 * next is_mem_size argument below.
4260 */
4261 meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MEM);
90133415 4262 } else if (arg_type_is_mem_size(arg_type)) {
39f19ebb 4263 bool zero_size_allowed = (arg_type == ARG_CONST_SIZE_OR_ZERO);
17a52670 4264
10060503
JF
4265 /* This is used to refine r0 return value bounds for helpers
4266 * that enforce this value as an upper bound on return values.
4267 * See do_refine_retval_range() for helpers that can refine
4268 * the return value. C type of helper is u32 so we pull register
4269 * bound from umax_value however, if negative verifier errors
4270 * out. Only upper bounds can be learned because retval is an
4271 * int type and negative retvals are allowed.
849fa506 4272 */
10060503 4273 meta->msize_max_value = reg->umax_value;
849fa506 4274
f1174f77
EC
4275 /* The register is SCALAR_VALUE; the access check
4276 * happens using its boundaries.
06c1c049 4277 */
f1174f77 4278 if (!tnum_is_const(reg->var_off))
06c1c049
GB
4279 /* For unprivileged variable accesses, disable raw
4280 * mode so that the program is required to
4281 * initialize all the memory that the helper could
4282 * just partially fill up.
4283 */
4284 meta = NULL;
4285
b03c9f9f 4286 if (reg->smin_value < 0) {
61bd5218 4287 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
f1174f77
EC
4288 regno);
4289 return -EACCES;
4290 }
06c1c049 4291
b03c9f9f 4292 if (reg->umin_value == 0) {
f1174f77
EC
4293 err = check_helper_mem_access(env, regno - 1, 0,
4294 zero_size_allowed,
4295 meta);
06c1c049
GB
4296 if (err)
4297 return err;
06c1c049 4298 }
f1174f77 4299
b03c9f9f 4300 if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
61bd5218 4301 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
f1174f77
EC
4302 regno);
4303 return -EACCES;
4304 }
4305 err = check_helper_mem_access(env, regno - 1,
b03c9f9f 4306 reg->umax_value,
f1174f77 4307 zero_size_allowed, meta);
b5dc0163
AS
4308 if (!err)
4309 err = mark_chain_precision(env, regno);
457f4436
AN
4310 } else if (arg_type_is_alloc_size(arg_type)) {
4311 if (!tnum_is_const(reg->var_off)) {
4312 verbose(env, "R%d unbounded size, use 'var &= const' or 'if (var < const)'\n",
4313 regno);
4314 return -EACCES;
4315 }
4316 meta->mem_size = reg->var_off.value;
57c3bb72
AI
4317 } else if (arg_type_is_int_ptr(arg_type)) {
4318 int size = int_ptr_type_to_size(arg_type);
4319
4320 err = check_helper_mem_access(env, regno, size, false, meta);
4321 if (err)
4322 return err;
4323 err = check_ptr_alignment(env, reg, 0, size, true);
17a52670
AS
4324 }
4325
4326 return err;
4327}
4328
0126240f
LB
4329static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
4330{
4331 enum bpf_attach_type eatype = env->prog->expected_attach_type;
7e40781c 4332 enum bpf_prog_type type = resolve_prog_type(env->prog);
0126240f
LB
4333
4334 if (func_id != BPF_FUNC_map_update_elem)
4335 return false;
4336
4337 /* It's not possible to get access to a locked struct sock in these
4338 * contexts, so updating is safe.
4339 */
4340 switch (type) {
4341 case BPF_PROG_TYPE_TRACING:
4342 if (eatype == BPF_TRACE_ITER)
4343 return true;
4344 break;
4345 case BPF_PROG_TYPE_SOCKET_FILTER:
4346 case BPF_PROG_TYPE_SCHED_CLS:
4347 case BPF_PROG_TYPE_SCHED_ACT:
4348 case BPF_PROG_TYPE_XDP:
4349 case BPF_PROG_TYPE_SK_REUSEPORT:
4350 case BPF_PROG_TYPE_FLOW_DISSECTOR:
4351 case BPF_PROG_TYPE_SK_LOOKUP:
4352 return true;
4353 default:
4354 break;
4355 }
4356
4357 verbose(env, "cannot update sockmap in this context\n");
4358 return false;
4359}
4360
e411901c
MF
4361static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
4362{
4363 return env->prog->jit_requested && IS_ENABLED(CONFIG_X86_64);
4364}
4365
61bd5218
JK
4366static int check_map_func_compatibility(struct bpf_verifier_env *env,
4367 struct bpf_map *map, int func_id)
35578d79 4368{
35578d79
KX
4369 if (!map)
4370 return 0;
4371
6aff67c8
AS
4372 /* We need a two way check, first is from map perspective ... */
4373 switch (map->map_type) {
4374 case BPF_MAP_TYPE_PROG_ARRAY:
4375 if (func_id != BPF_FUNC_tail_call)
4376 goto error;
4377 break;
4378 case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
4379 if (func_id != BPF_FUNC_perf_event_read &&
908432ca 4380 func_id != BPF_FUNC_perf_event_output &&
a7658e1a 4381 func_id != BPF_FUNC_skb_output &&
d831ee84
EC
4382 func_id != BPF_FUNC_perf_event_read_value &&
4383 func_id != BPF_FUNC_xdp_output)
6aff67c8
AS
4384 goto error;
4385 break;
457f4436
AN
4386 case BPF_MAP_TYPE_RINGBUF:
4387 if (func_id != BPF_FUNC_ringbuf_output &&
4388 func_id != BPF_FUNC_ringbuf_reserve &&
4389 func_id != BPF_FUNC_ringbuf_submit &&
4390 func_id != BPF_FUNC_ringbuf_discard &&
4391 func_id != BPF_FUNC_ringbuf_query)
4392 goto error;
4393 break;
6aff67c8
AS
4394 case BPF_MAP_TYPE_STACK_TRACE:
4395 if (func_id != BPF_FUNC_get_stackid)
4396 goto error;
4397 break;
4ed8ec52 4398 case BPF_MAP_TYPE_CGROUP_ARRAY:
60747ef4 4399 if (func_id != BPF_FUNC_skb_under_cgroup &&
60d20f91 4400 func_id != BPF_FUNC_current_task_under_cgroup)
4a482f34
MKL
4401 goto error;
4402 break;
cd339431 4403 case BPF_MAP_TYPE_CGROUP_STORAGE:
b741f163 4404 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
cd339431
RG
4405 if (func_id != BPF_FUNC_get_local_storage)
4406 goto error;
4407 break;
546ac1ff 4408 case BPF_MAP_TYPE_DEVMAP:
6f9d451a 4409 case BPF_MAP_TYPE_DEVMAP_HASH:
0cdbb4b0
THJ
4410 if (func_id != BPF_FUNC_redirect_map &&
4411 func_id != BPF_FUNC_map_lookup_elem)
546ac1ff
JF
4412 goto error;
4413 break;
fbfc504a
BT
4414 /* Restrict bpf side of cpumap and xskmap, open when use-cases
4415 * appear.
4416 */
6710e112
JDB
4417 case BPF_MAP_TYPE_CPUMAP:
4418 if (func_id != BPF_FUNC_redirect_map)
4419 goto error;
4420 break;
fada7fdc
JL
4421 case BPF_MAP_TYPE_XSKMAP:
4422 if (func_id != BPF_FUNC_redirect_map &&
4423 func_id != BPF_FUNC_map_lookup_elem)
4424 goto error;
4425 break;
56f668df 4426 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
bcc6b1b7 4427 case BPF_MAP_TYPE_HASH_OF_MAPS:
56f668df
MKL
4428 if (func_id != BPF_FUNC_map_lookup_elem)
4429 goto error;
16a43625 4430 break;
174a79ff
JF
4431 case BPF_MAP_TYPE_SOCKMAP:
4432 if (func_id != BPF_FUNC_sk_redirect_map &&
4433 func_id != BPF_FUNC_sock_map_update &&
4f738adb 4434 func_id != BPF_FUNC_map_delete_elem &&
9fed9000 4435 func_id != BPF_FUNC_msg_redirect_map &&
64d85290 4436 func_id != BPF_FUNC_sk_select_reuseport &&
0126240f
LB
4437 func_id != BPF_FUNC_map_lookup_elem &&
4438 !may_update_sockmap(env, func_id))
174a79ff
JF
4439 goto error;
4440 break;
81110384
JF
4441 case BPF_MAP_TYPE_SOCKHASH:
4442 if (func_id != BPF_FUNC_sk_redirect_hash &&
4443 func_id != BPF_FUNC_sock_hash_update &&
4444 func_id != BPF_FUNC_map_delete_elem &&
9fed9000 4445 func_id != BPF_FUNC_msg_redirect_hash &&
64d85290 4446 func_id != BPF_FUNC_sk_select_reuseport &&
0126240f
LB
4447 func_id != BPF_FUNC_map_lookup_elem &&
4448 !may_update_sockmap(env, func_id))
81110384
JF
4449 goto error;
4450 break;
2dbb9b9e
MKL
4451 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
4452 if (func_id != BPF_FUNC_sk_select_reuseport)
4453 goto error;
4454 break;
f1a2e44a
MV
4455 case BPF_MAP_TYPE_QUEUE:
4456 case BPF_MAP_TYPE_STACK:
4457 if (func_id != BPF_FUNC_map_peek_elem &&
4458 func_id != BPF_FUNC_map_pop_elem &&
4459 func_id != BPF_FUNC_map_push_elem)
4460 goto error;
4461 break;
6ac99e8f
MKL
4462 case BPF_MAP_TYPE_SK_STORAGE:
4463 if (func_id != BPF_FUNC_sk_storage_get &&
4464 func_id != BPF_FUNC_sk_storage_delete)
4465 goto error;
4466 break;
8ea63684
KS
4467 case BPF_MAP_TYPE_INODE_STORAGE:
4468 if (func_id != BPF_FUNC_inode_storage_get &&
4469 func_id != BPF_FUNC_inode_storage_delete)
4470 goto error;
4471 break;
6aff67c8
AS
4472 default:
4473 break;
4474 }
4475
4476 /* ... and second from the function itself. */
4477 switch (func_id) {
4478 case BPF_FUNC_tail_call:
4479 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
4480 goto error;
e411901c
MF
4481 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
4482 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
f4d7e40a
AS
4483 return -EINVAL;
4484 }
6aff67c8
AS
4485 break;
4486 case BPF_FUNC_perf_event_read:
4487 case BPF_FUNC_perf_event_output:
908432ca 4488 case BPF_FUNC_perf_event_read_value:
a7658e1a 4489 case BPF_FUNC_skb_output:
d831ee84 4490 case BPF_FUNC_xdp_output:
6aff67c8
AS
4491 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
4492 goto error;
4493 break;
4494 case BPF_FUNC_get_stackid:
4495 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
4496 goto error;
4497 break;
60d20f91 4498 case BPF_FUNC_current_task_under_cgroup:
747ea55e 4499 case BPF_FUNC_skb_under_cgroup:
4a482f34
MKL
4500 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
4501 goto error;
4502 break;
97f91a7c 4503 case BPF_FUNC_redirect_map:
9c270af3 4504 if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
6f9d451a 4505 map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
fbfc504a
BT
4506 map->map_type != BPF_MAP_TYPE_CPUMAP &&
4507 map->map_type != BPF_MAP_TYPE_XSKMAP)
97f91a7c
JF
4508 goto error;
4509 break;
174a79ff 4510 case BPF_FUNC_sk_redirect_map:
4f738adb 4511 case BPF_FUNC_msg_redirect_map:
81110384 4512 case BPF_FUNC_sock_map_update:
174a79ff
JF
4513 if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
4514 goto error;
4515 break;
81110384
JF
4516 case BPF_FUNC_sk_redirect_hash:
4517 case BPF_FUNC_msg_redirect_hash:
4518 case BPF_FUNC_sock_hash_update:
4519 if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
174a79ff
JF
4520 goto error;
4521 break;
cd339431 4522 case BPF_FUNC_get_local_storage:
b741f163
RG
4523 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
4524 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
cd339431
RG
4525 goto error;
4526 break;
2dbb9b9e 4527 case BPF_FUNC_sk_select_reuseport:
9fed9000
JS
4528 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
4529 map->map_type != BPF_MAP_TYPE_SOCKMAP &&
4530 map->map_type != BPF_MAP_TYPE_SOCKHASH)
2dbb9b9e
MKL
4531 goto error;
4532 break;
f1a2e44a
MV
4533 case BPF_FUNC_map_peek_elem:
4534 case BPF_FUNC_map_pop_elem:
4535 case BPF_FUNC_map_push_elem:
4536 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
4537 map->map_type != BPF_MAP_TYPE_STACK)
4538 goto error;
4539 break;
6ac99e8f
MKL
4540 case BPF_FUNC_sk_storage_get:
4541 case BPF_FUNC_sk_storage_delete:
4542 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
4543 goto error;
4544 break;
8ea63684
KS
4545 case BPF_FUNC_inode_storage_get:
4546 case BPF_FUNC_inode_storage_delete:
4547 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
4548 goto error;
4549 break;
6aff67c8
AS
4550 default:
4551 break;
35578d79
KX
4552 }
4553
4554 return 0;
6aff67c8 4555error:
61bd5218 4556 verbose(env, "cannot pass map_type %d into func %s#%d\n",
ebb676da 4557 map->map_type, func_id_name(func_id), func_id);
6aff67c8 4558 return -EINVAL;
35578d79
KX
4559}
4560
90133415 4561static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
435faee1
DB
4562{
4563 int count = 0;
4564
39f19ebb 4565 if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
435faee1 4566 count++;
39f19ebb 4567 if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
435faee1 4568 count++;
39f19ebb 4569 if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
435faee1 4570 count++;
39f19ebb 4571 if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
435faee1 4572 count++;
39f19ebb 4573 if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
435faee1
DB
4574 count++;
4575
90133415
DB
4576 /* We only support one arg being in raw mode at the moment,
4577 * which is sufficient for the helper functions we have
4578 * right now.
4579 */
4580 return count <= 1;
4581}
4582
4583static bool check_args_pair_invalid(enum bpf_arg_type arg_curr,
4584 enum bpf_arg_type arg_next)
4585{
4586 return (arg_type_is_mem_ptr(arg_curr) &&
4587 !arg_type_is_mem_size(arg_next)) ||
4588 (!arg_type_is_mem_ptr(arg_curr) &&
4589 arg_type_is_mem_size(arg_next));
4590}
4591
4592static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
4593{
4594 /* bpf_xxx(..., buf, len) call will access 'len'
4595 * bytes from memory 'buf'. Both arg types need
4596 * to be paired, so make sure there's no buggy
4597 * helper function specification.
4598 */
4599 if (arg_type_is_mem_size(fn->arg1_type) ||
4600 arg_type_is_mem_ptr(fn->arg5_type) ||
4601 check_args_pair_invalid(fn->arg1_type, fn->arg2_type) ||
4602 check_args_pair_invalid(fn->arg2_type, fn->arg3_type) ||
4603 check_args_pair_invalid(fn->arg3_type, fn->arg4_type) ||
4604 check_args_pair_invalid(fn->arg4_type, fn->arg5_type))
4605 return false;
4606
4607 return true;
4608}
4609
1b986589 4610static bool check_refcount_ok(const struct bpf_func_proto *fn, int func_id)
fd978bf7
JS
4611{
4612 int count = 0;
4613
1b986589 4614 if (arg_type_may_be_refcounted(fn->arg1_type))
fd978bf7 4615 count++;
1b986589 4616 if (arg_type_may_be_refcounted(fn->arg2_type))
fd978bf7 4617 count++;
1b986589 4618 if (arg_type_may_be_refcounted(fn->arg3_type))
fd978bf7 4619 count++;
1b986589 4620 if (arg_type_may_be_refcounted(fn->arg4_type))
fd978bf7 4621 count++;
1b986589 4622 if (arg_type_may_be_refcounted(fn->arg5_type))
fd978bf7
JS
4623 count++;
4624
1b986589
MKL
4625 /* A reference acquiring function cannot acquire
4626 * another refcounted ptr.
4627 */
64d85290 4628 if (may_be_acquire_function(func_id) && count)
1b986589
MKL
4629 return false;
4630
fd978bf7
JS
4631 /* We only support one arg being unreferenced at the moment,
4632 * which is sufficient for the helper functions we have right now.
4633 */
4634 return count <= 1;
4635}
4636
9436ef6e
LB
4637static bool check_btf_id_ok(const struct bpf_func_proto *fn)
4638{
4639 int i;
4640
1df8f55a 4641 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
9436ef6e
LB
4642 if (fn->arg_type[i] == ARG_PTR_TO_BTF_ID && !fn->arg_btf_id[i])
4643 return false;
4644
1df8f55a
MKL
4645 if (fn->arg_type[i] != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i])
4646 return false;
4647 }
4648
9436ef6e
LB
4649 return true;
4650}
4651
1b986589 4652static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
90133415
DB
4653{
4654 return check_raw_mode_ok(fn) &&
fd978bf7 4655 check_arg_pair_ok(fn) &&
9436ef6e 4656 check_btf_id_ok(fn) &&
1b986589 4657 check_refcount_ok(fn, func_id) ? 0 : -EINVAL;
435faee1
DB
4658}
4659
de8f3a83
DB
4660/* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
4661 * are now invalid, so turn them into unknown SCALAR_VALUE.
f1174f77 4662 */
f4d7e40a
AS
4663static void __clear_all_pkt_pointers(struct bpf_verifier_env *env,
4664 struct bpf_func_state *state)
969bf05e 4665{
58e2af8b 4666 struct bpf_reg_state *regs = state->regs, *reg;
969bf05e
AS
4667 int i;
4668
4669 for (i = 0; i < MAX_BPF_REG; i++)
de8f3a83 4670 if (reg_is_pkt_pointer_any(&regs[i]))
61bd5218 4671 mark_reg_unknown(env, regs, i);
969bf05e 4672
f3709f69
JS
4673 bpf_for_each_spilled_reg(i, state, reg) {
4674 if (!reg)
969bf05e 4675 continue;
de8f3a83 4676 if (reg_is_pkt_pointer_any(reg))
f54c7898 4677 __mark_reg_unknown(env, reg);
969bf05e
AS
4678 }
4679}
4680
f4d7e40a
AS
4681static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
4682{
4683 struct bpf_verifier_state *vstate = env->cur_state;
4684 int i;
4685
4686 for (i = 0; i <= vstate->curframe; i++)
4687 __clear_all_pkt_pointers(env, vstate->frame[i]);
4688}
4689
fd978bf7 4690static void release_reg_references(struct bpf_verifier_env *env,
1b986589
MKL
4691 struct bpf_func_state *state,
4692 int ref_obj_id)
fd978bf7
JS
4693{
4694 struct bpf_reg_state *regs = state->regs, *reg;
4695 int i;
4696
4697 for (i = 0; i < MAX_BPF_REG; i++)
1b986589 4698 if (regs[i].ref_obj_id == ref_obj_id)
fd978bf7
JS
4699 mark_reg_unknown(env, regs, i);
4700
4701 bpf_for_each_spilled_reg(i, state, reg) {
4702 if (!reg)
4703 continue;
1b986589 4704 if (reg->ref_obj_id == ref_obj_id)
f54c7898 4705 __mark_reg_unknown(env, reg);
fd978bf7
JS
4706 }
4707}
4708
4709/* The pointer with the specified id has released its reference to kernel
4710 * resources. Identify all copies of the same pointer and clear the reference.
4711 */
4712static int release_reference(struct bpf_verifier_env *env,
1b986589 4713 int ref_obj_id)
fd978bf7
JS
4714{
4715 struct bpf_verifier_state *vstate = env->cur_state;
1b986589 4716 int err;
fd978bf7
JS
4717 int i;
4718
1b986589
MKL
4719 err = release_reference_state(cur_func(env), ref_obj_id);
4720 if (err)
4721 return err;
4722
fd978bf7 4723 for (i = 0; i <= vstate->curframe; i++)
1b986589 4724 release_reg_references(env, vstate->frame[i], ref_obj_id);
fd978bf7 4725
1b986589 4726 return 0;
fd978bf7
JS
4727}
4728
51c39bb1
AS
4729static void clear_caller_saved_regs(struct bpf_verifier_env *env,
4730 struct bpf_reg_state *regs)
4731{
4732 int i;
4733
4734 /* after the call registers r0 - r5 were scratched */
4735 for (i = 0; i < CALLER_SAVED_REGS; i++) {
4736 mark_reg_not_init(env, regs, caller_saved[i]);
4737 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
4738 }
4739}
4740
f4d7e40a
AS
4741static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
4742 int *insn_idx)
4743{
4744 struct bpf_verifier_state *state = env->cur_state;
51c39bb1 4745 struct bpf_func_info_aux *func_info_aux;
f4d7e40a 4746 struct bpf_func_state *caller, *callee;
fd978bf7 4747 int i, err, subprog, target_insn;
51c39bb1 4748 bool is_global = false;
f4d7e40a 4749
aada9ce6 4750 if (state->curframe + 1 >= MAX_CALL_FRAMES) {
f4d7e40a 4751 verbose(env, "the call stack of %d frames is too deep\n",
aada9ce6 4752 state->curframe + 2);
f4d7e40a
AS
4753 return -E2BIG;
4754 }
4755
4756 target_insn = *insn_idx + insn->imm;
4757 subprog = find_subprog(env, target_insn + 1);
4758 if (subprog < 0) {
4759 verbose(env, "verifier bug. No program starts at insn %d\n",
4760 target_insn + 1);
4761 return -EFAULT;
4762 }
4763
4764 caller = state->frame[state->curframe];
4765 if (state->frame[state->curframe + 1]) {
4766 verbose(env, "verifier bug. Frame %d already allocated\n",
4767 state->curframe + 1);
4768 return -EFAULT;
4769 }
4770
51c39bb1
AS
4771 func_info_aux = env->prog->aux->func_info_aux;
4772 if (func_info_aux)
4773 is_global = func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
4774 err = btf_check_func_arg_match(env, subprog, caller->regs);
4775 if (err == -EFAULT)
4776 return err;
4777 if (is_global) {
4778 if (err) {
4779 verbose(env, "Caller passes invalid args into func#%d\n",
4780 subprog);
4781 return err;
4782 } else {
4783 if (env->log.level & BPF_LOG_LEVEL)
4784 verbose(env,
4785 "Func#%d is global and valid. Skipping.\n",
4786 subprog);
4787 clear_caller_saved_regs(env, caller->regs);
4788
4789 /* All global functions return SCALAR_VALUE */
4790 mark_reg_unknown(env, caller->regs, BPF_REG_0);
4791
4792 /* continue with next insn after call */
4793 return 0;
4794 }
4795 }
4796
f4d7e40a
AS
4797 callee = kzalloc(sizeof(*callee), GFP_KERNEL);
4798 if (!callee)
4799 return -ENOMEM;
4800 state->frame[state->curframe + 1] = callee;
4801
4802 /* callee cannot access r0, r6 - r9 for reading and has to write
4803 * into its own stack before reading from it.
4804 * callee can read/write into caller's stack
4805 */
4806 init_func_state(env, callee,
4807 /* remember the callsite, it will be used by bpf_exit */
4808 *insn_idx /* callsite */,
4809 state->curframe + 1 /* frameno within this callchain */,
f910cefa 4810 subprog /* subprog number within this prog */);
f4d7e40a 4811
fd978bf7
JS
4812 /* Transfer references to the callee */
4813 err = transfer_reference_state(callee, caller);
4814 if (err)
4815 return err;
4816
679c782d
EC
4817 /* copy r1 - r5 args that callee can access. The copy includes parent
4818 * pointers, which connects us up to the liveness chain
4819 */
f4d7e40a
AS
4820 for (i = BPF_REG_1; i <= BPF_REG_5; i++)
4821 callee->regs[i] = caller->regs[i];
4822
51c39bb1 4823 clear_caller_saved_regs(env, caller->regs);
f4d7e40a
AS
4824
4825 /* only increment it after check_reg_arg() finished */
4826 state->curframe++;
4827
4828 /* and go analyze first insn of the callee */
4829 *insn_idx = target_insn;
4830
06ee7115 4831 if (env->log.level & BPF_LOG_LEVEL) {
f4d7e40a
AS
4832 verbose(env, "caller:\n");
4833 print_verifier_state(env, caller);
4834 verbose(env, "callee:\n");
4835 print_verifier_state(env, callee);
4836 }
4837 return 0;
4838}
4839
4840static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
4841{
4842 struct bpf_verifier_state *state = env->cur_state;
4843 struct bpf_func_state *caller, *callee;
4844 struct bpf_reg_state *r0;
fd978bf7 4845 int err;
f4d7e40a
AS
4846
4847 callee = state->frame[state->curframe];
4848 r0 = &callee->regs[BPF_REG_0];
4849 if (r0->type == PTR_TO_STACK) {
4850 /* technically it's ok to return caller's stack pointer
4851 * (or caller's caller's pointer) back to the caller,
4852 * since these pointers are valid. Only current stack
4853 * pointer will be invalid as soon as function exits,
4854 * but let's be conservative
4855 */
4856 verbose(env, "cannot return stack pointer to the caller\n");
4857 return -EINVAL;
4858 }
4859
4860 state->curframe--;
4861 caller = state->frame[state->curframe];
4862 /* return to the caller whatever r0 had in the callee */
4863 caller->regs[BPF_REG_0] = *r0;
4864
fd978bf7
JS
4865 /* Transfer references to the caller */
4866 err = transfer_reference_state(caller, callee);
4867 if (err)
4868 return err;
4869
f4d7e40a 4870 *insn_idx = callee->callsite + 1;
06ee7115 4871 if (env->log.level & BPF_LOG_LEVEL) {
f4d7e40a
AS
4872 verbose(env, "returning from callee:\n");
4873 print_verifier_state(env, callee);
4874 verbose(env, "to caller at %d:\n", *insn_idx);
4875 print_verifier_state(env, caller);
4876 }
4877 /* clear everything in the callee */
4878 free_func_state(callee);
4879 state->frame[state->curframe + 1] = NULL;
4880 return 0;
4881}
4882
849fa506
YS
4883static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
4884 int func_id,
4885 struct bpf_call_arg_meta *meta)
4886{
4887 struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
4888
4889 if (ret_type != RET_INTEGER ||
4890 (func_id != BPF_FUNC_get_stack &&
47cc0ed5
DB
4891 func_id != BPF_FUNC_probe_read_str &&
4892 func_id != BPF_FUNC_probe_read_kernel_str &&
4893 func_id != BPF_FUNC_probe_read_user_str))
849fa506
YS
4894 return;
4895
10060503 4896 ret_reg->smax_value = meta->msize_max_value;
fa123ac0 4897 ret_reg->s32_max_value = meta->msize_max_value;
849fa506
YS
4898 __reg_deduce_bounds(ret_reg);
4899 __reg_bound_offset(ret_reg);
10060503 4900 __update_reg_bounds(ret_reg);
849fa506
YS
4901}
4902
c93552c4
DB
4903static int
4904record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
4905 int func_id, int insn_idx)
4906{
4907 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
591fe988 4908 struct bpf_map *map = meta->map_ptr;
c93552c4
DB
4909
4910 if (func_id != BPF_FUNC_tail_call &&
09772d92
DB
4911 func_id != BPF_FUNC_map_lookup_elem &&
4912 func_id != BPF_FUNC_map_update_elem &&
f1a2e44a
MV
4913 func_id != BPF_FUNC_map_delete_elem &&
4914 func_id != BPF_FUNC_map_push_elem &&
4915 func_id != BPF_FUNC_map_pop_elem &&
4916 func_id != BPF_FUNC_map_peek_elem)
c93552c4 4917 return 0;
09772d92 4918
591fe988 4919 if (map == NULL) {
c93552c4
DB
4920 verbose(env, "kernel subsystem misconfigured verifier\n");
4921 return -EINVAL;
4922 }
4923
591fe988
DB
4924 /* In case of read-only, some additional restrictions
4925 * need to be applied in order to prevent altering the
4926 * state of the map from program side.
4927 */
4928 if ((map->map_flags & BPF_F_RDONLY_PROG) &&
4929 (func_id == BPF_FUNC_map_delete_elem ||
4930 func_id == BPF_FUNC_map_update_elem ||
4931 func_id == BPF_FUNC_map_push_elem ||
4932 func_id == BPF_FUNC_map_pop_elem)) {
4933 verbose(env, "write into map forbidden\n");
4934 return -EACCES;
4935 }
4936
d2e4c1e6 4937 if (!BPF_MAP_PTR(aux->map_ptr_state))
c93552c4 4938 bpf_map_ptr_store(aux, meta->map_ptr,
2c78ee89 4939 !meta->map_ptr->bypass_spec_v1);
d2e4c1e6 4940 else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
c93552c4 4941 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
2c78ee89 4942 !meta->map_ptr->bypass_spec_v1);
c93552c4
DB
4943 return 0;
4944}
4945
d2e4c1e6
DB
4946static int
4947record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
4948 int func_id, int insn_idx)
4949{
4950 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
4951 struct bpf_reg_state *regs = cur_regs(env), *reg;
4952 struct bpf_map *map = meta->map_ptr;
4953 struct tnum range;
4954 u64 val;
cc52d914 4955 int err;
d2e4c1e6
DB
4956
4957 if (func_id != BPF_FUNC_tail_call)
4958 return 0;
4959 if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
4960 verbose(env, "kernel subsystem misconfigured verifier\n");
4961 return -EINVAL;
4962 }
4963
4964 range = tnum_range(0, map->max_entries - 1);
4965 reg = &regs[BPF_REG_3];
4966
4967 if (!register_is_const(reg) || !tnum_in(range, reg->var_off)) {
4968 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
4969 return 0;
4970 }
4971
cc52d914
DB
4972 err = mark_chain_precision(env, BPF_REG_3);
4973 if (err)
4974 return err;
4975
d2e4c1e6
DB
4976 val = reg->var_off.value;
4977 if (bpf_map_key_unseen(aux))
4978 bpf_map_key_store(aux, val);
4979 else if (!bpf_map_key_poisoned(aux) &&
4980 bpf_map_key_immediate(aux) != val)
4981 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
4982 return 0;
4983}
4984
fd978bf7
JS
4985static int check_reference_leak(struct bpf_verifier_env *env)
4986{
4987 struct bpf_func_state *state = cur_func(env);
4988 int i;
4989
4990 for (i = 0; i < state->acquired_refs; i++) {
4991 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
4992 state->refs[i].id, state->refs[i].insn_idx);
4993 }
4994 return state->acquired_refs ? -EINVAL : 0;
4995}
4996
f4d7e40a 4997static int check_helper_call(struct bpf_verifier_env *env, int func_id, int insn_idx)
17a52670 4998{
17a52670 4999 const struct bpf_func_proto *fn = NULL;
638f5b90 5000 struct bpf_reg_state *regs;
33ff9823 5001 struct bpf_call_arg_meta meta;
969bf05e 5002 bool changes_data;
17a52670
AS
5003 int i, err;
5004
5005 /* find function prototype */
5006 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
61bd5218
JK
5007 verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
5008 func_id);
17a52670
AS
5009 return -EINVAL;
5010 }
5011
00176a34 5012 if (env->ops->get_func_proto)
5e43f899 5013 fn = env->ops->get_func_proto(func_id, env->prog);
17a52670 5014 if (!fn) {
61bd5218
JK
5015 verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
5016 func_id);
17a52670
AS
5017 return -EINVAL;
5018 }
5019
5020 /* eBPF programs must be GPL compatible to use GPL-ed functions */
24701ece 5021 if (!env->prog->gpl_compatible && fn->gpl_only) {
3fe2867c 5022 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
17a52670
AS
5023 return -EINVAL;
5024 }
5025
eae2e83e
JO
5026 if (fn->allowed && !fn->allowed(env->prog)) {
5027 verbose(env, "helper call is not allowed in probe\n");
5028 return -EINVAL;
5029 }
5030
04514d13 5031 /* With LD_ABS/IND some JITs save/restore skb from r1. */
17bedab2 5032 changes_data = bpf_helper_changes_pkt_data(fn->func);
04514d13
DB
5033 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
5034 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
5035 func_id_name(func_id), func_id);
5036 return -EINVAL;
5037 }
969bf05e 5038
33ff9823 5039 memset(&meta, 0, sizeof(meta));
36bbef52 5040 meta.pkt_access = fn->pkt_access;
33ff9823 5041
1b986589 5042 err = check_func_proto(fn, func_id);
435faee1 5043 if (err) {
61bd5218 5044 verbose(env, "kernel subsystem misconfigured func %s#%d\n",
ebb676da 5045 func_id_name(func_id), func_id);
435faee1
DB
5046 return err;
5047 }
5048
d83525ca 5049 meta.func_id = func_id;
17a52670 5050 /* check args */
a7658e1a 5051 for (i = 0; i < 5; i++) {
af7ec138 5052 err = check_func_arg(env, i, &meta, fn);
a7658e1a
AS
5053 if (err)
5054 return err;
5055 }
17a52670 5056
c93552c4
DB
5057 err = record_func_map(env, &meta, func_id, insn_idx);
5058 if (err)
5059 return err;
5060
d2e4c1e6
DB
5061 err = record_func_key(env, &meta, func_id, insn_idx);
5062 if (err)
5063 return err;
5064
435faee1
DB
5065 /* Mark slots with STACK_MISC in case of raw mode, stack offset
5066 * is inferred from register state.
5067 */
5068 for (i = 0; i < meta.access_size; i++) {
ca369602
DB
5069 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
5070 BPF_WRITE, -1, false);
435faee1
DB
5071 if (err)
5072 return err;
5073 }
5074
fd978bf7
JS
5075 if (func_id == BPF_FUNC_tail_call) {
5076 err = check_reference_leak(env);
5077 if (err) {
5078 verbose(env, "tail_call would lead to reference leak\n");
5079 return err;
5080 }
5081 } else if (is_release_function(func_id)) {
1b986589 5082 err = release_reference(env, meta.ref_obj_id);
46f8bc92
MKL
5083 if (err) {
5084 verbose(env, "func %s#%d reference has not been acquired before\n",
5085 func_id_name(func_id), func_id);
fd978bf7 5086 return err;
46f8bc92 5087 }
fd978bf7
JS
5088 }
5089
638f5b90 5090 regs = cur_regs(env);
cd339431
RG
5091
5092 /* check that flags argument in get_local_storage(map, flags) is 0,
5093 * this is required because get_local_storage() can't return an error.
5094 */
5095 if (func_id == BPF_FUNC_get_local_storage &&
5096 !register_is_null(&regs[BPF_REG_2])) {
5097 verbose(env, "get_local_storage() doesn't support non-zero flags\n");
5098 return -EINVAL;
5099 }
5100
17a52670 5101 /* reset caller saved regs */
dc503a8a 5102 for (i = 0; i < CALLER_SAVED_REGS; i++) {
61bd5218 5103 mark_reg_not_init(env, regs, caller_saved[i]);
dc503a8a
EC
5104 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
5105 }
17a52670 5106
5327ed3d
JW
5107 /* helper call returns 64-bit value. */
5108 regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
5109
dc503a8a 5110 /* update return register (already marked as written above) */
17a52670 5111 if (fn->ret_type == RET_INTEGER) {
f1174f77 5112 /* sets type to SCALAR_VALUE */
61bd5218 5113 mark_reg_unknown(env, regs, BPF_REG_0);
17a52670
AS
5114 } else if (fn->ret_type == RET_VOID) {
5115 regs[BPF_REG_0].type = NOT_INIT;
3e6a4b3e
RG
5116 } else if (fn->ret_type == RET_PTR_TO_MAP_VALUE_OR_NULL ||
5117 fn->ret_type == RET_PTR_TO_MAP_VALUE) {
f1174f77 5118 /* There is no offset yet applied, variable or fixed */
61bd5218 5119 mark_reg_known_zero(env, regs, BPF_REG_0);
17a52670
AS
5120 /* remember map_ptr, so that check_map_access()
5121 * can check 'value_size' boundary of memory access
5122 * to map element returned from bpf_map_lookup_elem()
5123 */
33ff9823 5124 if (meta.map_ptr == NULL) {
61bd5218
JK
5125 verbose(env,
5126 "kernel subsystem misconfigured verifier\n");
17a52670
AS
5127 return -EINVAL;
5128 }
33ff9823 5129 regs[BPF_REG_0].map_ptr = meta.map_ptr;
4d31f301
DB
5130 if (fn->ret_type == RET_PTR_TO_MAP_VALUE) {
5131 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE;
e16d2f1a
AS
5132 if (map_value_has_spin_lock(meta.map_ptr))
5133 regs[BPF_REG_0].id = ++env->id_gen;
4d31f301
DB
5134 } else {
5135 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE_OR_NULL;
5136 regs[BPF_REG_0].id = ++env->id_gen;
5137 }
c64b7983
JS
5138 } else if (fn->ret_type == RET_PTR_TO_SOCKET_OR_NULL) {
5139 mark_reg_known_zero(env, regs, BPF_REG_0);
5140 regs[BPF_REG_0].type = PTR_TO_SOCKET_OR_NULL;
0f3adc28 5141 regs[BPF_REG_0].id = ++env->id_gen;
85a51f8c
LB
5142 } else if (fn->ret_type == RET_PTR_TO_SOCK_COMMON_OR_NULL) {
5143 mark_reg_known_zero(env, regs, BPF_REG_0);
5144 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON_OR_NULL;
5145 regs[BPF_REG_0].id = ++env->id_gen;
655a51e5
MKL
5146 } else if (fn->ret_type == RET_PTR_TO_TCP_SOCK_OR_NULL) {
5147 mark_reg_known_zero(env, regs, BPF_REG_0);
5148 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK_OR_NULL;
5149 regs[BPF_REG_0].id = ++env->id_gen;
457f4436
AN
5150 } else if (fn->ret_type == RET_PTR_TO_ALLOC_MEM_OR_NULL) {
5151 mark_reg_known_zero(env, regs, BPF_REG_0);
5152 regs[BPF_REG_0].type = PTR_TO_MEM_OR_NULL;
5153 regs[BPF_REG_0].id = ++env->id_gen;
5154 regs[BPF_REG_0].mem_size = meta.mem_size;
63d9b80d
HL
5155 } else if (fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID_OR_NULL ||
5156 fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID) {
eaa6bcb7
HL
5157 const struct btf_type *t;
5158
5159 mark_reg_known_zero(env, regs, BPF_REG_0);
5160 t = btf_type_skip_modifiers(btf_vmlinux, meta.ret_btf_id, NULL);
5161 if (!btf_type_is_struct(t)) {
5162 u32 tsize;
5163 const struct btf_type *ret;
5164 const char *tname;
5165
5166 /* resolve the type size of ksym. */
5167 ret = btf_resolve_size(btf_vmlinux, t, &tsize);
5168 if (IS_ERR(ret)) {
5169 tname = btf_name_by_offset(btf_vmlinux, t->name_off);
5170 verbose(env, "unable to resolve the size of type '%s': %ld\n",
5171 tname, PTR_ERR(ret));
5172 return -EINVAL;
5173 }
63d9b80d
HL
5174 regs[BPF_REG_0].type =
5175 fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID ?
5176 PTR_TO_MEM : PTR_TO_MEM_OR_NULL;
eaa6bcb7
HL
5177 regs[BPF_REG_0].mem_size = tsize;
5178 } else {
63d9b80d
HL
5179 regs[BPF_REG_0].type =
5180 fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID ?
5181 PTR_TO_BTF_ID : PTR_TO_BTF_ID_OR_NULL;
eaa6bcb7
HL
5182 regs[BPF_REG_0].btf_id = meta.ret_btf_id;
5183 }
af7ec138
YS
5184 } else if (fn->ret_type == RET_PTR_TO_BTF_ID_OR_NULL) {
5185 int ret_btf_id;
5186
5187 mark_reg_known_zero(env, regs, BPF_REG_0);
5188 regs[BPF_REG_0].type = PTR_TO_BTF_ID_OR_NULL;
5189 ret_btf_id = *fn->ret_btf_id;
5190 if (ret_btf_id == 0) {
5191 verbose(env, "invalid return type %d of func %s#%d\n",
5192 fn->ret_type, func_id_name(func_id), func_id);
5193 return -EINVAL;
5194 }
5195 regs[BPF_REG_0].btf_id = ret_btf_id;
17a52670 5196 } else {
61bd5218 5197 verbose(env, "unknown return type %d of func %s#%d\n",
ebb676da 5198 fn->ret_type, func_id_name(func_id), func_id);
17a52670
AS
5199 return -EINVAL;
5200 }
04fd61ab 5201
0f3adc28 5202 if (is_ptr_cast_function(func_id)) {
1b986589
MKL
5203 /* For release_reference() */
5204 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
64d85290 5205 } else if (is_acquire_function(func_id, meta.map_ptr)) {
0f3adc28
LB
5206 int id = acquire_reference_state(env, insn_idx);
5207
5208 if (id < 0)
5209 return id;
5210 /* For mark_ptr_or_null_reg() */
5211 regs[BPF_REG_0].id = id;
5212 /* For release_reference() */
5213 regs[BPF_REG_0].ref_obj_id = id;
5214 }
1b986589 5215
849fa506
YS
5216 do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
5217
61bd5218 5218 err = check_map_func_compatibility(env, meta.map_ptr, func_id);
35578d79
KX
5219 if (err)
5220 return err;
04fd61ab 5221
fa28dcb8
SL
5222 if ((func_id == BPF_FUNC_get_stack ||
5223 func_id == BPF_FUNC_get_task_stack) &&
5224 !env->prog->has_callchain_buf) {
c195651e
YS
5225 const char *err_str;
5226
5227#ifdef CONFIG_PERF_EVENTS
5228 err = get_callchain_buffers(sysctl_perf_event_max_stack);
5229 err_str = "cannot get callchain buffer for func %s#%d\n";
5230#else
5231 err = -ENOTSUPP;
5232 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
5233#endif
5234 if (err) {
5235 verbose(env, err_str, func_id_name(func_id), func_id);
5236 return err;
5237 }
5238
5239 env->prog->has_callchain_buf = true;
5240 }
5241
5d99cb2c
SL
5242 if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
5243 env->prog->call_get_stack = true;
5244
969bf05e
AS
5245 if (changes_data)
5246 clear_all_pkt_pointers(env);
5247 return 0;
5248}
5249
b03c9f9f
EC
5250static bool signed_add_overflows(s64 a, s64 b)
5251{
5252 /* Do the add in u64, where overflow is well-defined */
5253 s64 res = (s64)((u64)a + (u64)b);
5254
5255 if (b < 0)
5256 return res > a;
5257 return res < a;
5258}
5259
3f50f132
JF
5260static bool signed_add32_overflows(s64 a, s64 b)
5261{
5262 /* Do the add in u32, where overflow is well-defined */
5263 s32 res = (s32)((u32)a + (u32)b);
5264
5265 if (b < 0)
5266 return res > a;
5267 return res < a;
5268}
5269
5270static bool signed_sub_overflows(s32 a, s32 b)
b03c9f9f
EC
5271{
5272 /* Do the sub in u64, where overflow is well-defined */
5273 s64 res = (s64)((u64)a - (u64)b);
5274
5275 if (b < 0)
5276 return res < a;
5277 return res > a;
969bf05e
AS
5278}
5279
3f50f132
JF
5280static bool signed_sub32_overflows(s32 a, s32 b)
5281{
5282 /* Do the sub in u64, where overflow is well-defined */
5283 s32 res = (s32)((u32)a - (u32)b);
5284
5285 if (b < 0)
5286 return res < a;
5287 return res > a;
5288}
5289
bb7f0f98
AS
5290static bool check_reg_sane_offset(struct bpf_verifier_env *env,
5291 const struct bpf_reg_state *reg,
5292 enum bpf_reg_type type)
5293{
5294 bool known = tnum_is_const(reg->var_off);
5295 s64 val = reg->var_off.value;
5296 s64 smin = reg->smin_value;
5297
5298 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
5299 verbose(env, "math between %s pointer and %lld is not allowed\n",
5300 reg_type_str[type], val);
5301 return false;
5302 }
5303
5304 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
5305 verbose(env, "%s pointer offset %d is not allowed\n",
5306 reg_type_str[type], reg->off);
5307 return false;
5308 }
5309
5310 if (smin == S64_MIN) {
5311 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
5312 reg_type_str[type]);
5313 return false;
5314 }
5315
5316 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
5317 verbose(env, "value %lld makes %s pointer be out of bounds\n",
5318 smin, reg_type_str[type]);
5319 return false;
5320 }
5321
5322 return true;
5323}
5324
979d63d5
DB
5325static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
5326{
5327 return &env->insn_aux_data[env->insn_idx];
5328}
5329
5330static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
5331 u32 *ptr_limit, u8 opcode, bool off_is_neg)
5332{
5333 bool mask_to_left = (opcode == BPF_ADD && off_is_neg) ||
5334 (opcode == BPF_SUB && !off_is_neg);
5335 u32 off;
5336
5337 switch (ptr_reg->type) {
5338 case PTR_TO_STACK:
088ec26d
AI
5339 /* Indirect variable offset stack access is prohibited in
5340 * unprivileged mode so it's not handled here.
5341 */
979d63d5
DB
5342 off = ptr_reg->off + ptr_reg->var_off.value;
5343 if (mask_to_left)
5344 *ptr_limit = MAX_BPF_STACK + off;
5345 else
5346 *ptr_limit = -off;
5347 return 0;
5348 case PTR_TO_MAP_VALUE:
5349 if (mask_to_left) {
5350 *ptr_limit = ptr_reg->umax_value + ptr_reg->off;
5351 } else {
5352 off = ptr_reg->smin_value + ptr_reg->off;
5353 *ptr_limit = ptr_reg->map_ptr->value_size - off;
5354 }
5355 return 0;
5356 default:
5357 return -EINVAL;
5358 }
5359}
5360
d3bd7413
DB
5361static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
5362 const struct bpf_insn *insn)
5363{
2c78ee89 5364 return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
d3bd7413
DB
5365}
5366
5367static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
5368 u32 alu_state, u32 alu_limit)
5369{
5370 /* If we arrived here from different branches with different
5371 * state or limits to sanitize, then this won't work.
5372 */
5373 if (aux->alu_state &&
5374 (aux->alu_state != alu_state ||
5375 aux->alu_limit != alu_limit))
5376 return -EACCES;
5377
5378 /* Corresponding fixup done in fixup_bpf_calls(). */
5379 aux->alu_state = alu_state;
5380 aux->alu_limit = alu_limit;
5381 return 0;
5382}
5383
5384static int sanitize_val_alu(struct bpf_verifier_env *env,
5385 struct bpf_insn *insn)
5386{
5387 struct bpf_insn_aux_data *aux = cur_aux(env);
5388
5389 if (can_skip_alu_sanitation(env, insn))
5390 return 0;
5391
5392 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
5393}
5394
979d63d5
DB
5395static int sanitize_ptr_alu(struct bpf_verifier_env *env,
5396 struct bpf_insn *insn,
5397 const struct bpf_reg_state *ptr_reg,
5398 struct bpf_reg_state *dst_reg,
5399 bool off_is_neg)
5400{
5401 struct bpf_verifier_state *vstate = env->cur_state;
5402 struct bpf_insn_aux_data *aux = cur_aux(env);
5403 bool ptr_is_dst_reg = ptr_reg == dst_reg;
5404 u8 opcode = BPF_OP(insn->code);
5405 u32 alu_state, alu_limit;
5406 struct bpf_reg_state tmp;
5407 bool ret;
5408
d3bd7413 5409 if (can_skip_alu_sanitation(env, insn))
979d63d5
DB
5410 return 0;
5411
5412 /* We already marked aux for masking from non-speculative
5413 * paths, thus we got here in the first place. We only care
5414 * to explore bad access from here.
5415 */
5416 if (vstate->speculative)
5417 goto do_sim;
5418
5419 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
5420 alu_state |= ptr_is_dst_reg ?
5421 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
5422
5423 if (retrieve_ptr_limit(ptr_reg, &alu_limit, opcode, off_is_neg))
5424 return 0;
d3bd7413 5425 if (update_alu_sanitation_state(aux, alu_state, alu_limit))
979d63d5 5426 return -EACCES;
979d63d5
DB
5427do_sim:
5428 /* Simulate and find potential out-of-bounds access under
5429 * speculative execution from truncation as a result of
5430 * masking when off was not within expected range. If off
5431 * sits in dst, then we temporarily need to move ptr there
5432 * to simulate dst (== 0) +/-= ptr. Needed, for example,
5433 * for cases where we use K-based arithmetic in one direction
5434 * and truncated reg-based in the other in order to explore
5435 * bad access.
5436 */
5437 if (!ptr_is_dst_reg) {
5438 tmp = *dst_reg;
5439 *dst_reg = *ptr_reg;
5440 }
5441 ret = push_stack(env, env->insn_idx + 1, env->insn_idx, true);
0803278b 5442 if (!ptr_is_dst_reg && ret)
979d63d5
DB
5443 *dst_reg = tmp;
5444 return !ret ? -EFAULT : 0;
5445}
5446
f1174f77 5447/* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
f1174f77
EC
5448 * Caller should also handle BPF_MOV case separately.
5449 * If we return -EACCES, caller may want to try again treating pointer as a
5450 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks.
5451 */
5452static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
5453 struct bpf_insn *insn,
5454 const struct bpf_reg_state *ptr_reg,
5455 const struct bpf_reg_state *off_reg)
969bf05e 5456{
f4d7e40a
AS
5457 struct bpf_verifier_state *vstate = env->cur_state;
5458 struct bpf_func_state *state = vstate->frame[vstate->curframe];
5459 struct bpf_reg_state *regs = state->regs, *dst_reg;
f1174f77 5460 bool known = tnum_is_const(off_reg->var_off);
b03c9f9f
EC
5461 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
5462 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
5463 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
5464 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
9d7eceed 5465 u32 dst = insn->dst_reg, src = insn->src_reg;
969bf05e 5466 u8 opcode = BPF_OP(insn->code);
979d63d5 5467 int ret;
969bf05e 5468
f1174f77 5469 dst_reg = &regs[dst];
969bf05e 5470
6f16101e
DB
5471 if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
5472 smin_val > smax_val || umin_val > umax_val) {
5473 /* Taint dst register if offset had invalid bounds derived from
5474 * e.g. dead branches.
5475 */
f54c7898 5476 __mark_reg_unknown(env, dst_reg);
6f16101e 5477 return 0;
f1174f77
EC
5478 }
5479
5480 if (BPF_CLASS(insn->code) != BPF_ALU64) {
5481 /* 32-bit ALU ops on pointers produce (meaningless) scalars */
6c693541
YS
5482 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
5483 __mark_reg_unknown(env, dst_reg);
5484 return 0;
5485 }
5486
82abbf8d
AS
5487 verbose(env,
5488 "R%d 32-bit pointer arithmetic prohibited\n",
5489 dst);
f1174f77 5490 return -EACCES;
969bf05e
AS
5491 }
5492
aad2eeaf
JS
5493 switch (ptr_reg->type) {
5494 case PTR_TO_MAP_VALUE_OR_NULL:
5495 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
5496 dst, reg_type_str[ptr_reg->type]);
f1174f77 5497 return -EACCES;
aad2eeaf 5498 case CONST_PTR_TO_MAP:
7c696732
YS
5499 /* smin_val represents the known value */
5500 if (known && smin_val == 0 && opcode == BPF_ADD)
5501 break;
8731745e 5502 fallthrough;
aad2eeaf 5503 case PTR_TO_PACKET_END:
c64b7983
JS
5504 case PTR_TO_SOCKET:
5505 case PTR_TO_SOCKET_OR_NULL:
46f8bc92
MKL
5506 case PTR_TO_SOCK_COMMON:
5507 case PTR_TO_SOCK_COMMON_OR_NULL:
655a51e5
MKL
5508 case PTR_TO_TCP_SOCK:
5509 case PTR_TO_TCP_SOCK_OR_NULL:
fada7fdc 5510 case PTR_TO_XDP_SOCK:
aad2eeaf
JS
5511 verbose(env, "R%d pointer arithmetic on %s prohibited\n",
5512 dst, reg_type_str[ptr_reg->type]);
f1174f77 5513 return -EACCES;
9d7eceed
DB
5514 case PTR_TO_MAP_VALUE:
5515 if (!env->allow_ptr_leaks && !known && (smin_val < 0) != (smax_val < 0)) {
5516 verbose(env, "R%d has unknown scalar with mixed signed bounds, pointer arithmetic with it prohibited for !root\n",
5517 off_reg == dst_reg ? dst : src);
5518 return -EACCES;
5519 }
df561f66 5520 fallthrough;
aad2eeaf
JS
5521 default:
5522 break;
f1174f77
EC
5523 }
5524
5525 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
5526 * The id may be overwritten later if we create a new variable offset.
969bf05e 5527 */
f1174f77
EC
5528 dst_reg->type = ptr_reg->type;
5529 dst_reg->id = ptr_reg->id;
969bf05e 5530
bb7f0f98
AS
5531 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
5532 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
5533 return -EINVAL;
5534
3f50f132
JF
5535 /* pointer types do not carry 32-bit bounds at the moment. */
5536 __mark_reg32_unbounded(dst_reg);
5537
f1174f77
EC
5538 switch (opcode) {
5539 case BPF_ADD:
979d63d5
DB
5540 ret = sanitize_ptr_alu(env, insn, ptr_reg, dst_reg, smin_val < 0);
5541 if (ret < 0) {
5542 verbose(env, "R%d tried to add from different maps or paths\n", dst);
5543 return ret;
5544 }
f1174f77
EC
5545 /* We can take a fixed offset as long as it doesn't overflow
5546 * the s32 'off' field
969bf05e 5547 */
b03c9f9f
EC
5548 if (known && (ptr_reg->off + smin_val ==
5549 (s64)(s32)(ptr_reg->off + smin_val))) {
f1174f77 5550 /* pointer += K. Accumulate it into fixed offset */
b03c9f9f
EC
5551 dst_reg->smin_value = smin_ptr;
5552 dst_reg->smax_value = smax_ptr;
5553 dst_reg->umin_value = umin_ptr;
5554 dst_reg->umax_value = umax_ptr;
f1174f77 5555 dst_reg->var_off = ptr_reg->var_off;
b03c9f9f 5556 dst_reg->off = ptr_reg->off + smin_val;
0962590e 5557 dst_reg->raw = ptr_reg->raw;
f1174f77
EC
5558 break;
5559 }
f1174f77
EC
5560 /* A new variable offset is created. Note that off_reg->off
5561 * == 0, since it's a scalar.
5562 * dst_reg gets the pointer type and since some positive
5563 * integer value was added to the pointer, give it a new 'id'
5564 * if it's a PTR_TO_PACKET.
5565 * this creates a new 'base' pointer, off_reg (variable) gets
5566 * added into the variable offset, and we copy the fixed offset
5567 * from ptr_reg.
969bf05e 5568 */
b03c9f9f
EC
5569 if (signed_add_overflows(smin_ptr, smin_val) ||
5570 signed_add_overflows(smax_ptr, smax_val)) {
5571 dst_reg->smin_value = S64_MIN;
5572 dst_reg->smax_value = S64_MAX;
5573 } else {
5574 dst_reg->smin_value = smin_ptr + smin_val;
5575 dst_reg->smax_value = smax_ptr + smax_val;
5576 }
5577 if (umin_ptr + umin_val < umin_ptr ||
5578 umax_ptr + umax_val < umax_ptr) {
5579 dst_reg->umin_value = 0;
5580 dst_reg->umax_value = U64_MAX;
5581 } else {
5582 dst_reg->umin_value = umin_ptr + umin_val;
5583 dst_reg->umax_value = umax_ptr + umax_val;
5584 }
f1174f77
EC
5585 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
5586 dst_reg->off = ptr_reg->off;
0962590e 5587 dst_reg->raw = ptr_reg->raw;
de8f3a83 5588 if (reg_is_pkt_pointer(ptr_reg)) {
f1174f77
EC
5589 dst_reg->id = ++env->id_gen;
5590 /* something was added to pkt_ptr, set range to zero */
0962590e 5591 dst_reg->raw = 0;
f1174f77
EC
5592 }
5593 break;
5594 case BPF_SUB:
979d63d5
DB
5595 ret = sanitize_ptr_alu(env, insn, ptr_reg, dst_reg, smin_val < 0);
5596 if (ret < 0) {
5597 verbose(env, "R%d tried to sub from different maps or paths\n", dst);
5598 return ret;
5599 }
f1174f77
EC
5600 if (dst_reg == off_reg) {
5601 /* scalar -= pointer. Creates an unknown scalar */
82abbf8d
AS
5602 verbose(env, "R%d tried to subtract pointer from scalar\n",
5603 dst);
f1174f77
EC
5604 return -EACCES;
5605 }
5606 /* We don't allow subtraction from FP, because (according to
5607 * test_verifier.c test "invalid fp arithmetic", JITs might not
5608 * be able to deal with it.
969bf05e 5609 */
f1174f77 5610 if (ptr_reg->type == PTR_TO_STACK) {
82abbf8d
AS
5611 verbose(env, "R%d subtraction from stack pointer prohibited\n",
5612 dst);
f1174f77
EC
5613 return -EACCES;
5614 }
b03c9f9f
EC
5615 if (known && (ptr_reg->off - smin_val ==
5616 (s64)(s32)(ptr_reg->off - smin_val))) {
f1174f77 5617 /* pointer -= K. Subtract it from fixed offset */
b03c9f9f
EC
5618 dst_reg->smin_value = smin_ptr;
5619 dst_reg->smax_value = smax_ptr;
5620 dst_reg->umin_value = umin_ptr;
5621 dst_reg->umax_value = umax_ptr;
f1174f77
EC
5622 dst_reg->var_off = ptr_reg->var_off;
5623 dst_reg->id = ptr_reg->id;
b03c9f9f 5624 dst_reg->off = ptr_reg->off - smin_val;
0962590e 5625 dst_reg->raw = ptr_reg->raw;
f1174f77
EC
5626 break;
5627 }
f1174f77
EC
5628 /* A new variable offset is created. If the subtrahend is known
5629 * nonnegative, then any reg->range we had before is still good.
969bf05e 5630 */
b03c9f9f
EC
5631 if (signed_sub_overflows(smin_ptr, smax_val) ||
5632 signed_sub_overflows(smax_ptr, smin_val)) {
5633 /* Overflow possible, we know nothing */
5634 dst_reg->smin_value = S64_MIN;
5635 dst_reg->smax_value = S64_MAX;
5636 } else {
5637 dst_reg->smin_value = smin_ptr - smax_val;
5638 dst_reg->smax_value = smax_ptr - smin_val;
5639 }
5640 if (umin_ptr < umax_val) {
5641 /* Overflow possible, we know nothing */
5642 dst_reg->umin_value = 0;
5643 dst_reg->umax_value = U64_MAX;
5644 } else {
5645 /* Cannot overflow (as long as bounds are consistent) */
5646 dst_reg->umin_value = umin_ptr - umax_val;
5647 dst_reg->umax_value = umax_ptr - umin_val;
5648 }
f1174f77
EC
5649 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
5650 dst_reg->off = ptr_reg->off;
0962590e 5651 dst_reg->raw = ptr_reg->raw;
de8f3a83 5652 if (reg_is_pkt_pointer(ptr_reg)) {
f1174f77
EC
5653 dst_reg->id = ++env->id_gen;
5654 /* something was added to pkt_ptr, set range to zero */
b03c9f9f 5655 if (smin_val < 0)
0962590e 5656 dst_reg->raw = 0;
43188702 5657 }
f1174f77
EC
5658 break;
5659 case BPF_AND:
5660 case BPF_OR:
5661 case BPF_XOR:
82abbf8d
AS
5662 /* bitwise ops on pointers are troublesome, prohibit. */
5663 verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
5664 dst, bpf_alu_string[opcode >> 4]);
f1174f77
EC
5665 return -EACCES;
5666 default:
5667 /* other operators (e.g. MUL,LSH) produce non-pointer results */
82abbf8d
AS
5668 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
5669 dst, bpf_alu_string[opcode >> 4]);
f1174f77 5670 return -EACCES;
43188702
JF
5671 }
5672
bb7f0f98
AS
5673 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
5674 return -EINVAL;
5675
b03c9f9f
EC
5676 __update_reg_bounds(dst_reg);
5677 __reg_deduce_bounds(dst_reg);
5678 __reg_bound_offset(dst_reg);
0d6303db
DB
5679
5680 /* For unprivileged we require that resulting offset must be in bounds
5681 * in order to be able to sanitize access later on.
5682 */
2c78ee89 5683 if (!env->bypass_spec_v1) {
e4298d25
DB
5684 if (dst_reg->type == PTR_TO_MAP_VALUE &&
5685 check_map_access(env, dst, dst_reg->off, 1, false)) {
5686 verbose(env, "R%d pointer arithmetic of map value goes out of range, "
5687 "prohibited for !root\n", dst);
5688 return -EACCES;
5689 } else if (dst_reg->type == PTR_TO_STACK &&
5690 check_stack_access(env, dst_reg, dst_reg->off +
5691 dst_reg->var_off.value, 1)) {
5692 verbose(env, "R%d stack pointer arithmetic goes out of range, "
5693 "prohibited for !root\n", dst);
5694 return -EACCES;
5695 }
0d6303db
DB
5696 }
5697
43188702
JF
5698 return 0;
5699}
5700
3f50f132
JF
5701static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
5702 struct bpf_reg_state *src_reg)
5703{
5704 s32 smin_val = src_reg->s32_min_value;
5705 s32 smax_val = src_reg->s32_max_value;
5706 u32 umin_val = src_reg->u32_min_value;
5707 u32 umax_val = src_reg->u32_max_value;
5708
5709 if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
5710 signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
5711 dst_reg->s32_min_value = S32_MIN;
5712 dst_reg->s32_max_value = S32_MAX;
5713 } else {
5714 dst_reg->s32_min_value += smin_val;
5715 dst_reg->s32_max_value += smax_val;
5716 }
5717 if (dst_reg->u32_min_value + umin_val < umin_val ||
5718 dst_reg->u32_max_value + umax_val < umax_val) {
5719 dst_reg->u32_min_value = 0;
5720 dst_reg->u32_max_value = U32_MAX;
5721 } else {
5722 dst_reg->u32_min_value += umin_val;
5723 dst_reg->u32_max_value += umax_val;
5724 }
5725}
5726
07cd2631
JF
5727static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
5728 struct bpf_reg_state *src_reg)
5729{
5730 s64 smin_val = src_reg->smin_value;
5731 s64 smax_val = src_reg->smax_value;
5732 u64 umin_val = src_reg->umin_value;
5733 u64 umax_val = src_reg->umax_value;
5734
5735 if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
5736 signed_add_overflows(dst_reg->smax_value, smax_val)) {
5737 dst_reg->smin_value = S64_MIN;
5738 dst_reg->smax_value = S64_MAX;
5739 } else {
5740 dst_reg->smin_value += smin_val;
5741 dst_reg->smax_value += smax_val;
5742 }
5743 if (dst_reg->umin_value + umin_val < umin_val ||
5744 dst_reg->umax_value + umax_val < umax_val) {
5745 dst_reg->umin_value = 0;
5746 dst_reg->umax_value = U64_MAX;
5747 } else {
5748 dst_reg->umin_value += umin_val;
5749 dst_reg->umax_value += umax_val;
5750 }
3f50f132
JF
5751}
5752
5753static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
5754 struct bpf_reg_state *src_reg)
5755{
5756 s32 smin_val = src_reg->s32_min_value;
5757 s32 smax_val = src_reg->s32_max_value;
5758 u32 umin_val = src_reg->u32_min_value;
5759 u32 umax_val = src_reg->u32_max_value;
5760
5761 if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
5762 signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
5763 /* Overflow possible, we know nothing */
5764 dst_reg->s32_min_value = S32_MIN;
5765 dst_reg->s32_max_value = S32_MAX;
5766 } else {
5767 dst_reg->s32_min_value -= smax_val;
5768 dst_reg->s32_max_value -= smin_val;
5769 }
5770 if (dst_reg->u32_min_value < umax_val) {
5771 /* Overflow possible, we know nothing */
5772 dst_reg->u32_min_value = 0;
5773 dst_reg->u32_max_value = U32_MAX;
5774 } else {
5775 /* Cannot overflow (as long as bounds are consistent) */
5776 dst_reg->u32_min_value -= umax_val;
5777 dst_reg->u32_max_value -= umin_val;
5778 }
07cd2631
JF
5779}
5780
5781static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
5782 struct bpf_reg_state *src_reg)
5783{
5784 s64 smin_val = src_reg->smin_value;
5785 s64 smax_val = src_reg->smax_value;
5786 u64 umin_val = src_reg->umin_value;
5787 u64 umax_val = src_reg->umax_value;
5788
5789 if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
5790 signed_sub_overflows(dst_reg->smax_value, smin_val)) {
5791 /* Overflow possible, we know nothing */
5792 dst_reg->smin_value = S64_MIN;
5793 dst_reg->smax_value = S64_MAX;
5794 } else {
5795 dst_reg->smin_value -= smax_val;
5796 dst_reg->smax_value -= smin_val;
5797 }
5798 if (dst_reg->umin_value < umax_val) {
5799 /* Overflow possible, we know nothing */
5800 dst_reg->umin_value = 0;
5801 dst_reg->umax_value = U64_MAX;
5802 } else {
5803 /* Cannot overflow (as long as bounds are consistent) */
5804 dst_reg->umin_value -= umax_val;
5805 dst_reg->umax_value -= umin_val;
5806 }
3f50f132
JF
5807}
5808
5809static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
5810 struct bpf_reg_state *src_reg)
5811{
5812 s32 smin_val = src_reg->s32_min_value;
5813 u32 umin_val = src_reg->u32_min_value;
5814 u32 umax_val = src_reg->u32_max_value;
5815
5816 if (smin_val < 0 || dst_reg->s32_min_value < 0) {
5817 /* Ain't nobody got time to multiply that sign */
5818 __mark_reg32_unbounded(dst_reg);
5819 return;
5820 }
5821 /* Both values are positive, so we can work with unsigned and
5822 * copy the result to signed (unless it exceeds S32_MAX).
5823 */
5824 if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
5825 /* Potential overflow, we know nothing */
5826 __mark_reg32_unbounded(dst_reg);
5827 return;
5828 }
5829 dst_reg->u32_min_value *= umin_val;
5830 dst_reg->u32_max_value *= umax_val;
5831 if (dst_reg->u32_max_value > S32_MAX) {
5832 /* Overflow possible, we know nothing */
5833 dst_reg->s32_min_value = S32_MIN;
5834 dst_reg->s32_max_value = S32_MAX;
5835 } else {
5836 dst_reg->s32_min_value = dst_reg->u32_min_value;
5837 dst_reg->s32_max_value = dst_reg->u32_max_value;
5838 }
07cd2631
JF
5839}
5840
5841static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
5842 struct bpf_reg_state *src_reg)
5843{
5844 s64 smin_val = src_reg->smin_value;
5845 u64 umin_val = src_reg->umin_value;
5846 u64 umax_val = src_reg->umax_value;
5847
07cd2631
JF
5848 if (smin_val < 0 || dst_reg->smin_value < 0) {
5849 /* Ain't nobody got time to multiply that sign */
3f50f132 5850 __mark_reg64_unbounded(dst_reg);
07cd2631
JF
5851 return;
5852 }
5853 /* Both values are positive, so we can work with unsigned and
5854 * copy the result to signed (unless it exceeds S64_MAX).
5855 */
5856 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
5857 /* Potential overflow, we know nothing */
3f50f132 5858 __mark_reg64_unbounded(dst_reg);
07cd2631
JF
5859 return;
5860 }
5861 dst_reg->umin_value *= umin_val;
5862 dst_reg->umax_value *= umax_val;
5863 if (dst_reg->umax_value > S64_MAX) {
5864 /* Overflow possible, we know nothing */
5865 dst_reg->smin_value = S64_MIN;
5866 dst_reg->smax_value = S64_MAX;
5867 } else {
5868 dst_reg->smin_value = dst_reg->umin_value;
5869 dst_reg->smax_value = dst_reg->umax_value;
5870 }
5871}
5872
3f50f132
JF
5873static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
5874 struct bpf_reg_state *src_reg)
5875{
5876 bool src_known = tnum_subreg_is_const(src_reg->var_off);
5877 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
5878 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
5879 s32 smin_val = src_reg->s32_min_value;
5880 u32 umax_val = src_reg->u32_max_value;
5881
5882 /* Assuming scalar64_min_max_and will be called so its safe
5883 * to skip updating register for known 32-bit case.
5884 */
5885 if (src_known && dst_known)
5886 return;
5887
5888 /* We get our minimum from the var_off, since that's inherently
5889 * bitwise. Our maximum is the minimum of the operands' maxima.
5890 */
5891 dst_reg->u32_min_value = var32_off.value;
5892 dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
5893 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
5894 /* Lose signed bounds when ANDing negative numbers,
5895 * ain't nobody got time for that.
5896 */
5897 dst_reg->s32_min_value = S32_MIN;
5898 dst_reg->s32_max_value = S32_MAX;
5899 } else {
5900 /* ANDing two positives gives a positive, so safe to
5901 * cast result into s64.
5902 */
5903 dst_reg->s32_min_value = dst_reg->u32_min_value;
5904 dst_reg->s32_max_value = dst_reg->u32_max_value;
5905 }
5906
5907}
5908
07cd2631
JF
5909static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
5910 struct bpf_reg_state *src_reg)
5911{
3f50f132
JF
5912 bool src_known = tnum_is_const(src_reg->var_off);
5913 bool dst_known = tnum_is_const(dst_reg->var_off);
07cd2631
JF
5914 s64 smin_val = src_reg->smin_value;
5915 u64 umax_val = src_reg->umax_value;
5916
3f50f132 5917 if (src_known && dst_known) {
4fbb38a3 5918 __mark_reg_known(dst_reg, dst_reg->var_off.value);
3f50f132
JF
5919 return;
5920 }
5921
07cd2631
JF
5922 /* We get our minimum from the var_off, since that's inherently
5923 * bitwise. Our maximum is the minimum of the operands' maxima.
5924 */
07cd2631
JF
5925 dst_reg->umin_value = dst_reg->var_off.value;
5926 dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
5927 if (dst_reg->smin_value < 0 || smin_val < 0) {
5928 /* Lose signed bounds when ANDing negative numbers,
5929 * ain't nobody got time for that.
5930 */
5931 dst_reg->smin_value = S64_MIN;
5932 dst_reg->smax_value = S64_MAX;
5933 } else {
5934 /* ANDing two positives gives a positive, so safe to
5935 * cast result into s64.
5936 */
5937 dst_reg->smin_value = dst_reg->umin_value;
5938 dst_reg->smax_value = dst_reg->umax_value;
5939 }
5940 /* We may learn something more from the var_off */
5941 __update_reg_bounds(dst_reg);
5942}
5943
3f50f132
JF
5944static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
5945 struct bpf_reg_state *src_reg)
5946{
5947 bool src_known = tnum_subreg_is_const(src_reg->var_off);
5948 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
5949 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
5b9fbeb7
DB
5950 s32 smin_val = src_reg->s32_min_value;
5951 u32 umin_val = src_reg->u32_min_value;
3f50f132
JF
5952
5953 /* Assuming scalar64_min_max_or will be called so it is safe
5954 * to skip updating register for known case.
5955 */
5956 if (src_known && dst_known)
5957 return;
5958
5959 /* We get our maximum from the var_off, and our minimum is the
5960 * maximum of the operands' minima
5961 */
5962 dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
5963 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
5964 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
5965 /* Lose signed bounds when ORing negative numbers,
5966 * ain't nobody got time for that.
5967 */
5968 dst_reg->s32_min_value = S32_MIN;
5969 dst_reg->s32_max_value = S32_MAX;
5970 } else {
5971 /* ORing two positives gives a positive, so safe to
5972 * cast result into s64.
5973 */
5b9fbeb7
DB
5974 dst_reg->s32_min_value = dst_reg->u32_min_value;
5975 dst_reg->s32_max_value = dst_reg->u32_max_value;
3f50f132
JF
5976 }
5977}
5978
07cd2631
JF
5979static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
5980 struct bpf_reg_state *src_reg)
5981{
3f50f132
JF
5982 bool src_known = tnum_is_const(src_reg->var_off);
5983 bool dst_known = tnum_is_const(dst_reg->var_off);
07cd2631
JF
5984 s64 smin_val = src_reg->smin_value;
5985 u64 umin_val = src_reg->umin_value;
5986
3f50f132 5987 if (src_known && dst_known) {
4fbb38a3 5988 __mark_reg_known(dst_reg, dst_reg->var_off.value);
3f50f132
JF
5989 return;
5990 }
5991
07cd2631
JF
5992 /* We get our maximum from the var_off, and our minimum is the
5993 * maximum of the operands' minima
5994 */
07cd2631
JF
5995 dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
5996 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
5997 if (dst_reg->smin_value < 0 || smin_val < 0) {
5998 /* Lose signed bounds when ORing negative numbers,
5999 * ain't nobody got time for that.
6000 */
6001 dst_reg->smin_value = S64_MIN;
6002 dst_reg->smax_value = S64_MAX;
6003 } else {
6004 /* ORing two positives gives a positive, so safe to
6005 * cast result into s64.
6006 */
6007 dst_reg->smin_value = dst_reg->umin_value;
6008 dst_reg->smax_value = dst_reg->umax_value;
6009 }
6010 /* We may learn something more from the var_off */
6011 __update_reg_bounds(dst_reg);
6012}
6013
2921c90d
YS
6014static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
6015 struct bpf_reg_state *src_reg)
6016{
6017 bool src_known = tnum_subreg_is_const(src_reg->var_off);
6018 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
6019 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
6020 s32 smin_val = src_reg->s32_min_value;
6021
6022 /* Assuming scalar64_min_max_xor will be called so it is safe
6023 * to skip updating register for known case.
6024 */
6025 if (src_known && dst_known)
6026 return;
6027
6028 /* We get both minimum and maximum from the var32_off. */
6029 dst_reg->u32_min_value = var32_off.value;
6030 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
6031
6032 if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
6033 /* XORing two positive sign numbers gives a positive,
6034 * so safe to cast u32 result into s32.
6035 */
6036 dst_reg->s32_min_value = dst_reg->u32_min_value;
6037 dst_reg->s32_max_value = dst_reg->u32_max_value;
6038 } else {
6039 dst_reg->s32_min_value = S32_MIN;
6040 dst_reg->s32_max_value = S32_MAX;
6041 }
6042}
6043
6044static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
6045 struct bpf_reg_state *src_reg)
6046{
6047 bool src_known = tnum_is_const(src_reg->var_off);
6048 bool dst_known = tnum_is_const(dst_reg->var_off);
6049 s64 smin_val = src_reg->smin_value;
6050
6051 if (src_known && dst_known) {
6052 /* dst_reg->var_off.value has been updated earlier */
6053 __mark_reg_known(dst_reg, dst_reg->var_off.value);
6054 return;
6055 }
6056
6057 /* We get both minimum and maximum from the var_off. */
6058 dst_reg->umin_value = dst_reg->var_off.value;
6059 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
6060
6061 if (dst_reg->smin_value >= 0 && smin_val >= 0) {
6062 /* XORing two positive sign numbers gives a positive,
6063 * so safe to cast u64 result into s64.
6064 */
6065 dst_reg->smin_value = dst_reg->umin_value;
6066 dst_reg->smax_value = dst_reg->umax_value;
6067 } else {
6068 dst_reg->smin_value = S64_MIN;
6069 dst_reg->smax_value = S64_MAX;
6070 }
6071
6072 __update_reg_bounds(dst_reg);
6073}
6074
3f50f132
JF
6075static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
6076 u64 umin_val, u64 umax_val)
07cd2631 6077{
07cd2631
JF
6078 /* We lose all sign bit information (except what we can pick
6079 * up from var_off)
6080 */
3f50f132
JF
6081 dst_reg->s32_min_value = S32_MIN;
6082 dst_reg->s32_max_value = S32_MAX;
6083 /* If we might shift our top bit out, then we know nothing */
6084 if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
6085 dst_reg->u32_min_value = 0;
6086 dst_reg->u32_max_value = U32_MAX;
6087 } else {
6088 dst_reg->u32_min_value <<= umin_val;
6089 dst_reg->u32_max_value <<= umax_val;
6090 }
6091}
6092
6093static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
6094 struct bpf_reg_state *src_reg)
6095{
6096 u32 umax_val = src_reg->u32_max_value;
6097 u32 umin_val = src_reg->u32_min_value;
6098 /* u32 alu operation will zext upper bits */
6099 struct tnum subreg = tnum_subreg(dst_reg->var_off);
6100
6101 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
6102 dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
6103 /* Not required but being careful mark reg64 bounds as unknown so
6104 * that we are forced to pick them up from tnum and zext later and
6105 * if some path skips this step we are still safe.
6106 */
6107 __mark_reg64_unbounded(dst_reg);
6108 __update_reg32_bounds(dst_reg);
6109}
6110
6111static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
6112 u64 umin_val, u64 umax_val)
6113{
6114 /* Special case <<32 because it is a common compiler pattern to sign
6115 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
6116 * positive we know this shift will also be positive so we can track
6117 * bounds correctly. Otherwise we lose all sign bit information except
6118 * what we can pick up from var_off. Perhaps we can generalize this
6119 * later to shifts of any length.
6120 */
6121 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
6122 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
6123 else
6124 dst_reg->smax_value = S64_MAX;
6125
6126 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
6127 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
6128 else
6129 dst_reg->smin_value = S64_MIN;
6130
07cd2631
JF
6131 /* If we might shift our top bit out, then we know nothing */
6132 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
6133 dst_reg->umin_value = 0;
6134 dst_reg->umax_value = U64_MAX;
6135 } else {
6136 dst_reg->umin_value <<= umin_val;
6137 dst_reg->umax_value <<= umax_val;
6138 }
3f50f132
JF
6139}
6140
6141static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
6142 struct bpf_reg_state *src_reg)
6143{
6144 u64 umax_val = src_reg->umax_value;
6145 u64 umin_val = src_reg->umin_value;
6146
6147 /* scalar64 calc uses 32bit unshifted bounds so must be called first */
6148 __scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
6149 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
6150
07cd2631
JF
6151 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
6152 /* We may learn something more from the var_off */
6153 __update_reg_bounds(dst_reg);
6154}
6155
3f50f132
JF
6156static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
6157 struct bpf_reg_state *src_reg)
6158{
6159 struct tnum subreg = tnum_subreg(dst_reg->var_off);
6160 u32 umax_val = src_reg->u32_max_value;
6161 u32 umin_val = src_reg->u32_min_value;
6162
6163 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
6164 * be negative, then either:
6165 * 1) src_reg might be zero, so the sign bit of the result is
6166 * unknown, so we lose our signed bounds
6167 * 2) it's known negative, thus the unsigned bounds capture the
6168 * signed bounds
6169 * 3) the signed bounds cross zero, so they tell us nothing
6170 * about the result
6171 * If the value in dst_reg is known nonnegative, then again the
6172 * unsigned bounts capture the signed bounds.
6173 * Thus, in all cases it suffices to blow away our signed bounds
6174 * and rely on inferring new ones from the unsigned bounds and
6175 * var_off of the result.
6176 */
6177 dst_reg->s32_min_value = S32_MIN;
6178 dst_reg->s32_max_value = S32_MAX;
6179
6180 dst_reg->var_off = tnum_rshift(subreg, umin_val);
6181 dst_reg->u32_min_value >>= umax_val;
6182 dst_reg->u32_max_value >>= umin_val;
6183
6184 __mark_reg64_unbounded(dst_reg);
6185 __update_reg32_bounds(dst_reg);
6186}
6187
07cd2631
JF
6188static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
6189 struct bpf_reg_state *src_reg)
6190{
6191 u64 umax_val = src_reg->umax_value;
6192 u64 umin_val = src_reg->umin_value;
6193
6194 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
6195 * be negative, then either:
6196 * 1) src_reg might be zero, so the sign bit of the result is
6197 * unknown, so we lose our signed bounds
6198 * 2) it's known negative, thus the unsigned bounds capture the
6199 * signed bounds
6200 * 3) the signed bounds cross zero, so they tell us nothing
6201 * about the result
6202 * If the value in dst_reg is known nonnegative, then again the
6203 * unsigned bounts capture the signed bounds.
6204 * Thus, in all cases it suffices to blow away our signed bounds
6205 * and rely on inferring new ones from the unsigned bounds and
6206 * var_off of the result.
6207 */
6208 dst_reg->smin_value = S64_MIN;
6209 dst_reg->smax_value = S64_MAX;
6210 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
6211 dst_reg->umin_value >>= umax_val;
6212 dst_reg->umax_value >>= umin_val;
3f50f132
JF
6213
6214 /* Its not easy to operate on alu32 bounds here because it depends
6215 * on bits being shifted in. Take easy way out and mark unbounded
6216 * so we can recalculate later from tnum.
6217 */
6218 __mark_reg32_unbounded(dst_reg);
07cd2631
JF
6219 __update_reg_bounds(dst_reg);
6220}
6221
3f50f132
JF
6222static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
6223 struct bpf_reg_state *src_reg)
07cd2631 6224{
3f50f132 6225 u64 umin_val = src_reg->u32_min_value;
07cd2631
JF
6226
6227 /* Upon reaching here, src_known is true and
6228 * umax_val is equal to umin_val.
6229 */
3f50f132
JF
6230 dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
6231 dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
07cd2631 6232
3f50f132
JF
6233 dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
6234
6235 /* blow away the dst_reg umin_value/umax_value and rely on
6236 * dst_reg var_off to refine the result.
6237 */
6238 dst_reg->u32_min_value = 0;
6239 dst_reg->u32_max_value = U32_MAX;
6240
6241 __mark_reg64_unbounded(dst_reg);
6242 __update_reg32_bounds(dst_reg);
6243}
6244
6245static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
6246 struct bpf_reg_state *src_reg)
6247{
6248 u64 umin_val = src_reg->umin_value;
6249
6250 /* Upon reaching here, src_known is true and umax_val is equal
6251 * to umin_val.
6252 */
6253 dst_reg->smin_value >>= umin_val;
6254 dst_reg->smax_value >>= umin_val;
6255
6256 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
07cd2631
JF
6257
6258 /* blow away the dst_reg umin_value/umax_value and rely on
6259 * dst_reg var_off to refine the result.
6260 */
6261 dst_reg->umin_value = 0;
6262 dst_reg->umax_value = U64_MAX;
3f50f132
JF
6263
6264 /* Its not easy to operate on alu32 bounds here because it depends
6265 * on bits being shifted in from upper 32-bits. Take easy way out
6266 * and mark unbounded so we can recalculate later from tnum.
6267 */
6268 __mark_reg32_unbounded(dst_reg);
07cd2631
JF
6269 __update_reg_bounds(dst_reg);
6270}
6271
468f6eaf
JH
6272/* WARNING: This function does calculations on 64-bit values, but the actual
6273 * execution may occur on 32-bit values. Therefore, things like bitshifts
6274 * need extra checks in the 32-bit case.
6275 */
f1174f77
EC
6276static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
6277 struct bpf_insn *insn,
6278 struct bpf_reg_state *dst_reg,
6279 struct bpf_reg_state src_reg)
969bf05e 6280{
638f5b90 6281 struct bpf_reg_state *regs = cur_regs(env);
48461135 6282 u8 opcode = BPF_OP(insn->code);
b0b3fb67 6283 bool src_known;
b03c9f9f
EC
6284 s64 smin_val, smax_val;
6285 u64 umin_val, umax_val;
3f50f132
JF
6286 s32 s32_min_val, s32_max_val;
6287 u32 u32_min_val, u32_max_val;
468f6eaf 6288 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
d3bd7413
DB
6289 u32 dst = insn->dst_reg;
6290 int ret;
3f50f132 6291 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
b799207e 6292
b03c9f9f
EC
6293 smin_val = src_reg.smin_value;
6294 smax_val = src_reg.smax_value;
6295 umin_val = src_reg.umin_value;
6296 umax_val = src_reg.umax_value;
f23cc643 6297
3f50f132
JF
6298 s32_min_val = src_reg.s32_min_value;
6299 s32_max_val = src_reg.s32_max_value;
6300 u32_min_val = src_reg.u32_min_value;
6301 u32_max_val = src_reg.u32_max_value;
6302
6303 if (alu32) {
6304 src_known = tnum_subreg_is_const(src_reg.var_off);
3f50f132
JF
6305 if ((src_known &&
6306 (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
6307 s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
6308 /* Taint dst register if offset had invalid bounds
6309 * derived from e.g. dead branches.
6310 */
6311 __mark_reg_unknown(env, dst_reg);
6312 return 0;
6313 }
6314 } else {
6315 src_known = tnum_is_const(src_reg.var_off);
3f50f132
JF
6316 if ((src_known &&
6317 (smin_val != smax_val || umin_val != umax_val)) ||
6318 smin_val > smax_val || umin_val > umax_val) {
6319 /* Taint dst register if offset had invalid bounds
6320 * derived from e.g. dead branches.
6321 */
6322 __mark_reg_unknown(env, dst_reg);
6323 return 0;
6324 }
6f16101e
DB
6325 }
6326
bb7f0f98
AS
6327 if (!src_known &&
6328 opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
f54c7898 6329 __mark_reg_unknown(env, dst_reg);
bb7f0f98
AS
6330 return 0;
6331 }
6332
3f50f132
JF
6333 /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
6334 * There are two classes of instructions: The first class we track both
6335 * alu32 and alu64 sign/unsigned bounds independently this provides the
6336 * greatest amount of precision when alu operations are mixed with jmp32
6337 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
6338 * and BPF_OR. This is possible because these ops have fairly easy to
6339 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
6340 * See alu32 verifier tests for examples. The second class of
6341 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
6342 * with regards to tracking sign/unsigned bounds because the bits may
6343 * cross subreg boundaries in the alu64 case. When this happens we mark
6344 * the reg unbounded in the subreg bound space and use the resulting
6345 * tnum to calculate an approximation of the sign/unsigned bounds.
6346 */
48461135
JB
6347 switch (opcode) {
6348 case BPF_ADD:
d3bd7413
DB
6349 ret = sanitize_val_alu(env, insn);
6350 if (ret < 0) {
6351 verbose(env, "R%d tried to add from different pointers or scalars\n", dst);
6352 return ret;
6353 }
3f50f132 6354 scalar32_min_max_add(dst_reg, &src_reg);
07cd2631 6355 scalar_min_max_add(dst_reg, &src_reg);
3f50f132 6356 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
48461135
JB
6357 break;
6358 case BPF_SUB:
d3bd7413
DB
6359 ret = sanitize_val_alu(env, insn);
6360 if (ret < 0) {
6361 verbose(env, "R%d tried to sub from different pointers or scalars\n", dst);
6362 return ret;
6363 }
3f50f132 6364 scalar32_min_max_sub(dst_reg, &src_reg);
07cd2631 6365 scalar_min_max_sub(dst_reg, &src_reg);
3f50f132 6366 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
48461135
JB
6367 break;
6368 case BPF_MUL:
3f50f132
JF
6369 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
6370 scalar32_min_max_mul(dst_reg, &src_reg);
07cd2631 6371 scalar_min_max_mul(dst_reg, &src_reg);
48461135
JB
6372 break;
6373 case BPF_AND:
3f50f132
JF
6374 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
6375 scalar32_min_max_and(dst_reg, &src_reg);
07cd2631 6376 scalar_min_max_and(dst_reg, &src_reg);
f1174f77
EC
6377 break;
6378 case BPF_OR:
3f50f132
JF
6379 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
6380 scalar32_min_max_or(dst_reg, &src_reg);
07cd2631 6381 scalar_min_max_or(dst_reg, &src_reg);
48461135 6382 break;
2921c90d
YS
6383 case BPF_XOR:
6384 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
6385 scalar32_min_max_xor(dst_reg, &src_reg);
6386 scalar_min_max_xor(dst_reg, &src_reg);
6387 break;
48461135 6388 case BPF_LSH:
468f6eaf
JH
6389 if (umax_val >= insn_bitness) {
6390 /* Shifts greater than 31 or 63 are undefined.
6391 * This includes shifts by a negative number.
b03c9f9f 6392 */
61bd5218 6393 mark_reg_unknown(env, regs, insn->dst_reg);
f1174f77
EC
6394 break;
6395 }
3f50f132
JF
6396 if (alu32)
6397 scalar32_min_max_lsh(dst_reg, &src_reg);
6398 else
6399 scalar_min_max_lsh(dst_reg, &src_reg);
48461135
JB
6400 break;
6401 case BPF_RSH:
468f6eaf
JH
6402 if (umax_val >= insn_bitness) {
6403 /* Shifts greater than 31 or 63 are undefined.
6404 * This includes shifts by a negative number.
b03c9f9f 6405 */
61bd5218 6406 mark_reg_unknown(env, regs, insn->dst_reg);
f1174f77
EC
6407 break;
6408 }
3f50f132
JF
6409 if (alu32)
6410 scalar32_min_max_rsh(dst_reg, &src_reg);
6411 else
6412 scalar_min_max_rsh(dst_reg, &src_reg);
48461135 6413 break;
9cbe1f5a
YS
6414 case BPF_ARSH:
6415 if (umax_val >= insn_bitness) {
6416 /* Shifts greater than 31 or 63 are undefined.
6417 * This includes shifts by a negative number.
6418 */
6419 mark_reg_unknown(env, regs, insn->dst_reg);
6420 break;
6421 }
3f50f132
JF
6422 if (alu32)
6423 scalar32_min_max_arsh(dst_reg, &src_reg);
6424 else
6425 scalar_min_max_arsh(dst_reg, &src_reg);
9cbe1f5a 6426 break;
48461135 6427 default:
61bd5218 6428 mark_reg_unknown(env, regs, insn->dst_reg);
48461135
JB
6429 break;
6430 }
6431
3f50f132
JF
6432 /* ALU32 ops are zero extended into 64bit register */
6433 if (alu32)
6434 zext_32_to_64(dst_reg);
468f6eaf 6435
294f2fc6 6436 __update_reg_bounds(dst_reg);
b03c9f9f
EC
6437 __reg_deduce_bounds(dst_reg);
6438 __reg_bound_offset(dst_reg);
f1174f77
EC
6439 return 0;
6440}
6441
6442/* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
6443 * and var_off.
6444 */
6445static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
6446 struct bpf_insn *insn)
6447{
f4d7e40a
AS
6448 struct bpf_verifier_state *vstate = env->cur_state;
6449 struct bpf_func_state *state = vstate->frame[vstate->curframe];
6450 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
f1174f77
EC
6451 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
6452 u8 opcode = BPF_OP(insn->code);
b5dc0163 6453 int err;
f1174f77
EC
6454
6455 dst_reg = &regs[insn->dst_reg];
f1174f77
EC
6456 src_reg = NULL;
6457 if (dst_reg->type != SCALAR_VALUE)
6458 ptr_reg = dst_reg;
75748837
AS
6459 else
6460 /* Make sure ID is cleared otherwise dst_reg min/max could be
6461 * incorrectly propagated into other registers by find_equal_scalars()
6462 */
6463 dst_reg->id = 0;
f1174f77
EC
6464 if (BPF_SRC(insn->code) == BPF_X) {
6465 src_reg = &regs[insn->src_reg];
f1174f77
EC
6466 if (src_reg->type != SCALAR_VALUE) {
6467 if (dst_reg->type != SCALAR_VALUE) {
6468 /* Combining two pointers by any ALU op yields
82abbf8d
AS
6469 * an arbitrary scalar. Disallow all math except
6470 * pointer subtraction
f1174f77 6471 */
dd066823 6472 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
82abbf8d
AS
6473 mark_reg_unknown(env, regs, insn->dst_reg);
6474 return 0;
f1174f77 6475 }
82abbf8d
AS
6476 verbose(env, "R%d pointer %s pointer prohibited\n",
6477 insn->dst_reg,
6478 bpf_alu_string[opcode >> 4]);
6479 return -EACCES;
f1174f77
EC
6480 } else {
6481 /* scalar += pointer
6482 * This is legal, but we have to reverse our
6483 * src/dest handling in computing the range
6484 */
b5dc0163
AS
6485 err = mark_chain_precision(env, insn->dst_reg);
6486 if (err)
6487 return err;
82abbf8d
AS
6488 return adjust_ptr_min_max_vals(env, insn,
6489 src_reg, dst_reg);
f1174f77
EC
6490 }
6491 } else if (ptr_reg) {
6492 /* pointer += scalar */
b5dc0163
AS
6493 err = mark_chain_precision(env, insn->src_reg);
6494 if (err)
6495 return err;
82abbf8d
AS
6496 return adjust_ptr_min_max_vals(env, insn,
6497 dst_reg, src_reg);
f1174f77
EC
6498 }
6499 } else {
6500 /* Pretend the src is a reg with a known value, since we only
6501 * need to be able to read from this state.
6502 */
6503 off_reg.type = SCALAR_VALUE;
b03c9f9f 6504 __mark_reg_known(&off_reg, insn->imm);
f1174f77 6505 src_reg = &off_reg;
82abbf8d
AS
6506 if (ptr_reg) /* pointer += K */
6507 return adjust_ptr_min_max_vals(env, insn,
6508 ptr_reg, src_reg);
f1174f77
EC
6509 }
6510
6511 /* Got here implies adding two SCALAR_VALUEs */
6512 if (WARN_ON_ONCE(ptr_reg)) {
f4d7e40a 6513 print_verifier_state(env, state);
61bd5218 6514 verbose(env, "verifier internal error: unexpected ptr_reg\n");
f1174f77
EC
6515 return -EINVAL;
6516 }
6517 if (WARN_ON(!src_reg)) {
f4d7e40a 6518 print_verifier_state(env, state);
61bd5218 6519 verbose(env, "verifier internal error: no src_reg\n");
f1174f77
EC
6520 return -EINVAL;
6521 }
6522 return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
48461135
JB
6523}
6524
17a52670 6525/* check validity of 32-bit and 64-bit arithmetic operations */
58e2af8b 6526static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
17a52670 6527{
638f5b90 6528 struct bpf_reg_state *regs = cur_regs(env);
17a52670
AS
6529 u8 opcode = BPF_OP(insn->code);
6530 int err;
6531
6532 if (opcode == BPF_END || opcode == BPF_NEG) {
6533 if (opcode == BPF_NEG) {
6534 if (BPF_SRC(insn->code) != 0 ||
6535 insn->src_reg != BPF_REG_0 ||
6536 insn->off != 0 || insn->imm != 0) {
61bd5218 6537 verbose(env, "BPF_NEG uses reserved fields\n");
17a52670
AS
6538 return -EINVAL;
6539 }
6540 } else {
6541 if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
e67b8a68
EC
6542 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
6543 BPF_CLASS(insn->code) == BPF_ALU64) {
61bd5218 6544 verbose(env, "BPF_END uses reserved fields\n");
17a52670
AS
6545 return -EINVAL;
6546 }
6547 }
6548
6549 /* check src operand */
dc503a8a 6550 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17a52670
AS
6551 if (err)
6552 return err;
6553
1be7f75d 6554 if (is_pointer_value(env, insn->dst_reg)) {
61bd5218 6555 verbose(env, "R%d pointer arithmetic prohibited\n",
1be7f75d
AS
6556 insn->dst_reg);
6557 return -EACCES;
6558 }
6559
17a52670 6560 /* check dest operand */
dc503a8a 6561 err = check_reg_arg(env, insn->dst_reg, DST_OP);
17a52670
AS
6562 if (err)
6563 return err;
6564
6565 } else if (opcode == BPF_MOV) {
6566
6567 if (BPF_SRC(insn->code) == BPF_X) {
6568 if (insn->imm != 0 || insn->off != 0) {
61bd5218 6569 verbose(env, "BPF_MOV uses reserved fields\n");
17a52670
AS
6570 return -EINVAL;
6571 }
6572
6573 /* check src operand */
dc503a8a 6574 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17a52670
AS
6575 if (err)
6576 return err;
6577 } else {
6578 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
61bd5218 6579 verbose(env, "BPF_MOV uses reserved fields\n");
17a52670
AS
6580 return -EINVAL;
6581 }
6582 }
6583
fbeb1603
AF
6584 /* check dest operand, mark as required later */
6585 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
17a52670
AS
6586 if (err)
6587 return err;
6588
6589 if (BPF_SRC(insn->code) == BPF_X) {
e434b8cd
JW
6590 struct bpf_reg_state *src_reg = regs + insn->src_reg;
6591 struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
6592
17a52670
AS
6593 if (BPF_CLASS(insn->code) == BPF_ALU64) {
6594 /* case: R1 = R2
6595 * copy register state to dest reg
6596 */
75748837
AS
6597 if (src_reg->type == SCALAR_VALUE && !src_reg->id)
6598 /* Assign src and dst registers the same ID
6599 * that will be used by find_equal_scalars()
6600 * to propagate min/max range.
6601 */
6602 src_reg->id = ++env->id_gen;
e434b8cd
JW
6603 *dst_reg = *src_reg;
6604 dst_reg->live |= REG_LIVE_WRITTEN;
5327ed3d 6605 dst_reg->subreg_def = DEF_NOT_SUBREG;
17a52670 6606 } else {
f1174f77 6607 /* R1 = (u32) R2 */
1be7f75d 6608 if (is_pointer_value(env, insn->src_reg)) {
61bd5218
JK
6609 verbose(env,
6610 "R%d partial copy of pointer\n",
1be7f75d
AS
6611 insn->src_reg);
6612 return -EACCES;
e434b8cd
JW
6613 } else if (src_reg->type == SCALAR_VALUE) {
6614 *dst_reg = *src_reg;
75748837
AS
6615 /* Make sure ID is cleared otherwise
6616 * dst_reg min/max could be incorrectly
6617 * propagated into src_reg by find_equal_scalars()
6618 */
6619 dst_reg->id = 0;
e434b8cd 6620 dst_reg->live |= REG_LIVE_WRITTEN;
5327ed3d 6621 dst_reg->subreg_def = env->insn_idx + 1;
e434b8cd
JW
6622 } else {
6623 mark_reg_unknown(env, regs,
6624 insn->dst_reg);
1be7f75d 6625 }
3f50f132 6626 zext_32_to_64(dst_reg);
17a52670
AS
6627 }
6628 } else {
6629 /* case: R = imm
6630 * remember the value we stored into this reg
6631 */
fbeb1603
AF
6632 /* clear any state __mark_reg_known doesn't set */
6633 mark_reg_unknown(env, regs, insn->dst_reg);
f1174f77 6634 regs[insn->dst_reg].type = SCALAR_VALUE;
95a762e2
JH
6635 if (BPF_CLASS(insn->code) == BPF_ALU64) {
6636 __mark_reg_known(regs + insn->dst_reg,
6637 insn->imm);
6638 } else {
6639 __mark_reg_known(regs + insn->dst_reg,
6640 (u32)insn->imm);
6641 }
17a52670
AS
6642 }
6643
6644 } else if (opcode > BPF_END) {
61bd5218 6645 verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
17a52670
AS
6646 return -EINVAL;
6647
6648 } else { /* all other ALU ops: and, sub, xor, add, ... */
6649
17a52670
AS
6650 if (BPF_SRC(insn->code) == BPF_X) {
6651 if (insn->imm != 0 || insn->off != 0) {
61bd5218 6652 verbose(env, "BPF_ALU uses reserved fields\n");
17a52670
AS
6653 return -EINVAL;
6654 }
6655 /* check src1 operand */
dc503a8a 6656 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17a52670
AS
6657 if (err)
6658 return err;
6659 } else {
6660 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
61bd5218 6661 verbose(env, "BPF_ALU uses reserved fields\n");
17a52670
AS
6662 return -EINVAL;
6663 }
6664 }
6665
6666 /* check src2 operand */
dc503a8a 6667 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17a52670
AS
6668 if (err)
6669 return err;
6670
6671 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
6672 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
61bd5218 6673 verbose(env, "div by zero\n");
17a52670
AS
6674 return -EINVAL;
6675 }
6676
229394e8
RV
6677 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
6678 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
6679 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
6680
6681 if (insn->imm < 0 || insn->imm >= size) {
61bd5218 6682 verbose(env, "invalid shift %d\n", insn->imm);
229394e8
RV
6683 return -EINVAL;
6684 }
6685 }
6686
1a0dc1ac 6687 /* check dest operand */
dc503a8a 6688 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
1a0dc1ac
AS
6689 if (err)
6690 return err;
6691
f1174f77 6692 return adjust_reg_min_max_vals(env, insn);
17a52670
AS
6693 }
6694
6695 return 0;
6696}
6697
c6a9efa1
PC
6698static void __find_good_pkt_pointers(struct bpf_func_state *state,
6699 struct bpf_reg_state *dst_reg,
6700 enum bpf_reg_type type, u16 new_range)
6701{
6702 struct bpf_reg_state *reg;
6703 int i;
6704
6705 for (i = 0; i < MAX_BPF_REG; i++) {
6706 reg = &state->regs[i];
6707 if (reg->type == type && reg->id == dst_reg->id)
6708 /* keep the maximum range already checked */
6709 reg->range = max(reg->range, new_range);
6710 }
6711
6712 bpf_for_each_spilled_reg(i, state, reg) {
6713 if (!reg)
6714 continue;
6715 if (reg->type == type && reg->id == dst_reg->id)
6716 reg->range = max(reg->range, new_range);
6717 }
6718}
6719
f4d7e40a 6720static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
de8f3a83 6721 struct bpf_reg_state *dst_reg,
f8ddadc4 6722 enum bpf_reg_type type,
fb2a311a 6723 bool range_right_open)
969bf05e 6724{
fb2a311a 6725 u16 new_range;
c6a9efa1 6726 int i;
2d2be8ca 6727
fb2a311a
DB
6728 if (dst_reg->off < 0 ||
6729 (dst_reg->off == 0 && range_right_open))
f1174f77
EC
6730 /* This doesn't give us any range */
6731 return;
6732
b03c9f9f
EC
6733 if (dst_reg->umax_value > MAX_PACKET_OFF ||
6734 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
f1174f77
EC
6735 /* Risk of overflow. For instance, ptr + (1<<63) may be less
6736 * than pkt_end, but that's because it's also less than pkt.
6737 */
6738 return;
6739
fb2a311a
DB
6740 new_range = dst_reg->off;
6741 if (range_right_open)
6742 new_range--;
6743
6744 /* Examples for register markings:
2d2be8ca 6745 *
fb2a311a 6746 * pkt_data in dst register:
2d2be8ca
DB
6747 *
6748 * r2 = r3;
6749 * r2 += 8;
6750 * if (r2 > pkt_end) goto <handle exception>
6751 * <access okay>
6752 *
b4e432f1
DB
6753 * r2 = r3;
6754 * r2 += 8;
6755 * if (r2 < pkt_end) goto <access okay>
6756 * <handle exception>
6757 *
2d2be8ca
DB
6758 * Where:
6759 * r2 == dst_reg, pkt_end == src_reg
6760 * r2=pkt(id=n,off=8,r=0)
6761 * r3=pkt(id=n,off=0,r=0)
6762 *
fb2a311a 6763 * pkt_data in src register:
2d2be8ca
DB
6764 *
6765 * r2 = r3;
6766 * r2 += 8;
6767 * if (pkt_end >= r2) goto <access okay>
6768 * <handle exception>
6769 *
b4e432f1
DB
6770 * r2 = r3;
6771 * r2 += 8;
6772 * if (pkt_end <= r2) goto <handle exception>
6773 * <access okay>
6774 *
2d2be8ca
DB
6775 * Where:
6776 * pkt_end == dst_reg, r2 == src_reg
6777 * r2=pkt(id=n,off=8,r=0)
6778 * r3=pkt(id=n,off=0,r=0)
6779 *
6780 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
fb2a311a
DB
6781 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
6782 * and [r3, r3 + 8-1) respectively is safe to access depending on
6783 * the check.
969bf05e 6784 */
2d2be8ca 6785
f1174f77
EC
6786 /* If our ids match, then we must have the same max_value. And we
6787 * don't care about the other reg's fixed offset, since if it's too big
6788 * the range won't allow anything.
6789 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
6790 */
c6a9efa1
PC
6791 for (i = 0; i <= vstate->curframe; i++)
6792 __find_good_pkt_pointers(vstate->frame[i], dst_reg, type,
6793 new_range);
969bf05e
AS
6794}
6795
3f50f132 6796static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
4f7b3e82 6797{
3f50f132
JF
6798 struct tnum subreg = tnum_subreg(reg->var_off);
6799 s32 sval = (s32)val;
a72dafaf 6800
3f50f132
JF
6801 switch (opcode) {
6802 case BPF_JEQ:
6803 if (tnum_is_const(subreg))
6804 return !!tnum_equals_const(subreg, val);
6805 break;
6806 case BPF_JNE:
6807 if (tnum_is_const(subreg))
6808 return !tnum_equals_const(subreg, val);
6809 break;
6810 case BPF_JSET:
6811 if ((~subreg.mask & subreg.value) & val)
6812 return 1;
6813 if (!((subreg.mask | subreg.value) & val))
6814 return 0;
6815 break;
6816 case BPF_JGT:
6817 if (reg->u32_min_value > val)
6818 return 1;
6819 else if (reg->u32_max_value <= val)
6820 return 0;
6821 break;
6822 case BPF_JSGT:
6823 if (reg->s32_min_value > sval)
6824 return 1;
6825 else if (reg->s32_max_value < sval)
6826 return 0;
6827 break;
6828 case BPF_JLT:
6829 if (reg->u32_max_value < val)
6830 return 1;
6831 else if (reg->u32_min_value >= val)
6832 return 0;
6833 break;
6834 case BPF_JSLT:
6835 if (reg->s32_max_value < sval)
6836 return 1;
6837 else if (reg->s32_min_value >= sval)
6838 return 0;
6839 break;
6840 case BPF_JGE:
6841 if (reg->u32_min_value >= val)
6842 return 1;
6843 else if (reg->u32_max_value < val)
6844 return 0;
6845 break;
6846 case BPF_JSGE:
6847 if (reg->s32_min_value >= sval)
6848 return 1;
6849 else if (reg->s32_max_value < sval)
6850 return 0;
6851 break;
6852 case BPF_JLE:
6853 if (reg->u32_max_value <= val)
6854 return 1;
6855 else if (reg->u32_min_value > val)
6856 return 0;
6857 break;
6858 case BPF_JSLE:
6859 if (reg->s32_max_value <= sval)
6860 return 1;
6861 else if (reg->s32_min_value > sval)
6862 return 0;
6863 break;
6864 }
4f7b3e82 6865
3f50f132
JF
6866 return -1;
6867}
092ed096 6868
3f50f132
JF
6869
6870static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
6871{
6872 s64 sval = (s64)val;
a72dafaf 6873
4f7b3e82
AS
6874 switch (opcode) {
6875 case BPF_JEQ:
6876 if (tnum_is_const(reg->var_off))
6877 return !!tnum_equals_const(reg->var_off, val);
6878 break;
6879 case BPF_JNE:
6880 if (tnum_is_const(reg->var_off))
6881 return !tnum_equals_const(reg->var_off, val);
6882 break;
960ea056
JK
6883 case BPF_JSET:
6884 if ((~reg->var_off.mask & reg->var_off.value) & val)
6885 return 1;
6886 if (!((reg->var_off.mask | reg->var_off.value) & val))
6887 return 0;
6888 break;
4f7b3e82
AS
6889 case BPF_JGT:
6890 if (reg->umin_value > val)
6891 return 1;
6892 else if (reg->umax_value <= val)
6893 return 0;
6894 break;
6895 case BPF_JSGT:
a72dafaf 6896 if (reg->smin_value > sval)
4f7b3e82 6897 return 1;
a72dafaf 6898 else if (reg->smax_value < sval)
4f7b3e82
AS
6899 return 0;
6900 break;
6901 case BPF_JLT:
6902 if (reg->umax_value < val)
6903 return 1;
6904 else if (reg->umin_value >= val)
6905 return 0;
6906 break;
6907 case BPF_JSLT:
a72dafaf 6908 if (reg->smax_value < sval)
4f7b3e82 6909 return 1;
a72dafaf 6910 else if (reg->smin_value >= sval)
4f7b3e82
AS
6911 return 0;
6912 break;
6913 case BPF_JGE:
6914 if (reg->umin_value >= val)
6915 return 1;
6916 else if (reg->umax_value < val)
6917 return 0;
6918 break;
6919 case BPF_JSGE:
a72dafaf 6920 if (reg->smin_value >= sval)
4f7b3e82 6921 return 1;
a72dafaf 6922 else if (reg->smax_value < sval)
4f7b3e82
AS
6923 return 0;
6924 break;
6925 case BPF_JLE:
6926 if (reg->umax_value <= val)
6927 return 1;
6928 else if (reg->umin_value > val)
6929 return 0;
6930 break;
6931 case BPF_JSLE:
a72dafaf 6932 if (reg->smax_value <= sval)
4f7b3e82 6933 return 1;
a72dafaf 6934 else if (reg->smin_value > sval)
4f7b3e82
AS
6935 return 0;
6936 break;
6937 }
6938
6939 return -1;
6940}
6941
3f50f132
JF
6942/* compute branch direction of the expression "if (reg opcode val) goto target;"
6943 * and return:
6944 * 1 - branch will be taken and "goto target" will be executed
6945 * 0 - branch will not be taken and fall-through to next insn
6946 * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
6947 * range [0,10]
604dca5e 6948 */
3f50f132
JF
6949static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
6950 bool is_jmp32)
604dca5e 6951{
cac616db
JF
6952 if (__is_pointer_value(false, reg)) {
6953 if (!reg_type_not_null(reg->type))
6954 return -1;
6955
6956 /* If pointer is valid tests against zero will fail so we can
6957 * use this to direct branch taken.
6958 */
6959 if (val != 0)
6960 return -1;
6961
6962 switch (opcode) {
6963 case BPF_JEQ:
6964 return 0;
6965 case BPF_JNE:
6966 return 1;
6967 default:
6968 return -1;
6969 }
6970 }
604dca5e 6971
3f50f132
JF
6972 if (is_jmp32)
6973 return is_branch32_taken(reg, val, opcode);
6974 return is_branch64_taken(reg, val, opcode);
604dca5e
JH
6975}
6976
48461135
JB
6977/* Adjusts the register min/max values in the case that the dst_reg is the
6978 * variable register that we are working on, and src_reg is a constant or we're
6979 * simply doing a BPF_K check.
f1174f77 6980 * In JEQ/JNE cases we also adjust the var_off values.
48461135
JB
6981 */
6982static void reg_set_min_max(struct bpf_reg_state *true_reg,
3f50f132
JF
6983 struct bpf_reg_state *false_reg,
6984 u64 val, u32 val32,
092ed096 6985 u8 opcode, bool is_jmp32)
48461135 6986{
3f50f132
JF
6987 struct tnum false_32off = tnum_subreg(false_reg->var_off);
6988 struct tnum false_64off = false_reg->var_off;
6989 struct tnum true_32off = tnum_subreg(true_reg->var_off);
6990 struct tnum true_64off = true_reg->var_off;
6991 s64 sval = (s64)val;
6992 s32 sval32 = (s32)val32;
a72dafaf 6993
f1174f77
EC
6994 /* If the dst_reg is a pointer, we can't learn anything about its
6995 * variable offset from the compare (unless src_reg were a pointer into
6996 * the same object, but we don't bother with that.
6997 * Since false_reg and true_reg have the same type by construction, we
6998 * only need to check one of them for pointerness.
6999 */
7000 if (__is_pointer_value(false, false_reg))
7001 return;
4cabc5b1 7002
48461135
JB
7003 switch (opcode) {
7004 case BPF_JEQ:
48461135 7005 case BPF_JNE:
a72dafaf
JW
7006 {
7007 struct bpf_reg_state *reg =
7008 opcode == BPF_JEQ ? true_reg : false_reg;
7009
e688c3db
AS
7010 /* JEQ/JNE comparison doesn't change the register equivalence.
7011 * r1 = r2;
7012 * if (r1 == 42) goto label;
7013 * ...
7014 * label: // here both r1 and r2 are known to be 42.
7015 *
7016 * Hence when marking register as known preserve it's ID.
48461135 7017 */
3f50f132
JF
7018 if (is_jmp32)
7019 __mark_reg32_known(reg, val32);
7020 else
e688c3db 7021 ___mark_reg_known(reg, val);
48461135 7022 break;
a72dafaf 7023 }
960ea056 7024 case BPF_JSET:
3f50f132
JF
7025 if (is_jmp32) {
7026 false_32off = tnum_and(false_32off, tnum_const(~val32));
7027 if (is_power_of_2(val32))
7028 true_32off = tnum_or(true_32off,
7029 tnum_const(val32));
7030 } else {
7031 false_64off = tnum_and(false_64off, tnum_const(~val));
7032 if (is_power_of_2(val))
7033 true_64off = tnum_or(true_64off,
7034 tnum_const(val));
7035 }
960ea056 7036 break;
48461135 7037 case BPF_JGE:
a72dafaf
JW
7038 case BPF_JGT:
7039 {
3f50f132
JF
7040 if (is_jmp32) {
7041 u32 false_umax = opcode == BPF_JGT ? val32 : val32 - 1;
7042 u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
7043
7044 false_reg->u32_max_value = min(false_reg->u32_max_value,
7045 false_umax);
7046 true_reg->u32_min_value = max(true_reg->u32_min_value,
7047 true_umin);
7048 } else {
7049 u64 false_umax = opcode == BPF_JGT ? val : val - 1;
7050 u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
7051
7052 false_reg->umax_value = min(false_reg->umax_value, false_umax);
7053 true_reg->umin_value = max(true_reg->umin_value, true_umin);
7054 }
b03c9f9f 7055 break;
a72dafaf 7056 }
48461135 7057 case BPF_JSGE:
a72dafaf
JW
7058 case BPF_JSGT:
7059 {
3f50f132
JF
7060 if (is_jmp32) {
7061 s32 false_smax = opcode == BPF_JSGT ? sval32 : sval32 - 1;
7062 s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
a72dafaf 7063
3f50f132
JF
7064 false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
7065 true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
7066 } else {
7067 s64 false_smax = opcode == BPF_JSGT ? sval : sval - 1;
7068 s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
7069
7070 false_reg->smax_value = min(false_reg->smax_value, false_smax);
7071 true_reg->smin_value = max(true_reg->smin_value, true_smin);
7072 }
48461135 7073 break;
a72dafaf 7074 }
b4e432f1 7075 case BPF_JLE:
a72dafaf
JW
7076 case BPF_JLT:
7077 {
3f50f132
JF
7078 if (is_jmp32) {
7079 u32 false_umin = opcode == BPF_JLT ? val32 : val32 + 1;
7080 u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
7081
7082 false_reg->u32_min_value = max(false_reg->u32_min_value,
7083 false_umin);
7084 true_reg->u32_max_value = min(true_reg->u32_max_value,
7085 true_umax);
7086 } else {
7087 u64 false_umin = opcode == BPF_JLT ? val : val + 1;
7088 u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
7089
7090 false_reg->umin_value = max(false_reg->umin_value, false_umin);
7091 true_reg->umax_value = min(true_reg->umax_value, true_umax);
7092 }
b4e432f1 7093 break;
a72dafaf 7094 }
b4e432f1 7095 case BPF_JSLE:
a72dafaf
JW
7096 case BPF_JSLT:
7097 {
3f50f132
JF
7098 if (is_jmp32) {
7099 s32 false_smin = opcode == BPF_JSLT ? sval32 : sval32 + 1;
7100 s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
a72dafaf 7101
3f50f132
JF
7102 false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
7103 true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
7104 } else {
7105 s64 false_smin = opcode == BPF_JSLT ? sval : sval + 1;
7106 s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
7107
7108 false_reg->smin_value = max(false_reg->smin_value, false_smin);
7109 true_reg->smax_value = min(true_reg->smax_value, true_smax);
7110 }
b4e432f1 7111 break;
a72dafaf 7112 }
48461135 7113 default:
0fc31b10 7114 return;
48461135
JB
7115 }
7116
3f50f132
JF
7117 if (is_jmp32) {
7118 false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
7119 tnum_subreg(false_32off));
7120 true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
7121 tnum_subreg(true_32off));
7122 __reg_combine_32_into_64(false_reg);
7123 __reg_combine_32_into_64(true_reg);
7124 } else {
7125 false_reg->var_off = false_64off;
7126 true_reg->var_off = true_64off;
7127 __reg_combine_64_into_32(false_reg);
7128 __reg_combine_64_into_32(true_reg);
7129 }
48461135
JB
7130}
7131
f1174f77
EC
7132/* Same as above, but for the case that dst_reg holds a constant and src_reg is
7133 * the variable reg.
48461135
JB
7134 */
7135static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
3f50f132
JF
7136 struct bpf_reg_state *false_reg,
7137 u64 val, u32 val32,
092ed096 7138 u8 opcode, bool is_jmp32)
48461135 7139{
0fc31b10
JH
7140 /* How can we transform "a <op> b" into "b <op> a"? */
7141 static const u8 opcode_flip[16] = {
7142 /* these stay the same */
7143 [BPF_JEQ >> 4] = BPF_JEQ,
7144 [BPF_JNE >> 4] = BPF_JNE,
7145 [BPF_JSET >> 4] = BPF_JSET,
7146 /* these swap "lesser" and "greater" (L and G in the opcodes) */
7147 [BPF_JGE >> 4] = BPF_JLE,
7148 [BPF_JGT >> 4] = BPF_JLT,
7149 [BPF_JLE >> 4] = BPF_JGE,
7150 [BPF_JLT >> 4] = BPF_JGT,
7151 [BPF_JSGE >> 4] = BPF_JSLE,
7152 [BPF_JSGT >> 4] = BPF_JSLT,
7153 [BPF_JSLE >> 4] = BPF_JSGE,
7154 [BPF_JSLT >> 4] = BPF_JSGT
7155 };
7156 opcode = opcode_flip[opcode >> 4];
7157 /* This uses zero as "not present in table"; luckily the zero opcode,
7158 * BPF_JA, can't get here.
b03c9f9f 7159 */
0fc31b10 7160 if (opcode)
3f50f132 7161 reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
f1174f77
EC
7162}
7163
7164/* Regs are known to be equal, so intersect their min/max/var_off */
7165static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
7166 struct bpf_reg_state *dst_reg)
7167{
b03c9f9f
EC
7168 src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
7169 dst_reg->umin_value);
7170 src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
7171 dst_reg->umax_value);
7172 src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
7173 dst_reg->smin_value);
7174 src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
7175 dst_reg->smax_value);
f1174f77
EC
7176 src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
7177 dst_reg->var_off);
b03c9f9f
EC
7178 /* We might have learned new bounds from the var_off. */
7179 __update_reg_bounds(src_reg);
7180 __update_reg_bounds(dst_reg);
7181 /* We might have learned something about the sign bit. */
7182 __reg_deduce_bounds(src_reg);
7183 __reg_deduce_bounds(dst_reg);
7184 /* We might have learned some bits from the bounds. */
7185 __reg_bound_offset(src_reg);
7186 __reg_bound_offset(dst_reg);
7187 /* Intersecting with the old var_off might have improved our bounds
7188 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
7189 * then new var_off is (0; 0x7f...fc) which improves our umax.
7190 */
7191 __update_reg_bounds(src_reg);
7192 __update_reg_bounds(dst_reg);
f1174f77
EC
7193}
7194
7195static void reg_combine_min_max(struct bpf_reg_state *true_src,
7196 struct bpf_reg_state *true_dst,
7197 struct bpf_reg_state *false_src,
7198 struct bpf_reg_state *false_dst,
7199 u8 opcode)
7200{
7201 switch (opcode) {
7202 case BPF_JEQ:
7203 __reg_combine_min_max(true_src, true_dst);
7204 break;
7205 case BPF_JNE:
7206 __reg_combine_min_max(false_src, false_dst);
b03c9f9f 7207 break;
4cabc5b1 7208 }
48461135
JB
7209}
7210
fd978bf7
JS
7211static void mark_ptr_or_null_reg(struct bpf_func_state *state,
7212 struct bpf_reg_state *reg, u32 id,
840b9615 7213 bool is_null)
57a09bf0 7214{
840b9615 7215 if (reg_type_may_be_null(reg->type) && reg->id == id) {
f1174f77
EC
7216 /* Old offset (both fixed and variable parts) should
7217 * have been known-zero, because we don't allow pointer
7218 * arithmetic on pointers that might be NULL.
7219 */
b03c9f9f
EC
7220 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value ||
7221 !tnum_equals_const(reg->var_off, 0) ||
f1174f77 7222 reg->off)) {
b03c9f9f
EC
7223 __mark_reg_known_zero(reg);
7224 reg->off = 0;
f1174f77
EC
7225 }
7226 if (is_null) {
7227 reg->type = SCALAR_VALUE;
840b9615 7228 } else if (reg->type == PTR_TO_MAP_VALUE_OR_NULL) {
64d85290
JS
7229 const struct bpf_map *map = reg->map_ptr;
7230
7231 if (map->inner_map_meta) {
840b9615 7232 reg->type = CONST_PTR_TO_MAP;
64d85290
JS
7233 reg->map_ptr = map->inner_map_meta;
7234 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
fada7fdc 7235 reg->type = PTR_TO_XDP_SOCK;
64d85290
JS
7236 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
7237 map->map_type == BPF_MAP_TYPE_SOCKHASH) {
7238 reg->type = PTR_TO_SOCKET;
840b9615
JS
7239 } else {
7240 reg->type = PTR_TO_MAP_VALUE;
7241 }
c64b7983
JS
7242 } else if (reg->type == PTR_TO_SOCKET_OR_NULL) {
7243 reg->type = PTR_TO_SOCKET;
46f8bc92
MKL
7244 } else if (reg->type == PTR_TO_SOCK_COMMON_OR_NULL) {
7245 reg->type = PTR_TO_SOCK_COMMON;
655a51e5
MKL
7246 } else if (reg->type == PTR_TO_TCP_SOCK_OR_NULL) {
7247 reg->type = PTR_TO_TCP_SOCK;
b121b341
YS
7248 } else if (reg->type == PTR_TO_BTF_ID_OR_NULL) {
7249 reg->type = PTR_TO_BTF_ID;
457f4436
AN
7250 } else if (reg->type == PTR_TO_MEM_OR_NULL) {
7251 reg->type = PTR_TO_MEM;
afbf21dc
YS
7252 } else if (reg->type == PTR_TO_RDONLY_BUF_OR_NULL) {
7253 reg->type = PTR_TO_RDONLY_BUF;
7254 } else if (reg->type == PTR_TO_RDWR_BUF_OR_NULL) {
7255 reg->type = PTR_TO_RDWR_BUF;
56f668df 7256 }
1b986589
MKL
7257 if (is_null) {
7258 /* We don't need id and ref_obj_id from this point
7259 * onwards anymore, thus we should better reset it,
7260 * so that state pruning has chances to take effect.
7261 */
7262 reg->id = 0;
7263 reg->ref_obj_id = 0;
7264 } else if (!reg_may_point_to_spin_lock(reg)) {
7265 /* For not-NULL ptr, reg->ref_obj_id will be reset
7266 * in release_reg_references().
7267 *
7268 * reg->id is still used by spin_lock ptr. Other
7269 * than spin_lock ptr type, reg->id can be reset.
fd978bf7
JS
7270 */
7271 reg->id = 0;
56f668df 7272 }
57a09bf0
TG
7273 }
7274}
7275
c6a9efa1
PC
7276static void __mark_ptr_or_null_regs(struct bpf_func_state *state, u32 id,
7277 bool is_null)
7278{
7279 struct bpf_reg_state *reg;
7280 int i;
7281
7282 for (i = 0; i < MAX_BPF_REG; i++)
7283 mark_ptr_or_null_reg(state, &state->regs[i], id, is_null);
7284
7285 bpf_for_each_spilled_reg(i, state, reg) {
7286 if (!reg)
7287 continue;
7288 mark_ptr_or_null_reg(state, reg, id, is_null);
7289 }
7290}
7291
57a09bf0
TG
7292/* The logic is similar to find_good_pkt_pointers(), both could eventually
7293 * be folded together at some point.
7294 */
840b9615
JS
7295static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
7296 bool is_null)
57a09bf0 7297{
f4d7e40a 7298 struct bpf_func_state *state = vstate->frame[vstate->curframe];
c6a9efa1 7299 struct bpf_reg_state *regs = state->regs;
1b986589 7300 u32 ref_obj_id = regs[regno].ref_obj_id;
a08dd0da 7301 u32 id = regs[regno].id;
c6a9efa1 7302 int i;
57a09bf0 7303
1b986589
MKL
7304 if (ref_obj_id && ref_obj_id == id && is_null)
7305 /* regs[regno] is in the " == NULL" branch.
7306 * No one could have freed the reference state before
7307 * doing the NULL check.
7308 */
7309 WARN_ON_ONCE(release_reference_state(state, id));
fd978bf7 7310
c6a9efa1
PC
7311 for (i = 0; i <= vstate->curframe; i++)
7312 __mark_ptr_or_null_regs(vstate->frame[i], id, is_null);
57a09bf0
TG
7313}
7314
5beca081
DB
7315static bool try_match_pkt_pointers(const struct bpf_insn *insn,
7316 struct bpf_reg_state *dst_reg,
7317 struct bpf_reg_state *src_reg,
7318 struct bpf_verifier_state *this_branch,
7319 struct bpf_verifier_state *other_branch)
7320{
7321 if (BPF_SRC(insn->code) != BPF_X)
7322 return false;
7323
092ed096
JW
7324 /* Pointers are always 64-bit. */
7325 if (BPF_CLASS(insn->code) == BPF_JMP32)
7326 return false;
7327
5beca081
DB
7328 switch (BPF_OP(insn->code)) {
7329 case BPF_JGT:
7330 if ((dst_reg->type == PTR_TO_PACKET &&
7331 src_reg->type == PTR_TO_PACKET_END) ||
7332 (dst_reg->type == PTR_TO_PACKET_META &&
7333 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
7334 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
7335 find_good_pkt_pointers(this_branch, dst_reg,
7336 dst_reg->type, false);
7337 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
7338 src_reg->type == PTR_TO_PACKET) ||
7339 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
7340 src_reg->type == PTR_TO_PACKET_META)) {
7341 /* pkt_end > pkt_data', pkt_data > pkt_meta' */
7342 find_good_pkt_pointers(other_branch, src_reg,
7343 src_reg->type, true);
7344 } else {
7345 return false;
7346 }
7347 break;
7348 case BPF_JLT:
7349 if ((dst_reg->type == PTR_TO_PACKET &&
7350 src_reg->type == PTR_TO_PACKET_END) ||
7351 (dst_reg->type == PTR_TO_PACKET_META &&
7352 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
7353 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
7354 find_good_pkt_pointers(other_branch, dst_reg,
7355 dst_reg->type, true);
7356 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
7357 src_reg->type == PTR_TO_PACKET) ||
7358 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
7359 src_reg->type == PTR_TO_PACKET_META)) {
7360 /* pkt_end < pkt_data', pkt_data > pkt_meta' */
7361 find_good_pkt_pointers(this_branch, src_reg,
7362 src_reg->type, false);
7363 } else {
7364 return false;
7365 }
7366 break;
7367 case BPF_JGE:
7368 if ((dst_reg->type == PTR_TO_PACKET &&
7369 src_reg->type == PTR_TO_PACKET_END) ||
7370 (dst_reg->type == PTR_TO_PACKET_META &&
7371 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
7372 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
7373 find_good_pkt_pointers(this_branch, dst_reg,
7374 dst_reg->type, true);
7375 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
7376 src_reg->type == PTR_TO_PACKET) ||
7377 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
7378 src_reg->type == PTR_TO_PACKET_META)) {
7379 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
7380 find_good_pkt_pointers(other_branch, src_reg,
7381 src_reg->type, false);
7382 } else {
7383 return false;
7384 }
7385 break;
7386 case BPF_JLE:
7387 if ((dst_reg->type == PTR_TO_PACKET &&
7388 src_reg->type == PTR_TO_PACKET_END) ||
7389 (dst_reg->type == PTR_TO_PACKET_META &&
7390 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
7391 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
7392 find_good_pkt_pointers(other_branch, dst_reg,
7393 dst_reg->type, false);
7394 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
7395 src_reg->type == PTR_TO_PACKET) ||
7396 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
7397 src_reg->type == PTR_TO_PACKET_META)) {
7398 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
7399 find_good_pkt_pointers(this_branch, src_reg,
7400 src_reg->type, true);
7401 } else {
7402 return false;
7403 }
7404 break;
7405 default:
7406 return false;
7407 }
7408
7409 return true;
7410}
7411
75748837
AS
7412static void find_equal_scalars(struct bpf_verifier_state *vstate,
7413 struct bpf_reg_state *known_reg)
7414{
7415 struct bpf_func_state *state;
7416 struct bpf_reg_state *reg;
7417 int i, j;
7418
7419 for (i = 0; i <= vstate->curframe; i++) {
7420 state = vstate->frame[i];
7421 for (j = 0; j < MAX_BPF_REG; j++) {
7422 reg = &state->regs[j];
7423 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
7424 *reg = *known_reg;
7425 }
7426
7427 bpf_for_each_spilled_reg(j, state, reg) {
7428 if (!reg)
7429 continue;
7430 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
7431 *reg = *known_reg;
7432 }
7433 }
7434}
7435
58e2af8b 7436static int check_cond_jmp_op(struct bpf_verifier_env *env,
17a52670
AS
7437 struct bpf_insn *insn, int *insn_idx)
7438{
f4d7e40a
AS
7439 struct bpf_verifier_state *this_branch = env->cur_state;
7440 struct bpf_verifier_state *other_branch;
7441 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
fb8d251e 7442 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
17a52670 7443 u8 opcode = BPF_OP(insn->code);
092ed096 7444 bool is_jmp32;
fb8d251e 7445 int pred = -1;
17a52670
AS
7446 int err;
7447
092ed096
JW
7448 /* Only conditional jumps are expected to reach here. */
7449 if (opcode == BPF_JA || opcode > BPF_JSLE) {
7450 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
17a52670
AS
7451 return -EINVAL;
7452 }
7453
7454 if (BPF_SRC(insn->code) == BPF_X) {
7455 if (insn->imm != 0) {
092ed096 7456 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
17a52670
AS
7457 return -EINVAL;
7458 }
7459
7460 /* check src1 operand */
dc503a8a 7461 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17a52670
AS
7462 if (err)
7463 return err;
1be7f75d
AS
7464
7465 if (is_pointer_value(env, insn->src_reg)) {
61bd5218 7466 verbose(env, "R%d pointer comparison prohibited\n",
1be7f75d
AS
7467 insn->src_reg);
7468 return -EACCES;
7469 }
fb8d251e 7470 src_reg = &regs[insn->src_reg];
17a52670
AS
7471 } else {
7472 if (insn->src_reg != BPF_REG_0) {
092ed096 7473 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
17a52670
AS
7474 return -EINVAL;
7475 }
7476 }
7477
7478 /* check src2 operand */
dc503a8a 7479 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17a52670
AS
7480 if (err)
7481 return err;
7482
1a0dc1ac 7483 dst_reg = &regs[insn->dst_reg];
092ed096 7484 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
1a0dc1ac 7485
3f50f132
JF
7486 if (BPF_SRC(insn->code) == BPF_K) {
7487 pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
7488 } else if (src_reg->type == SCALAR_VALUE &&
7489 is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
7490 pred = is_branch_taken(dst_reg,
7491 tnum_subreg(src_reg->var_off).value,
7492 opcode,
7493 is_jmp32);
7494 } else if (src_reg->type == SCALAR_VALUE &&
7495 !is_jmp32 && tnum_is_const(src_reg->var_off)) {
7496 pred = is_branch_taken(dst_reg,
7497 src_reg->var_off.value,
7498 opcode,
7499 is_jmp32);
7500 }
7501
b5dc0163 7502 if (pred >= 0) {
cac616db
JF
7503 /* If we get here with a dst_reg pointer type it is because
7504 * above is_branch_taken() special cased the 0 comparison.
7505 */
7506 if (!__is_pointer_value(false, dst_reg))
7507 err = mark_chain_precision(env, insn->dst_reg);
b5dc0163
AS
7508 if (BPF_SRC(insn->code) == BPF_X && !err)
7509 err = mark_chain_precision(env, insn->src_reg);
7510 if (err)
7511 return err;
7512 }
fb8d251e
AS
7513 if (pred == 1) {
7514 /* only follow the goto, ignore fall-through */
7515 *insn_idx += insn->off;
7516 return 0;
7517 } else if (pred == 0) {
7518 /* only follow fall-through branch, since
7519 * that's where the program will go
7520 */
7521 return 0;
17a52670
AS
7522 }
7523
979d63d5
DB
7524 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
7525 false);
17a52670
AS
7526 if (!other_branch)
7527 return -EFAULT;
f4d7e40a 7528 other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
17a52670 7529
48461135
JB
7530 /* detect if we are comparing against a constant value so we can adjust
7531 * our min/max values for our dst register.
f1174f77
EC
7532 * this is only legit if both are scalars (or pointers to the same
7533 * object, I suppose, but we don't support that right now), because
7534 * otherwise the different base pointers mean the offsets aren't
7535 * comparable.
48461135
JB
7536 */
7537 if (BPF_SRC(insn->code) == BPF_X) {
092ed096 7538 struct bpf_reg_state *src_reg = &regs[insn->src_reg];
092ed096 7539
f1174f77 7540 if (dst_reg->type == SCALAR_VALUE &&
092ed096
JW
7541 src_reg->type == SCALAR_VALUE) {
7542 if (tnum_is_const(src_reg->var_off) ||
3f50f132
JF
7543 (is_jmp32 &&
7544 tnum_is_const(tnum_subreg(src_reg->var_off))))
f4d7e40a 7545 reg_set_min_max(&other_branch_regs[insn->dst_reg],
092ed096 7546 dst_reg,
3f50f132
JF
7547 src_reg->var_off.value,
7548 tnum_subreg(src_reg->var_off).value,
092ed096
JW
7549 opcode, is_jmp32);
7550 else if (tnum_is_const(dst_reg->var_off) ||
3f50f132
JF
7551 (is_jmp32 &&
7552 tnum_is_const(tnum_subreg(dst_reg->var_off))))
f4d7e40a 7553 reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
092ed096 7554 src_reg,
3f50f132
JF
7555 dst_reg->var_off.value,
7556 tnum_subreg(dst_reg->var_off).value,
092ed096
JW
7557 opcode, is_jmp32);
7558 else if (!is_jmp32 &&
7559 (opcode == BPF_JEQ || opcode == BPF_JNE))
f1174f77 7560 /* Comparing for equality, we can combine knowledge */
f4d7e40a
AS
7561 reg_combine_min_max(&other_branch_regs[insn->src_reg],
7562 &other_branch_regs[insn->dst_reg],
092ed096 7563 src_reg, dst_reg, opcode);
e688c3db
AS
7564 if (src_reg->id &&
7565 !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
75748837
AS
7566 find_equal_scalars(this_branch, src_reg);
7567 find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
7568 }
7569
f1174f77
EC
7570 }
7571 } else if (dst_reg->type == SCALAR_VALUE) {
f4d7e40a 7572 reg_set_min_max(&other_branch_regs[insn->dst_reg],
3f50f132
JF
7573 dst_reg, insn->imm, (u32)insn->imm,
7574 opcode, is_jmp32);
48461135
JB
7575 }
7576
e688c3db
AS
7577 if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
7578 !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
75748837
AS
7579 find_equal_scalars(this_branch, dst_reg);
7580 find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
7581 }
7582
092ed096
JW
7583 /* detect if R == 0 where R is returned from bpf_map_lookup_elem().
7584 * NOTE: these optimizations below are related with pointer comparison
7585 * which will never be JMP32.
7586 */
7587 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
1a0dc1ac 7588 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
840b9615
JS
7589 reg_type_may_be_null(dst_reg->type)) {
7590 /* Mark all identical registers in each branch as either
57a09bf0
TG
7591 * safe or unknown depending R == 0 or R != 0 conditional.
7592 */
840b9615
JS
7593 mark_ptr_or_null_regs(this_branch, insn->dst_reg,
7594 opcode == BPF_JNE);
7595 mark_ptr_or_null_regs(other_branch, insn->dst_reg,
7596 opcode == BPF_JEQ);
5beca081
DB
7597 } else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
7598 this_branch, other_branch) &&
7599 is_pointer_value(env, insn->dst_reg)) {
61bd5218
JK
7600 verbose(env, "R%d pointer comparison prohibited\n",
7601 insn->dst_reg);
1be7f75d 7602 return -EACCES;
17a52670 7603 }
06ee7115 7604 if (env->log.level & BPF_LOG_LEVEL)
f4d7e40a 7605 print_verifier_state(env, this_branch->frame[this_branch->curframe]);
17a52670
AS
7606 return 0;
7607}
7608
17a52670 7609/* verify BPF_LD_IMM64 instruction */
58e2af8b 7610static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
17a52670 7611{
d8eca5bb 7612 struct bpf_insn_aux_data *aux = cur_aux(env);
638f5b90 7613 struct bpf_reg_state *regs = cur_regs(env);
4976b718 7614 struct bpf_reg_state *dst_reg;
d8eca5bb 7615 struct bpf_map *map;
17a52670
AS
7616 int err;
7617
7618 if (BPF_SIZE(insn->code) != BPF_DW) {
61bd5218 7619 verbose(env, "invalid BPF_LD_IMM insn\n");
17a52670
AS
7620 return -EINVAL;
7621 }
7622 if (insn->off != 0) {
61bd5218 7623 verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
17a52670
AS
7624 return -EINVAL;
7625 }
7626
dc503a8a 7627 err = check_reg_arg(env, insn->dst_reg, DST_OP);
17a52670
AS
7628 if (err)
7629 return err;
7630
4976b718 7631 dst_reg = &regs[insn->dst_reg];
6b173873 7632 if (insn->src_reg == 0) {
6b173873
JK
7633 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
7634
4976b718 7635 dst_reg->type = SCALAR_VALUE;
b03c9f9f 7636 __mark_reg_known(&regs[insn->dst_reg], imm);
17a52670 7637 return 0;
6b173873 7638 }
17a52670 7639
4976b718
HL
7640 if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
7641 mark_reg_known_zero(env, regs, insn->dst_reg);
7642
7643 dst_reg->type = aux->btf_var.reg_type;
7644 switch (dst_reg->type) {
7645 case PTR_TO_MEM:
7646 dst_reg->mem_size = aux->btf_var.mem_size;
7647 break;
7648 case PTR_TO_BTF_ID:
eaa6bcb7 7649 case PTR_TO_PERCPU_BTF_ID:
4976b718
HL
7650 dst_reg->btf_id = aux->btf_var.btf_id;
7651 break;
7652 default:
7653 verbose(env, "bpf verifier is misconfigured\n");
7654 return -EFAULT;
7655 }
7656 return 0;
7657 }
7658
d8eca5bb
DB
7659 map = env->used_maps[aux->map_index];
7660 mark_reg_known_zero(env, regs, insn->dst_reg);
4976b718 7661 dst_reg->map_ptr = map;
d8eca5bb
DB
7662
7663 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE) {
4976b718
HL
7664 dst_reg->type = PTR_TO_MAP_VALUE;
7665 dst_reg->off = aux->map_off;
d8eca5bb 7666 if (map_value_has_spin_lock(map))
4976b718 7667 dst_reg->id = ++env->id_gen;
d8eca5bb 7668 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD) {
4976b718 7669 dst_reg->type = CONST_PTR_TO_MAP;
d8eca5bb
DB
7670 } else {
7671 verbose(env, "bpf verifier is misconfigured\n");
7672 return -EINVAL;
7673 }
17a52670 7674
17a52670
AS
7675 return 0;
7676}
7677
96be4325
DB
7678static bool may_access_skb(enum bpf_prog_type type)
7679{
7680 switch (type) {
7681 case BPF_PROG_TYPE_SOCKET_FILTER:
7682 case BPF_PROG_TYPE_SCHED_CLS:
94caee8c 7683 case BPF_PROG_TYPE_SCHED_ACT:
96be4325
DB
7684 return true;
7685 default:
7686 return false;
7687 }
7688}
7689
ddd872bc
AS
7690/* verify safety of LD_ABS|LD_IND instructions:
7691 * - they can only appear in the programs where ctx == skb
7692 * - since they are wrappers of function calls, they scratch R1-R5 registers,
7693 * preserve R6-R9, and store return value into R0
7694 *
7695 * Implicit input:
7696 * ctx == skb == R6 == CTX
7697 *
7698 * Explicit input:
7699 * SRC == any register
7700 * IMM == 32-bit immediate
7701 *
7702 * Output:
7703 * R0 - 8/16/32-bit skb data converted to cpu endianness
7704 */
58e2af8b 7705static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
ddd872bc 7706{
638f5b90 7707 struct bpf_reg_state *regs = cur_regs(env);
6d4f151a 7708 static const int ctx_reg = BPF_REG_6;
ddd872bc 7709 u8 mode = BPF_MODE(insn->code);
ddd872bc
AS
7710 int i, err;
7711
7e40781c 7712 if (!may_access_skb(resolve_prog_type(env->prog))) {
61bd5218 7713 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
ddd872bc
AS
7714 return -EINVAL;
7715 }
7716
e0cea7ce
DB
7717 if (!env->ops->gen_ld_abs) {
7718 verbose(env, "bpf verifier is misconfigured\n");
7719 return -EINVAL;
7720 }
7721
ddd872bc 7722 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
d82bccc6 7723 BPF_SIZE(insn->code) == BPF_DW ||
ddd872bc 7724 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
61bd5218 7725 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
ddd872bc
AS
7726 return -EINVAL;
7727 }
7728
7729 /* check whether implicit source operand (register R6) is readable */
6d4f151a 7730 err = check_reg_arg(env, ctx_reg, SRC_OP);
ddd872bc
AS
7731 if (err)
7732 return err;
7733
fd978bf7
JS
7734 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
7735 * gen_ld_abs() may terminate the program at runtime, leading to
7736 * reference leak.
7737 */
7738 err = check_reference_leak(env);
7739 if (err) {
7740 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
7741 return err;
7742 }
7743
d83525ca
AS
7744 if (env->cur_state->active_spin_lock) {
7745 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
7746 return -EINVAL;
7747 }
7748
6d4f151a 7749 if (regs[ctx_reg].type != PTR_TO_CTX) {
61bd5218
JK
7750 verbose(env,
7751 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
ddd872bc
AS
7752 return -EINVAL;
7753 }
7754
7755 if (mode == BPF_IND) {
7756 /* check explicit source operand */
dc503a8a 7757 err = check_reg_arg(env, insn->src_reg, SRC_OP);
ddd872bc
AS
7758 if (err)
7759 return err;
7760 }
7761
6d4f151a
DB
7762 err = check_ctx_reg(env, &regs[ctx_reg], ctx_reg);
7763 if (err < 0)
7764 return err;
7765
ddd872bc 7766 /* reset caller saved regs to unreadable */
dc503a8a 7767 for (i = 0; i < CALLER_SAVED_REGS; i++) {
61bd5218 7768 mark_reg_not_init(env, regs, caller_saved[i]);
dc503a8a
EC
7769 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
7770 }
ddd872bc
AS
7771
7772 /* mark destination R0 register as readable, since it contains
dc503a8a
EC
7773 * the value fetched from the packet.
7774 * Already marked as written above.
ddd872bc 7775 */
61bd5218 7776 mark_reg_unknown(env, regs, BPF_REG_0);
5327ed3d
JW
7777 /* ld_abs load up to 32-bit skb data. */
7778 regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
ddd872bc
AS
7779 return 0;
7780}
7781
390ee7e2
AS
7782static int check_return_code(struct bpf_verifier_env *env)
7783{
5cf1e914 7784 struct tnum enforce_attach_type_range = tnum_unknown;
27ae7997 7785 const struct bpf_prog *prog = env->prog;
390ee7e2
AS
7786 struct bpf_reg_state *reg;
7787 struct tnum range = tnum_range(0, 1);
7e40781c 7788 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
27ae7997
MKL
7789 int err;
7790
9e4e01df 7791 /* LSM and struct_ops func-ptr's return type could be "void" */
7e40781c
UP
7792 if ((prog_type == BPF_PROG_TYPE_STRUCT_OPS ||
7793 prog_type == BPF_PROG_TYPE_LSM) &&
27ae7997
MKL
7794 !prog->aux->attach_func_proto->type)
7795 return 0;
7796
7797 /* eBPF calling convetion is such that R0 is used
7798 * to return the value from eBPF program.
7799 * Make sure that it's readable at this time
7800 * of bpf_exit, which means that program wrote
7801 * something into it earlier
7802 */
7803 err = check_reg_arg(env, BPF_REG_0, SRC_OP);
7804 if (err)
7805 return err;
7806
7807 if (is_pointer_value(env, BPF_REG_0)) {
7808 verbose(env, "R0 leaks addr as return value\n");
7809 return -EACCES;
7810 }
390ee7e2 7811
7e40781c 7812 switch (prog_type) {
983695fa
DB
7813 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
7814 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
1b66d253
DB
7815 env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
7816 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
7817 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
7818 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
7819 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
983695fa 7820 range = tnum_range(1, 1);
ed4ed404 7821 break;
390ee7e2 7822 case BPF_PROG_TYPE_CGROUP_SKB:
5cf1e914 7823 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
7824 range = tnum_range(0, 3);
7825 enforce_attach_type_range = tnum_range(2, 3);
7826 }
ed4ed404 7827 break;
390ee7e2
AS
7828 case BPF_PROG_TYPE_CGROUP_SOCK:
7829 case BPF_PROG_TYPE_SOCK_OPS:
ebc614f6 7830 case BPF_PROG_TYPE_CGROUP_DEVICE:
7b146ceb 7831 case BPF_PROG_TYPE_CGROUP_SYSCTL:
0d01da6a 7832 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
390ee7e2 7833 break;
15ab09bd
AS
7834 case BPF_PROG_TYPE_RAW_TRACEPOINT:
7835 if (!env->prog->aux->attach_btf_id)
7836 return 0;
7837 range = tnum_const(0);
7838 break;
15d83c4d 7839 case BPF_PROG_TYPE_TRACING:
e92888c7
YS
7840 switch (env->prog->expected_attach_type) {
7841 case BPF_TRACE_FENTRY:
7842 case BPF_TRACE_FEXIT:
7843 range = tnum_const(0);
7844 break;
7845 case BPF_TRACE_RAW_TP:
7846 case BPF_MODIFY_RETURN:
15d83c4d 7847 return 0;
2ec0616e
DB
7848 case BPF_TRACE_ITER:
7849 break;
e92888c7
YS
7850 default:
7851 return -ENOTSUPP;
7852 }
15d83c4d 7853 break;
e9ddbb77
JS
7854 case BPF_PROG_TYPE_SK_LOOKUP:
7855 range = tnum_range(SK_DROP, SK_PASS);
7856 break;
e92888c7
YS
7857 case BPF_PROG_TYPE_EXT:
7858 /* freplace program can return anything as its return value
7859 * depends on the to-be-replaced kernel func or bpf program.
7860 */
390ee7e2
AS
7861 default:
7862 return 0;
7863 }
7864
638f5b90 7865 reg = cur_regs(env) + BPF_REG_0;
390ee7e2 7866 if (reg->type != SCALAR_VALUE) {
61bd5218 7867 verbose(env, "At program exit the register R0 is not a known value (%s)\n",
390ee7e2
AS
7868 reg_type_str[reg->type]);
7869 return -EINVAL;
7870 }
7871
7872 if (!tnum_in(range, reg->var_off)) {
5cf1e914 7873 char tn_buf[48];
7874
61bd5218 7875 verbose(env, "At program exit the register R0 ");
390ee7e2 7876 if (!tnum_is_unknown(reg->var_off)) {
390ee7e2 7877 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
61bd5218 7878 verbose(env, "has value %s", tn_buf);
390ee7e2 7879 } else {
61bd5218 7880 verbose(env, "has unknown scalar value");
390ee7e2 7881 }
5cf1e914 7882 tnum_strn(tn_buf, sizeof(tn_buf), range);
983695fa 7883 verbose(env, " should have been in %s\n", tn_buf);
390ee7e2
AS
7884 return -EINVAL;
7885 }
5cf1e914 7886
7887 if (!tnum_is_unknown(enforce_attach_type_range) &&
7888 tnum_in(enforce_attach_type_range, reg->var_off))
7889 env->prog->enforce_expected_attach_type = 1;
390ee7e2
AS
7890 return 0;
7891}
7892
475fb78f
AS
7893/* non-recursive DFS pseudo code
7894 * 1 procedure DFS-iterative(G,v):
7895 * 2 label v as discovered
7896 * 3 let S be a stack
7897 * 4 S.push(v)
7898 * 5 while S is not empty
7899 * 6 t <- S.pop()
7900 * 7 if t is what we're looking for:
7901 * 8 return t
7902 * 9 for all edges e in G.adjacentEdges(t) do
7903 * 10 if edge e is already labelled
7904 * 11 continue with the next edge
7905 * 12 w <- G.adjacentVertex(t,e)
7906 * 13 if vertex w is not discovered and not explored
7907 * 14 label e as tree-edge
7908 * 15 label w as discovered
7909 * 16 S.push(w)
7910 * 17 continue at 5
7911 * 18 else if vertex w is discovered
7912 * 19 label e as back-edge
7913 * 20 else
7914 * 21 // vertex w is explored
7915 * 22 label e as forward- or cross-edge
7916 * 23 label t as explored
7917 * 24 S.pop()
7918 *
7919 * convention:
7920 * 0x10 - discovered
7921 * 0x11 - discovered and fall-through edge labelled
7922 * 0x12 - discovered and fall-through and branch edges labelled
7923 * 0x20 - explored
7924 */
7925
7926enum {
7927 DISCOVERED = 0x10,
7928 EXPLORED = 0x20,
7929 FALLTHROUGH = 1,
7930 BRANCH = 2,
7931};
7932
dc2a4ebc
AS
7933static u32 state_htab_size(struct bpf_verifier_env *env)
7934{
7935 return env->prog->len;
7936}
7937
5d839021
AS
7938static struct bpf_verifier_state_list **explored_state(
7939 struct bpf_verifier_env *env,
7940 int idx)
7941{
dc2a4ebc
AS
7942 struct bpf_verifier_state *cur = env->cur_state;
7943 struct bpf_func_state *state = cur->frame[cur->curframe];
7944
7945 return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
5d839021
AS
7946}
7947
7948static void init_explored_state(struct bpf_verifier_env *env, int idx)
7949{
a8f500af 7950 env->insn_aux_data[idx].prune_point = true;
5d839021 7951}
f1bca824 7952
475fb78f
AS
7953/* t, w, e - match pseudo-code above:
7954 * t - index of current instruction
7955 * w - next instruction
7956 * e - edge
7957 */
2589726d
AS
7958static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
7959 bool loop_ok)
475fb78f 7960{
7df737e9
AS
7961 int *insn_stack = env->cfg.insn_stack;
7962 int *insn_state = env->cfg.insn_state;
7963
475fb78f
AS
7964 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
7965 return 0;
7966
7967 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
7968 return 0;
7969
7970 if (w < 0 || w >= env->prog->len) {
d9762e84 7971 verbose_linfo(env, t, "%d: ", t);
61bd5218 7972 verbose(env, "jump out of range from insn %d to %d\n", t, w);
475fb78f
AS
7973 return -EINVAL;
7974 }
7975
f1bca824
AS
7976 if (e == BRANCH)
7977 /* mark branch target for state pruning */
5d839021 7978 init_explored_state(env, w);
f1bca824 7979
475fb78f
AS
7980 if (insn_state[w] == 0) {
7981 /* tree-edge */
7982 insn_state[t] = DISCOVERED | e;
7983 insn_state[w] = DISCOVERED;
7df737e9 7984 if (env->cfg.cur_stack >= env->prog->len)
475fb78f 7985 return -E2BIG;
7df737e9 7986 insn_stack[env->cfg.cur_stack++] = w;
475fb78f
AS
7987 return 1;
7988 } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
2c78ee89 7989 if (loop_ok && env->bpf_capable)
2589726d 7990 return 0;
d9762e84
MKL
7991 verbose_linfo(env, t, "%d: ", t);
7992 verbose_linfo(env, w, "%d: ", w);
61bd5218 7993 verbose(env, "back-edge from insn %d to %d\n", t, w);
475fb78f
AS
7994 return -EINVAL;
7995 } else if (insn_state[w] == EXPLORED) {
7996 /* forward- or cross-edge */
7997 insn_state[t] = DISCOVERED | e;
7998 } else {
61bd5218 7999 verbose(env, "insn state internal bug\n");
475fb78f
AS
8000 return -EFAULT;
8001 }
8002 return 0;
8003}
8004
8005/* non-recursive depth-first-search to detect loops in BPF program
8006 * loop == back-edge in directed graph
8007 */
58e2af8b 8008static int check_cfg(struct bpf_verifier_env *env)
475fb78f
AS
8009{
8010 struct bpf_insn *insns = env->prog->insnsi;
8011 int insn_cnt = env->prog->len;
7df737e9 8012 int *insn_stack, *insn_state;
475fb78f
AS
8013 int ret = 0;
8014 int i, t;
8015
7df737e9 8016 insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
475fb78f
AS
8017 if (!insn_state)
8018 return -ENOMEM;
8019
7df737e9 8020 insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
475fb78f 8021 if (!insn_stack) {
71dde681 8022 kvfree(insn_state);
475fb78f
AS
8023 return -ENOMEM;
8024 }
8025
8026 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
8027 insn_stack[0] = 0; /* 0 is the first instruction */
7df737e9 8028 env->cfg.cur_stack = 1;
475fb78f
AS
8029
8030peek_stack:
7df737e9 8031 if (env->cfg.cur_stack == 0)
475fb78f 8032 goto check_state;
7df737e9 8033 t = insn_stack[env->cfg.cur_stack - 1];
475fb78f 8034
092ed096
JW
8035 if (BPF_CLASS(insns[t].code) == BPF_JMP ||
8036 BPF_CLASS(insns[t].code) == BPF_JMP32) {
475fb78f
AS
8037 u8 opcode = BPF_OP(insns[t].code);
8038
8039 if (opcode == BPF_EXIT) {
8040 goto mark_explored;
8041 } else if (opcode == BPF_CALL) {
2589726d 8042 ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
475fb78f
AS
8043 if (ret == 1)
8044 goto peek_stack;
8045 else if (ret < 0)
8046 goto err_free;
07016151 8047 if (t + 1 < insn_cnt)
5d839021 8048 init_explored_state(env, t + 1);
cc8b0b92 8049 if (insns[t].src_reg == BPF_PSEUDO_CALL) {
5d839021 8050 init_explored_state(env, t);
2589726d
AS
8051 ret = push_insn(t, t + insns[t].imm + 1, BRANCH,
8052 env, false);
cc8b0b92
AS
8053 if (ret == 1)
8054 goto peek_stack;
8055 else if (ret < 0)
8056 goto err_free;
8057 }
475fb78f
AS
8058 } else if (opcode == BPF_JA) {
8059 if (BPF_SRC(insns[t].code) != BPF_K) {
8060 ret = -EINVAL;
8061 goto err_free;
8062 }
8063 /* unconditional jump with single edge */
8064 ret = push_insn(t, t + insns[t].off + 1,
2589726d 8065 FALLTHROUGH, env, true);
475fb78f
AS
8066 if (ret == 1)
8067 goto peek_stack;
8068 else if (ret < 0)
8069 goto err_free;
b5dc0163
AS
8070 /* unconditional jmp is not a good pruning point,
8071 * but it's marked, since backtracking needs
8072 * to record jmp history in is_state_visited().
8073 */
8074 init_explored_state(env, t + insns[t].off + 1);
f1bca824
AS
8075 /* tell verifier to check for equivalent states
8076 * after every call and jump
8077 */
c3de6317 8078 if (t + 1 < insn_cnt)
5d839021 8079 init_explored_state(env, t + 1);
475fb78f
AS
8080 } else {
8081 /* conditional jump with two edges */
5d839021 8082 init_explored_state(env, t);
2589726d 8083 ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
475fb78f
AS
8084 if (ret == 1)
8085 goto peek_stack;
8086 else if (ret < 0)
8087 goto err_free;
8088
2589726d 8089 ret = push_insn(t, t + insns[t].off + 1, BRANCH, env, true);
475fb78f
AS
8090 if (ret == 1)
8091 goto peek_stack;
8092 else if (ret < 0)
8093 goto err_free;
8094 }
8095 } else {
8096 /* all other non-branch instructions with single
8097 * fall-through edge
8098 */
2589726d 8099 ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
475fb78f
AS
8100 if (ret == 1)
8101 goto peek_stack;
8102 else if (ret < 0)
8103 goto err_free;
8104 }
8105
8106mark_explored:
8107 insn_state[t] = EXPLORED;
7df737e9 8108 if (env->cfg.cur_stack-- <= 0) {
61bd5218 8109 verbose(env, "pop stack internal bug\n");
475fb78f
AS
8110 ret = -EFAULT;
8111 goto err_free;
8112 }
8113 goto peek_stack;
8114
8115check_state:
8116 for (i = 0; i < insn_cnt; i++) {
8117 if (insn_state[i] != EXPLORED) {
61bd5218 8118 verbose(env, "unreachable insn %d\n", i);
475fb78f
AS
8119 ret = -EINVAL;
8120 goto err_free;
8121 }
8122 }
8123 ret = 0; /* cfg looks good */
8124
8125err_free:
71dde681
AS
8126 kvfree(insn_state);
8127 kvfree(insn_stack);
7df737e9 8128 env->cfg.insn_state = env->cfg.insn_stack = NULL;
475fb78f
AS
8129 return ret;
8130}
8131
09b28d76
AS
8132static int check_abnormal_return(struct bpf_verifier_env *env)
8133{
8134 int i;
8135
8136 for (i = 1; i < env->subprog_cnt; i++) {
8137 if (env->subprog_info[i].has_ld_abs) {
8138 verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
8139 return -EINVAL;
8140 }
8141 if (env->subprog_info[i].has_tail_call) {
8142 verbose(env, "tail_call is not allowed in subprogs without BTF\n");
8143 return -EINVAL;
8144 }
8145 }
8146 return 0;
8147}
8148
838e9690
YS
8149/* The minimum supported BTF func info size */
8150#define MIN_BPF_FUNCINFO_SIZE 8
8151#define MAX_FUNCINFO_REC_SIZE 252
8152
c454a46b
MKL
8153static int check_btf_func(struct bpf_verifier_env *env,
8154 const union bpf_attr *attr,
8155 union bpf_attr __user *uattr)
838e9690 8156{
09b28d76 8157 const struct btf_type *type, *func_proto, *ret_type;
d0b2818e 8158 u32 i, nfuncs, urec_size, min_size;
838e9690 8159 u32 krec_size = sizeof(struct bpf_func_info);
c454a46b 8160 struct bpf_func_info *krecord;
8c1b6e69 8161 struct bpf_func_info_aux *info_aux = NULL;
c454a46b
MKL
8162 struct bpf_prog *prog;
8163 const struct btf *btf;
838e9690 8164 void __user *urecord;
d0b2818e 8165 u32 prev_offset = 0;
09b28d76 8166 bool scalar_return;
e7ed83d6 8167 int ret = -ENOMEM;
838e9690
YS
8168
8169 nfuncs = attr->func_info_cnt;
09b28d76
AS
8170 if (!nfuncs) {
8171 if (check_abnormal_return(env))
8172 return -EINVAL;
838e9690 8173 return 0;
09b28d76 8174 }
838e9690
YS
8175
8176 if (nfuncs != env->subprog_cnt) {
8177 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
8178 return -EINVAL;
8179 }
8180
8181 urec_size = attr->func_info_rec_size;
8182 if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
8183 urec_size > MAX_FUNCINFO_REC_SIZE ||
8184 urec_size % sizeof(u32)) {
8185 verbose(env, "invalid func info rec size %u\n", urec_size);
8186 return -EINVAL;
8187 }
8188
c454a46b
MKL
8189 prog = env->prog;
8190 btf = prog->aux->btf;
838e9690
YS
8191
8192 urecord = u64_to_user_ptr(attr->func_info);
8193 min_size = min_t(u32, krec_size, urec_size);
8194
ba64e7d8 8195 krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
c454a46b
MKL
8196 if (!krecord)
8197 return -ENOMEM;
8c1b6e69
AS
8198 info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
8199 if (!info_aux)
8200 goto err_free;
ba64e7d8 8201
838e9690
YS
8202 for (i = 0; i < nfuncs; i++) {
8203 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
8204 if (ret) {
8205 if (ret == -E2BIG) {
8206 verbose(env, "nonzero tailing record in func info");
8207 /* set the size kernel expects so loader can zero
8208 * out the rest of the record.
8209 */
8210 if (put_user(min_size, &uattr->func_info_rec_size))
8211 ret = -EFAULT;
8212 }
c454a46b 8213 goto err_free;
838e9690
YS
8214 }
8215
ba64e7d8 8216 if (copy_from_user(&krecord[i], urecord, min_size)) {
838e9690 8217 ret = -EFAULT;
c454a46b 8218 goto err_free;
838e9690
YS
8219 }
8220
d30d42e0 8221 /* check insn_off */
09b28d76 8222 ret = -EINVAL;
838e9690 8223 if (i == 0) {
d30d42e0 8224 if (krecord[i].insn_off) {
838e9690 8225 verbose(env,
d30d42e0
MKL
8226 "nonzero insn_off %u for the first func info record",
8227 krecord[i].insn_off);
c454a46b 8228 goto err_free;
838e9690 8229 }
d30d42e0 8230 } else if (krecord[i].insn_off <= prev_offset) {
838e9690
YS
8231 verbose(env,
8232 "same or smaller insn offset (%u) than previous func info record (%u)",
d30d42e0 8233 krecord[i].insn_off, prev_offset);
c454a46b 8234 goto err_free;
838e9690
YS
8235 }
8236
d30d42e0 8237 if (env->subprog_info[i].start != krecord[i].insn_off) {
838e9690 8238 verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
c454a46b 8239 goto err_free;
838e9690
YS
8240 }
8241
8242 /* check type_id */
ba64e7d8 8243 type = btf_type_by_id(btf, krecord[i].type_id);
51c39bb1 8244 if (!type || !btf_type_is_func(type)) {
838e9690 8245 verbose(env, "invalid type id %d in func info",
ba64e7d8 8246 krecord[i].type_id);
c454a46b 8247 goto err_free;
838e9690 8248 }
51c39bb1 8249 info_aux[i].linkage = BTF_INFO_VLEN(type->info);
09b28d76
AS
8250
8251 func_proto = btf_type_by_id(btf, type->type);
8252 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
8253 /* btf_func_check() already verified it during BTF load */
8254 goto err_free;
8255 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
8256 scalar_return =
8257 btf_type_is_small_int(ret_type) || btf_type_is_enum(ret_type);
8258 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
8259 verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
8260 goto err_free;
8261 }
8262 if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
8263 verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
8264 goto err_free;
8265 }
8266
d30d42e0 8267 prev_offset = krecord[i].insn_off;
838e9690
YS
8268 urecord += urec_size;
8269 }
8270
ba64e7d8
YS
8271 prog->aux->func_info = krecord;
8272 prog->aux->func_info_cnt = nfuncs;
8c1b6e69 8273 prog->aux->func_info_aux = info_aux;
838e9690
YS
8274 return 0;
8275
c454a46b 8276err_free:
ba64e7d8 8277 kvfree(krecord);
8c1b6e69 8278 kfree(info_aux);
838e9690
YS
8279 return ret;
8280}
8281
ba64e7d8
YS
8282static void adjust_btf_func(struct bpf_verifier_env *env)
8283{
8c1b6e69 8284 struct bpf_prog_aux *aux = env->prog->aux;
ba64e7d8
YS
8285 int i;
8286
8c1b6e69 8287 if (!aux->func_info)
ba64e7d8
YS
8288 return;
8289
8290 for (i = 0; i < env->subprog_cnt; i++)
8c1b6e69 8291 aux->func_info[i].insn_off = env->subprog_info[i].start;
ba64e7d8
YS
8292}
8293
c454a46b
MKL
8294#define MIN_BPF_LINEINFO_SIZE (offsetof(struct bpf_line_info, line_col) + \
8295 sizeof(((struct bpf_line_info *)(0))->line_col))
8296#define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE
8297
8298static int check_btf_line(struct bpf_verifier_env *env,
8299 const union bpf_attr *attr,
8300 union bpf_attr __user *uattr)
8301{
8302 u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
8303 struct bpf_subprog_info *sub;
8304 struct bpf_line_info *linfo;
8305 struct bpf_prog *prog;
8306 const struct btf *btf;
8307 void __user *ulinfo;
8308 int err;
8309
8310 nr_linfo = attr->line_info_cnt;
8311 if (!nr_linfo)
8312 return 0;
8313
8314 rec_size = attr->line_info_rec_size;
8315 if (rec_size < MIN_BPF_LINEINFO_SIZE ||
8316 rec_size > MAX_LINEINFO_REC_SIZE ||
8317 rec_size & (sizeof(u32) - 1))
8318 return -EINVAL;
8319
8320 /* Need to zero it in case the userspace may
8321 * pass in a smaller bpf_line_info object.
8322 */
8323 linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
8324 GFP_KERNEL | __GFP_NOWARN);
8325 if (!linfo)
8326 return -ENOMEM;
8327
8328 prog = env->prog;
8329 btf = prog->aux->btf;
8330
8331 s = 0;
8332 sub = env->subprog_info;
8333 ulinfo = u64_to_user_ptr(attr->line_info);
8334 expected_size = sizeof(struct bpf_line_info);
8335 ncopy = min_t(u32, expected_size, rec_size);
8336 for (i = 0; i < nr_linfo; i++) {
8337 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
8338 if (err) {
8339 if (err == -E2BIG) {
8340 verbose(env, "nonzero tailing record in line_info");
8341 if (put_user(expected_size,
8342 &uattr->line_info_rec_size))
8343 err = -EFAULT;
8344 }
8345 goto err_free;
8346 }
8347
8348 if (copy_from_user(&linfo[i], ulinfo, ncopy)) {
8349 err = -EFAULT;
8350 goto err_free;
8351 }
8352
8353 /*
8354 * Check insn_off to ensure
8355 * 1) strictly increasing AND
8356 * 2) bounded by prog->len
8357 *
8358 * The linfo[0].insn_off == 0 check logically falls into
8359 * the later "missing bpf_line_info for func..." case
8360 * because the first linfo[0].insn_off must be the
8361 * first sub also and the first sub must have
8362 * subprog_info[0].start == 0.
8363 */
8364 if ((i && linfo[i].insn_off <= prev_offset) ||
8365 linfo[i].insn_off >= prog->len) {
8366 verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
8367 i, linfo[i].insn_off, prev_offset,
8368 prog->len);
8369 err = -EINVAL;
8370 goto err_free;
8371 }
8372
fdbaa0be
MKL
8373 if (!prog->insnsi[linfo[i].insn_off].code) {
8374 verbose(env,
8375 "Invalid insn code at line_info[%u].insn_off\n",
8376 i);
8377 err = -EINVAL;
8378 goto err_free;
8379 }
8380
23127b33
MKL
8381 if (!btf_name_by_offset(btf, linfo[i].line_off) ||
8382 !btf_name_by_offset(btf, linfo[i].file_name_off)) {
c454a46b
MKL
8383 verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
8384 err = -EINVAL;
8385 goto err_free;
8386 }
8387
8388 if (s != env->subprog_cnt) {
8389 if (linfo[i].insn_off == sub[s].start) {
8390 sub[s].linfo_idx = i;
8391 s++;
8392 } else if (sub[s].start < linfo[i].insn_off) {
8393 verbose(env, "missing bpf_line_info for func#%u\n", s);
8394 err = -EINVAL;
8395 goto err_free;
8396 }
8397 }
8398
8399 prev_offset = linfo[i].insn_off;
8400 ulinfo += rec_size;
8401 }
8402
8403 if (s != env->subprog_cnt) {
8404 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
8405 env->subprog_cnt - s, s);
8406 err = -EINVAL;
8407 goto err_free;
8408 }
8409
8410 prog->aux->linfo = linfo;
8411 prog->aux->nr_linfo = nr_linfo;
8412
8413 return 0;
8414
8415err_free:
8416 kvfree(linfo);
8417 return err;
8418}
8419
8420static int check_btf_info(struct bpf_verifier_env *env,
8421 const union bpf_attr *attr,
8422 union bpf_attr __user *uattr)
8423{
8424 struct btf *btf;
8425 int err;
8426
09b28d76
AS
8427 if (!attr->func_info_cnt && !attr->line_info_cnt) {
8428 if (check_abnormal_return(env))
8429 return -EINVAL;
c454a46b 8430 return 0;
09b28d76 8431 }
c454a46b
MKL
8432
8433 btf = btf_get_by_fd(attr->prog_btf_fd);
8434 if (IS_ERR(btf))
8435 return PTR_ERR(btf);
8436 env->prog->aux->btf = btf;
8437
8438 err = check_btf_func(env, attr, uattr);
8439 if (err)
8440 return err;
8441
8442 err = check_btf_line(env, attr, uattr);
8443 if (err)
8444 return err;
8445
8446 return 0;
ba64e7d8
YS
8447}
8448
f1174f77
EC
8449/* check %cur's range satisfies %old's */
8450static bool range_within(struct bpf_reg_state *old,
8451 struct bpf_reg_state *cur)
8452{
b03c9f9f
EC
8453 return old->umin_value <= cur->umin_value &&
8454 old->umax_value >= cur->umax_value &&
8455 old->smin_value <= cur->smin_value &&
8456 old->smax_value >= cur->smax_value;
f1174f77
EC
8457}
8458
8459/* Maximum number of register states that can exist at once */
8460#define ID_MAP_SIZE (MAX_BPF_REG + MAX_BPF_STACK / BPF_REG_SIZE)
8461struct idpair {
8462 u32 old;
8463 u32 cur;
8464};
8465
8466/* If in the old state two registers had the same id, then they need to have
8467 * the same id in the new state as well. But that id could be different from
8468 * the old state, so we need to track the mapping from old to new ids.
8469 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
8470 * regs with old id 5 must also have new id 9 for the new state to be safe. But
8471 * regs with a different old id could still have new id 9, we don't care about
8472 * that.
8473 * So we look through our idmap to see if this old id has been seen before. If
8474 * so, we require the new id to match; otherwise, we add the id pair to the map.
969bf05e 8475 */
f1174f77 8476static bool check_ids(u32 old_id, u32 cur_id, struct idpair *idmap)
969bf05e 8477{
f1174f77 8478 unsigned int i;
969bf05e 8479
f1174f77
EC
8480 for (i = 0; i < ID_MAP_SIZE; i++) {
8481 if (!idmap[i].old) {
8482 /* Reached an empty slot; haven't seen this id before */
8483 idmap[i].old = old_id;
8484 idmap[i].cur = cur_id;
8485 return true;
8486 }
8487 if (idmap[i].old == old_id)
8488 return idmap[i].cur == cur_id;
8489 }
8490 /* We ran out of idmap slots, which should be impossible */
8491 WARN_ON_ONCE(1);
8492 return false;
8493}
8494
9242b5f5
AS
8495static void clean_func_state(struct bpf_verifier_env *env,
8496 struct bpf_func_state *st)
8497{
8498 enum bpf_reg_liveness live;
8499 int i, j;
8500
8501 for (i = 0; i < BPF_REG_FP; i++) {
8502 live = st->regs[i].live;
8503 /* liveness must not touch this register anymore */
8504 st->regs[i].live |= REG_LIVE_DONE;
8505 if (!(live & REG_LIVE_READ))
8506 /* since the register is unused, clear its state
8507 * to make further comparison simpler
8508 */
f54c7898 8509 __mark_reg_not_init(env, &st->regs[i]);
9242b5f5
AS
8510 }
8511
8512 for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
8513 live = st->stack[i].spilled_ptr.live;
8514 /* liveness must not touch this stack slot anymore */
8515 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
8516 if (!(live & REG_LIVE_READ)) {
f54c7898 8517 __mark_reg_not_init(env, &st->stack[i].spilled_ptr);
9242b5f5
AS
8518 for (j = 0; j < BPF_REG_SIZE; j++)
8519 st->stack[i].slot_type[j] = STACK_INVALID;
8520 }
8521 }
8522}
8523
8524static void clean_verifier_state(struct bpf_verifier_env *env,
8525 struct bpf_verifier_state *st)
8526{
8527 int i;
8528
8529 if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
8530 /* all regs in this state in all frames were already marked */
8531 return;
8532
8533 for (i = 0; i <= st->curframe; i++)
8534 clean_func_state(env, st->frame[i]);
8535}
8536
8537/* the parentage chains form a tree.
8538 * the verifier states are added to state lists at given insn and
8539 * pushed into state stack for future exploration.
8540 * when the verifier reaches bpf_exit insn some of the verifer states
8541 * stored in the state lists have their final liveness state already,
8542 * but a lot of states will get revised from liveness point of view when
8543 * the verifier explores other branches.
8544 * Example:
8545 * 1: r0 = 1
8546 * 2: if r1 == 100 goto pc+1
8547 * 3: r0 = 2
8548 * 4: exit
8549 * when the verifier reaches exit insn the register r0 in the state list of
8550 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
8551 * of insn 2 and goes exploring further. At the insn 4 it will walk the
8552 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
8553 *
8554 * Since the verifier pushes the branch states as it sees them while exploring
8555 * the program the condition of walking the branch instruction for the second
8556 * time means that all states below this branch were already explored and
8557 * their final liveness markes are already propagated.
8558 * Hence when the verifier completes the search of state list in is_state_visited()
8559 * we can call this clean_live_states() function to mark all liveness states
8560 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
8561 * will not be used.
8562 * This function also clears the registers and stack for states that !READ
8563 * to simplify state merging.
8564 *
8565 * Important note here that walking the same branch instruction in the callee
8566 * doesn't meant that the states are DONE. The verifier has to compare
8567 * the callsites
8568 */
8569static void clean_live_states(struct bpf_verifier_env *env, int insn,
8570 struct bpf_verifier_state *cur)
8571{
8572 struct bpf_verifier_state_list *sl;
8573 int i;
8574
5d839021 8575 sl = *explored_state(env, insn);
a8f500af 8576 while (sl) {
2589726d
AS
8577 if (sl->state.branches)
8578 goto next;
dc2a4ebc
AS
8579 if (sl->state.insn_idx != insn ||
8580 sl->state.curframe != cur->curframe)
9242b5f5
AS
8581 goto next;
8582 for (i = 0; i <= cur->curframe; i++)
8583 if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
8584 goto next;
8585 clean_verifier_state(env, &sl->state);
8586next:
8587 sl = sl->next;
8588 }
8589}
8590
f1174f77 8591/* Returns true if (rold safe implies rcur safe) */
1b688a19
EC
8592static bool regsafe(struct bpf_reg_state *rold, struct bpf_reg_state *rcur,
8593 struct idpair *idmap)
f1174f77 8594{
f4d7e40a
AS
8595 bool equal;
8596
dc503a8a
EC
8597 if (!(rold->live & REG_LIVE_READ))
8598 /* explored state didn't use this */
8599 return true;
8600
679c782d 8601 equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, parent)) == 0;
f4d7e40a
AS
8602
8603 if (rold->type == PTR_TO_STACK)
8604 /* two stack pointers are equal only if they're pointing to
8605 * the same stack frame, since fp-8 in foo != fp-8 in bar
8606 */
8607 return equal && rold->frameno == rcur->frameno;
8608
8609 if (equal)
969bf05e
AS
8610 return true;
8611
f1174f77
EC
8612 if (rold->type == NOT_INIT)
8613 /* explored state can't have used this */
969bf05e 8614 return true;
f1174f77
EC
8615 if (rcur->type == NOT_INIT)
8616 return false;
8617 switch (rold->type) {
8618 case SCALAR_VALUE:
8619 if (rcur->type == SCALAR_VALUE) {
b5dc0163
AS
8620 if (!rold->precise && !rcur->precise)
8621 return true;
f1174f77
EC
8622 /* new val must satisfy old val knowledge */
8623 return range_within(rold, rcur) &&
8624 tnum_in(rold->var_off, rcur->var_off);
8625 } else {
179d1c56
JH
8626 /* We're trying to use a pointer in place of a scalar.
8627 * Even if the scalar was unbounded, this could lead to
8628 * pointer leaks because scalars are allowed to leak
8629 * while pointers are not. We could make this safe in
8630 * special cases if root is calling us, but it's
8631 * probably not worth the hassle.
f1174f77 8632 */
179d1c56 8633 return false;
f1174f77
EC
8634 }
8635 case PTR_TO_MAP_VALUE:
1b688a19
EC
8636 /* If the new min/max/var_off satisfy the old ones and
8637 * everything else matches, we are OK.
d83525ca
AS
8638 * 'id' is not compared, since it's only used for maps with
8639 * bpf_spin_lock inside map element and in such cases if
8640 * the rest of the prog is valid for one map element then
8641 * it's valid for all map elements regardless of the key
8642 * used in bpf_map_lookup()
1b688a19
EC
8643 */
8644 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
8645 range_within(rold, rcur) &&
8646 tnum_in(rold->var_off, rcur->var_off);
f1174f77
EC
8647 case PTR_TO_MAP_VALUE_OR_NULL:
8648 /* a PTR_TO_MAP_VALUE could be safe to use as a
8649 * PTR_TO_MAP_VALUE_OR_NULL into the same map.
8650 * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
8651 * checked, doing so could have affected others with the same
8652 * id, and we can't check for that because we lost the id when
8653 * we converted to a PTR_TO_MAP_VALUE.
8654 */
8655 if (rcur->type != PTR_TO_MAP_VALUE_OR_NULL)
8656 return false;
8657 if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
8658 return false;
8659 /* Check our ids match any regs they're supposed to */
8660 return check_ids(rold->id, rcur->id, idmap);
de8f3a83 8661 case PTR_TO_PACKET_META:
f1174f77 8662 case PTR_TO_PACKET:
de8f3a83 8663 if (rcur->type != rold->type)
f1174f77
EC
8664 return false;
8665 /* We must have at least as much range as the old ptr
8666 * did, so that any accesses which were safe before are
8667 * still safe. This is true even if old range < old off,
8668 * since someone could have accessed through (ptr - k), or
8669 * even done ptr -= k in a register, to get a safe access.
8670 */
8671 if (rold->range > rcur->range)
8672 return false;
8673 /* If the offsets don't match, we can't trust our alignment;
8674 * nor can we be sure that we won't fall out of range.
8675 */
8676 if (rold->off != rcur->off)
8677 return false;
8678 /* id relations must be preserved */
8679 if (rold->id && !check_ids(rold->id, rcur->id, idmap))
8680 return false;
8681 /* new val must satisfy old val knowledge */
8682 return range_within(rold, rcur) &&
8683 tnum_in(rold->var_off, rcur->var_off);
8684 case PTR_TO_CTX:
8685 case CONST_PTR_TO_MAP:
f1174f77 8686 case PTR_TO_PACKET_END:
d58e468b 8687 case PTR_TO_FLOW_KEYS:
c64b7983
JS
8688 case PTR_TO_SOCKET:
8689 case PTR_TO_SOCKET_OR_NULL:
46f8bc92
MKL
8690 case PTR_TO_SOCK_COMMON:
8691 case PTR_TO_SOCK_COMMON_OR_NULL:
655a51e5
MKL
8692 case PTR_TO_TCP_SOCK:
8693 case PTR_TO_TCP_SOCK_OR_NULL:
fada7fdc 8694 case PTR_TO_XDP_SOCK:
f1174f77
EC
8695 /* Only valid matches are exact, which memcmp() above
8696 * would have accepted
8697 */
8698 default:
8699 /* Don't know what's going on, just say it's not safe */
8700 return false;
8701 }
969bf05e 8702
f1174f77
EC
8703 /* Shouldn't get here; if we do, say it's not safe */
8704 WARN_ON_ONCE(1);
969bf05e
AS
8705 return false;
8706}
8707
f4d7e40a
AS
8708static bool stacksafe(struct bpf_func_state *old,
8709 struct bpf_func_state *cur,
638f5b90
AS
8710 struct idpair *idmap)
8711{
8712 int i, spi;
8713
638f5b90
AS
8714 /* walk slots of the explored stack and ignore any additional
8715 * slots in the current stack, since explored(safe) state
8716 * didn't use them
8717 */
8718 for (i = 0; i < old->allocated_stack; i++) {
8719 spi = i / BPF_REG_SIZE;
8720
b233920c
AS
8721 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
8722 i += BPF_REG_SIZE - 1;
cc2b14d5 8723 /* explored state didn't use this */
fd05e57b 8724 continue;
b233920c 8725 }
cc2b14d5 8726
638f5b90
AS
8727 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
8728 continue;
19e2dbb7
AS
8729
8730 /* explored stack has more populated slots than current stack
8731 * and these slots were used
8732 */
8733 if (i >= cur->allocated_stack)
8734 return false;
8735
cc2b14d5
AS
8736 /* if old state was safe with misc data in the stack
8737 * it will be safe with zero-initialized stack.
8738 * The opposite is not true
8739 */
8740 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
8741 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
8742 continue;
638f5b90
AS
8743 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
8744 cur->stack[spi].slot_type[i % BPF_REG_SIZE])
8745 /* Ex: old explored (safe) state has STACK_SPILL in
b8c1a309 8746 * this stack slot, but current has STACK_MISC ->
638f5b90
AS
8747 * this verifier states are not equivalent,
8748 * return false to continue verification of this path
8749 */
8750 return false;
8751 if (i % BPF_REG_SIZE)
8752 continue;
8753 if (old->stack[spi].slot_type[0] != STACK_SPILL)
8754 continue;
8755 if (!regsafe(&old->stack[spi].spilled_ptr,
8756 &cur->stack[spi].spilled_ptr,
8757 idmap))
8758 /* when explored and current stack slot are both storing
8759 * spilled registers, check that stored pointers types
8760 * are the same as well.
8761 * Ex: explored safe path could have stored
8762 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
8763 * but current path has stored:
8764 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
8765 * such verifier states are not equivalent.
8766 * return false to continue verification of this path
8767 */
8768 return false;
8769 }
8770 return true;
8771}
8772
fd978bf7
JS
8773static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur)
8774{
8775 if (old->acquired_refs != cur->acquired_refs)
8776 return false;
8777 return !memcmp(old->refs, cur->refs,
8778 sizeof(*old->refs) * old->acquired_refs);
8779}
8780
f1bca824
AS
8781/* compare two verifier states
8782 *
8783 * all states stored in state_list are known to be valid, since
8784 * verifier reached 'bpf_exit' instruction through them
8785 *
8786 * this function is called when verifier exploring different branches of
8787 * execution popped from the state stack. If it sees an old state that has
8788 * more strict register state and more strict stack state then this execution
8789 * branch doesn't need to be explored further, since verifier already
8790 * concluded that more strict state leads to valid finish.
8791 *
8792 * Therefore two states are equivalent if register state is more conservative
8793 * and explored stack state is more conservative than the current one.
8794 * Example:
8795 * explored current
8796 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
8797 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
8798 *
8799 * In other words if current stack state (one being explored) has more
8800 * valid slots than old one that already passed validation, it means
8801 * the verifier can stop exploring and conclude that current state is valid too
8802 *
8803 * Similarly with registers. If explored state has register type as invalid
8804 * whereas register type in current state is meaningful, it means that
8805 * the current state will reach 'bpf_exit' instruction safely
8806 */
f4d7e40a
AS
8807static bool func_states_equal(struct bpf_func_state *old,
8808 struct bpf_func_state *cur)
f1bca824 8809{
f1174f77
EC
8810 struct idpair *idmap;
8811 bool ret = false;
f1bca824
AS
8812 int i;
8813
f1174f77
EC
8814 idmap = kcalloc(ID_MAP_SIZE, sizeof(struct idpair), GFP_KERNEL);
8815 /* If we failed to allocate the idmap, just say it's not safe */
8816 if (!idmap)
1a0dc1ac 8817 return false;
f1174f77
EC
8818
8819 for (i = 0; i < MAX_BPF_REG; i++) {
1b688a19 8820 if (!regsafe(&old->regs[i], &cur->regs[i], idmap))
f1174f77 8821 goto out_free;
f1bca824
AS
8822 }
8823
638f5b90
AS
8824 if (!stacksafe(old, cur, idmap))
8825 goto out_free;
fd978bf7
JS
8826
8827 if (!refsafe(old, cur))
8828 goto out_free;
f1174f77
EC
8829 ret = true;
8830out_free:
8831 kfree(idmap);
8832 return ret;
f1bca824
AS
8833}
8834
f4d7e40a
AS
8835static bool states_equal(struct bpf_verifier_env *env,
8836 struct bpf_verifier_state *old,
8837 struct bpf_verifier_state *cur)
8838{
8839 int i;
8840
8841 if (old->curframe != cur->curframe)
8842 return false;
8843
979d63d5
DB
8844 /* Verification state from speculative execution simulation
8845 * must never prune a non-speculative execution one.
8846 */
8847 if (old->speculative && !cur->speculative)
8848 return false;
8849
d83525ca
AS
8850 if (old->active_spin_lock != cur->active_spin_lock)
8851 return false;
8852
f4d7e40a
AS
8853 /* for states to be equal callsites have to be the same
8854 * and all frame states need to be equivalent
8855 */
8856 for (i = 0; i <= old->curframe; i++) {
8857 if (old->frame[i]->callsite != cur->frame[i]->callsite)
8858 return false;
8859 if (!func_states_equal(old->frame[i], cur->frame[i]))
8860 return false;
8861 }
8862 return true;
8863}
8864
5327ed3d
JW
8865/* Return 0 if no propagation happened. Return negative error code if error
8866 * happened. Otherwise, return the propagated bit.
8867 */
55e7f3b5
JW
8868static int propagate_liveness_reg(struct bpf_verifier_env *env,
8869 struct bpf_reg_state *reg,
8870 struct bpf_reg_state *parent_reg)
8871{
5327ed3d
JW
8872 u8 parent_flag = parent_reg->live & REG_LIVE_READ;
8873 u8 flag = reg->live & REG_LIVE_READ;
55e7f3b5
JW
8874 int err;
8875
5327ed3d
JW
8876 /* When comes here, read flags of PARENT_REG or REG could be any of
8877 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
8878 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
8879 */
8880 if (parent_flag == REG_LIVE_READ64 ||
8881 /* Or if there is no read flag from REG. */
8882 !flag ||
8883 /* Or if the read flag from REG is the same as PARENT_REG. */
8884 parent_flag == flag)
55e7f3b5
JW
8885 return 0;
8886
5327ed3d 8887 err = mark_reg_read(env, reg, parent_reg, flag);
55e7f3b5
JW
8888 if (err)
8889 return err;
8890
5327ed3d 8891 return flag;
55e7f3b5
JW
8892}
8893
8e9cd9ce 8894/* A write screens off any subsequent reads; but write marks come from the
f4d7e40a
AS
8895 * straight-line code between a state and its parent. When we arrive at an
8896 * equivalent state (jump target or such) we didn't arrive by the straight-line
8897 * code, so read marks in the state must propagate to the parent regardless
8898 * of the state's write marks. That's what 'parent == state->parent' comparison
679c782d 8899 * in mark_reg_read() is for.
8e9cd9ce 8900 */
f4d7e40a
AS
8901static int propagate_liveness(struct bpf_verifier_env *env,
8902 const struct bpf_verifier_state *vstate,
8903 struct bpf_verifier_state *vparent)
dc503a8a 8904{
3f8cafa4 8905 struct bpf_reg_state *state_reg, *parent_reg;
f4d7e40a 8906 struct bpf_func_state *state, *parent;
3f8cafa4 8907 int i, frame, err = 0;
dc503a8a 8908
f4d7e40a
AS
8909 if (vparent->curframe != vstate->curframe) {
8910 WARN(1, "propagate_live: parent frame %d current frame %d\n",
8911 vparent->curframe, vstate->curframe);
8912 return -EFAULT;
8913 }
dc503a8a
EC
8914 /* Propagate read liveness of registers... */
8915 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
83d16312 8916 for (frame = 0; frame <= vstate->curframe; frame++) {
3f8cafa4
JW
8917 parent = vparent->frame[frame];
8918 state = vstate->frame[frame];
8919 parent_reg = parent->regs;
8920 state_reg = state->regs;
83d16312
JK
8921 /* We don't need to worry about FP liveness, it's read-only */
8922 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
55e7f3b5
JW
8923 err = propagate_liveness_reg(env, &state_reg[i],
8924 &parent_reg[i]);
5327ed3d 8925 if (err < 0)
3f8cafa4 8926 return err;
5327ed3d
JW
8927 if (err == REG_LIVE_READ64)
8928 mark_insn_zext(env, &parent_reg[i]);
dc503a8a 8929 }
f4d7e40a 8930
1b04aee7 8931 /* Propagate stack slots. */
f4d7e40a
AS
8932 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
8933 i < parent->allocated_stack / BPF_REG_SIZE; i++) {
3f8cafa4
JW
8934 parent_reg = &parent->stack[i].spilled_ptr;
8935 state_reg = &state->stack[i].spilled_ptr;
55e7f3b5
JW
8936 err = propagate_liveness_reg(env, state_reg,
8937 parent_reg);
5327ed3d 8938 if (err < 0)
3f8cafa4 8939 return err;
dc503a8a
EC
8940 }
8941 }
5327ed3d 8942 return 0;
dc503a8a
EC
8943}
8944
a3ce685d
AS
8945/* find precise scalars in the previous equivalent state and
8946 * propagate them into the current state
8947 */
8948static int propagate_precision(struct bpf_verifier_env *env,
8949 const struct bpf_verifier_state *old)
8950{
8951 struct bpf_reg_state *state_reg;
8952 struct bpf_func_state *state;
8953 int i, err = 0;
8954
8955 state = old->frame[old->curframe];
8956 state_reg = state->regs;
8957 for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
8958 if (state_reg->type != SCALAR_VALUE ||
8959 !state_reg->precise)
8960 continue;
8961 if (env->log.level & BPF_LOG_LEVEL2)
8962 verbose(env, "propagating r%d\n", i);
8963 err = mark_chain_precision(env, i);
8964 if (err < 0)
8965 return err;
8966 }
8967
8968 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
8969 if (state->stack[i].slot_type[0] != STACK_SPILL)
8970 continue;
8971 state_reg = &state->stack[i].spilled_ptr;
8972 if (state_reg->type != SCALAR_VALUE ||
8973 !state_reg->precise)
8974 continue;
8975 if (env->log.level & BPF_LOG_LEVEL2)
8976 verbose(env, "propagating fp%d\n",
8977 (-i - 1) * BPF_REG_SIZE);
8978 err = mark_chain_precision_stack(env, i);
8979 if (err < 0)
8980 return err;
8981 }
8982 return 0;
8983}
8984
2589726d
AS
8985static bool states_maybe_looping(struct bpf_verifier_state *old,
8986 struct bpf_verifier_state *cur)
8987{
8988 struct bpf_func_state *fold, *fcur;
8989 int i, fr = cur->curframe;
8990
8991 if (old->curframe != fr)
8992 return false;
8993
8994 fold = old->frame[fr];
8995 fcur = cur->frame[fr];
8996 for (i = 0; i < MAX_BPF_REG; i++)
8997 if (memcmp(&fold->regs[i], &fcur->regs[i],
8998 offsetof(struct bpf_reg_state, parent)))
8999 return false;
9000 return true;
9001}
9002
9003
58e2af8b 9004static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
f1bca824 9005{
58e2af8b 9006 struct bpf_verifier_state_list *new_sl;
9f4686c4 9007 struct bpf_verifier_state_list *sl, **pprev;
679c782d 9008 struct bpf_verifier_state *cur = env->cur_state, *new;
ceefbc96 9009 int i, j, err, states_cnt = 0;
10d274e8 9010 bool add_new_state = env->test_state_freq ? true : false;
f1bca824 9011
b5dc0163 9012 cur->last_insn_idx = env->prev_insn_idx;
a8f500af 9013 if (!env->insn_aux_data[insn_idx].prune_point)
f1bca824
AS
9014 /* this 'insn_idx' instruction wasn't marked, so we will not
9015 * be doing state search here
9016 */
9017 return 0;
9018
2589726d
AS
9019 /* bpf progs typically have pruning point every 4 instructions
9020 * http://vger.kernel.org/bpfconf2019.html#session-1
9021 * Do not add new state for future pruning if the verifier hasn't seen
9022 * at least 2 jumps and at least 8 instructions.
9023 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
9024 * In tests that amounts to up to 50% reduction into total verifier
9025 * memory consumption and 20% verifier time speedup.
9026 */
9027 if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
9028 env->insn_processed - env->prev_insn_processed >= 8)
9029 add_new_state = true;
9030
a8f500af
AS
9031 pprev = explored_state(env, insn_idx);
9032 sl = *pprev;
9033
9242b5f5
AS
9034 clean_live_states(env, insn_idx, cur);
9035
a8f500af 9036 while (sl) {
dc2a4ebc
AS
9037 states_cnt++;
9038 if (sl->state.insn_idx != insn_idx)
9039 goto next;
2589726d
AS
9040 if (sl->state.branches) {
9041 if (states_maybe_looping(&sl->state, cur) &&
9042 states_equal(env, &sl->state, cur)) {
9043 verbose_linfo(env, insn_idx, "; ");
9044 verbose(env, "infinite loop detected at insn %d\n", insn_idx);
9045 return -EINVAL;
9046 }
9047 /* if the verifier is processing a loop, avoid adding new state
9048 * too often, since different loop iterations have distinct
9049 * states and may not help future pruning.
9050 * This threshold shouldn't be too low to make sure that
9051 * a loop with large bound will be rejected quickly.
9052 * The most abusive loop will be:
9053 * r1 += 1
9054 * if r1 < 1000000 goto pc-2
9055 * 1M insn_procssed limit / 100 == 10k peak states.
9056 * This threshold shouldn't be too high either, since states
9057 * at the end of the loop are likely to be useful in pruning.
9058 */
9059 if (env->jmps_processed - env->prev_jmps_processed < 20 &&
9060 env->insn_processed - env->prev_insn_processed < 100)
9061 add_new_state = false;
9062 goto miss;
9063 }
638f5b90 9064 if (states_equal(env, &sl->state, cur)) {
9f4686c4 9065 sl->hit_cnt++;
f1bca824 9066 /* reached equivalent register/stack state,
dc503a8a
EC
9067 * prune the search.
9068 * Registers read by the continuation are read by us.
8e9cd9ce
EC
9069 * If we have any write marks in env->cur_state, they
9070 * will prevent corresponding reads in the continuation
9071 * from reaching our parent (an explored_state). Our
9072 * own state will get the read marks recorded, but
9073 * they'll be immediately forgotten as we're pruning
9074 * this state and will pop a new one.
f1bca824 9075 */
f4d7e40a 9076 err = propagate_liveness(env, &sl->state, cur);
a3ce685d
AS
9077
9078 /* if previous state reached the exit with precision and
9079 * current state is equivalent to it (except precsion marks)
9080 * the precision needs to be propagated back in
9081 * the current state.
9082 */
9083 err = err ? : push_jmp_history(env, cur);
9084 err = err ? : propagate_precision(env, &sl->state);
f4d7e40a
AS
9085 if (err)
9086 return err;
f1bca824 9087 return 1;
dc503a8a 9088 }
2589726d
AS
9089miss:
9090 /* when new state is not going to be added do not increase miss count.
9091 * Otherwise several loop iterations will remove the state
9092 * recorded earlier. The goal of these heuristics is to have
9093 * states from some iterations of the loop (some in the beginning
9094 * and some at the end) to help pruning.
9095 */
9096 if (add_new_state)
9097 sl->miss_cnt++;
9f4686c4
AS
9098 /* heuristic to determine whether this state is beneficial
9099 * to keep checking from state equivalence point of view.
9100 * Higher numbers increase max_states_per_insn and verification time,
9101 * but do not meaningfully decrease insn_processed.
9102 */
9103 if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
9104 /* the state is unlikely to be useful. Remove it to
9105 * speed up verification
9106 */
9107 *pprev = sl->next;
9108 if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
2589726d
AS
9109 u32 br = sl->state.branches;
9110
9111 WARN_ONCE(br,
9112 "BUG live_done but branches_to_explore %d\n",
9113 br);
9f4686c4
AS
9114 free_verifier_state(&sl->state, false);
9115 kfree(sl);
9116 env->peak_states--;
9117 } else {
9118 /* cannot free this state, since parentage chain may
9119 * walk it later. Add it for free_list instead to
9120 * be freed at the end of verification
9121 */
9122 sl->next = env->free_list;
9123 env->free_list = sl;
9124 }
9125 sl = *pprev;
9126 continue;
9127 }
dc2a4ebc 9128next:
9f4686c4
AS
9129 pprev = &sl->next;
9130 sl = *pprev;
f1bca824
AS
9131 }
9132
06ee7115
AS
9133 if (env->max_states_per_insn < states_cnt)
9134 env->max_states_per_insn = states_cnt;
9135
2c78ee89 9136 if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
b5dc0163 9137 return push_jmp_history(env, cur);
ceefbc96 9138
2589726d 9139 if (!add_new_state)
b5dc0163 9140 return push_jmp_history(env, cur);
ceefbc96 9141
2589726d
AS
9142 /* There were no equivalent states, remember the current one.
9143 * Technically the current state is not proven to be safe yet,
f4d7e40a 9144 * but it will either reach outer most bpf_exit (which means it's safe)
2589726d 9145 * or it will be rejected. When there are no loops the verifier won't be
f4d7e40a 9146 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
2589726d
AS
9147 * again on the way to bpf_exit.
9148 * When looping the sl->state.branches will be > 0 and this state
9149 * will not be considered for equivalence until branches == 0.
f1bca824 9150 */
638f5b90 9151 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
f1bca824
AS
9152 if (!new_sl)
9153 return -ENOMEM;
06ee7115
AS
9154 env->total_states++;
9155 env->peak_states++;
2589726d
AS
9156 env->prev_jmps_processed = env->jmps_processed;
9157 env->prev_insn_processed = env->insn_processed;
f1bca824
AS
9158
9159 /* add new state to the head of linked list */
679c782d
EC
9160 new = &new_sl->state;
9161 err = copy_verifier_state(new, cur);
1969db47 9162 if (err) {
679c782d 9163 free_verifier_state(new, false);
1969db47
AS
9164 kfree(new_sl);
9165 return err;
9166 }
dc2a4ebc 9167 new->insn_idx = insn_idx;
2589726d
AS
9168 WARN_ONCE(new->branches != 1,
9169 "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
b5dc0163 9170
2589726d 9171 cur->parent = new;
b5dc0163
AS
9172 cur->first_insn_idx = insn_idx;
9173 clear_jmp_history(cur);
5d839021
AS
9174 new_sl->next = *explored_state(env, insn_idx);
9175 *explored_state(env, insn_idx) = new_sl;
7640ead9
JK
9176 /* connect new state to parentage chain. Current frame needs all
9177 * registers connected. Only r6 - r9 of the callers are alive (pushed
9178 * to the stack implicitly by JITs) so in callers' frames connect just
9179 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
9180 * the state of the call instruction (with WRITTEN set), and r0 comes
9181 * from callee with its full parentage chain, anyway.
9182 */
8e9cd9ce
EC
9183 /* clear write marks in current state: the writes we did are not writes
9184 * our child did, so they don't screen off its reads from us.
9185 * (There are no read marks in current state, because reads always mark
9186 * their parent and current state never has children yet. Only
9187 * explored_states can get read marks.)
9188 */
eea1c227
AS
9189 for (j = 0; j <= cur->curframe; j++) {
9190 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
9191 cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
9192 for (i = 0; i < BPF_REG_FP; i++)
9193 cur->frame[j]->regs[i].live = REG_LIVE_NONE;
9194 }
f4d7e40a
AS
9195
9196 /* all stack frames are accessible from callee, clear them all */
9197 for (j = 0; j <= cur->curframe; j++) {
9198 struct bpf_func_state *frame = cur->frame[j];
679c782d 9199 struct bpf_func_state *newframe = new->frame[j];
f4d7e40a 9200
679c782d 9201 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
cc2b14d5 9202 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
679c782d
EC
9203 frame->stack[i].spilled_ptr.parent =
9204 &newframe->stack[i].spilled_ptr;
9205 }
f4d7e40a 9206 }
f1bca824
AS
9207 return 0;
9208}
9209
c64b7983
JS
9210/* Return true if it's OK to have the same insn return a different type. */
9211static bool reg_type_mismatch_ok(enum bpf_reg_type type)
9212{
9213 switch (type) {
9214 case PTR_TO_CTX:
9215 case PTR_TO_SOCKET:
9216 case PTR_TO_SOCKET_OR_NULL:
46f8bc92
MKL
9217 case PTR_TO_SOCK_COMMON:
9218 case PTR_TO_SOCK_COMMON_OR_NULL:
655a51e5
MKL
9219 case PTR_TO_TCP_SOCK:
9220 case PTR_TO_TCP_SOCK_OR_NULL:
fada7fdc 9221 case PTR_TO_XDP_SOCK:
2a02759e 9222 case PTR_TO_BTF_ID:
b121b341 9223 case PTR_TO_BTF_ID_OR_NULL:
c64b7983
JS
9224 return false;
9225 default:
9226 return true;
9227 }
9228}
9229
9230/* If an instruction was previously used with particular pointer types, then we
9231 * need to be careful to avoid cases such as the below, where it may be ok
9232 * for one branch accessing the pointer, but not ok for the other branch:
9233 *
9234 * R1 = sock_ptr
9235 * goto X;
9236 * ...
9237 * R1 = some_other_valid_ptr;
9238 * goto X;
9239 * ...
9240 * R2 = *(u32 *)(R1 + 0);
9241 */
9242static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
9243{
9244 return src != prev && (!reg_type_mismatch_ok(src) ||
9245 !reg_type_mismatch_ok(prev));
9246}
9247
58e2af8b 9248static int do_check(struct bpf_verifier_env *env)
17a52670 9249{
6f8a57cc 9250 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
51c39bb1 9251 struct bpf_verifier_state *state = env->cur_state;
17a52670 9252 struct bpf_insn *insns = env->prog->insnsi;
638f5b90 9253 struct bpf_reg_state *regs;
06ee7115 9254 int insn_cnt = env->prog->len;
17a52670 9255 bool do_print_state = false;
b5dc0163 9256 int prev_insn_idx = -1;
17a52670 9257
17a52670
AS
9258 for (;;) {
9259 struct bpf_insn *insn;
9260 u8 class;
9261 int err;
9262
b5dc0163 9263 env->prev_insn_idx = prev_insn_idx;
c08435ec 9264 if (env->insn_idx >= insn_cnt) {
61bd5218 9265 verbose(env, "invalid insn idx %d insn_cnt %d\n",
c08435ec 9266 env->insn_idx, insn_cnt);
17a52670
AS
9267 return -EFAULT;
9268 }
9269
c08435ec 9270 insn = &insns[env->insn_idx];
17a52670
AS
9271 class = BPF_CLASS(insn->code);
9272
06ee7115 9273 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
61bd5218
JK
9274 verbose(env,
9275 "BPF program is too large. Processed %d insn\n",
06ee7115 9276 env->insn_processed);
17a52670
AS
9277 return -E2BIG;
9278 }
9279
c08435ec 9280 err = is_state_visited(env, env->insn_idx);
f1bca824
AS
9281 if (err < 0)
9282 return err;
9283 if (err == 1) {
9284 /* found equivalent state, can prune the search */
06ee7115 9285 if (env->log.level & BPF_LOG_LEVEL) {
f1bca824 9286 if (do_print_state)
979d63d5
DB
9287 verbose(env, "\nfrom %d to %d%s: safe\n",
9288 env->prev_insn_idx, env->insn_idx,
9289 env->cur_state->speculative ?
9290 " (speculative execution)" : "");
f1bca824 9291 else
c08435ec 9292 verbose(env, "%d: safe\n", env->insn_idx);
f1bca824
AS
9293 }
9294 goto process_bpf_exit;
9295 }
9296
c3494801
AS
9297 if (signal_pending(current))
9298 return -EAGAIN;
9299
3c2ce60b
DB
9300 if (need_resched())
9301 cond_resched();
9302
06ee7115
AS
9303 if (env->log.level & BPF_LOG_LEVEL2 ||
9304 (env->log.level & BPF_LOG_LEVEL && do_print_state)) {
9305 if (env->log.level & BPF_LOG_LEVEL2)
c08435ec 9306 verbose(env, "%d:", env->insn_idx);
c5fc9692 9307 else
979d63d5
DB
9308 verbose(env, "\nfrom %d to %d%s:",
9309 env->prev_insn_idx, env->insn_idx,
9310 env->cur_state->speculative ?
9311 " (speculative execution)" : "");
f4d7e40a 9312 print_verifier_state(env, state->frame[state->curframe]);
17a52670
AS
9313 do_print_state = false;
9314 }
9315
06ee7115 9316 if (env->log.level & BPF_LOG_LEVEL) {
7105e828
DB
9317 const struct bpf_insn_cbs cbs = {
9318 .cb_print = verbose,
abe08840 9319 .private_data = env,
7105e828
DB
9320 };
9321
c08435ec
DB
9322 verbose_linfo(env, env->insn_idx, "; ");
9323 verbose(env, "%d: ", env->insn_idx);
abe08840 9324 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
17a52670
AS
9325 }
9326
cae1927c 9327 if (bpf_prog_is_dev_bound(env->prog->aux)) {
c08435ec
DB
9328 err = bpf_prog_offload_verify_insn(env, env->insn_idx,
9329 env->prev_insn_idx);
cae1927c
JK
9330 if (err)
9331 return err;
9332 }
13a27dfc 9333
638f5b90 9334 regs = cur_regs(env);
51c39bb1 9335 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
b5dc0163 9336 prev_insn_idx = env->insn_idx;
fd978bf7 9337
17a52670 9338 if (class == BPF_ALU || class == BPF_ALU64) {
1be7f75d 9339 err = check_alu_op(env, insn);
17a52670
AS
9340 if (err)
9341 return err;
9342
9343 } else if (class == BPF_LDX) {
3df126f3 9344 enum bpf_reg_type *prev_src_type, src_reg_type;
9bac3d6d
AS
9345
9346 /* check for reserved fields is already done */
9347
17a52670 9348 /* check src operand */
dc503a8a 9349 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17a52670
AS
9350 if (err)
9351 return err;
9352
dc503a8a 9353 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
17a52670
AS
9354 if (err)
9355 return err;
9356
725f9dcd
AS
9357 src_reg_type = regs[insn->src_reg].type;
9358
17a52670
AS
9359 /* check that memory (src_reg + off) is readable,
9360 * the state of dst_reg will be updated by this func
9361 */
c08435ec
DB
9362 err = check_mem_access(env, env->insn_idx, insn->src_reg,
9363 insn->off, BPF_SIZE(insn->code),
9364 BPF_READ, insn->dst_reg, false);
17a52670
AS
9365 if (err)
9366 return err;
9367
c08435ec 9368 prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type;
3df126f3
JK
9369
9370 if (*prev_src_type == NOT_INIT) {
9bac3d6d
AS
9371 /* saw a valid insn
9372 * dst_reg = *(u32 *)(src_reg + off)
3df126f3 9373 * save type to validate intersecting paths
9bac3d6d 9374 */
3df126f3 9375 *prev_src_type = src_reg_type;
9bac3d6d 9376
c64b7983 9377 } else if (reg_type_mismatch(src_reg_type, *prev_src_type)) {
9bac3d6d
AS
9378 /* ABuser program is trying to use the same insn
9379 * dst_reg = *(u32*) (src_reg + off)
9380 * with different pointer types:
9381 * src_reg == ctx in one branch and
9382 * src_reg == stack|map in some other branch.
9383 * Reject it.
9384 */
61bd5218 9385 verbose(env, "same insn cannot be used with different pointers\n");
9bac3d6d
AS
9386 return -EINVAL;
9387 }
9388
17a52670 9389 } else if (class == BPF_STX) {
3df126f3 9390 enum bpf_reg_type *prev_dst_type, dst_reg_type;
d691f9e8 9391
17a52670 9392 if (BPF_MODE(insn->code) == BPF_XADD) {
c08435ec 9393 err = check_xadd(env, env->insn_idx, insn);
17a52670
AS
9394 if (err)
9395 return err;
c08435ec 9396 env->insn_idx++;
17a52670
AS
9397 continue;
9398 }
9399
17a52670 9400 /* check src1 operand */
dc503a8a 9401 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17a52670
AS
9402 if (err)
9403 return err;
9404 /* check src2 operand */
dc503a8a 9405 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17a52670
AS
9406 if (err)
9407 return err;
9408
d691f9e8
AS
9409 dst_reg_type = regs[insn->dst_reg].type;
9410
17a52670 9411 /* check that memory (dst_reg + off) is writeable */
c08435ec
DB
9412 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
9413 insn->off, BPF_SIZE(insn->code),
9414 BPF_WRITE, insn->src_reg, false);
17a52670
AS
9415 if (err)
9416 return err;
9417
c08435ec 9418 prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type;
3df126f3
JK
9419
9420 if (*prev_dst_type == NOT_INIT) {
9421 *prev_dst_type = dst_reg_type;
c64b7983 9422 } else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) {
61bd5218 9423 verbose(env, "same insn cannot be used with different pointers\n");
d691f9e8
AS
9424 return -EINVAL;
9425 }
9426
17a52670
AS
9427 } else if (class == BPF_ST) {
9428 if (BPF_MODE(insn->code) != BPF_MEM ||
9429 insn->src_reg != BPF_REG_0) {
61bd5218 9430 verbose(env, "BPF_ST uses reserved fields\n");
17a52670
AS
9431 return -EINVAL;
9432 }
9433 /* check src operand */
dc503a8a 9434 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17a52670
AS
9435 if (err)
9436 return err;
9437
f37a8cb8 9438 if (is_ctx_reg(env, insn->dst_reg)) {
9d2be44a 9439 verbose(env, "BPF_ST stores into R%d %s is not allowed\n",
2a159c6f
DB
9440 insn->dst_reg,
9441 reg_type_str[reg_state(env, insn->dst_reg)->type]);
f37a8cb8
DB
9442 return -EACCES;
9443 }
9444
17a52670 9445 /* check that memory (dst_reg + off) is writeable */
c08435ec
DB
9446 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
9447 insn->off, BPF_SIZE(insn->code),
9448 BPF_WRITE, -1, false);
17a52670
AS
9449 if (err)
9450 return err;
9451
092ed096 9452 } else if (class == BPF_JMP || class == BPF_JMP32) {
17a52670
AS
9453 u8 opcode = BPF_OP(insn->code);
9454
2589726d 9455 env->jmps_processed++;
17a52670
AS
9456 if (opcode == BPF_CALL) {
9457 if (BPF_SRC(insn->code) != BPF_K ||
9458 insn->off != 0 ||
f4d7e40a
AS
9459 (insn->src_reg != BPF_REG_0 &&
9460 insn->src_reg != BPF_PSEUDO_CALL) ||
092ed096
JW
9461 insn->dst_reg != BPF_REG_0 ||
9462 class == BPF_JMP32) {
61bd5218 9463 verbose(env, "BPF_CALL uses reserved fields\n");
17a52670
AS
9464 return -EINVAL;
9465 }
9466
d83525ca
AS
9467 if (env->cur_state->active_spin_lock &&
9468 (insn->src_reg == BPF_PSEUDO_CALL ||
9469 insn->imm != BPF_FUNC_spin_unlock)) {
9470 verbose(env, "function calls are not allowed while holding a lock\n");
9471 return -EINVAL;
9472 }
f4d7e40a 9473 if (insn->src_reg == BPF_PSEUDO_CALL)
c08435ec 9474 err = check_func_call(env, insn, &env->insn_idx);
f4d7e40a 9475 else
c08435ec 9476 err = check_helper_call(env, insn->imm, env->insn_idx);
17a52670
AS
9477 if (err)
9478 return err;
9479
9480 } else if (opcode == BPF_JA) {
9481 if (BPF_SRC(insn->code) != BPF_K ||
9482 insn->imm != 0 ||
9483 insn->src_reg != BPF_REG_0 ||
092ed096
JW
9484 insn->dst_reg != BPF_REG_0 ||
9485 class == BPF_JMP32) {
61bd5218 9486 verbose(env, "BPF_JA uses reserved fields\n");
17a52670
AS
9487 return -EINVAL;
9488 }
9489
c08435ec 9490 env->insn_idx += insn->off + 1;
17a52670
AS
9491 continue;
9492
9493 } else if (opcode == BPF_EXIT) {
9494 if (BPF_SRC(insn->code) != BPF_K ||
9495 insn->imm != 0 ||
9496 insn->src_reg != BPF_REG_0 ||
092ed096
JW
9497 insn->dst_reg != BPF_REG_0 ||
9498 class == BPF_JMP32) {
61bd5218 9499 verbose(env, "BPF_EXIT uses reserved fields\n");
17a52670
AS
9500 return -EINVAL;
9501 }
9502
d83525ca
AS
9503 if (env->cur_state->active_spin_lock) {
9504 verbose(env, "bpf_spin_unlock is missing\n");
9505 return -EINVAL;
9506 }
9507
f4d7e40a
AS
9508 if (state->curframe) {
9509 /* exit from nested function */
c08435ec 9510 err = prepare_func_exit(env, &env->insn_idx);
f4d7e40a
AS
9511 if (err)
9512 return err;
9513 do_print_state = true;
9514 continue;
9515 }
9516
fd978bf7
JS
9517 err = check_reference_leak(env);
9518 if (err)
9519 return err;
9520
390ee7e2
AS
9521 err = check_return_code(env);
9522 if (err)
9523 return err;
f1bca824 9524process_bpf_exit:
2589726d 9525 update_branch_counts(env, env->cur_state);
b5dc0163 9526 err = pop_stack(env, &prev_insn_idx,
6f8a57cc 9527 &env->insn_idx, pop_log);
638f5b90
AS
9528 if (err < 0) {
9529 if (err != -ENOENT)
9530 return err;
17a52670
AS
9531 break;
9532 } else {
9533 do_print_state = true;
9534 continue;
9535 }
9536 } else {
c08435ec 9537 err = check_cond_jmp_op(env, insn, &env->insn_idx);
17a52670
AS
9538 if (err)
9539 return err;
9540 }
9541 } else if (class == BPF_LD) {
9542 u8 mode = BPF_MODE(insn->code);
9543
9544 if (mode == BPF_ABS || mode == BPF_IND) {
ddd872bc
AS
9545 err = check_ld_abs(env, insn);
9546 if (err)
9547 return err;
9548
17a52670
AS
9549 } else if (mode == BPF_IMM) {
9550 err = check_ld_imm(env, insn);
9551 if (err)
9552 return err;
9553
c08435ec 9554 env->insn_idx++;
51c39bb1 9555 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
17a52670 9556 } else {
61bd5218 9557 verbose(env, "invalid BPF_LD mode\n");
17a52670
AS
9558 return -EINVAL;
9559 }
9560 } else {
61bd5218 9561 verbose(env, "unknown insn class %d\n", class);
17a52670
AS
9562 return -EINVAL;
9563 }
9564
c08435ec 9565 env->insn_idx++;
17a52670
AS
9566 }
9567
9568 return 0;
9569}
9570
4976b718
HL
9571/* replace pseudo btf_id with kernel symbol address */
9572static int check_pseudo_btf_id(struct bpf_verifier_env *env,
9573 struct bpf_insn *insn,
9574 struct bpf_insn_aux_data *aux)
9575{
eaa6bcb7
HL
9576 u32 datasec_id, type, id = insn->imm;
9577 const struct btf_var_secinfo *vsi;
9578 const struct btf_type *datasec;
4976b718
HL
9579 const struct btf_type *t;
9580 const char *sym_name;
eaa6bcb7 9581 bool percpu = false;
4976b718 9582 u64 addr;
eaa6bcb7 9583 int i;
4976b718
HL
9584
9585 if (!btf_vmlinux) {
9586 verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
9587 return -EINVAL;
9588 }
9589
9590 if (insn[1].imm != 0) {
9591 verbose(env, "reserved field (insn[1].imm) is used in pseudo_btf_id ldimm64 insn.\n");
9592 return -EINVAL;
9593 }
9594
9595 t = btf_type_by_id(btf_vmlinux, id);
9596 if (!t) {
9597 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
9598 return -ENOENT;
9599 }
9600
9601 if (!btf_type_is_var(t)) {
9602 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR.\n",
9603 id);
9604 return -EINVAL;
9605 }
9606
9607 sym_name = btf_name_by_offset(btf_vmlinux, t->name_off);
9608 addr = kallsyms_lookup_name(sym_name);
9609 if (!addr) {
9610 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
9611 sym_name);
9612 return -ENOENT;
9613 }
9614
eaa6bcb7
HL
9615 datasec_id = btf_find_by_name_kind(btf_vmlinux, ".data..percpu",
9616 BTF_KIND_DATASEC);
9617 if (datasec_id > 0) {
9618 datasec = btf_type_by_id(btf_vmlinux, datasec_id);
9619 for_each_vsi(i, datasec, vsi) {
9620 if (vsi->type == id) {
9621 percpu = true;
9622 break;
9623 }
9624 }
9625 }
9626
4976b718
HL
9627 insn[0].imm = (u32)addr;
9628 insn[1].imm = addr >> 32;
9629
9630 type = t->type;
9631 t = btf_type_skip_modifiers(btf_vmlinux, type, NULL);
eaa6bcb7
HL
9632 if (percpu) {
9633 aux->btf_var.reg_type = PTR_TO_PERCPU_BTF_ID;
9634 aux->btf_var.btf_id = type;
9635 } else if (!btf_type_is_struct(t)) {
4976b718
HL
9636 const struct btf_type *ret;
9637 const char *tname;
9638 u32 tsize;
9639
9640 /* resolve the type size of ksym. */
9641 ret = btf_resolve_size(btf_vmlinux, t, &tsize);
9642 if (IS_ERR(ret)) {
9643 tname = btf_name_by_offset(btf_vmlinux, t->name_off);
9644 verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
9645 tname, PTR_ERR(ret));
9646 return -EINVAL;
9647 }
9648 aux->btf_var.reg_type = PTR_TO_MEM;
9649 aux->btf_var.mem_size = tsize;
9650 } else {
9651 aux->btf_var.reg_type = PTR_TO_BTF_ID;
9652 aux->btf_var.btf_id = type;
9653 }
9654 return 0;
9655}
9656
56f668df
MKL
9657static int check_map_prealloc(struct bpf_map *map)
9658{
9659 return (map->map_type != BPF_MAP_TYPE_HASH &&
bcc6b1b7
MKL
9660 map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
9661 map->map_type != BPF_MAP_TYPE_HASH_OF_MAPS) ||
56f668df
MKL
9662 !(map->map_flags & BPF_F_NO_PREALLOC);
9663}
9664
d83525ca
AS
9665static bool is_tracing_prog_type(enum bpf_prog_type type)
9666{
9667 switch (type) {
9668 case BPF_PROG_TYPE_KPROBE:
9669 case BPF_PROG_TYPE_TRACEPOINT:
9670 case BPF_PROG_TYPE_PERF_EVENT:
9671 case BPF_PROG_TYPE_RAW_TRACEPOINT:
9672 return true;
9673 default:
9674 return false;
9675 }
9676}
9677
94dacdbd
TG
9678static bool is_preallocated_map(struct bpf_map *map)
9679{
9680 if (!check_map_prealloc(map))
9681 return false;
9682 if (map->inner_map_meta && !check_map_prealloc(map->inner_map_meta))
9683 return false;
9684 return true;
9685}
9686
61bd5218
JK
9687static int check_map_prog_compatibility(struct bpf_verifier_env *env,
9688 struct bpf_map *map,
fdc15d38
AS
9689 struct bpf_prog *prog)
9690
9691{
7e40781c 9692 enum bpf_prog_type prog_type = resolve_prog_type(prog);
94dacdbd
TG
9693 /*
9694 * Validate that trace type programs use preallocated hash maps.
9695 *
9696 * For programs attached to PERF events this is mandatory as the
9697 * perf NMI can hit any arbitrary code sequence.
9698 *
9699 * All other trace types using preallocated hash maps are unsafe as
9700 * well because tracepoint or kprobes can be inside locked regions
9701 * of the memory allocator or at a place where a recursion into the
9702 * memory allocator would see inconsistent state.
9703 *
2ed905c5
TG
9704 * On RT enabled kernels run-time allocation of all trace type
9705 * programs is strictly prohibited due to lock type constraints. On
9706 * !RT kernels it is allowed for backwards compatibility reasons for
9707 * now, but warnings are emitted so developers are made aware of
9708 * the unsafety and can fix their programs before this is enforced.
56f668df 9709 */
7e40781c
UP
9710 if (is_tracing_prog_type(prog_type) && !is_preallocated_map(map)) {
9711 if (prog_type == BPF_PROG_TYPE_PERF_EVENT) {
61bd5218 9712 verbose(env, "perf_event programs can only use preallocated hash map\n");
56f668df
MKL
9713 return -EINVAL;
9714 }
2ed905c5
TG
9715 if (IS_ENABLED(CONFIG_PREEMPT_RT)) {
9716 verbose(env, "trace type programs can only use preallocated hash map\n");
9717 return -EINVAL;
9718 }
94dacdbd
TG
9719 WARN_ONCE(1, "trace type BPF program uses run-time allocation\n");
9720 verbose(env, "trace type programs with run-time allocated hash maps are unsafe. Switch to preallocated hash maps.\n");
fdc15d38 9721 }
a3884572 9722
7e40781c
UP
9723 if ((is_tracing_prog_type(prog_type) ||
9724 prog_type == BPF_PROG_TYPE_SOCKET_FILTER) &&
d83525ca
AS
9725 map_value_has_spin_lock(map)) {
9726 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
9727 return -EINVAL;
9728 }
9729
a3884572 9730 if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) &&
09728266 9731 !bpf_offload_prog_map_match(prog, map)) {
a3884572
JK
9732 verbose(env, "offload device mismatch between prog and map\n");
9733 return -EINVAL;
9734 }
9735
85d33df3
MKL
9736 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
9737 verbose(env, "bpf_struct_ops map cannot be used in prog\n");
9738 return -EINVAL;
9739 }
9740
1e6c62a8
AS
9741 if (prog->aux->sleepable)
9742 switch (map->map_type) {
9743 case BPF_MAP_TYPE_HASH:
9744 case BPF_MAP_TYPE_LRU_HASH:
9745 case BPF_MAP_TYPE_ARRAY:
9746 if (!is_preallocated_map(map)) {
9747 verbose(env,
9748 "Sleepable programs can only use preallocated hash maps\n");
9749 return -EINVAL;
9750 }
9751 break;
9752 default:
9753 verbose(env,
9754 "Sleepable programs can only use array and hash maps\n");
9755 return -EINVAL;
9756 }
9757
fdc15d38
AS
9758 return 0;
9759}
9760
b741f163
RG
9761static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
9762{
9763 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
9764 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
9765}
9766
4976b718
HL
9767/* find and rewrite pseudo imm in ld_imm64 instructions:
9768 *
9769 * 1. if it accesses map FD, replace it with actual map pointer.
9770 * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
9771 *
9772 * NOTE: btf_vmlinux is required for converting pseudo btf_id.
0246e64d 9773 */
4976b718 9774static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
0246e64d
AS
9775{
9776 struct bpf_insn *insn = env->prog->insnsi;
9777 int insn_cnt = env->prog->len;
fdc15d38 9778 int i, j, err;
0246e64d 9779
f1f7714e 9780 err = bpf_prog_calc_tag(env->prog);
aafe6ae9
DB
9781 if (err)
9782 return err;
9783
0246e64d 9784 for (i = 0; i < insn_cnt; i++, insn++) {
9bac3d6d 9785 if (BPF_CLASS(insn->code) == BPF_LDX &&
d691f9e8 9786 (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
61bd5218 9787 verbose(env, "BPF_LDX uses reserved fields\n");
9bac3d6d
AS
9788 return -EINVAL;
9789 }
9790
d691f9e8
AS
9791 if (BPF_CLASS(insn->code) == BPF_STX &&
9792 ((BPF_MODE(insn->code) != BPF_MEM &&
9793 BPF_MODE(insn->code) != BPF_XADD) || insn->imm != 0)) {
61bd5218 9794 verbose(env, "BPF_STX uses reserved fields\n");
d691f9e8
AS
9795 return -EINVAL;
9796 }
9797
0246e64d 9798 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
d8eca5bb 9799 struct bpf_insn_aux_data *aux;
0246e64d
AS
9800 struct bpf_map *map;
9801 struct fd f;
d8eca5bb 9802 u64 addr;
0246e64d
AS
9803
9804 if (i == insn_cnt - 1 || insn[1].code != 0 ||
9805 insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
9806 insn[1].off != 0) {
61bd5218 9807 verbose(env, "invalid bpf_ld_imm64 insn\n");
0246e64d
AS
9808 return -EINVAL;
9809 }
9810
d8eca5bb 9811 if (insn[0].src_reg == 0)
0246e64d
AS
9812 /* valid generic load 64-bit imm */
9813 goto next_insn;
9814
4976b718
HL
9815 if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
9816 aux = &env->insn_aux_data[i];
9817 err = check_pseudo_btf_id(env, insn, aux);
9818 if (err)
9819 return err;
9820 goto next_insn;
9821 }
9822
d8eca5bb
DB
9823 /* In final convert_pseudo_ld_imm64() step, this is
9824 * converted into regular 64-bit imm load insn.
9825 */
9826 if ((insn[0].src_reg != BPF_PSEUDO_MAP_FD &&
9827 insn[0].src_reg != BPF_PSEUDO_MAP_VALUE) ||
9828 (insn[0].src_reg == BPF_PSEUDO_MAP_FD &&
9829 insn[1].imm != 0)) {
9830 verbose(env,
9831 "unrecognized bpf_ld_imm64 insn\n");
0246e64d
AS
9832 return -EINVAL;
9833 }
9834
20182390 9835 f = fdget(insn[0].imm);
c2101297 9836 map = __bpf_map_get(f);
0246e64d 9837 if (IS_ERR(map)) {
61bd5218 9838 verbose(env, "fd %d is not pointing to valid bpf_map\n",
20182390 9839 insn[0].imm);
0246e64d
AS
9840 return PTR_ERR(map);
9841 }
9842
61bd5218 9843 err = check_map_prog_compatibility(env, map, env->prog);
fdc15d38
AS
9844 if (err) {
9845 fdput(f);
9846 return err;
9847 }
9848
d8eca5bb
DB
9849 aux = &env->insn_aux_data[i];
9850 if (insn->src_reg == BPF_PSEUDO_MAP_FD) {
9851 addr = (unsigned long)map;
9852 } else {
9853 u32 off = insn[1].imm;
9854
9855 if (off >= BPF_MAX_VAR_OFF) {
9856 verbose(env, "direct value offset of %u is not allowed\n", off);
9857 fdput(f);
9858 return -EINVAL;
9859 }
9860
9861 if (!map->ops->map_direct_value_addr) {
9862 verbose(env, "no direct value access support for this map type\n");
9863 fdput(f);
9864 return -EINVAL;
9865 }
9866
9867 err = map->ops->map_direct_value_addr(map, &addr, off);
9868 if (err) {
9869 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
9870 map->value_size, off);
9871 fdput(f);
9872 return err;
9873 }
9874
9875 aux->map_off = off;
9876 addr += off;
9877 }
9878
9879 insn[0].imm = (u32)addr;
9880 insn[1].imm = addr >> 32;
0246e64d
AS
9881
9882 /* check whether we recorded this map already */
d8eca5bb 9883 for (j = 0; j < env->used_map_cnt; j++) {
0246e64d 9884 if (env->used_maps[j] == map) {
d8eca5bb 9885 aux->map_index = j;
0246e64d
AS
9886 fdput(f);
9887 goto next_insn;
9888 }
d8eca5bb 9889 }
0246e64d
AS
9890
9891 if (env->used_map_cnt >= MAX_USED_MAPS) {
9892 fdput(f);
9893 return -E2BIG;
9894 }
9895
0246e64d
AS
9896 /* hold the map. If the program is rejected by verifier,
9897 * the map will be released by release_maps() or it
9898 * will be used by the valid program until it's unloaded
ab7f5bf0 9899 * and all maps are released in free_used_maps()
0246e64d 9900 */
1e0bd5a0 9901 bpf_map_inc(map);
d8eca5bb
DB
9902
9903 aux->map_index = env->used_map_cnt;
92117d84
AS
9904 env->used_maps[env->used_map_cnt++] = map;
9905
b741f163 9906 if (bpf_map_is_cgroup_storage(map) &&
e4730423 9907 bpf_cgroup_storage_assign(env->prog->aux, map)) {
b741f163 9908 verbose(env, "only one cgroup storage of each type is allowed\n");
de9cbbaa
RG
9909 fdput(f);
9910 return -EBUSY;
9911 }
9912
0246e64d
AS
9913 fdput(f);
9914next_insn:
9915 insn++;
9916 i++;
5e581dad
DB
9917 continue;
9918 }
9919
9920 /* Basic sanity check before we invest more work here. */
9921 if (!bpf_opcode_in_insntable(insn->code)) {
9922 verbose(env, "unknown opcode %02x\n", insn->code);
9923 return -EINVAL;
0246e64d
AS
9924 }
9925 }
9926
9927 /* now all pseudo BPF_LD_IMM64 instructions load valid
9928 * 'struct bpf_map *' into a register instead of user map_fd.
9929 * These pointers will be used later by verifier to validate map access.
9930 */
9931 return 0;
9932}
9933
9934/* drop refcnt of maps used by the rejected program */
58e2af8b 9935static void release_maps(struct bpf_verifier_env *env)
0246e64d 9936{
a2ea0746
DB
9937 __bpf_free_used_maps(env->prog->aux, env->used_maps,
9938 env->used_map_cnt);
0246e64d
AS
9939}
9940
9941/* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
58e2af8b 9942static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
0246e64d
AS
9943{
9944 struct bpf_insn *insn = env->prog->insnsi;
9945 int insn_cnt = env->prog->len;
9946 int i;
9947
9948 for (i = 0; i < insn_cnt; i++, insn++)
9949 if (insn->code == (BPF_LD | BPF_IMM | BPF_DW))
9950 insn->src_reg = 0;
9951}
9952
8041902d
AS
9953/* single env->prog->insni[off] instruction was replaced with the range
9954 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying
9955 * [0, off) and [off, end) to new locations, so the patched range stays zero
9956 */
b325fbca
JW
9957static int adjust_insn_aux_data(struct bpf_verifier_env *env,
9958 struct bpf_prog *new_prog, u32 off, u32 cnt)
8041902d
AS
9959{
9960 struct bpf_insn_aux_data *new_data, *old_data = env->insn_aux_data;
b325fbca
JW
9961 struct bpf_insn *insn = new_prog->insnsi;
9962 u32 prog_len;
c131187d 9963 int i;
8041902d 9964
b325fbca
JW
9965 /* aux info at OFF always needs adjustment, no matter fast path
9966 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
9967 * original insn at old prog.
9968 */
9969 old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
9970
8041902d
AS
9971 if (cnt == 1)
9972 return 0;
b325fbca 9973 prog_len = new_prog->len;
fad953ce
KC
9974 new_data = vzalloc(array_size(prog_len,
9975 sizeof(struct bpf_insn_aux_data)));
8041902d
AS
9976 if (!new_data)
9977 return -ENOMEM;
9978 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
9979 memcpy(new_data + off + cnt - 1, old_data + off,
9980 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
b325fbca 9981 for (i = off; i < off + cnt - 1; i++) {
51c39bb1 9982 new_data[i].seen = env->pass_cnt;
b325fbca
JW
9983 new_data[i].zext_dst = insn_has_def32(env, insn + i);
9984 }
8041902d
AS
9985 env->insn_aux_data = new_data;
9986 vfree(old_data);
9987 return 0;
9988}
9989
cc8b0b92
AS
9990static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
9991{
9992 int i;
9993
9994 if (len == 1)
9995 return;
4cb3d99c
JW
9996 /* NOTE: fake 'exit' subprog should be updated as well. */
9997 for (i = 0; i <= env->subprog_cnt; i++) {
afd59424 9998 if (env->subprog_info[i].start <= off)
cc8b0b92 9999 continue;
9c8105bd 10000 env->subprog_info[i].start += len - 1;
cc8b0b92
AS
10001 }
10002}
10003
a748c697
MF
10004static void adjust_poke_descs(struct bpf_prog *prog, u32 len)
10005{
10006 struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
10007 int i, sz = prog->aux->size_poke_tab;
10008 struct bpf_jit_poke_descriptor *desc;
10009
10010 for (i = 0; i < sz; i++) {
10011 desc = &tab[i];
10012 desc->insn_idx += len - 1;
10013 }
10014}
10015
8041902d
AS
10016static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
10017 const struct bpf_insn *patch, u32 len)
10018{
10019 struct bpf_prog *new_prog;
10020
10021 new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
4f73379e
AS
10022 if (IS_ERR(new_prog)) {
10023 if (PTR_ERR(new_prog) == -ERANGE)
10024 verbose(env,
10025 "insn %d cannot be patched due to 16-bit range\n",
10026 env->insn_aux_data[off].orig_idx);
8041902d 10027 return NULL;
4f73379e 10028 }
b325fbca 10029 if (adjust_insn_aux_data(env, new_prog, off, len))
8041902d 10030 return NULL;
cc8b0b92 10031 adjust_subprog_starts(env, off, len);
a748c697 10032 adjust_poke_descs(new_prog, len);
8041902d
AS
10033 return new_prog;
10034}
10035
52875a04
JK
10036static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
10037 u32 off, u32 cnt)
10038{
10039 int i, j;
10040
10041 /* find first prog starting at or after off (first to remove) */
10042 for (i = 0; i < env->subprog_cnt; i++)
10043 if (env->subprog_info[i].start >= off)
10044 break;
10045 /* find first prog starting at or after off + cnt (first to stay) */
10046 for (j = i; j < env->subprog_cnt; j++)
10047 if (env->subprog_info[j].start >= off + cnt)
10048 break;
10049 /* if j doesn't start exactly at off + cnt, we are just removing
10050 * the front of previous prog
10051 */
10052 if (env->subprog_info[j].start != off + cnt)
10053 j--;
10054
10055 if (j > i) {
10056 struct bpf_prog_aux *aux = env->prog->aux;
10057 int move;
10058
10059 /* move fake 'exit' subprog as well */
10060 move = env->subprog_cnt + 1 - j;
10061
10062 memmove(env->subprog_info + i,
10063 env->subprog_info + j,
10064 sizeof(*env->subprog_info) * move);
10065 env->subprog_cnt -= j - i;
10066
10067 /* remove func_info */
10068 if (aux->func_info) {
10069 move = aux->func_info_cnt - j;
10070
10071 memmove(aux->func_info + i,
10072 aux->func_info + j,
10073 sizeof(*aux->func_info) * move);
10074 aux->func_info_cnt -= j - i;
10075 /* func_info->insn_off is set after all code rewrites,
10076 * in adjust_btf_func() - no need to adjust
10077 */
10078 }
10079 } else {
10080 /* convert i from "first prog to remove" to "first to adjust" */
10081 if (env->subprog_info[i].start == off)
10082 i++;
10083 }
10084
10085 /* update fake 'exit' subprog as well */
10086 for (; i <= env->subprog_cnt; i++)
10087 env->subprog_info[i].start -= cnt;
10088
10089 return 0;
10090}
10091
10092static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
10093 u32 cnt)
10094{
10095 struct bpf_prog *prog = env->prog;
10096 u32 i, l_off, l_cnt, nr_linfo;
10097 struct bpf_line_info *linfo;
10098
10099 nr_linfo = prog->aux->nr_linfo;
10100 if (!nr_linfo)
10101 return 0;
10102
10103 linfo = prog->aux->linfo;
10104
10105 /* find first line info to remove, count lines to be removed */
10106 for (i = 0; i < nr_linfo; i++)
10107 if (linfo[i].insn_off >= off)
10108 break;
10109
10110 l_off = i;
10111 l_cnt = 0;
10112 for (; i < nr_linfo; i++)
10113 if (linfo[i].insn_off < off + cnt)
10114 l_cnt++;
10115 else
10116 break;
10117
10118 /* First live insn doesn't match first live linfo, it needs to "inherit"
10119 * last removed linfo. prog is already modified, so prog->len == off
10120 * means no live instructions after (tail of the program was removed).
10121 */
10122 if (prog->len != off && l_cnt &&
10123 (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
10124 l_cnt--;
10125 linfo[--i].insn_off = off + cnt;
10126 }
10127
10128 /* remove the line info which refer to the removed instructions */
10129 if (l_cnt) {
10130 memmove(linfo + l_off, linfo + i,
10131 sizeof(*linfo) * (nr_linfo - i));
10132
10133 prog->aux->nr_linfo -= l_cnt;
10134 nr_linfo = prog->aux->nr_linfo;
10135 }
10136
10137 /* pull all linfo[i].insn_off >= off + cnt in by cnt */
10138 for (i = l_off; i < nr_linfo; i++)
10139 linfo[i].insn_off -= cnt;
10140
10141 /* fix up all subprogs (incl. 'exit') which start >= off */
10142 for (i = 0; i <= env->subprog_cnt; i++)
10143 if (env->subprog_info[i].linfo_idx > l_off) {
10144 /* program may have started in the removed region but
10145 * may not be fully removed
10146 */
10147 if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
10148 env->subprog_info[i].linfo_idx -= l_cnt;
10149 else
10150 env->subprog_info[i].linfo_idx = l_off;
10151 }
10152
10153 return 0;
10154}
10155
10156static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
10157{
10158 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
10159 unsigned int orig_prog_len = env->prog->len;
10160 int err;
10161
08ca90af
JK
10162 if (bpf_prog_is_dev_bound(env->prog->aux))
10163 bpf_prog_offload_remove_insns(env, off, cnt);
10164
52875a04
JK
10165 err = bpf_remove_insns(env->prog, off, cnt);
10166 if (err)
10167 return err;
10168
10169 err = adjust_subprog_starts_after_remove(env, off, cnt);
10170 if (err)
10171 return err;
10172
10173 err = bpf_adj_linfo_after_remove(env, off, cnt);
10174 if (err)
10175 return err;
10176
10177 memmove(aux_data + off, aux_data + off + cnt,
10178 sizeof(*aux_data) * (orig_prog_len - off - cnt));
10179
10180 return 0;
10181}
10182
2a5418a1
DB
10183/* The verifier does more data flow analysis than llvm and will not
10184 * explore branches that are dead at run time. Malicious programs can
10185 * have dead code too. Therefore replace all dead at-run-time code
10186 * with 'ja -1'.
10187 *
10188 * Just nops are not optimal, e.g. if they would sit at the end of the
10189 * program and through another bug we would manage to jump there, then
10190 * we'd execute beyond program memory otherwise. Returning exception
10191 * code also wouldn't work since we can have subprogs where the dead
10192 * code could be located.
c131187d
AS
10193 */
10194static void sanitize_dead_code(struct bpf_verifier_env *env)
10195{
10196 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
2a5418a1 10197 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
c131187d
AS
10198 struct bpf_insn *insn = env->prog->insnsi;
10199 const int insn_cnt = env->prog->len;
10200 int i;
10201
10202 for (i = 0; i < insn_cnt; i++) {
10203 if (aux_data[i].seen)
10204 continue;
2a5418a1 10205 memcpy(insn + i, &trap, sizeof(trap));
c131187d
AS
10206 }
10207}
10208
e2ae4ca2
JK
10209static bool insn_is_cond_jump(u8 code)
10210{
10211 u8 op;
10212
092ed096
JW
10213 if (BPF_CLASS(code) == BPF_JMP32)
10214 return true;
10215
e2ae4ca2
JK
10216 if (BPF_CLASS(code) != BPF_JMP)
10217 return false;
10218
10219 op = BPF_OP(code);
10220 return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
10221}
10222
10223static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
10224{
10225 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
10226 struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
10227 struct bpf_insn *insn = env->prog->insnsi;
10228 const int insn_cnt = env->prog->len;
10229 int i;
10230
10231 for (i = 0; i < insn_cnt; i++, insn++) {
10232 if (!insn_is_cond_jump(insn->code))
10233 continue;
10234
10235 if (!aux_data[i + 1].seen)
10236 ja.off = insn->off;
10237 else if (!aux_data[i + 1 + insn->off].seen)
10238 ja.off = 0;
10239 else
10240 continue;
10241
08ca90af
JK
10242 if (bpf_prog_is_dev_bound(env->prog->aux))
10243 bpf_prog_offload_replace_insn(env, i, &ja);
10244
e2ae4ca2
JK
10245 memcpy(insn, &ja, sizeof(ja));
10246 }
10247}
10248
52875a04
JK
10249static int opt_remove_dead_code(struct bpf_verifier_env *env)
10250{
10251 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
10252 int insn_cnt = env->prog->len;
10253 int i, err;
10254
10255 for (i = 0; i < insn_cnt; i++) {
10256 int j;
10257
10258 j = 0;
10259 while (i + j < insn_cnt && !aux_data[i + j].seen)
10260 j++;
10261 if (!j)
10262 continue;
10263
10264 err = verifier_remove_insns(env, i, j);
10265 if (err)
10266 return err;
10267 insn_cnt = env->prog->len;
10268 }
10269
10270 return 0;
10271}
10272
a1b14abc
JK
10273static int opt_remove_nops(struct bpf_verifier_env *env)
10274{
10275 const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
10276 struct bpf_insn *insn = env->prog->insnsi;
10277 int insn_cnt = env->prog->len;
10278 int i, err;
10279
10280 for (i = 0; i < insn_cnt; i++) {
10281 if (memcmp(&insn[i], &ja, sizeof(ja)))
10282 continue;
10283
10284 err = verifier_remove_insns(env, i, 1);
10285 if (err)
10286 return err;
10287 insn_cnt--;
10288 i--;
10289 }
10290
10291 return 0;
10292}
10293
d6c2308c
JW
10294static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
10295 const union bpf_attr *attr)
a4b1d3c1 10296{
d6c2308c 10297 struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
a4b1d3c1 10298 struct bpf_insn_aux_data *aux = env->insn_aux_data;
d6c2308c 10299 int i, patch_len, delta = 0, len = env->prog->len;
a4b1d3c1 10300 struct bpf_insn *insns = env->prog->insnsi;
a4b1d3c1 10301 struct bpf_prog *new_prog;
d6c2308c 10302 bool rnd_hi32;
a4b1d3c1 10303
d6c2308c 10304 rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
a4b1d3c1 10305 zext_patch[1] = BPF_ZEXT_REG(0);
d6c2308c
JW
10306 rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
10307 rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
10308 rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
a4b1d3c1
JW
10309 for (i = 0; i < len; i++) {
10310 int adj_idx = i + delta;
10311 struct bpf_insn insn;
10312
d6c2308c
JW
10313 insn = insns[adj_idx];
10314 if (!aux[adj_idx].zext_dst) {
10315 u8 code, class;
10316 u32 imm_rnd;
10317
10318 if (!rnd_hi32)
10319 continue;
10320
10321 code = insn.code;
10322 class = BPF_CLASS(code);
10323 if (insn_no_def(&insn))
10324 continue;
10325
10326 /* NOTE: arg "reg" (the fourth one) is only used for
10327 * BPF_STX which has been ruled out in above
10328 * check, it is safe to pass NULL here.
10329 */
10330 if (is_reg64(env, &insn, insn.dst_reg, NULL, DST_OP)) {
10331 if (class == BPF_LD &&
10332 BPF_MODE(code) == BPF_IMM)
10333 i++;
10334 continue;
10335 }
10336
10337 /* ctx load could be transformed into wider load. */
10338 if (class == BPF_LDX &&
10339 aux[adj_idx].ptr_type == PTR_TO_CTX)
10340 continue;
10341
10342 imm_rnd = get_random_int();
10343 rnd_hi32_patch[0] = insn;
10344 rnd_hi32_patch[1].imm = imm_rnd;
10345 rnd_hi32_patch[3].dst_reg = insn.dst_reg;
10346 patch = rnd_hi32_patch;
10347 patch_len = 4;
10348 goto apply_patch_buffer;
10349 }
10350
10351 if (!bpf_jit_needs_zext())
a4b1d3c1
JW
10352 continue;
10353
a4b1d3c1
JW
10354 zext_patch[0] = insn;
10355 zext_patch[1].dst_reg = insn.dst_reg;
10356 zext_patch[1].src_reg = insn.dst_reg;
d6c2308c
JW
10357 patch = zext_patch;
10358 patch_len = 2;
10359apply_patch_buffer:
10360 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
a4b1d3c1
JW
10361 if (!new_prog)
10362 return -ENOMEM;
10363 env->prog = new_prog;
10364 insns = new_prog->insnsi;
10365 aux = env->insn_aux_data;
d6c2308c 10366 delta += patch_len - 1;
a4b1d3c1
JW
10367 }
10368
10369 return 0;
10370}
10371
c64b7983
JS
10372/* convert load instructions that access fields of a context type into a
10373 * sequence of instructions that access fields of the underlying structure:
10374 * struct __sk_buff -> struct sk_buff
10375 * struct bpf_sock_ops -> struct sock
9bac3d6d 10376 */
58e2af8b 10377static int convert_ctx_accesses(struct bpf_verifier_env *env)
9bac3d6d 10378{
00176a34 10379 const struct bpf_verifier_ops *ops = env->ops;
f96da094 10380 int i, cnt, size, ctx_field_size, delta = 0;
3df126f3 10381 const int insn_cnt = env->prog->len;
36bbef52 10382 struct bpf_insn insn_buf[16], *insn;
46f53a65 10383 u32 target_size, size_default, off;
9bac3d6d 10384 struct bpf_prog *new_prog;
d691f9e8 10385 enum bpf_access_type type;
f96da094 10386 bool is_narrower_load;
9bac3d6d 10387
b09928b9
DB
10388 if (ops->gen_prologue || env->seen_direct_write) {
10389 if (!ops->gen_prologue) {
10390 verbose(env, "bpf verifier is misconfigured\n");
10391 return -EINVAL;
10392 }
36bbef52
DB
10393 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
10394 env->prog);
10395 if (cnt >= ARRAY_SIZE(insn_buf)) {
61bd5218 10396 verbose(env, "bpf verifier is misconfigured\n");
36bbef52
DB
10397 return -EINVAL;
10398 } else if (cnt) {
8041902d 10399 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
36bbef52
DB
10400 if (!new_prog)
10401 return -ENOMEM;
8041902d 10402
36bbef52 10403 env->prog = new_prog;
3df126f3 10404 delta += cnt - 1;
36bbef52
DB
10405 }
10406 }
10407
c64b7983 10408 if (bpf_prog_is_dev_bound(env->prog->aux))
9bac3d6d
AS
10409 return 0;
10410
3df126f3 10411 insn = env->prog->insnsi + delta;
36bbef52 10412
9bac3d6d 10413 for (i = 0; i < insn_cnt; i++, insn++) {
c64b7983
JS
10414 bpf_convert_ctx_access_t convert_ctx_access;
10415
62c7989b
DB
10416 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
10417 insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
10418 insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
ea2e7ce5 10419 insn->code == (BPF_LDX | BPF_MEM | BPF_DW))
d691f9e8 10420 type = BPF_READ;
62c7989b
DB
10421 else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
10422 insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
10423 insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
ea2e7ce5 10424 insn->code == (BPF_STX | BPF_MEM | BPF_DW))
d691f9e8
AS
10425 type = BPF_WRITE;
10426 else
9bac3d6d
AS
10427 continue;
10428
af86ca4e
AS
10429 if (type == BPF_WRITE &&
10430 env->insn_aux_data[i + delta].sanitize_stack_off) {
10431 struct bpf_insn patch[] = {
10432 /* Sanitize suspicious stack slot with zero.
10433 * There are no memory dependencies for this store,
10434 * since it's only using frame pointer and immediate
10435 * constant of zero
10436 */
10437 BPF_ST_MEM(BPF_DW, BPF_REG_FP,
10438 env->insn_aux_data[i + delta].sanitize_stack_off,
10439 0),
10440 /* the original STX instruction will immediately
10441 * overwrite the same stack slot with appropriate value
10442 */
10443 *insn,
10444 };
10445
10446 cnt = ARRAY_SIZE(patch);
10447 new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
10448 if (!new_prog)
10449 return -ENOMEM;
10450
10451 delta += cnt - 1;
10452 env->prog = new_prog;
10453 insn = new_prog->insnsi + i + delta;
10454 continue;
10455 }
10456
c64b7983
JS
10457 switch (env->insn_aux_data[i + delta].ptr_type) {
10458 case PTR_TO_CTX:
10459 if (!ops->convert_ctx_access)
10460 continue;
10461 convert_ctx_access = ops->convert_ctx_access;
10462 break;
10463 case PTR_TO_SOCKET:
46f8bc92 10464 case PTR_TO_SOCK_COMMON:
c64b7983
JS
10465 convert_ctx_access = bpf_sock_convert_ctx_access;
10466 break;
655a51e5
MKL
10467 case PTR_TO_TCP_SOCK:
10468 convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
10469 break;
fada7fdc
JL
10470 case PTR_TO_XDP_SOCK:
10471 convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
10472 break;
2a02759e 10473 case PTR_TO_BTF_ID:
27ae7997
MKL
10474 if (type == BPF_READ) {
10475 insn->code = BPF_LDX | BPF_PROBE_MEM |
10476 BPF_SIZE((insn)->code);
10477 env->prog->aux->num_exentries++;
7e40781c 10478 } else if (resolve_prog_type(env->prog) != BPF_PROG_TYPE_STRUCT_OPS) {
2a02759e
AS
10479 verbose(env, "Writes through BTF pointers are not allowed\n");
10480 return -EINVAL;
10481 }
2a02759e 10482 continue;
c64b7983 10483 default:
9bac3d6d 10484 continue;
c64b7983 10485 }
9bac3d6d 10486
31fd8581 10487 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
f96da094 10488 size = BPF_LDST_BYTES(insn);
31fd8581
YS
10489
10490 /* If the read access is a narrower load of the field,
10491 * convert to a 4/8-byte load, to minimum program type specific
10492 * convert_ctx_access changes. If conversion is successful,
10493 * we will apply proper mask to the result.
10494 */
f96da094 10495 is_narrower_load = size < ctx_field_size;
46f53a65
AI
10496 size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
10497 off = insn->off;
31fd8581 10498 if (is_narrower_load) {
f96da094
DB
10499 u8 size_code;
10500
10501 if (type == BPF_WRITE) {
61bd5218 10502 verbose(env, "bpf verifier narrow ctx access misconfigured\n");
f96da094
DB
10503 return -EINVAL;
10504 }
31fd8581 10505
f96da094 10506 size_code = BPF_H;
31fd8581
YS
10507 if (ctx_field_size == 4)
10508 size_code = BPF_W;
10509 else if (ctx_field_size == 8)
10510 size_code = BPF_DW;
f96da094 10511
bc23105c 10512 insn->off = off & ~(size_default - 1);
31fd8581
YS
10513 insn->code = BPF_LDX | BPF_MEM | size_code;
10514 }
f96da094
DB
10515
10516 target_size = 0;
c64b7983
JS
10517 cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
10518 &target_size);
f96da094
DB
10519 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
10520 (ctx_field_size && !target_size)) {
61bd5218 10521 verbose(env, "bpf verifier is misconfigured\n");
9bac3d6d
AS
10522 return -EINVAL;
10523 }
f96da094
DB
10524
10525 if (is_narrower_load && size < target_size) {
d895a0f1
IL
10526 u8 shift = bpf_ctx_narrow_access_offset(
10527 off, size, size_default) * 8;
46f53a65
AI
10528 if (ctx_field_size <= 4) {
10529 if (shift)
10530 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
10531 insn->dst_reg,
10532 shift);
31fd8581 10533 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
f96da094 10534 (1 << size * 8) - 1);
46f53a65
AI
10535 } else {
10536 if (shift)
10537 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
10538 insn->dst_reg,
10539 shift);
31fd8581 10540 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
e2f7fc0a 10541 (1ULL << size * 8) - 1);
46f53a65 10542 }
31fd8581 10543 }
9bac3d6d 10544
8041902d 10545 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
9bac3d6d
AS
10546 if (!new_prog)
10547 return -ENOMEM;
10548
3df126f3 10549 delta += cnt - 1;
9bac3d6d
AS
10550
10551 /* keep walking new program and skip insns we just inserted */
10552 env->prog = new_prog;
3df126f3 10553 insn = new_prog->insnsi + i + delta;
9bac3d6d
AS
10554 }
10555
10556 return 0;
10557}
10558
1c2a088a
AS
10559static int jit_subprogs(struct bpf_verifier_env *env)
10560{
10561 struct bpf_prog *prog = env->prog, **func, *tmp;
10562 int i, j, subprog_start, subprog_end = 0, len, subprog;
a748c697 10563 struct bpf_map *map_ptr;
7105e828 10564 struct bpf_insn *insn;
1c2a088a 10565 void *old_bpf_func;
c4c0bdc0 10566 int err, num_exentries;
1c2a088a 10567
f910cefa 10568 if (env->subprog_cnt <= 1)
1c2a088a
AS
10569 return 0;
10570
7105e828 10571 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
1c2a088a
AS
10572 if (insn->code != (BPF_JMP | BPF_CALL) ||
10573 insn->src_reg != BPF_PSEUDO_CALL)
10574 continue;
c7a89784
DB
10575 /* Upon error here we cannot fall back to interpreter but
10576 * need a hard reject of the program. Thus -EFAULT is
10577 * propagated in any case.
10578 */
1c2a088a
AS
10579 subprog = find_subprog(env, i + insn->imm + 1);
10580 if (subprog < 0) {
10581 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
10582 i + insn->imm + 1);
10583 return -EFAULT;
10584 }
10585 /* temporarily remember subprog id inside insn instead of
10586 * aux_data, since next loop will split up all insns into funcs
10587 */
f910cefa 10588 insn->off = subprog;
1c2a088a
AS
10589 /* remember original imm in case JIT fails and fallback
10590 * to interpreter will be needed
10591 */
10592 env->insn_aux_data[i].call_imm = insn->imm;
10593 /* point imm to __bpf_call_base+1 from JITs point of view */
10594 insn->imm = 1;
10595 }
10596
c454a46b
MKL
10597 err = bpf_prog_alloc_jited_linfo(prog);
10598 if (err)
10599 goto out_undo_insn;
10600
10601 err = -ENOMEM;
6396bb22 10602 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
1c2a088a 10603 if (!func)
c7a89784 10604 goto out_undo_insn;
1c2a088a 10605
f910cefa 10606 for (i = 0; i < env->subprog_cnt; i++) {
1c2a088a 10607 subprog_start = subprog_end;
4cb3d99c 10608 subprog_end = env->subprog_info[i + 1].start;
1c2a088a
AS
10609
10610 len = subprog_end - subprog_start;
492ecee8
AS
10611 /* BPF_PROG_RUN doesn't call subprogs directly,
10612 * hence main prog stats include the runtime of subprogs.
10613 * subprogs don't have IDs and not reachable via prog_get_next_id
10614 * func[i]->aux->stats will never be accessed and stays NULL
10615 */
10616 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
1c2a088a
AS
10617 if (!func[i])
10618 goto out_free;
10619 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
10620 len * sizeof(struct bpf_insn));
4f74d809 10621 func[i]->type = prog->type;
1c2a088a 10622 func[i]->len = len;
4f74d809
DB
10623 if (bpf_prog_calc_tag(func[i]))
10624 goto out_free;
1c2a088a 10625 func[i]->is_func = 1;
ba64e7d8
YS
10626 func[i]->aux->func_idx = i;
10627 /* the btf and func_info will be freed only at prog->aux */
10628 func[i]->aux->btf = prog->aux->btf;
10629 func[i]->aux->func_info = prog->aux->func_info;
10630
a748c697
MF
10631 for (j = 0; j < prog->aux->size_poke_tab; j++) {
10632 u32 insn_idx = prog->aux->poke_tab[j].insn_idx;
10633 int ret;
10634
10635 if (!(insn_idx >= subprog_start &&
10636 insn_idx <= subprog_end))
10637 continue;
10638
10639 ret = bpf_jit_add_poke_descriptor(func[i],
10640 &prog->aux->poke_tab[j]);
10641 if (ret < 0) {
10642 verbose(env, "adding tail call poke descriptor failed\n");
10643 goto out_free;
10644 }
10645
10646 func[i]->insnsi[insn_idx - subprog_start].imm = ret + 1;
10647
10648 map_ptr = func[i]->aux->poke_tab[ret].tail_call.map;
10649 ret = map_ptr->ops->map_poke_track(map_ptr, func[i]->aux);
10650 if (ret < 0) {
10651 verbose(env, "tracking tail call prog failed\n");
10652 goto out_free;
10653 }
10654 }
10655
1c2a088a
AS
10656 /* Use bpf_prog_F_tag to indicate functions in stack traces.
10657 * Long term would need debug info to populate names
10658 */
10659 func[i]->aux->name[0] = 'F';
9c8105bd 10660 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
1c2a088a 10661 func[i]->jit_requested = 1;
c454a46b
MKL
10662 func[i]->aux->linfo = prog->aux->linfo;
10663 func[i]->aux->nr_linfo = prog->aux->nr_linfo;
10664 func[i]->aux->jited_linfo = prog->aux->jited_linfo;
10665 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
c4c0bdc0
YS
10666 num_exentries = 0;
10667 insn = func[i]->insnsi;
10668 for (j = 0; j < func[i]->len; j++, insn++) {
10669 if (BPF_CLASS(insn->code) == BPF_LDX &&
10670 BPF_MODE(insn->code) == BPF_PROBE_MEM)
10671 num_exentries++;
10672 }
10673 func[i]->aux->num_exentries = num_exentries;
ebf7d1f5 10674 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
1c2a088a
AS
10675 func[i] = bpf_int_jit_compile(func[i]);
10676 if (!func[i]->jited) {
10677 err = -ENOTSUPP;
10678 goto out_free;
10679 }
10680 cond_resched();
10681 }
a748c697
MF
10682
10683 /* Untrack main program's aux structs so that during map_poke_run()
10684 * we will not stumble upon the unfilled poke descriptors; each
10685 * of the main program's poke descs got distributed across subprogs
10686 * and got tracked onto map, so we are sure that none of them will
10687 * be missed after the operation below
10688 */
10689 for (i = 0; i < prog->aux->size_poke_tab; i++) {
10690 map_ptr = prog->aux->poke_tab[i].tail_call.map;
10691
10692 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
10693 }
10694
1c2a088a
AS
10695 /* at this point all bpf functions were successfully JITed
10696 * now populate all bpf_calls with correct addresses and
10697 * run last pass of JIT
10698 */
f910cefa 10699 for (i = 0; i < env->subprog_cnt; i++) {
1c2a088a
AS
10700 insn = func[i]->insnsi;
10701 for (j = 0; j < func[i]->len; j++, insn++) {
10702 if (insn->code != (BPF_JMP | BPF_CALL) ||
10703 insn->src_reg != BPF_PSEUDO_CALL)
10704 continue;
10705 subprog = insn->off;
0d306c31
PB
10706 insn->imm = BPF_CAST_CALL(func[subprog]->bpf_func) -
10707 __bpf_call_base;
1c2a088a 10708 }
2162fed4
SD
10709
10710 /* we use the aux data to keep a list of the start addresses
10711 * of the JITed images for each function in the program
10712 *
10713 * for some architectures, such as powerpc64, the imm field
10714 * might not be large enough to hold the offset of the start
10715 * address of the callee's JITed image from __bpf_call_base
10716 *
10717 * in such cases, we can lookup the start address of a callee
10718 * by using its subprog id, available from the off field of
10719 * the call instruction, as an index for this list
10720 */
10721 func[i]->aux->func = func;
10722 func[i]->aux->func_cnt = env->subprog_cnt;
1c2a088a 10723 }
f910cefa 10724 for (i = 0; i < env->subprog_cnt; i++) {
1c2a088a
AS
10725 old_bpf_func = func[i]->bpf_func;
10726 tmp = bpf_int_jit_compile(func[i]);
10727 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
10728 verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
c7a89784 10729 err = -ENOTSUPP;
1c2a088a
AS
10730 goto out_free;
10731 }
10732 cond_resched();
10733 }
10734
10735 /* finally lock prog and jit images for all functions and
10736 * populate kallsysm
10737 */
f910cefa 10738 for (i = 0; i < env->subprog_cnt; i++) {
1c2a088a
AS
10739 bpf_prog_lock_ro(func[i]);
10740 bpf_prog_kallsyms_add(func[i]);
10741 }
7105e828
DB
10742
10743 /* Last step: make now unused interpreter insns from main
10744 * prog consistent for later dump requests, so they can
10745 * later look the same as if they were interpreted only.
10746 */
10747 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
7105e828
DB
10748 if (insn->code != (BPF_JMP | BPF_CALL) ||
10749 insn->src_reg != BPF_PSEUDO_CALL)
10750 continue;
10751 insn->off = env->insn_aux_data[i].call_imm;
10752 subprog = find_subprog(env, i + insn->off + 1);
dbecd738 10753 insn->imm = subprog;
7105e828
DB
10754 }
10755
1c2a088a
AS
10756 prog->jited = 1;
10757 prog->bpf_func = func[0]->bpf_func;
10758 prog->aux->func = func;
f910cefa 10759 prog->aux->func_cnt = env->subprog_cnt;
c454a46b 10760 bpf_prog_free_unused_jited_linfo(prog);
1c2a088a
AS
10761 return 0;
10762out_free:
a748c697
MF
10763 for (i = 0; i < env->subprog_cnt; i++) {
10764 if (!func[i])
10765 continue;
10766
10767 for (j = 0; j < func[i]->aux->size_poke_tab; j++) {
10768 map_ptr = func[i]->aux->poke_tab[j].tail_call.map;
10769 map_ptr->ops->map_poke_untrack(map_ptr, func[i]->aux);
10770 }
10771 bpf_jit_free(func[i]);
10772 }
1c2a088a 10773 kfree(func);
c7a89784 10774out_undo_insn:
1c2a088a
AS
10775 /* cleanup main prog to be interpreted */
10776 prog->jit_requested = 0;
10777 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
10778 if (insn->code != (BPF_JMP | BPF_CALL) ||
10779 insn->src_reg != BPF_PSEUDO_CALL)
10780 continue;
10781 insn->off = 0;
10782 insn->imm = env->insn_aux_data[i].call_imm;
10783 }
c454a46b 10784 bpf_prog_free_jited_linfo(prog);
1c2a088a
AS
10785 return err;
10786}
10787
1ea47e01
AS
10788static int fixup_call_args(struct bpf_verifier_env *env)
10789{
19d28fbd 10790#ifndef CONFIG_BPF_JIT_ALWAYS_ON
1ea47e01
AS
10791 struct bpf_prog *prog = env->prog;
10792 struct bpf_insn *insn = prog->insnsi;
10793 int i, depth;
19d28fbd 10794#endif
e4052d06 10795 int err = 0;
1ea47e01 10796
e4052d06
QM
10797 if (env->prog->jit_requested &&
10798 !bpf_prog_is_dev_bound(env->prog->aux)) {
19d28fbd
DM
10799 err = jit_subprogs(env);
10800 if (err == 0)
1c2a088a 10801 return 0;
c7a89784
DB
10802 if (err == -EFAULT)
10803 return err;
19d28fbd
DM
10804 }
10805#ifndef CONFIG_BPF_JIT_ALWAYS_ON
e411901c
MF
10806 if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
10807 /* When JIT fails the progs with bpf2bpf calls and tail_calls
10808 * have to be rejected, since interpreter doesn't support them yet.
10809 */
10810 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
10811 return -EINVAL;
10812 }
1ea47e01
AS
10813 for (i = 0; i < prog->len; i++, insn++) {
10814 if (insn->code != (BPF_JMP | BPF_CALL) ||
10815 insn->src_reg != BPF_PSEUDO_CALL)
10816 continue;
10817 depth = get_callee_stack_depth(env, insn, i);
10818 if (depth < 0)
10819 return depth;
10820 bpf_patch_call_args(insn, depth);
10821 }
19d28fbd
DM
10822 err = 0;
10823#endif
10824 return err;
1ea47e01
AS
10825}
10826
79741b3b 10827/* fixup insn->imm field of bpf_call instructions
81ed18ab 10828 * and inline eligible helpers as explicit sequence of BPF instructions
e245c5c6
AS
10829 *
10830 * this function is called after eBPF program passed verification
10831 */
79741b3b 10832static int fixup_bpf_calls(struct bpf_verifier_env *env)
e245c5c6 10833{
79741b3b 10834 struct bpf_prog *prog = env->prog;
d2e4c1e6 10835 bool expect_blinding = bpf_jit_blinding_enabled(prog);
79741b3b 10836 struct bpf_insn *insn = prog->insnsi;
e245c5c6 10837 const struct bpf_func_proto *fn;
79741b3b 10838 const int insn_cnt = prog->len;
09772d92 10839 const struct bpf_map_ops *ops;
c93552c4 10840 struct bpf_insn_aux_data *aux;
81ed18ab
AS
10841 struct bpf_insn insn_buf[16];
10842 struct bpf_prog *new_prog;
10843 struct bpf_map *map_ptr;
d2e4c1e6 10844 int i, ret, cnt, delta = 0;
e245c5c6 10845
79741b3b 10846 for (i = 0; i < insn_cnt; i++, insn++) {
f6b1b3bf
DB
10847 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
10848 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
10849 insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
68fda450 10850 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
f6b1b3bf
DB
10851 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
10852 struct bpf_insn mask_and_div[] = {
10853 BPF_MOV32_REG(insn->src_reg, insn->src_reg),
10854 /* Rx div 0 -> 0 */
10855 BPF_JMP_IMM(BPF_JNE, insn->src_reg, 0, 2),
10856 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
10857 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
10858 *insn,
10859 };
10860 struct bpf_insn mask_and_mod[] = {
10861 BPF_MOV32_REG(insn->src_reg, insn->src_reg),
10862 /* Rx mod 0 -> Rx */
10863 BPF_JMP_IMM(BPF_JEQ, insn->src_reg, 0, 1),
10864 *insn,
10865 };
10866 struct bpf_insn *patchlet;
10867
10868 if (insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
10869 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
10870 patchlet = mask_and_div + (is64 ? 1 : 0);
10871 cnt = ARRAY_SIZE(mask_and_div) - (is64 ? 1 : 0);
10872 } else {
10873 patchlet = mask_and_mod + (is64 ? 1 : 0);
10874 cnt = ARRAY_SIZE(mask_and_mod) - (is64 ? 1 : 0);
10875 }
10876
10877 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
68fda450
AS
10878 if (!new_prog)
10879 return -ENOMEM;
10880
10881 delta += cnt - 1;
10882 env->prog = prog = new_prog;
10883 insn = new_prog->insnsi + i + delta;
10884 continue;
10885 }
10886
e0cea7ce
DB
10887 if (BPF_CLASS(insn->code) == BPF_LD &&
10888 (BPF_MODE(insn->code) == BPF_ABS ||
10889 BPF_MODE(insn->code) == BPF_IND)) {
10890 cnt = env->ops->gen_ld_abs(insn, insn_buf);
10891 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
10892 verbose(env, "bpf verifier is misconfigured\n");
10893 return -EINVAL;
10894 }
10895
10896 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
10897 if (!new_prog)
10898 return -ENOMEM;
10899
10900 delta += cnt - 1;
10901 env->prog = prog = new_prog;
10902 insn = new_prog->insnsi + i + delta;
10903 continue;
10904 }
10905
979d63d5
DB
10906 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
10907 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
10908 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
10909 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
10910 struct bpf_insn insn_buf[16];
10911 struct bpf_insn *patch = &insn_buf[0];
10912 bool issrc, isneg;
10913 u32 off_reg;
10914
10915 aux = &env->insn_aux_data[i + delta];
3612af78
DB
10916 if (!aux->alu_state ||
10917 aux->alu_state == BPF_ALU_NON_POINTER)
979d63d5
DB
10918 continue;
10919
10920 isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
10921 issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
10922 BPF_ALU_SANITIZE_SRC;
10923
10924 off_reg = issrc ? insn->src_reg : insn->dst_reg;
10925 if (isneg)
10926 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
10927 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit - 1);
10928 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
10929 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
10930 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
10931 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
10932 if (issrc) {
10933 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX,
10934 off_reg);
10935 insn->src_reg = BPF_REG_AX;
10936 } else {
10937 *patch++ = BPF_ALU64_REG(BPF_AND, off_reg,
10938 BPF_REG_AX);
10939 }
10940 if (isneg)
10941 insn->code = insn->code == code_add ?
10942 code_sub : code_add;
10943 *patch++ = *insn;
10944 if (issrc && isneg)
10945 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
10946 cnt = patch - insn_buf;
10947
10948 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
10949 if (!new_prog)
10950 return -ENOMEM;
10951
10952 delta += cnt - 1;
10953 env->prog = prog = new_prog;
10954 insn = new_prog->insnsi + i + delta;
10955 continue;
10956 }
10957
79741b3b
AS
10958 if (insn->code != (BPF_JMP | BPF_CALL))
10959 continue;
cc8b0b92
AS
10960 if (insn->src_reg == BPF_PSEUDO_CALL)
10961 continue;
e245c5c6 10962
79741b3b
AS
10963 if (insn->imm == BPF_FUNC_get_route_realm)
10964 prog->dst_needed = 1;
10965 if (insn->imm == BPF_FUNC_get_prandom_u32)
10966 bpf_user_rnd_init_once();
9802d865
JB
10967 if (insn->imm == BPF_FUNC_override_return)
10968 prog->kprobe_override = 1;
79741b3b 10969 if (insn->imm == BPF_FUNC_tail_call) {
7b9f6da1
DM
10970 /* If we tail call into other programs, we
10971 * cannot make any assumptions since they can
10972 * be replaced dynamically during runtime in
10973 * the program array.
10974 */
10975 prog->cb_access = 1;
e411901c
MF
10976 if (!allow_tail_call_in_subprogs(env))
10977 prog->aux->stack_depth = MAX_BPF_STACK;
10978 prog->aux->max_pkt_offset = MAX_PACKET_OFF;
7b9f6da1 10979
79741b3b
AS
10980 /* mark bpf_tail_call as different opcode to avoid
10981 * conditional branch in the interpeter for every normal
10982 * call and to prevent accidental JITing by JIT compiler
10983 * that doesn't support bpf_tail_call yet
e245c5c6 10984 */
79741b3b 10985 insn->imm = 0;
71189fa9 10986 insn->code = BPF_JMP | BPF_TAIL_CALL;
b2157399 10987
c93552c4 10988 aux = &env->insn_aux_data[i + delta];
2c78ee89 10989 if (env->bpf_capable && !expect_blinding &&
cc52d914 10990 prog->jit_requested &&
d2e4c1e6
DB
10991 !bpf_map_key_poisoned(aux) &&
10992 !bpf_map_ptr_poisoned(aux) &&
10993 !bpf_map_ptr_unpriv(aux)) {
10994 struct bpf_jit_poke_descriptor desc = {
10995 .reason = BPF_POKE_REASON_TAIL_CALL,
10996 .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
10997 .tail_call.key = bpf_map_key_immediate(aux),
a748c697 10998 .insn_idx = i + delta,
d2e4c1e6
DB
10999 };
11000
11001 ret = bpf_jit_add_poke_descriptor(prog, &desc);
11002 if (ret < 0) {
11003 verbose(env, "adding tail call poke descriptor failed\n");
11004 return ret;
11005 }
11006
11007 insn->imm = ret + 1;
11008 continue;
11009 }
11010
c93552c4
DB
11011 if (!bpf_map_ptr_unpriv(aux))
11012 continue;
11013
b2157399
AS
11014 /* instead of changing every JIT dealing with tail_call
11015 * emit two extra insns:
11016 * if (index >= max_entries) goto out;
11017 * index &= array->index_mask;
11018 * to avoid out-of-bounds cpu speculation
11019 */
c93552c4 11020 if (bpf_map_ptr_poisoned(aux)) {
40950343 11021 verbose(env, "tail_call abusing map_ptr\n");
b2157399
AS
11022 return -EINVAL;
11023 }
c93552c4 11024
d2e4c1e6 11025 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
b2157399
AS
11026 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
11027 map_ptr->max_entries, 2);
11028 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
11029 container_of(map_ptr,
11030 struct bpf_array,
11031 map)->index_mask);
11032 insn_buf[2] = *insn;
11033 cnt = 3;
11034 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
11035 if (!new_prog)
11036 return -ENOMEM;
11037
11038 delta += cnt - 1;
11039 env->prog = prog = new_prog;
11040 insn = new_prog->insnsi + i + delta;
79741b3b
AS
11041 continue;
11042 }
e245c5c6 11043
89c63074 11044 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
09772d92
DB
11045 * and other inlining handlers are currently limited to 64 bit
11046 * only.
89c63074 11047 */
60b58afc 11048 if (prog->jit_requested && BITS_PER_LONG == 64 &&
09772d92
DB
11049 (insn->imm == BPF_FUNC_map_lookup_elem ||
11050 insn->imm == BPF_FUNC_map_update_elem ||
84430d42
DB
11051 insn->imm == BPF_FUNC_map_delete_elem ||
11052 insn->imm == BPF_FUNC_map_push_elem ||
11053 insn->imm == BPF_FUNC_map_pop_elem ||
11054 insn->imm == BPF_FUNC_map_peek_elem)) {
c93552c4
DB
11055 aux = &env->insn_aux_data[i + delta];
11056 if (bpf_map_ptr_poisoned(aux))
11057 goto patch_call_imm;
11058
d2e4c1e6 11059 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
09772d92
DB
11060 ops = map_ptr->ops;
11061 if (insn->imm == BPF_FUNC_map_lookup_elem &&
11062 ops->map_gen_lookup) {
11063 cnt = ops->map_gen_lookup(map_ptr, insn_buf);
4a8f87e6
DB
11064 if (cnt == -EOPNOTSUPP)
11065 goto patch_map_ops_generic;
11066 if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
09772d92
DB
11067 verbose(env, "bpf verifier is misconfigured\n");
11068 return -EINVAL;
11069 }
81ed18ab 11070
09772d92
DB
11071 new_prog = bpf_patch_insn_data(env, i + delta,
11072 insn_buf, cnt);
11073 if (!new_prog)
11074 return -ENOMEM;
81ed18ab 11075
09772d92
DB
11076 delta += cnt - 1;
11077 env->prog = prog = new_prog;
11078 insn = new_prog->insnsi + i + delta;
11079 continue;
11080 }
81ed18ab 11081
09772d92
DB
11082 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
11083 (void *(*)(struct bpf_map *map, void *key))NULL));
11084 BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
11085 (int (*)(struct bpf_map *map, void *key))NULL));
11086 BUILD_BUG_ON(!__same_type(ops->map_update_elem,
11087 (int (*)(struct bpf_map *map, void *key, void *value,
11088 u64 flags))NULL));
84430d42
DB
11089 BUILD_BUG_ON(!__same_type(ops->map_push_elem,
11090 (int (*)(struct bpf_map *map, void *value,
11091 u64 flags))NULL));
11092 BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
11093 (int (*)(struct bpf_map *map, void *value))NULL));
11094 BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
11095 (int (*)(struct bpf_map *map, void *value))NULL));
4a8f87e6 11096patch_map_ops_generic:
09772d92
DB
11097 switch (insn->imm) {
11098 case BPF_FUNC_map_lookup_elem:
11099 insn->imm = BPF_CAST_CALL(ops->map_lookup_elem) -
11100 __bpf_call_base;
11101 continue;
11102 case BPF_FUNC_map_update_elem:
11103 insn->imm = BPF_CAST_CALL(ops->map_update_elem) -
11104 __bpf_call_base;
11105 continue;
11106 case BPF_FUNC_map_delete_elem:
11107 insn->imm = BPF_CAST_CALL(ops->map_delete_elem) -
11108 __bpf_call_base;
11109 continue;
84430d42
DB
11110 case BPF_FUNC_map_push_elem:
11111 insn->imm = BPF_CAST_CALL(ops->map_push_elem) -
11112 __bpf_call_base;
11113 continue;
11114 case BPF_FUNC_map_pop_elem:
11115 insn->imm = BPF_CAST_CALL(ops->map_pop_elem) -
11116 __bpf_call_base;
11117 continue;
11118 case BPF_FUNC_map_peek_elem:
11119 insn->imm = BPF_CAST_CALL(ops->map_peek_elem) -
11120 __bpf_call_base;
11121 continue;
09772d92 11122 }
81ed18ab 11123
09772d92 11124 goto patch_call_imm;
81ed18ab
AS
11125 }
11126
5576b991
MKL
11127 if (prog->jit_requested && BITS_PER_LONG == 64 &&
11128 insn->imm == BPF_FUNC_jiffies64) {
11129 struct bpf_insn ld_jiffies_addr[2] = {
11130 BPF_LD_IMM64(BPF_REG_0,
11131 (unsigned long)&jiffies),
11132 };
11133
11134 insn_buf[0] = ld_jiffies_addr[0];
11135 insn_buf[1] = ld_jiffies_addr[1];
11136 insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
11137 BPF_REG_0, 0);
11138 cnt = 3;
11139
11140 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
11141 cnt);
11142 if (!new_prog)
11143 return -ENOMEM;
11144
11145 delta += cnt - 1;
11146 env->prog = prog = new_prog;
11147 insn = new_prog->insnsi + i + delta;
11148 continue;
11149 }
11150
81ed18ab 11151patch_call_imm:
5e43f899 11152 fn = env->ops->get_func_proto(insn->imm, env->prog);
79741b3b
AS
11153 /* all functions that have prototype and verifier allowed
11154 * programs to call them, must be real in-kernel functions
11155 */
11156 if (!fn->func) {
61bd5218
JK
11157 verbose(env,
11158 "kernel subsystem misconfigured func %s#%d\n",
79741b3b
AS
11159 func_id_name(insn->imm), insn->imm);
11160 return -EFAULT;
e245c5c6 11161 }
79741b3b 11162 insn->imm = fn->func - __bpf_call_base;
e245c5c6 11163 }
e245c5c6 11164
d2e4c1e6
DB
11165 /* Since poke tab is now finalized, publish aux to tracker. */
11166 for (i = 0; i < prog->aux->size_poke_tab; i++) {
11167 map_ptr = prog->aux->poke_tab[i].tail_call.map;
11168 if (!map_ptr->ops->map_poke_track ||
11169 !map_ptr->ops->map_poke_untrack ||
11170 !map_ptr->ops->map_poke_run) {
11171 verbose(env, "bpf verifier is misconfigured\n");
11172 return -EINVAL;
11173 }
11174
11175 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
11176 if (ret < 0) {
11177 verbose(env, "tracking tail call prog failed\n");
11178 return ret;
11179 }
11180 }
11181
79741b3b
AS
11182 return 0;
11183}
e245c5c6 11184
58e2af8b 11185static void free_states(struct bpf_verifier_env *env)
f1bca824 11186{
58e2af8b 11187 struct bpf_verifier_state_list *sl, *sln;
f1bca824
AS
11188 int i;
11189
9f4686c4
AS
11190 sl = env->free_list;
11191 while (sl) {
11192 sln = sl->next;
11193 free_verifier_state(&sl->state, false);
11194 kfree(sl);
11195 sl = sln;
11196 }
51c39bb1 11197 env->free_list = NULL;
9f4686c4 11198
f1bca824
AS
11199 if (!env->explored_states)
11200 return;
11201
dc2a4ebc 11202 for (i = 0; i < state_htab_size(env); i++) {
f1bca824
AS
11203 sl = env->explored_states[i];
11204
a8f500af
AS
11205 while (sl) {
11206 sln = sl->next;
11207 free_verifier_state(&sl->state, false);
11208 kfree(sl);
11209 sl = sln;
11210 }
51c39bb1 11211 env->explored_states[i] = NULL;
f1bca824 11212 }
51c39bb1 11213}
f1bca824 11214
51c39bb1
AS
11215/* The verifier is using insn_aux_data[] to store temporary data during
11216 * verification and to store information for passes that run after the
11217 * verification like dead code sanitization. do_check_common() for subprogram N
11218 * may analyze many other subprograms. sanitize_insn_aux_data() clears all
11219 * temporary data after do_check_common() finds that subprogram N cannot be
11220 * verified independently. pass_cnt counts the number of times
11221 * do_check_common() was run and insn->aux->seen tells the pass number
11222 * insn_aux_data was touched. These variables are compared to clear temporary
11223 * data from failed pass. For testing and experiments do_check_common() can be
11224 * run multiple times even when prior attempt to verify is unsuccessful.
11225 */
11226static void sanitize_insn_aux_data(struct bpf_verifier_env *env)
11227{
11228 struct bpf_insn *insn = env->prog->insnsi;
11229 struct bpf_insn_aux_data *aux;
11230 int i, class;
11231
11232 for (i = 0; i < env->prog->len; i++) {
11233 class = BPF_CLASS(insn[i].code);
11234 if (class != BPF_LDX && class != BPF_STX)
11235 continue;
11236 aux = &env->insn_aux_data[i];
11237 if (aux->seen != env->pass_cnt)
11238 continue;
11239 memset(aux, 0, offsetof(typeof(*aux), orig_idx));
11240 }
f1bca824
AS
11241}
11242
51c39bb1
AS
11243static int do_check_common(struct bpf_verifier_env *env, int subprog)
11244{
6f8a57cc 11245 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
51c39bb1
AS
11246 struct bpf_verifier_state *state;
11247 struct bpf_reg_state *regs;
11248 int ret, i;
11249
11250 env->prev_linfo = NULL;
11251 env->pass_cnt++;
11252
11253 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
11254 if (!state)
11255 return -ENOMEM;
11256 state->curframe = 0;
11257 state->speculative = false;
11258 state->branches = 1;
11259 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
11260 if (!state->frame[0]) {
11261 kfree(state);
11262 return -ENOMEM;
11263 }
11264 env->cur_state = state;
11265 init_func_state(env, state->frame[0],
11266 BPF_MAIN_FUNC /* callsite */,
11267 0 /* frameno */,
11268 subprog);
11269
11270 regs = state->frame[state->curframe]->regs;
be8704ff 11271 if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
51c39bb1
AS
11272 ret = btf_prepare_func_args(env, subprog, regs);
11273 if (ret)
11274 goto out;
11275 for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
11276 if (regs[i].type == PTR_TO_CTX)
11277 mark_reg_known_zero(env, regs, i);
11278 else if (regs[i].type == SCALAR_VALUE)
11279 mark_reg_unknown(env, regs, i);
11280 }
11281 } else {
11282 /* 1st arg to a function */
11283 regs[BPF_REG_1].type = PTR_TO_CTX;
11284 mark_reg_known_zero(env, regs, BPF_REG_1);
11285 ret = btf_check_func_arg_match(env, subprog, regs);
11286 if (ret == -EFAULT)
11287 /* unlikely verifier bug. abort.
11288 * ret == 0 and ret < 0 are sadly acceptable for
11289 * main() function due to backward compatibility.
11290 * Like socket filter program may be written as:
11291 * int bpf_prog(struct pt_regs *ctx)
11292 * and never dereference that ctx in the program.
11293 * 'struct pt_regs' is a type mismatch for socket
11294 * filter that should be using 'struct __sk_buff'.
11295 */
11296 goto out;
11297 }
11298
11299 ret = do_check(env);
11300out:
f59bbfc2
AS
11301 /* check for NULL is necessary, since cur_state can be freed inside
11302 * do_check() under memory pressure.
11303 */
11304 if (env->cur_state) {
11305 free_verifier_state(env->cur_state, true);
11306 env->cur_state = NULL;
11307 }
6f8a57cc
AN
11308 while (!pop_stack(env, NULL, NULL, false));
11309 if (!ret && pop_log)
11310 bpf_vlog_reset(&env->log, 0);
51c39bb1
AS
11311 free_states(env);
11312 if (ret)
11313 /* clean aux data in case subprog was rejected */
11314 sanitize_insn_aux_data(env);
11315 return ret;
11316}
11317
11318/* Verify all global functions in a BPF program one by one based on their BTF.
11319 * All global functions must pass verification. Otherwise the whole program is rejected.
11320 * Consider:
11321 * int bar(int);
11322 * int foo(int f)
11323 * {
11324 * return bar(f);
11325 * }
11326 * int bar(int b)
11327 * {
11328 * ...
11329 * }
11330 * foo() will be verified first for R1=any_scalar_value. During verification it
11331 * will be assumed that bar() already verified successfully and call to bar()
11332 * from foo() will be checked for type match only. Later bar() will be verified
11333 * independently to check that it's safe for R1=any_scalar_value.
11334 */
11335static int do_check_subprogs(struct bpf_verifier_env *env)
11336{
11337 struct bpf_prog_aux *aux = env->prog->aux;
11338 int i, ret;
11339
11340 if (!aux->func_info)
11341 return 0;
11342
11343 for (i = 1; i < env->subprog_cnt; i++) {
11344 if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
11345 continue;
11346 env->insn_idx = env->subprog_info[i].start;
11347 WARN_ON_ONCE(env->insn_idx == 0);
11348 ret = do_check_common(env, i);
11349 if (ret) {
11350 return ret;
11351 } else if (env->log.level & BPF_LOG_LEVEL) {
11352 verbose(env,
11353 "Func#%d is safe for any args that match its prototype\n",
11354 i);
11355 }
11356 }
11357 return 0;
11358}
11359
11360static int do_check_main(struct bpf_verifier_env *env)
11361{
11362 int ret;
11363
11364 env->insn_idx = 0;
11365 ret = do_check_common(env, 0);
11366 if (!ret)
11367 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
11368 return ret;
11369}
11370
11371
06ee7115
AS
11372static void print_verification_stats(struct bpf_verifier_env *env)
11373{
11374 int i;
11375
11376 if (env->log.level & BPF_LOG_STATS) {
11377 verbose(env, "verification time %lld usec\n",
11378 div_u64(env->verification_time, 1000));
11379 verbose(env, "stack depth ");
11380 for (i = 0; i < env->subprog_cnt; i++) {
11381 u32 depth = env->subprog_info[i].stack_depth;
11382
11383 verbose(env, "%d", depth);
11384 if (i + 1 < env->subprog_cnt)
11385 verbose(env, "+");
11386 }
11387 verbose(env, "\n");
11388 }
11389 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
11390 "total_states %d peak_states %d mark_read %d\n",
11391 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
11392 env->max_states_per_insn, env->total_states,
11393 env->peak_states, env->longest_mark_read_walk);
f1bca824
AS
11394}
11395
27ae7997
MKL
11396static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
11397{
11398 const struct btf_type *t, *func_proto;
11399 const struct bpf_struct_ops *st_ops;
11400 const struct btf_member *member;
11401 struct bpf_prog *prog = env->prog;
11402 u32 btf_id, member_idx;
11403 const char *mname;
11404
11405 btf_id = prog->aux->attach_btf_id;
11406 st_ops = bpf_struct_ops_find(btf_id);
11407 if (!st_ops) {
11408 verbose(env, "attach_btf_id %u is not a supported struct\n",
11409 btf_id);
11410 return -ENOTSUPP;
11411 }
11412
11413 t = st_ops->type;
11414 member_idx = prog->expected_attach_type;
11415 if (member_idx >= btf_type_vlen(t)) {
11416 verbose(env, "attach to invalid member idx %u of struct %s\n",
11417 member_idx, st_ops->name);
11418 return -EINVAL;
11419 }
11420
11421 member = &btf_type_member(t)[member_idx];
11422 mname = btf_name_by_offset(btf_vmlinux, member->name_off);
11423 func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
11424 NULL);
11425 if (!func_proto) {
11426 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
11427 mname, member_idx, st_ops->name);
11428 return -EINVAL;
11429 }
11430
11431 if (st_ops->check_member) {
11432 int err = st_ops->check_member(t, member);
11433
11434 if (err) {
11435 verbose(env, "attach to unsupported member %s of struct %s\n",
11436 mname, st_ops->name);
11437 return err;
11438 }
11439 }
11440
11441 prog->aux->attach_func_proto = func_proto;
11442 prog->aux->attach_func_name = mname;
11443 env->ops = st_ops->verifier_ops;
11444
11445 return 0;
11446}
6ba43b76
KS
11447#define SECURITY_PREFIX "security_"
11448
f7b12b6f 11449static int check_attach_modify_return(unsigned long addr, const char *func_name)
6ba43b76 11450{
69191754 11451 if (within_error_injection_list(addr) ||
f7b12b6f 11452 !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
6ba43b76 11453 return 0;
6ba43b76 11454
6ba43b76
KS
11455 return -EINVAL;
11456}
27ae7997 11457
1e6c62a8
AS
11458/* non exhaustive list of sleepable bpf_lsm_*() functions */
11459BTF_SET_START(btf_sleepable_lsm_hooks)
11460#ifdef CONFIG_BPF_LSM
1e6c62a8 11461BTF_ID(func, bpf_lsm_bprm_committed_creds)
29523c5e
AS
11462#else
11463BTF_ID_UNUSED
1e6c62a8
AS
11464#endif
11465BTF_SET_END(btf_sleepable_lsm_hooks)
11466
11467static int check_sleepable_lsm_hook(u32 btf_id)
11468{
11469 return btf_id_set_contains(&btf_sleepable_lsm_hooks, btf_id);
11470}
11471
11472/* list of non-sleepable functions that are otherwise on
11473 * ALLOW_ERROR_INJECTION list
11474 */
11475BTF_SET_START(btf_non_sleepable_error_inject)
11476/* Three functions below can be called from sleepable and non-sleepable context.
11477 * Assume non-sleepable from bpf safety point of view.
11478 */
11479BTF_ID(func, __add_to_page_cache_locked)
11480BTF_ID(func, should_fail_alloc_page)
11481BTF_ID(func, should_failslab)
11482BTF_SET_END(btf_non_sleepable_error_inject)
11483
11484static int check_non_sleepable_error_inject(u32 btf_id)
11485{
11486 return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
11487}
11488
f7b12b6f
THJ
11489int bpf_check_attach_target(struct bpf_verifier_log *log,
11490 const struct bpf_prog *prog,
11491 const struct bpf_prog *tgt_prog,
11492 u32 btf_id,
11493 struct bpf_attach_target_info *tgt_info)
38207291 11494{
be8704ff 11495 bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
f1b9509c 11496 const char prefix[] = "btf_trace_";
5b92a28a 11497 int ret = 0, subprog = -1, i;
38207291 11498 const struct btf_type *t;
5b92a28a 11499 bool conservative = true;
38207291 11500 const char *tname;
5b92a28a 11501 struct btf *btf;
f7b12b6f 11502 long addr = 0;
38207291 11503
f1b9509c 11504 if (!btf_id) {
efc68158 11505 bpf_log(log, "Tracing programs must provide btf_id\n");
f1b9509c
AS
11506 return -EINVAL;
11507 }
f7b12b6f 11508 btf = tgt_prog ? tgt_prog->aux->btf : btf_vmlinux;
5b92a28a 11509 if (!btf) {
efc68158 11510 bpf_log(log,
5b92a28a
AS
11511 "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
11512 return -EINVAL;
11513 }
11514 t = btf_type_by_id(btf, btf_id);
f1b9509c 11515 if (!t) {
efc68158 11516 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
f1b9509c
AS
11517 return -EINVAL;
11518 }
5b92a28a 11519 tname = btf_name_by_offset(btf, t->name_off);
f1b9509c 11520 if (!tname) {
efc68158 11521 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
f1b9509c
AS
11522 return -EINVAL;
11523 }
5b92a28a
AS
11524 if (tgt_prog) {
11525 struct bpf_prog_aux *aux = tgt_prog->aux;
11526
11527 for (i = 0; i < aux->func_info_cnt; i++)
11528 if (aux->func_info[i].type_id == btf_id) {
11529 subprog = i;
11530 break;
11531 }
11532 if (subprog == -1) {
efc68158 11533 bpf_log(log, "Subprog %s doesn't exist\n", tname);
5b92a28a
AS
11534 return -EINVAL;
11535 }
11536 conservative = aux->func_info_aux[subprog].unreliable;
be8704ff
AS
11537 if (prog_extension) {
11538 if (conservative) {
efc68158 11539 bpf_log(log,
be8704ff
AS
11540 "Cannot replace static functions\n");
11541 return -EINVAL;
11542 }
11543 if (!prog->jit_requested) {
efc68158 11544 bpf_log(log,
be8704ff
AS
11545 "Extension programs should be JITed\n");
11546 return -EINVAL;
11547 }
be8704ff
AS
11548 }
11549 if (!tgt_prog->jited) {
efc68158 11550 bpf_log(log, "Can attach to only JITed progs\n");
be8704ff
AS
11551 return -EINVAL;
11552 }
11553 if (tgt_prog->type == prog->type) {
11554 /* Cannot fentry/fexit another fentry/fexit program.
11555 * Cannot attach program extension to another extension.
11556 * It's ok to attach fentry/fexit to extension program.
11557 */
efc68158 11558 bpf_log(log, "Cannot recursively attach\n");
be8704ff
AS
11559 return -EINVAL;
11560 }
11561 if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
11562 prog_extension &&
11563 (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
11564 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
11565 /* Program extensions can extend all program types
11566 * except fentry/fexit. The reason is the following.
11567 * The fentry/fexit programs are used for performance
11568 * analysis, stats and can be attached to any program
11569 * type except themselves. When extension program is
11570 * replacing XDP function it is necessary to allow
11571 * performance analysis of all functions. Both original
11572 * XDP program and its program extension. Hence
11573 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
11574 * allowed. If extending of fentry/fexit was allowed it
11575 * would be possible to create long call chain
11576 * fentry->extension->fentry->extension beyond
11577 * reasonable stack size. Hence extending fentry is not
11578 * allowed.
11579 */
efc68158 11580 bpf_log(log, "Cannot extend fentry/fexit\n");
be8704ff
AS
11581 return -EINVAL;
11582 }
5b92a28a 11583 } else {
be8704ff 11584 if (prog_extension) {
efc68158 11585 bpf_log(log, "Cannot replace kernel functions\n");
be8704ff
AS
11586 return -EINVAL;
11587 }
5b92a28a 11588 }
f1b9509c
AS
11589
11590 switch (prog->expected_attach_type) {
11591 case BPF_TRACE_RAW_TP:
5b92a28a 11592 if (tgt_prog) {
efc68158 11593 bpf_log(log,
5b92a28a
AS
11594 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
11595 return -EINVAL;
11596 }
38207291 11597 if (!btf_type_is_typedef(t)) {
efc68158 11598 bpf_log(log, "attach_btf_id %u is not a typedef\n",
38207291
MKL
11599 btf_id);
11600 return -EINVAL;
11601 }
f1b9509c 11602 if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
efc68158 11603 bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
38207291
MKL
11604 btf_id, tname);
11605 return -EINVAL;
11606 }
11607 tname += sizeof(prefix) - 1;
5b92a28a 11608 t = btf_type_by_id(btf, t->type);
38207291
MKL
11609 if (!btf_type_is_ptr(t))
11610 /* should never happen in valid vmlinux build */
11611 return -EINVAL;
5b92a28a 11612 t = btf_type_by_id(btf, t->type);
38207291
MKL
11613 if (!btf_type_is_func_proto(t))
11614 /* should never happen in valid vmlinux build */
11615 return -EINVAL;
11616
f7b12b6f 11617 break;
15d83c4d
YS
11618 case BPF_TRACE_ITER:
11619 if (!btf_type_is_func(t)) {
efc68158 11620 bpf_log(log, "attach_btf_id %u is not a function\n",
15d83c4d
YS
11621 btf_id);
11622 return -EINVAL;
11623 }
11624 t = btf_type_by_id(btf, t->type);
11625 if (!btf_type_is_func_proto(t))
11626 return -EINVAL;
f7b12b6f
THJ
11627 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
11628 if (ret)
11629 return ret;
11630 break;
be8704ff
AS
11631 default:
11632 if (!prog_extension)
11633 return -EINVAL;
df561f66 11634 fallthrough;
ae240823 11635 case BPF_MODIFY_RETURN:
9e4e01df 11636 case BPF_LSM_MAC:
fec56f58
AS
11637 case BPF_TRACE_FENTRY:
11638 case BPF_TRACE_FEXIT:
11639 if (!btf_type_is_func(t)) {
efc68158 11640 bpf_log(log, "attach_btf_id %u is not a function\n",
fec56f58
AS
11641 btf_id);
11642 return -EINVAL;
11643 }
be8704ff 11644 if (prog_extension &&
efc68158 11645 btf_check_type_match(log, prog, btf, t))
be8704ff 11646 return -EINVAL;
5b92a28a 11647 t = btf_type_by_id(btf, t->type);
fec56f58
AS
11648 if (!btf_type_is_func_proto(t))
11649 return -EINVAL;
f7b12b6f 11650
4a1e7c0c
THJ
11651 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
11652 (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
11653 prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
11654 return -EINVAL;
11655
f7b12b6f 11656 if (tgt_prog && conservative)
5b92a28a 11657 t = NULL;
f7b12b6f
THJ
11658
11659 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
fec56f58 11660 if (ret < 0)
f7b12b6f
THJ
11661 return ret;
11662
5b92a28a 11663 if (tgt_prog) {
e9eeec58
YS
11664 if (subprog == 0)
11665 addr = (long) tgt_prog->bpf_func;
11666 else
11667 addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
5b92a28a
AS
11668 } else {
11669 addr = kallsyms_lookup_name(tname);
11670 if (!addr) {
efc68158 11671 bpf_log(log,
5b92a28a
AS
11672 "The address of function %s cannot be found\n",
11673 tname);
f7b12b6f 11674 return -ENOENT;
5b92a28a 11675 }
fec56f58 11676 }
18644cec 11677
1e6c62a8
AS
11678 if (prog->aux->sleepable) {
11679 ret = -EINVAL;
11680 switch (prog->type) {
11681 case BPF_PROG_TYPE_TRACING:
11682 /* fentry/fexit/fmod_ret progs can be sleepable only if they are
11683 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
11684 */
11685 if (!check_non_sleepable_error_inject(btf_id) &&
11686 within_error_injection_list(addr))
11687 ret = 0;
11688 break;
11689 case BPF_PROG_TYPE_LSM:
11690 /* LSM progs check that they are attached to bpf_lsm_*() funcs.
11691 * Only some of them are sleepable.
11692 */
11693 if (check_sleepable_lsm_hook(btf_id))
11694 ret = 0;
11695 break;
11696 default:
11697 break;
11698 }
f7b12b6f
THJ
11699 if (ret) {
11700 bpf_log(log, "%s is not sleepable\n", tname);
11701 return ret;
11702 }
1e6c62a8 11703 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
1af9270e 11704 if (tgt_prog) {
efc68158 11705 bpf_log(log, "can't modify return codes of BPF programs\n");
f7b12b6f
THJ
11706 return -EINVAL;
11707 }
11708 ret = check_attach_modify_return(addr, tname);
11709 if (ret) {
11710 bpf_log(log, "%s() is not modifiable\n", tname);
11711 return ret;
1af9270e 11712 }
18644cec 11713 }
f7b12b6f
THJ
11714
11715 break;
11716 }
11717 tgt_info->tgt_addr = addr;
11718 tgt_info->tgt_name = tname;
11719 tgt_info->tgt_type = t;
11720 return 0;
11721}
11722
11723static int check_attach_btf_id(struct bpf_verifier_env *env)
11724{
11725 struct bpf_prog *prog = env->prog;
3aac1ead 11726 struct bpf_prog *tgt_prog = prog->aux->dst_prog;
f7b12b6f
THJ
11727 struct bpf_attach_target_info tgt_info = {};
11728 u32 btf_id = prog->aux->attach_btf_id;
11729 struct bpf_trampoline *tr;
11730 int ret;
11731 u64 key;
11732
11733 if (prog->aux->sleepable && prog->type != BPF_PROG_TYPE_TRACING &&
11734 prog->type != BPF_PROG_TYPE_LSM) {
11735 verbose(env, "Only fentry/fexit/fmod_ret and lsm programs can be sleepable\n");
11736 return -EINVAL;
11737 }
11738
11739 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
11740 return check_struct_ops_btf_id(env);
11741
11742 if (prog->type != BPF_PROG_TYPE_TRACING &&
11743 prog->type != BPF_PROG_TYPE_LSM &&
11744 prog->type != BPF_PROG_TYPE_EXT)
11745 return 0;
11746
11747 ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
11748 if (ret)
fec56f58 11749 return ret;
f7b12b6f
THJ
11750
11751 if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
3aac1ead
THJ
11752 /* to make freplace equivalent to their targets, they need to
11753 * inherit env->ops and expected_attach_type for the rest of the
11754 * verification
11755 */
f7b12b6f
THJ
11756 env->ops = bpf_verifier_ops[tgt_prog->type];
11757 prog->expected_attach_type = tgt_prog->expected_attach_type;
11758 }
11759
11760 /* store info about the attachment target that will be used later */
11761 prog->aux->attach_func_proto = tgt_info.tgt_type;
11762 prog->aux->attach_func_name = tgt_info.tgt_name;
11763
4a1e7c0c
THJ
11764 if (tgt_prog) {
11765 prog->aux->saved_dst_prog_type = tgt_prog->type;
11766 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
11767 }
11768
f7b12b6f
THJ
11769 if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
11770 prog->aux->attach_btf_trace = true;
11771 return 0;
11772 } else if (prog->expected_attach_type == BPF_TRACE_ITER) {
11773 if (!bpf_iter_prog_supported(prog))
11774 return -EINVAL;
11775 return 0;
11776 }
11777
11778 if (prog->type == BPF_PROG_TYPE_LSM) {
11779 ret = bpf_lsm_verify_prog(&env->log, prog);
11780 if (ret < 0)
11781 return ret;
38207291 11782 }
f7b12b6f
THJ
11783
11784 key = bpf_trampoline_compute_key(tgt_prog, btf_id);
11785 tr = bpf_trampoline_get(key, &tgt_info);
11786 if (!tr)
11787 return -ENOMEM;
11788
3aac1ead 11789 prog->aux->dst_trampoline = tr;
f7b12b6f 11790 return 0;
38207291
MKL
11791}
11792
76654e67
AM
11793struct btf *bpf_get_btf_vmlinux(void)
11794{
11795 if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
11796 mutex_lock(&bpf_verifier_lock);
11797 if (!btf_vmlinux)
11798 btf_vmlinux = btf_parse_vmlinux();
11799 mutex_unlock(&bpf_verifier_lock);
11800 }
11801 return btf_vmlinux;
11802}
11803
838e9690
YS
11804int bpf_check(struct bpf_prog **prog, union bpf_attr *attr,
11805 union bpf_attr __user *uattr)
51580e79 11806{
06ee7115 11807 u64 start_time = ktime_get_ns();
58e2af8b 11808 struct bpf_verifier_env *env;
b9193c1b 11809 struct bpf_verifier_log *log;
9e4c24e7 11810 int i, len, ret = -EINVAL;
e2ae4ca2 11811 bool is_priv;
51580e79 11812
eba0c929
AB
11813 /* no program is valid */
11814 if (ARRAY_SIZE(bpf_verifier_ops) == 0)
11815 return -EINVAL;
11816
58e2af8b 11817 /* 'struct bpf_verifier_env' can be global, but since it's not small,
cbd35700
AS
11818 * allocate/free it every time bpf_check() is called
11819 */
58e2af8b 11820 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
cbd35700
AS
11821 if (!env)
11822 return -ENOMEM;
61bd5218 11823 log = &env->log;
cbd35700 11824
9e4c24e7 11825 len = (*prog)->len;
fad953ce 11826 env->insn_aux_data =
9e4c24e7 11827 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
3df126f3
JK
11828 ret = -ENOMEM;
11829 if (!env->insn_aux_data)
11830 goto err_free_env;
9e4c24e7
JK
11831 for (i = 0; i < len; i++)
11832 env->insn_aux_data[i].orig_idx = i;
9bac3d6d 11833 env->prog = *prog;
00176a34 11834 env->ops = bpf_verifier_ops[env->prog->type];
2c78ee89 11835 is_priv = bpf_capable();
0246e64d 11836
76654e67 11837 bpf_get_btf_vmlinux();
8580ac94 11838
cbd35700 11839 /* grab the mutex to protect few globals used by verifier */
45a73c17
AS
11840 if (!is_priv)
11841 mutex_lock(&bpf_verifier_lock);
cbd35700
AS
11842
11843 if (attr->log_level || attr->log_buf || attr->log_size) {
11844 /* user requested verbose verifier output
11845 * and supplied buffer to store the verification trace
11846 */
e7bf8249
JK
11847 log->level = attr->log_level;
11848 log->ubuf = (char __user *) (unsigned long) attr->log_buf;
11849 log->len_total = attr->log_size;
cbd35700
AS
11850
11851 ret = -EINVAL;
e7bf8249 11852 /* log attributes have to be sane */
7a9f5c65 11853 if (log->len_total < 128 || log->len_total > UINT_MAX >> 2 ||
06ee7115 11854 !log->level || !log->ubuf || log->level & ~BPF_LOG_MASK)
3df126f3 11855 goto err_unlock;
cbd35700 11856 }
1ad2f583 11857
8580ac94
AS
11858 if (IS_ERR(btf_vmlinux)) {
11859 /* Either gcc or pahole or kernel are broken. */
11860 verbose(env, "in-kernel BTF is malformed\n");
11861 ret = PTR_ERR(btf_vmlinux);
38207291 11862 goto skip_full_check;
8580ac94
AS
11863 }
11864
1ad2f583
DB
11865 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
11866 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
e07b98d9 11867 env->strict_alignment = true;
e9ee9efc
DM
11868 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
11869 env->strict_alignment = false;
cbd35700 11870
2c78ee89 11871 env->allow_ptr_leaks = bpf_allow_ptr_leaks();
41c48f3a 11872 env->allow_ptr_to_map_access = bpf_allow_ptr_to_map_access();
2c78ee89
AS
11873 env->bypass_spec_v1 = bpf_bypass_spec_v1();
11874 env->bypass_spec_v4 = bpf_bypass_spec_v4();
11875 env->bpf_capable = bpf_capable();
e2ae4ca2 11876
10d274e8
AS
11877 if (is_priv)
11878 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
11879
cae1927c 11880 if (bpf_prog_is_dev_bound(env->prog->aux)) {
a40a2632 11881 ret = bpf_prog_offload_verifier_prep(env->prog);
ab3f0063 11882 if (ret)
f4e3ec0d 11883 goto skip_full_check;
ab3f0063
JK
11884 }
11885
dc2a4ebc 11886 env->explored_states = kvcalloc(state_htab_size(env),
58e2af8b 11887 sizeof(struct bpf_verifier_state_list *),
f1bca824
AS
11888 GFP_USER);
11889 ret = -ENOMEM;
11890 if (!env->explored_states)
11891 goto skip_full_check;
11892
d9762e84 11893 ret = check_subprogs(env);
475fb78f
AS
11894 if (ret < 0)
11895 goto skip_full_check;
11896
c454a46b 11897 ret = check_btf_info(env, attr, uattr);
838e9690
YS
11898 if (ret < 0)
11899 goto skip_full_check;
11900
be8704ff
AS
11901 ret = check_attach_btf_id(env);
11902 if (ret)
11903 goto skip_full_check;
11904
4976b718
HL
11905 ret = resolve_pseudo_ldimm64(env);
11906 if (ret < 0)
11907 goto skip_full_check;
11908
d9762e84
MKL
11909 ret = check_cfg(env);
11910 if (ret < 0)
11911 goto skip_full_check;
11912
51c39bb1
AS
11913 ret = do_check_subprogs(env);
11914 ret = ret ?: do_check_main(env);
cbd35700 11915
c941ce9c
QM
11916 if (ret == 0 && bpf_prog_is_dev_bound(env->prog->aux))
11917 ret = bpf_prog_offload_finalize(env);
11918
0246e64d 11919skip_full_check:
51c39bb1 11920 kvfree(env->explored_states);
0246e64d 11921
c131187d 11922 if (ret == 0)
9b38c405 11923 ret = check_max_stack_depth(env);
c131187d 11924
9b38c405 11925 /* instruction rewrites happen after this point */
e2ae4ca2
JK
11926 if (is_priv) {
11927 if (ret == 0)
11928 opt_hard_wire_dead_code_branches(env);
52875a04
JK
11929 if (ret == 0)
11930 ret = opt_remove_dead_code(env);
a1b14abc
JK
11931 if (ret == 0)
11932 ret = opt_remove_nops(env);
52875a04
JK
11933 } else {
11934 if (ret == 0)
11935 sanitize_dead_code(env);
e2ae4ca2
JK
11936 }
11937
9bac3d6d
AS
11938 if (ret == 0)
11939 /* program is valid, convert *(u32*)(ctx + off) accesses */
11940 ret = convert_ctx_accesses(env);
11941
e245c5c6 11942 if (ret == 0)
79741b3b 11943 ret = fixup_bpf_calls(env);
e245c5c6 11944
a4b1d3c1
JW
11945 /* do 32-bit optimization after insn patching has done so those patched
11946 * insns could be handled correctly.
11947 */
d6c2308c
JW
11948 if (ret == 0 && !bpf_prog_is_dev_bound(env->prog->aux)) {
11949 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
11950 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
11951 : false;
a4b1d3c1
JW
11952 }
11953
1ea47e01
AS
11954 if (ret == 0)
11955 ret = fixup_call_args(env);
11956
06ee7115
AS
11957 env->verification_time = ktime_get_ns() - start_time;
11958 print_verification_stats(env);
11959
a2a7d570 11960 if (log->level && bpf_verifier_log_full(log))
cbd35700 11961 ret = -ENOSPC;
a2a7d570 11962 if (log->level && !log->ubuf) {
cbd35700 11963 ret = -EFAULT;
a2a7d570 11964 goto err_release_maps;
cbd35700
AS
11965 }
11966
0246e64d
AS
11967 if (ret == 0 && env->used_map_cnt) {
11968 /* if program passed verifier, update used_maps in bpf_prog_info */
9bac3d6d
AS
11969 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
11970 sizeof(env->used_maps[0]),
11971 GFP_KERNEL);
0246e64d 11972
9bac3d6d 11973 if (!env->prog->aux->used_maps) {
0246e64d 11974 ret = -ENOMEM;
a2a7d570 11975 goto err_release_maps;
0246e64d
AS
11976 }
11977
9bac3d6d 11978 memcpy(env->prog->aux->used_maps, env->used_maps,
0246e64d 11979 sizeof(env->used_maps[0]) * env->used_map_cnt);
9bac3d6d 11980 env->prog->aux->used_map_cnt = env->used_map_cnt;
0246e64d
AS
11981
11982 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
11983 * bpf_ld_imm64 instructions
11984 */
11985 convert_pseudo_ld_imm64(env);
11986 }
cbd35700 11987
ba64e7d8
YS
11988 if (ret == 0)
11989 adjust_btf_func(env);
11990
a2a7d570 11991err_release_maps:
9bac3d6d 11992 if (!env->prog->aux->used_maps)
0246e64d 11993 /* if we didn't copy map pointers into bpf_prog_info, release
ab7f5bf0 11994 * them now. Otherwise free_used_maps() will release them.
0246e64d
AS
11995 */
11996 release_maps(env);
03f87c0b
THJ
11997
11998 /* extension progs temporarily inherit the attach_type of their targets
11999 for verification purposes, so set it back to zero before returning
12000 */
12001 if (env->prog->type == BPF_PROG_TYPE_EXT)
12002 env->prog->expected_attach_type = 0;
12003
9bac3d6d 12004 *prog = env->prog;
3df126f3 12005err_unlock:
45a73c17
AS
12006 if (!is_priv)
12007 mutex_unlock(&bpf_verifier_lock);
3df126f3
JK
12008 vfree(env->insn_aux_data);
12009err_free_env:
12010 kfree(env);
51580e79
AS
12011 return ret;
12012}