]> git.proxmox.com Git - mirror_ubuntu-jammy-kernel.git/blame - kernel/bpf/verifier.c
Merge git://git.kernel.org/pub/scm/linux/kernel/git/bpf/bpf-next
[mirror_ubuntu-jammy-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
b03c9f9f
EC
1013/* Mark the unknown part of a register (variable offset or scalar value) as
1014 * known to have the value @imm.
1015 */
1016static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1017{
a9c676bc
AS
1018 /* Clear id, off, and union(map_ptr, range) */
1019 memset(((u8 *)reg) + sizeof(reg->type), 0,
1020 offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
b03c9f9f
EC
1021 reg->var_off = tnum_const(imm);
1022 reg->smin_value = (s64)imm;
1023 reg->smax_value = (s64)imm;
1024 reg->umin_value = imm;
1025 reg->umax_value = imm;
3f50f132
JF
1026
1027 reg->s32_min_value = (s32)imm;
1028 reg->s32_max_value = (s32)imm;
1029 reg->u32_min_value = (u32)imm;
1030 reg->u32_max_value = (u32)imm;
1031}
1032
1033static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1034{
1035 reg->var_off = tnum_const_subreg(reg->var_off, imm);
1036 reg->s32_min_value = (s32)imm;
1037 reg->s32_max_value = (s32)imm;
1038 reg->u32_min_value = (u32)imm;
1039 reg->u32_max_value = (u32)imm;
b03c9f9f
EC
1040}
1041
f1174f77
EC
1042/* Mark the 'variable offset' part of a register as zero. This should be
1043 * used only on registers holding a pointer type.
1044 */
1045static void __mark_reg_known_zero(struct bpf_reg_state *reg)
a9789ef9 1046{
b03c9f9f 1047 __mark_reg_known(reg, 0);
f1174f77 1048}
a9789ef9 1049
cc2b14d5
AS
1050static void __mark_reg_const_zero(struct bpf_reg_state *reg)
1051{
1052 __mark_reg_known(reg, 0);
cc2b14d5
AS
1053 reg->type = SCALAR_VALUE;
1054}
1055
61bd5218
JK
1056static void mark_reg_known_zero(struct bpf_verifier_env *env,
1057 struct bpf_reg_state *regs, u32 regno)
f1174f77
EC
1058{
1059 if (WARN_ON(regno >= MAX_BPF_REG)) {
61bd5218 1060 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
f1174f77
EC
1061 /* Something bad happened, let's kill all regs */
1062 for (regno = 0; regno < MAX_BPF_REG; regno++)
f54c7898 1063 __mark_reg_not_init(env, regs + regno);
f1174f77
EC
1064 return;
1065 }
1066 __mark_reg_known_zero(regs + regno);
1067}
1068
de8f3a83
DB
1069static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1070{
1071 return type_is_pkt_pointer(reg->type);
1072}
1073
1074static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
1075{
1076 return reg_is_pkt_pointer(reg) ||
1077 reg->type == PTR_TO_PACKET_END;
1078}
1079
1080/* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
1081static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
1082 enum bpf_reg_type which)
1083{
1084 /* The register can already have a range from prior markings.
1085 * This is fine as long as it hasn't been advanced from its
1086 * origin.
1087 */
1088 return reg->type == which &&
1089 reg->id == 0 &&
1090 reg->off == 0 &&
1091 tnum_equals_const(reg->var_off, 0);
1092}
1093
3f50f132
JF
1094/* Reset the min/max bounds of a register */
1095static void __mark_reg_unbounded(struct bpf_reg_state *reg)
1096{
1097 reg->smin_value = S64_MIN;
1098 reg->smax_value = S64_MAX;
1099 reg->umin_value = 0;
1100 reg->umax_value = U64_MAX;
1101
1102 reg->s32_min_value = S32_MIN;
1103 reg->s32_max_value = S32_MAX;
1104 reg->u32_min_value = 0;
1105 reg->u32_max_value = U32_MAX;
1106}
1107
1108static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
1109{
1110 reg->smin_value = S64_MIN;
1111 reg->smax_value = S64_MAX;
1112 reg->umin_value = 0;
1113 reg->umax_value = U64_MAX;
1114}
1115
1116static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
1117{
1118 reg->s32_min_value = S32_MIN;
1119 reg->s32_max_value = S32_MAX;
1120 reg->u32_min_value = 0;
1121 reg->u32_max_value = U32_MAX;
1122}
1123
1124static void __update_reg32_bounds(struct bpf_reg_state *reg)
1125{
1126 struct tnum var32_off = tnum_subreg(reg->var_off);
1127
1128 /* min signed is max(sign bit) | min(other bits) */
1129 reg->s32_min_value = max_t(s32, reg->s32_min_value,
1130 var32_off.value | (var32_off.mask & S32_MIN));
1131 /* max signed is min(sign bit) | max(other bits) */
1132 reg->s32_max_value = min_t(s32, reg->s32_max_value,
1133 var32_off.value | (var32_off.mask & S32_MAX));
1134 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
1135 reg->u32_max_value = min(reg->u32_max_value,
1136 (u32)(var32_off.value | var32_off.mask));
1137}
1138
1139static void __update_reg64_bounds(struct bpf_reg_state *reg)
b03c9f9f
EC
1140{
1141 /* min signed is max(sign bit) | min(other bits) */
1142 reg->smin_value = max_t(s64, reg->smin_value,
1143 reg->var_off.value | (reg->var_off.mask & S64_MIN));
1144 /* max signed is min(sign bit) | max(other bits) */
1145 reg->smax_value = min_t(s64, reg->smax_value,
1146 reg->var_off.value | (reg->var_off.mask & S64_MAX));
1147 reg->umin_value = max(reg->umin_value, reg->var_off.value);
1148 reg->umax_value = min(reg->umax_value,
1149 reg->var_off.value | reg->var_off.mask);
1150}
1151
3f50f132
JF
1152static void __update_reg_bounds(struct bpf_reg_state *reg)
1153{
1154 __update_reg32_bounds(reg);
1155 __update_reg64_bounds(reg);
1156}
1157
b03c9f9f 1158/* Uses signed min/max values to inform unsigned, and vice-versa */
3f50f132
JF
1159static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
1160{
1161 /* Learn sign from signed bounds.
1162 * If we cannot cross the sign boundary, then signed and unsigned bounds
1163 * are the same, so combine. This works even in the negative case, e.g.
1164 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1165 */
1166 if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) {
1167 reg->s32_min_value = reg->u32_min_value =
1168 max_t(u32, reg->s32_min_value, reg->u32_min_value);
1169 reg->s32_max_value = reg->u32_max_value =
1170 min_t(u32, reg->s32_max_value, reg->u32_max_value);
1171 return;
1172 }
1173 /* Learn sign from unsigned bounds. Signed bounds cross the sign
1174 * boundary, so we must be careful.
1175 */
1176 if ((s32)reg->u32_max_value >= 0) {
1177 /* Positive. We can't learn anything from the smin, but smax
1178 * is positive, hence safe.
1179 */
1180 reg->s32_min_value = reg->u32_min_value;
1181 reg->s32_max_value = reg->u32_max_value =
1182 min_t(u32, reg->s32_max_value, reg->u32_max_value);
1183 } else if ((s32)reg->u32_min_value < 0) {
1184 /* Negative. We can't learn anything from the smax, but smin
1185 * is negative, hence safe.
1186 */
1187 reg->s32_min_value = reg->u32_min_value =
1188 max_t(u32, reg->s32_min_value, reg->u32_min_value);
1189 reg->s32_max_value = reg->u32_max_value;
1190 }
1191}
1192
1193static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
b03c9f9f
EC
1194{
1195 /* Learn sign from signed bounds.
1196 * If we cannot cross the sign boundary, then signed and unsigned bounds
1197 * are the same, so combine. This works even in the negative case, e.g.
1198 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1199 */
1200 if (reg->smin_value >= 0 || reg->smax_value < 0) {
1201 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1202 reg->umin_value);
1203 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1204 reg->umax_value);
1205 return;
1206 }
1207 /* Learn sign from unsigned bounds. Signed bounds cross the sign
1208 * boundary, so we must be careful.
1209 */
1210 if ((s64)reg->umax_value >= 0) {
1211 /* Positive. We can't learn anything from the smin, but smax
1212 * is positive, hence safe.
1213 */
1214 reg->smin_value = reg->umin_value;
1215 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1216 reg->umax_value);
1217 } else if ((s64)reg->umin_value < 0) {
1218 /* Negative. We can't learn anything from the smax, but smin
1219 * is negative, hence safe.
1220 */
1221 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1222 reg->umin_value);
1223 reg->smax_value = reg->umax_value;
1224 }
1225}
1226
3f50f132
JF
1227static void __reg_deduce_bounds(struct bpf_reg_state *reg)
1228{
1229 __reg32_deduce_bounds(reg);
1230 __reg64_deduce_bounds(reg);
1231}
1232
b03c9f9f
EC
1233/* Attempts to improve var_off based on unsigned min/max information */
1234static void __reg_bound_offset(struct bpf_reg_state *reg)
1235{
3f50f132
JF
1236 struct tnum var64_off = tnum_intersect(reg->var_off,
1237 tnum_range(reg->umin_value,
1238 reg->umax_value));
1239 struct tnum var32_off = tnum_intersect(tnum_subreg(reg->var_off),
1240 tnum_range(reg->u32_min_value,
1241 reg->u32_max_value));
1242
1243 reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
b03c9f9f
EC
1244}
1245
3f50f132 1246static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
b03c9f9f 1247{
3f50f132
JF
1248 reg->umin_value = reg->u32_min_value;
1249 reg->umax_value = reg->u32_max_value;
1250 /* Attempt to pull 32-bit signed bounds into 64-bit bounds
1251 * but must be positive otherwise set to worse case bounds
1252 * and refine later from tnum.
1253 */
3a71dc36 1254 if (reg->s32_min_value >= 0 && reg->s32_max_value >= 0)
3f50f132
JF
1255 reg->smax_value = reg->s32_max_value;
1256 else
1257 reg->smax_value = U32_MAX;
3a71dc36
JF
1258 if (reg->s32_min_value >= 0)
1259 reg->smin_value = reg->s32_min_value;
1260 else
1261 reg->smin_value = 0;
3f50f132
JF
1262}
1263
1264static void __reg_combine_32_into_64(struct bpf_reg_state *reg)
1265{
1266 /* special case when 64-bit register has upper 32-bit register
1267 * zeroed. Typically happens after zext or <<32, >>32 sequence
1268 * allowing us to use 32-bit bounds directly,
1269 */
1270 if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) {
1271 __reg_assign_32_into_64(reg);
1272 } else {
1273 /* Otherwise the best we can do is push lower 32bit known and
1274 * unknown bits into register (var_off set from jmp logic)
1275 * then learn as much as possible from the 64-bit tnum
1276 * known and unknown bits. The previous smin/smax bounds are
1277 * invalid here because of jmp32 compare so mark them unknown
1278 * so they do not impact tnum bounds calculation.
1279 */
1280 __mark_reg64_unbounded(reg);
1281 __update_reg_bounds(reg);
1282 }
1283
1284 /* Intersecting with the old var_off might have improved our bounds
1285 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1286 * then new var_off is (0; 0x7f...fc) which improves our umax.
1287 */
1288 __reg_deduce_bounds(reg);
1289 __reg_bound_offset(reg);
1290 __update_reg_bounds(reg);
1291}
1292
1293static bool __reg64_bound_s32(s64 a)
1294{
1295 if (a > S32_MIN && a < S32_MAX)
1296 return true;
1297 return false;
1298}
1299
1300static bool __reg64_bound_u32(u64 a)
1301{
1302 if (a > U32_MIN && a < U32_MAX)
1303 return true;
1304 return false;
1305}
1306
1307static void __reg_combine_64_into_32(struct bpf_reg_state *reg)
1308{
1309 __mark_reg32_unbounded(reg);
1310
1311 if (__reg64_bound_s32(reg->smin_value))
1312 reg->s32_min_value = (s32)reg->smin_value;
1313 if (__reg64_bound_s32(reg->smax_value))
1314 reg->s32_max_value = (s32)reg->smax_value;
1315 if (__reg64_bound_u32(reg->umin_value))
1316 reg->u32_min_value = (u32)reg->umin_value;
1317 if (__reg64_bound_u32(reg->umax_value))
1318 reg->u32_max_value = (u32)reg->umax_value;
1319
1320 /* Intersecting with the old var_off might have improved our bounds
1321 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1322 * then new var_off is (0; 0x7f...fc) which improves our umax.
1323 */
1324 __reg_deduce_bounds(reg);
1325 __reg_bound_offset(reg);
1326 __update_reg_bounds(reg);
b03c9f9f
EC
1327}
1328
f1174f77 1329/* Mark a register as having a completely unknown (scalar) value. */
f54c7898
DB
1330static void __mark_reg_unknown(const struct bpf_verifier_env *env,
1331 struct bpf_reg_state *reg)
f1174f77 1332{
a9c676bc
AS
1333 /*
1334 * Clear type, id, off, and union(map_ptr, range) and
1335 * padding between 'type' and union
1336 */
1337 memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
f1174f77 1338 reg->type = SCALAR_VALUE;
f1174f77 1339 reg->var_off = tnum_unknown;
f4d7e40a 1340 reg->frameno = 0;
2c78ee89 1341 reg->precise = env->subprog_cnt > 1 || !env->bpf_capable;
b03c9f9f 1342 __mark_reg_unbounded(reg);
f1174f77
EC
1343}
1344
61bd5218
JK
1345static void mark_reg_unknown(struct bpf_verifier_env *env,
1346 struct bpf_reg_state *regs, u32 regno)
f1174f77
EC
1347{
1348 if (WARN_ON(regno >= MAX_BPF_REG)) {
61bd5218 1349 verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
19ceb417
AS
1350 /* Something bad happened, let's kill all regs except FP */
1351 for (regno = 0; regno < BPF_REG_FP; regno++)
f54c7898 1352 __mark_reg_not_init(env, regs + regno);
f1174f77
EC
1353 return;
1354 }
f54c7898 1355 __mark_reg_unknown(env, regs + regno);
f1174f77
EC
1356}
1357
f54c7898
DB
1358static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1359 struct bpf_reg_state *reg)
f1174f77 1360{
f54c7898 1361 __mark_reg_unknown(env, reg);
f1174f77
EC
1362 reg->type = NOT_INIT;
1363}
1364
61bd5218
JK
1365static void mark_reg_not_init(struct bpf_verifier_env *env,
1366 struct bpf_reg_state *regs, u32 regno)
f1174f77
EC
1367{
1368 if (WARN_ON(regno >= MAX_BPF_REG)) {
61bd5218 1369 verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
19ceb417
AS
1370 /* Something bad happened, let's kill all regs except FP */
1371 for (regno = 0; regno < BPF_REG_FP; regno++)
f54c7898 1372 __mark_reg_not_init(env, regs + regno);
f1174f77
EC
1373 return;
1374 }
f54c7898 1375 __mark_reg_not_init(env, regs + regno);
a9789ef9
DB
1376}
1377
41c48f3a
AI
1378static void mark_btf_ld_reg(struct bpf_verifier_env *env,
1379 struct bpf_reg_state *regs, u32 regno,
1380 enum bpf_reg_type reg_type, u32 btf_id)
1381{
1382 if (reg_type == SCALAR_VALUE) {
1383 mark_reg_unknown(env, regs, regno);
1384 return;
1385 }
1386 mark_reg_known_zero(env, regs, regno);
1387 regs[regno].type = PTR_TO_BTF_ID;
1388 regs[regno].btf_id = btf_id;
1389}
1390
5327ed3d 1391#define DEF_NOT_SUBREG (0)
61bd5218 1392static void init_reg_state(struct bpf_verifier_env *env,
f4d7e40a 1393 struct bpf_func_state *state)
17a52670 1394{
f4d7e40a 1395 struct bpf_reg_state *regs = state->regs;
17a52670
AS
1396 int i;
1397
dc503a8a 1398 for (i = 0; i < MAX_BPF_REG; i++) {
61bd5218 1399 mark_reg_not_init(env, regs, i);
dc503a8a 1400 regs[i].live = REG_LIVE_NONE;
679c782d 1401 regs[i].parent = NULL;
5327ed3d 1402 regs[i].subreg_def = DEF_NOT_SUBREG;
dc503a8a 1403 }
17a52670
AS
1404
1405 /* frame pointer */
f1174f77 1406 regs[BPF_REG_FP].type = PTR_TO_STACK;
61bd5218 1407 mark_reg_known_zero(env, regs, BPF_REG_FP);
f4d7e40a 1408 regs[BPF_REG_FP].frameno = state->frameno;
6760bf2d
DB
1409}
1410
f4d7e40a
AS
1411#define BPF_MAIN_FUNC (-1)
1412static void init_func_state(struct bpf_verifier_env *env,
1413 struct bpf_func_state *state,
1414 int callsite, int frameno, int subprogno)
1415{
1416 state->callsite = callsite;
1417 state->frameno = frameno;
1418 state->subprogno = subprogno;
1419 init_reg_state(env, state);
1420}
1421
17a52670
AS
1422enum reg_arg_type {
1423 SRC_OP, /* register is used as source operand */
1424 DST_OP, /* register is used as destination operand */
1425 DST_OP_NO_MARK /* same as above, check only, don't mark */
1426};
1427
cc8b0b92
AS
1428static int cmp_subprogs(const void *a, const void *b)
1429{
9c8105bd
JW
1430 return ((struct bpf_subprog_info *)a)->start -
1431 ((struct bpf_subprog_info *)b)->start;
cc8b0b92
AS
1432}
1433
1434static int find_subprog(struct bpf_verifier_env *env, int off)
1435{
9c8105bd 1436 struct bpf_subprog_info *p;
cc8b0b92 1437
9c8105bd
JW
1438 p = bsearch(&off, env->subprog_info, env->subprog_cnt,
1439 sizeof(env->subprog_info[0]), cmp_subprogs);
cc8b0b92
AS
1440 if (!p)
1441 return -ENOENT;
9c8105bd 1442 return p - env->subprog_info;
cc8b0b92
AS
1443
1444}
1445
1446static int add_subprog(struct bpf_verifier_env *env, int off)
1447{
1448 int insn_cnt = env->prog->len;
1449 int ret;
1450
1451 if (off >= insn_cnt || off < 0) {
1452 verbose(env, "call to invalid destination\n");
1453 return -EINVAL;
1454 }
1455 ret = find_subprog(env, off);
1456 if (ret >= 0)
1457 return 0;
4cb3d99c 1458 if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
cc8b0b92
AS
1459 verbose(env, "too many subprograms\n");
1460 return -E2BIG;
1461 }
9c8105bd
JW
1462 env->subprog_info[env->subprog_cnt++].start = off;
1463 sort(env->subprog_info, env->subprog_cnt,
1464 sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
cc8b0b92
AS
1465 return 0;
1466}
1467
1468static int check_subprogs(struct bpf_verifier_env *env)
1469{
1470 int i, ret, subprog_start, subprog_end, off, cur_subprog = 0;
9c8105bd 1471 struct bpf_subprog_info *subprog = env->subprog_info;
cc8b0b92
AS
1472 struct bpf_insn *insn = env->prog->insnsi;
1473 int insn_cnt = env->prog->len;
1474
f910cefa
JW
1475 /* Add entry function. */
1476 ret = add_subprog(env, 0);
1477 if (ret < 0)
1478 return ret;
1479
cc8b0b92
AS
1480 /* determine subprog starts. The end is one before the next starts */
1481 for (i = 0; i < insn_cnt; i++) {
1482 if (insn[i].code != (BPF_JMP | BPF_CALL))
1483 continue;
1484 if (insn[i].src_reg != BPF_PSEUDO_CALL)
1485 continue;
2c78ee89
AS
1486 if (!env->bpf_capable) {
1487 verbose(env,
1488 "function calls to other bpf functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
cc8b0b92
AS
1489 return -EPERM;
1490 }
cc8b0b92
AS
1491 ret = add_subprog(env, i + insn[i].imm + 1);
1492 if (ret < 0)
1493 return ret;
1494 }
1495
4cb3d99c
JW
1496 /* Add a fake 'exit' subprog which could simplify subprog iteration
1497 * logic. 'subprog_cnt' should not be increased.
1498 */
1499 subprog[env->subprog_cnt].start = insn_cnt;
1500
06ee7115 1501 if (env->log.level & BPF_LOG_LEVEL2)
cc8b0b92 1502 for (i = 0; i < env->subprog_cnt; i++)
9c8105bd 1503 verbose(env, "func#%d @%d\n", i, subprog[i].start);
cc8b0b92
AS
1504
1505 /* now check that all jumps are within the same subprog */
4cb3d99c
JW
1506 subprog_start = subprog[cur_subprog].start;
1507 subprog_end = subprog[cur_subprog + 1].start;
cc8b0b92
AS
1508 for (i = 0; i < insn_cnt; i++) {
1509 u8 code = insn[i].code;
1510
7f6e4312
MF
1511 if (code == (BPF_JMP | BPF_CALL) &&
1512 insn[i].imm == BPF_FUNC_tail_call &&
1513 insn[i].src_reg != BPF_PSEUDO_CALL)
1514 subprog[cur_subprog].has_tail_call = true;
09b28d76
AS
1515 if (BPF_CLASS(code) == BPF_LD &&
1516 (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
1517 subprog[cur_subprog].has_ld_abs = true;
092ed096 1518 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
cc8b0b92
AS
1519 goto next;
1520 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
1521 goto next;
1522 off = i + insn[i].off + 1;
1523 if (off < subprog_start || off >= subprog_end) {
1524 verbose(env, "jump out of range from insn %d to %d\n", i, off);
1525 return -EINVAL;
1526 }
1527next:
1528 if (i == subprog_end - 1) {
1529 /* to avoid fall-through from one subprog into another
1530 * the last insn of the subprog should be either exit
1531 * or unconditional jump back
1532 */
1533 if (code != (BPF_JMP | BPF_EXIT) &&
1534 code != (BPF_JMP | BPF_JA)) {
1535 verbose(env, "last insn is not an exit or jmp\n");
1536 return -EINVAL;
1537 }
1538 subprog_start = subprog_end;
4cb3d99c
JW
1539 cur_subprog++;
1540 if (cur_subprog < env->subprog_cnt)
9c8105bd 1541 subprog_end = subprog[cur_subprog + 1].start;
cc8b0b92
AS
1542 }
1543 }
1544 return 0;
1545}
1546
679c782d
EC
1547/* Parentage chain of this register (or stack slot) should take care of all
1548 * issues like callee-saved registers, stack slot allocation time, etc.
1549 */
f4d7e40a 1550static int mark_reg_read(struct bpf_verifier_env *env,
679c782d 1551 const struct bpf_reg_state *state,
5327ed3d 1552 struct bpf_reg_state *parent, u8 flag)
f4d7e40a
AS
1553{
1554 bool writes = parent == state->parent; /* Observe write marks */
06ee7115 1555 int cnt = 0;
dc503a8a
EC
1556
1557 while (parent) {
1558 /* if read wasn't screened by an earlier write ... */
679c782d 1559 if (writes && state->live & REG_LIVE_WRITTEN)
dc503a8a 1560 break;
9242b5f5
AS
1561 if (parent->live & REG_LIVE_DONE) {
1562 verbose(env, "verifier BUG type %s var_off %lld off %d\n",
1563 reg_type_str[parent->type],
1564 parent->var_off.value, parent->off);
1565 return -EFAULT;
1566 }
5327ed3d
JW
1567 /* The first condition is more likely to be true than the
1568 * second, checked it first.
1569 */
1570 if ((parent->live & REG_LIVE_READ) == flag ||
1571 parent->live & REG_LIVE_READ64)
25af32da
AS
1572 /* The parentage chain never changes and
1573 * this parent was already marked as LIVE_READ.
1574 * There is no need to keep walking the chain again and
1575 * keep re-marking all parents as LIVE_READ.
1576 * This case happens when the same register is read
1577 * multiple times without writes into it in-between.
5327ed3d
JW
1578 * Also, if parent has the stronger REG_LIVE_READ64 set,
1579 * then no need to set the weak REG_LIVE_READ32.
25af32da
AS
1580 */
1581 break;
dc503a8a 1582 /* ... then we depend on parent's value */
5327ed3d
JW
1583 parent->live |= flag;
1584 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
1585 if (flag == REG_LIVE_READ64)
1586 parent->live &= ~REG_LIVE_READ32;
dc503a8a
EC
1587 state = parent;
1588 parent = state->parent;
f4d7e40a 1589 writes = true;
06ee7115 1590 cnt++;
dc503a8a 1591 }
06ee7115
AS
1592
1593 if (env->longest_mark_read_walk < cnt)
1594 env->longest_mark_read_walk = cnt;
f4d7e40a 1595 return 0;
dc503a8a
EC
1596}
1597
5327ed3d
JW
1598/* This function is supposed to be used by the following 32-bit optimization
1599 * code only. It returns TRUE if the source or destination register operates
1600 * on 64-bit, otherwise return FALSE.
1601 */
1602static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
1603 u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
1604{
1605 u8 code, class, op;
1606
1607 code = insn->code;
1608 class = BPF_CLASS(code);
1609 op = BPF_OP(code);
1610 if (class == BPF_JMP) {
1611 /* BPF_EXIT for "main" will reach here. Return TRUE
1612 * conservatively.
1613 */
1614 if (op == BPF_EXIT)
1615 return true;
1616 if (op == BPF_CALL) {
1617 /* BPF to BPF call will reach here because of marking
1618 * caller saved clobber with DST_OP_NO_MARK for which we
1619 * don't care the register def because they are anyway
1620 * marked as NOT_INIT already.
1621 */
1622 if (insn->src_reg == BPF_PSEUDO_CALL)
1623 return false;
1624 /* Helper call will reach here because of arg type
1625 * check, conservatively return TRUE.
1626 */
1627 if (t == SRC_OP)
1628 return true;
1629
1630 return false;
1631 }
1632 }
1633
1634 if (class == BPF_ALU64 || class == BPF_JMP ||
1635 /* BPF_END always use BPF_ALU class. */
1636 (class == BPF_ALU && op == BPF_END && insn->imm == 64))
1637 return true;
1638
1639 if (class == BPF_ALU || class == BPF_JMP32)
1640 return false;
1641
1642 if (class == BPF_LDX) {
1643 if (t != SRC_OP)
1644 return BPF_SIZE(code) == BPF_DW;
1645 /* LDX source must be ptr. */
1646 return true;
1647 }
1648
1649 if (class == BPF_STX) {
1650 if (reg->type != SCALAR_VALUE)
1651 return true;
1652 return BPF_SIZE(code) == BPF_DW;
1653 }
1654
1655 if (class == BPF_LD) {
1656 u8 mode = BPF_MODE(code);
1657
1658 /* LD_IMM64 */
1659 if (mode == BPF_IMM)
1660 return true;
1661
1662 /* Both LD_IND and LD_ABS return 32-bit data. */
1663 if (t != SRC_OP)
1664 return false;
1665
1666 /* Implicit ctx ptr. */
1667 if (regno == BPF_REG_6)
1668 return true;
1669
1670 /* Explicit source could be any width. */
1671 return true;
1672 }
1673
1674 if (class == BPF_ST)
1675 /* The only source register for BPF_ST is a ptr. */
1676 return true;
1677
1678 /* Conservatively return true at default. */
1679 return true;
1680}
1681
b325fbca
JW
1682/* Return TRUE if INSN doesn't have explicit value define. */
1683static bool insn_no_def(struct bpf_insn *insn)
1684{
1685 u8 class = BPF_CLASS(insn->code);
1686
1687 return (class == BPF_JMP || class == BPF_JMP32 ||
1688 class == BPF_STX || class == BPF_ST);
1689}
1690
1691/* Return TRUE if INSN has defined any 32-bit value explicitly. */
1692static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
1693{
1694 if (insn_no_def(insn))
1695 return false;
1696
1697 return !is_reg64(env, insn, insn->dst_reg, NULL, DST_OP);
1698}
1699
5327ed3d
JW
1700static void mark_insn_zext(struct bpf_verifier_env *env,
1701 struct bpf_reg_state *reg)
1702{
1703 s32 def_idx = reg->subreg_def;
1704
1705 if (def_idx == DEF_NOT_SUBREG)
1706 return;
1707
1708 env->insn_aux_data[def_idx - 1].zext_dst = true;
1709 /* The dst will be zero extended, so won't be sub-register anymore. */
1710 reg->subreg_def = DEF_NOT_SUBREG;
1711}
1712
dc503a8a 1713static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
17a52670
AS
1714 enum reg_arg_type t)
1715{
f4d7e40a
AS
1716 struct bpf_verifier_state *vstate = env->cur_state;
1717 struct bpf_func_state *state = vstate->frame[vstate->curframe];
5327ed3d 1718 struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
c342dc10 1719 struct bpf_reg_state *reg, *regs = state->regs;
5327ed3d 1720 bool rw64;
dc503a8a 1721
17a52670 1722 if (regno >= MAX_BPF_REG) {
61bd5218 1723 verbose(env, "R%d is invalid\n", regno);
17a52670
AS
1724 return -EINVAL;
1725 }
1726
c342dc10 1727 reg = &regs[regno];
5327ed3d 1728 rw64 = is_reg64(env, insn, regno, reg, t);
17a52670
AS
1729 if (t == SRC_OP) {
1730 /* check whether register used as source operand can be read */
c342dc10 1731 if (reg->type == NOT_INIT) {
61bd5218 1732 verbose(env, "R%d !read_ok\n", regno);
17a52670
AS
1733 return -EACCES;
1734 }
679c782d 1735 /* We don't need to worry about FP liveness because it's read-only */
c342dc10
JW
1736 if (regno == BPF_REG_FP)
1737 return 0;
1738
5327ed3d
JW
1739 if (rw64)
1740 mark_insn_zext(env, reg);
1741
1742 return mark_reg_read(env, reg, reg->parent,
1743 rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
17a52670
AS
1744 } else {
1745 /* check whether register used as dest operand can be written to */
1746 if (regno == BPF_REG_FP) {
61bd5218 1747 verbose(env, "frame pointer is read only\n");
17a52670
AS
1748 return -EACCES;
1749 }
c342dc10 1750 reg->live |= REG_LIVE_WRITTEN;
5327ed3d 1751 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
17a52670 1752 if (t == DST_OP)
61bd5218 1753 mark_reg_unknown(env, regs, regno);
17a52670
AS
1754 }
1755 return 0;
1756}
1757
b5dc0163
AS
1758/* for any branch, call, exit record the history of jmps in the given state */
1759static int push_jmp_history(struct bpf_verifier_env *env,
1760 struct bpf_verifier_state *cur)
1761{
1762 u32 cnt = cur->jmp_history_cnt;
1763 struct bpf_idx_pair *p;
1764
1765 cnt++;
1766 p = krealloc(cur->jmp_history, cnt * sizeof(*p), GFP_USER);
1767 if (!p)
1768 return -ENOMEM;
1769 p[cnt - 1].idx = env->insn_idx;
1770 p[cnt - 1].prev_idx = env->prev_insn_idx;
1771 cur->jmp_history = p;
1772 cur->jmp_history_cnt = cnt;
1773 return 0;
1774}
1775
1776/* Backtrack one insn at a time. If idx is not at the top of recorded
1777 * history then previous instruction came from straight line execution.
1778 */
1779static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
1780 u32 *history)
1781{
1782 u32 cnt = *history;
1783
1784 if (cnt && st->jmp_history[cnt - 1].idx == i) {
1785 i = st->jmp_history[cnt - 1].prev_idx;
1786 (*history)--;
1787 } else {
1788 i--;
1789 }
1790 return i;
1791}
1792
1793/* For given verifier state backtrack_insn() is called from the last insn to
1794 * the first insn. Its purpose is to compute a bitmask of registers and
1795 * stack slots that needs precision in the parent verifier state.
1796 */
1797static int backtrack_insn(struct bpf_verifier_env *env, int idx,
1798 u32 *reg_mask, u64 *stack_mask)
1799{
1800 const struct bpf_insn_cbs cbs = {
1801 .cb_print = verbose,
1802 .private_data = env,
1803 };
1804 struct bpf_insn *insn = env->prog->insnsi + idx;
1805 u8 class = BPF_CLASS(insn->code);
1806 u8 opcode = BPF_OP(insn->code);
1807 u8 mode = BPF_MODE(insn->code);
1808 u32 dreg = 1u << insn->dst_reg;
1809 u32 sreg = 1u << insn->src_reg;
1810 u32 spi;
1811
1812 if (insn->code == 0)
1813 return 0;
1814 if (env->log.level & BPF_LOG_LEVEL) {
1815 verbose(env, "regs=%x stack=%llx before ", *reg_mask, *stack_mask);
1816 verbose(env, "%d: ", idx);
1817 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
1818 }
1819
1820 if (class == BPF_ALU || class == BPF_ALU64) {
1821 if (!(*reg_mask & dreg))
1822 return 0;
1823 if (opcode == BPF_MOV) {
1824 if (BPF_SRC(insn->code) == BPF_X) {
1825 /* dreg = sreg
1826 * dreg needs precision after this insn
1827 * sreg needs precision before this insn
1828 */
1829 *reg_mask &= ~dreg;
1830 *reg_mask |= sreg;
1831 } else {
1832 /* dreg = K
1833 * dreg needs precision after this insn.
1834 * Corresponding register is already marked
1835 * as precise=true in this verifier state.
1836 * No further markings in parent are necessary
1837 */
1838 *reg_mask &= ~dreg;
1839 }
1840 } else {
1841 if (BPF_SRC(insn->code) == BPF_X) {
1842 /* dreg += sreg
1843 * both dreg and sreg need precision
1844 * before this insn
1845 */
1846 *reg_mask |= sreg;
1847 } /* else dreg += K
1848 * dreg still needs precision before this insn
1849 */
1850 }
1851 } else if (class == BPF_LDX) {
1852 if (!(*reg_mask & dreg))
1853 return 0;
1854 *reg_mask &= ~dreg;
1855
1856 /* scalars can only be spilled into stack w/o losing precision.
1857 * Load from any other memory can be zero extended.
1858 * The desire to keep that precision is already indicated
1859 * by 'precise' mark in corresponding register of this state.
1860 * No further tracking necessary.
1861 */
1862 if (insn->src_reg != BPF_REG_FP)
1863 return 0;
1864 if (BPF_SIZE(insn->code) != BPF_DW)
1865 return 0;
1866
1867 /* dreg = *(u64 *)[fp - off] was a fill from the stack.
1868 * that [fp - off] slot contains scalar that needs to be
1869 * tracked with precision
1870 */
1871 spi = (-insn->off - 1) / BPF_REG_SIZE;
1872 if (spi >= 64) {
1873 verbose(env, "BUG spi %d\n", spi);
1874 WARN_ONCE(1, "verifier backtracking bug");
1875 return -EFAULT;
1876 }
1877 *stack_mask |= 1ull << spi;
b3b50f05 1878 } else if (class == BPF_STX || class == BPF_ST) {
b5dc0163 1879 if (*reg_mask & dreg)
b3b50f05 1880 /* stx & st shouldn't be using _scalar_ dst_reg
b5dc0163
AS
1881 * to access memory. It means backtracking
1882 * encountered a case of pointer subtraction.
1883 */
1884 return -ENOTSUPP;
1885 /* scalars can only be spilled into stack */
1886 if (insn->dst_reg != BPF_REG_FP)
1887 return 0;
1888 if (BPF_SIZE(insn->code) != BPF_DW)
1889 return 0;
1890 spi = (-insn->off - 1) / BPF_REG_SIZE;
1891 if (spi >= 64) {
1892 verbose(env, "BUG spi %d\n", spi);
1893 WARN_ONCE(1, "verifier backtracking bug");
1894 return -EFAULT;
1895 }
1896 if (!(*stack_mask & (1ull << spi)))
1897 return 0;
1898 *stack_mask &= ~(1ull << spi);
b3b50f05
AN
1899 if (class == BPF_STX)
1900 *reg_mask |= sreg;
b5dc0163
AS
1901 } else if (class == BPF_JMP || class == BPF_JMP32) {
1902 if (opcode == BPF_CALL) {
1903 if (insn->src_reg == BPF_PSEUDO_CALL)
1904 return -ENOTSUPP;
1905 /* regular helper call sets R0 */
1906 *reg_mask &= ~1;
1907 if (*reg_mask & 0x3f) {
1908 /* if backtracing was looking for registers R1-R5
1909 * they should have been found already.
1910 */
1911 verbose(env, "BUG regs %x\n", *reg_mask);
1912 WARN_ONCE(1, "verifier backtracking bug");
1913 return -EFAULT;
1914 }
1915 } else if (opcode == BPF_EXIT) {
1916 return -ENOTSUPP;
1917 }
1918 } else if (class == BPF_LD) {
1919 if (!(*reg_mask & dreg))
1920 return 0;
1921 *reg_mask &= ~dreg;
1922 /* It's ld_imm64 or ld_abs or ld_ind.
1923 * For ld_imm64 no further tracking of precision
1924 * into parent is necessary
1925 */
1926 if (mode == BPF_IND || mode == BPF_ABS)
1927 /* to be analyzed */
1928 return -ENOTSUPP;
b5dc0163
AS
1929 }
1930 return 0;
1931}
1932
1933/* the scalar precision tracking algorithm:
1934 * . at the start all registers have precise=false.
1935 * . scalar ranges are tracked as normal through alu and jmp insns.
1936 * . once precise value of the scalar register is used in:
1937 * . ptr + scalar alu
1938 * . if (scalar cond K|scalar)
1939 * . helper_call(.., scalar, ...) where ARG_CONST is expected
1940 * backtrack through the verifier states and mark all registers and
1941 * stack slots with spilled constants that these scalar regisers
1942 * should be precise.
1943 * . during state pruning two registers (or spilled stack slots)
1944 * are equivalent if both are not precise.
1945 *
1946 * Note the verifier cannot simply walk register parentage chain,
1947 * since many different registers and stack slots could have been
1948 * used to compute single precise scalar.
1949 *
1950 * The approach of starting with precise=true for all registers and then
1951 * backtrack to mark a register as not precise when the verifier detects
1952 * that program doesn't care about specific value (e.g., when helper
1953 * takes register as ARG_ANYTHING parameter) is not safe.
1954 *
1955 * It's ok to walk single parentage chain of the verifier states.
1956 * It's possible that this backtracking will go all the way till 1st insn.
1957 * All other branches will be explored for needing precision later.
1958 *
1959 * The backtracking needs to deal with cases like:
1960 * 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)
1961 * r9 -= r8
1962 * r5 = r9
1963 * if r5 > 0x79f goto pc+7
1964 * R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
1965 * r5 += 1
1966 * ...
1967 * call bpf_perf_event_output#25
1968 * where .arg5_type = ARG_CONST_SIZE_OR_ZERO
1969 *
1970 * and this case:
1971 * r6 = 1
1972 * call foo // uses callee's r6 inside to compute r0
1973 * r0 += r6
1974 * if r0 == 0 goto
1975 *
1976 * to track above reg_mask/stack_mask needs to be independent for each frame.
1977 *
1978 * Also if parent's curframe > frame where backtracking started,
1979 * the verifier need to mark registers in both frames, otherwise callees
1980 * may incorrectly prune callers. This is similar to
1981 * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
1982 *
1983 * For now backtracking falls back into conservative marking.
1984 */
1985static void mark_all_scalars_precise(struct bpf_verifier_env *env,
1986 struct bpf_verifier_state *st)
1987{
1988 struct bpf_func_state *func;
1989 struct bpf_reg_state *reg;
1990 int i, j;
1991
1992 /* big hammer: mark all scalars precise in this path.
1993 * pop_stack may still get !precise scalars.
1994 */
1995 for (; st; st = st->parent)
1996 for (i = 0; i <= st->curframe; i++) {
1997 func = st->frame[i];
1998 for (j = 0; j < BPF_REG_FP; j++) {
1999 reg = &func->regs[j];
2000 if (reg->type != SCALAR_VALUE)
2001 continue;
2002 reg->precise = true;
2003 }
2004 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
2005 if (func->stack[j].slot_type[0] != STACK_SPILL)
2006 continue;
2007 reg = &func->stack[j].spilled_ptr;
2008 if (reg->type != SCALAR_VALUE)
2009 continue;
2010 reg->precise = true;
2011 }
2012 }
2013}
2014
a3ce685d
AS
2015static int __mark_chain_precision(struct bpf_verifier_env *env, int regno,
2016 int spi)
b5dc0163
AS
2017{
2018 struct bpf_verifier_state *st = env->cur_state;
2019 int first_idx = st->first_insn_idx;
2020 int last_idx = env->insn_idx;
2021 struct bpf_func_state *func;
2022 struct bpf_reg_state *reg;
a3ce685d
AS
2023 u32 reg_mask = regno >= 0 ? 1u << regno : 0;
2024 u64 stack_mask = spi >= 0 ? 1ull << spi : 0;
b5dc0163 2025 bool skip_first = true;
a3ce685d 2026 bool new_marks = false;
b5dc0163
AS
2027 int i, err;
2028
2c78ee89 2029 if (!env->bpf_capable)
b5dc0163
AS
2030 return 0;
2031
2032 func = st->frame[st->curframe];
a3ce685d
AS
2033 if (regno >= 0) {
2034 reg = &func->regs[regno];
2035 if (reg->type != SCALAR_VALUE) {
2036 WARN_ONCE(1, "backtracing misuse");
2037 return -EFAULT;
2038 }
2039 if (!reg->precise)
2040 new_marks = true;
2041 else
2042 reg_mask = 0;
2043 reg->precise = true;
b5dc0163 2044 }
b5dc0163 2045
a3ce685d
AS
2046 while (spi >= 0) {
2047 if (func->stack[spi].slot_type[0] != STACK_SPILL) {
2048 stack_mask = 0;
2049 break;
2050 }
2051 reg = &func->stack[spi].spilled_ptr;
2052 if (reg->type != SCALAR_VALUE) {
2053 stack_mask = 0;
2054 break;
2055 }
2056 if (!reg->precise)
2057 new_marks = true;
2058 else
2059 stack_mask = 0;
2060 reg->precise = true;
2061 break;
2062 }
2063
2064 if (!new_marks)
2065 return 0;
2066 if (!reg_mask && !stack_mask)
2067 return 0;
b5dc0163
AS
2068 for (;;) {
2069 DECLARE_BITMAP(mask, 64);
b5dc0163
AS
2070 u32 history = st->jmp_history_cnt;
2071
2072 if (env->log.level & BPF_LOG_LEVEL)
2073 verbose(env, "last_idx %d first_idx %d\n", last_idx, first_idx);
2074 for (i = last_idx;;) {
2075 if (skip_first) {
2076 err = 0;
2077 skip_first = false;
2078 } else {
2079 err = backtrack_insn(env, i, &reg_mask, &stack_mask);
2080 }
2081 if (err == -ENOTSUPP) {
2082 mark_all_scalars_precise(env, st);
2083 return 0;
2084 } else if (err) {
2085 return err;
2086 }
2087 if (!reg_mask && !stack_mask)
2088 /* Found assignment(s) into tracked register in this state.
2089 * Since this state is already marked, just return.
2090 * Nothing to be tracked further in the parent state.
2091 */
2092 return 0;
2093 if (i == first_idx)
2094 break;
2095 i = get_prev_insn_idx(st, i, &history);
2096 if (i >= env->prog->len) {
2097 /* This can happen if backtracking reached insn 0
2098 * and there are still reg_mask or stack_mask
2099 * to backtrack.
2100 * It means the backtracking missed the spot where
2101 * particular register was initialized with a constant.
2102 */
2103 verbose(env, "BUG backtracking idx %d\n", i);
2104 WARN_ONCE(1, "verifier backtracking bug");
2105 return -EFAULT;
2106 }
2107 }
2108 st = st->parent;
2109 if (!st)
2110 break;
2111
a3ce685d 2112 new_marks = false;
b5dc0163
AS
2113 func = st->frame[st->curframe];
2114 bitmap_from_u64(mask, reg_mask);
2115 for_each_set_bit(i, mask, 32) {
2116 reg = &func->regs[i];
a3ce685d
AS
2117 if (reg->type != SCALAR_VALUE) {
2118 reg_mask &= ~(1u << i);
b5dc0163 2119 continue;
a3ce685d 2120 }
b5dc0163
AS
2121 if (!reg->precise)
2122 new_marks = true;
2123 reg->precise = true;
2124 }
2125
2126 bitmap_from_u64(mask, stack_mask);
2127 for_each_set_bit(i, mask, 64) {
2128 if (i >= func->allocated_stack / BPF_REG_SIZE) {
2339cd6c
AS
2129 /* the sequence of instructions:
2130 * 2: (bf) r3 = r10
2131 * 3: (7b) *(u64 *)(r3 -8) = r0
2132 * 4: (79) r4 = *(u64 *)(r10 -8)
2133 * doesn't contain jmps. It's backtracked
2134 * as a single block.
2135 * During backtracking insn 3 is not recognized as
2136 * stack access, so at the end of backtracking
2137 * stack slot fp-8 is still marked in stack_mask.
2138 * However the parent state may not have accessed
2139 * fp-8 and it's "unallocated" stack space.
2140 * In such case fallback to conservative.
b5dc0163 2141 */
2339cd6c
AS
2142 mark_all_scalars_precise(env, st);
2143 return 0;
b5dc0163
AS
2144 }
2145
a3ce685d
AS
2146 if (func->stack[i].slot_type[0] != STACK_SPILL) {
2147 stack_mask &= ~(1ull << i);
b5dc0163 2148 continue;
a3ce685d 2149 }
b5dc0163 2150 reg = &func->stack[i].spilled_ptr;
a3ce685d
AS
2151 if (reg->type != SCALAR_VALUE) {
2152 stack_mask &= ~(1ull << i);
b5dc0163 2153 continue;
a3ce685d 2154 }
b5dc0163
AS
2155 if (!reg->precise)
2156 new_marks = true;
2157 reg->precise = true;
2158 }
2159 if (env->log.level & BPF_LOG_LEVEL) {
2160 print_verifier_state(env, func);
2161 verbose(env, "parent %s regs=%x stack=%llx marks\n",
2162 new_marks ? "didn't have" : "already had",
2163 reg_mask, stack_mask);
2164 }
2165
a3ce685d
AS
2166 if (!reg_mask && !stack_mask)
2167 break;
b5dc0163
AS
2168 if (!new_marks)
2169 break;
2170
2171 last_idx = st->last_insn_idx;
2172 first_idx = st->first_insn_idx;
2173 }
2174 return 0;
2175}
2176
a3ce685d
AS
2177static int mark_chain_precision(struct bpf_verifier_env *env, int regno)
2178{
2179 return __mark_chain_precision(env, regno, -1);
2180}
2181
2182static int mark_chain_precision_stack(struct bpf_verifier_env *env, int spi)
2183{
2184 return __mark_chain_precision(env, -1, spi);
2185}
b5dc0163 2186
1be7f75d
AS
2187static bool is_spillable_regtype(enum bpf_reg_type type)
2188{
2189 switch (type) {
2190 case PTR_TO_MAP_VALUE:
2191 case PTR_TO_MAP_VALUE_OR_NULL:
2192 case PTR_TO_STACK:
2193 case PTR_TO_CTX:
969bf05e 2194 case PTR_TO_PACKET:
de8f3a83 2195 case PTR_TO_PACKET_META:
969bf05e 2196 case PTR_TO_PACKET_END:
d58e468b 2197 case PTR_TO_FLOW_KEYS:
1be7f75d 2198 case CONST_PTR_TO_MAP:
c64b7983
JS
2199 case PTR_TO_SOCKET:
2200 case PTR_TO_SOCKET_OR_NULL:
46f8bc92
MKL
2201 case PTR_TO_SOCK_COMMON:
2202 case PTR_TO_SOCK_COMMON_OR_NULL:
655a51e5
MKL
2203 case PTR_TO_TCP_SOCK:
2204 case PTR_TO_TCP_SOCK_OR_NULL:
fada7fdc 2205 case PTR_TO_XDP_SOCK:
65726b5b 2206 case PTR_TO_BTF_ID:
b121b341 2207 case PTR_TO_BTF_ID_OR_NULL:
afbf21dc
YS
2208 case PTR_TO_RDONLY_BUF:
2209 case PTR_TO_RDONLY_BUF_OR_NULL:
2210 case PTR_TO_RDWR_BUF:
2211 case PTR_TO_RDWR_BUF_OR_NULL:
eaa6bcb7 2212 case PTR_TO_PERCPU_BTF_ID:
1be7f75d
AS
2213 return true;
2214 default:
2215 return false;
2216 }
2217}
2218
cc2b14d5
AS
2219/* Does this register contain a constant zero? */
2220static bool register_is_null(struct bpf_reg_state *reg)
2221{
2222 return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
2223}
2224
f7cf25b2
AS
2225static bool register_is_const(struct bpf_reg_state *reg)
2226{
2227 return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
2228}
2229
5689d49b
YS
2230static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
2231{
2232 return tnum_is_unknown(reg->var_off) &&
2233 reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
2234 reg->umin_value == 0 && reg->umax_value == U64_MAX &&
2235 reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
2236 reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
2237}
2238
2239static bool register_is_bounded(struct bpf_reg_state *reg)
2240{
2241 return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
2242}
2243
6e7e63cb
JH
2244static bool __is_pointer_value(bool allow_ptr_leaks,
2245 const struct bpf_reg_state *reg)
2246{
2247 if (allow_ptr_leaks)
2248 return false;
2249
2250 return reg->type != SCALAR_VALUE;
2251}
2252
f7cf25b2
AS
2253static void save_register_state(struct bpf_func_state *state,
2254 int spi, struct bpf_reg_state *reg)
2255{
2256 int i;
2257
2258 state->stack[spi].spilled_ptr = *reg;
2259 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
2260
2261 for (i = 0; i < BPF_REG_SIZE; i++)
2262 state->stack[spi].slot_type[i] = STACK_SPILL;
2263}
2264
17a52670
AS
2265/* check_stack_read/write functions track spill/fill of registers,
2266 * stack boundary and alignment are checked in check_mem_access()
2267 */
61bd5218 2268static int check_stack_write(struct bpf_verifier_env *env,
f4d7e40a 2269 struct bpf_func_state *state, /* func where register points to */
af86ca4e 2270 int off, int size, int value_regno, int insn_idx)
17a52670 2271{
f4d7e40a 2272 struct bpf_func_state *cur; /* state of the current function */
638f5b90 2273 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
b5dc0163 2274 u32 dst_reg = env->prog->insnsi[insn_idx].dst_reg;
f7cf25b2 2275 struct bpf_reg_state *reg = NULL;
638f5b90 2276
f4d7e40a 2277 err = realloc_func_state(state, round_up(slot + 1, BPF_REG_SIZE),
fd978bf7 2278 state->acquired_refs, true);
638f5b90
AS
2279 if (err)
2280 return err;
9c399760
AS
2281 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
2282 * so it's aligned access and [off, off + size) are within stack limits
2283 */
638f5b90
AS
2284 if (!env->allow_ptr_leaks &&
2285 state->stack[spi].slot_type[0] == STACK_SPILL &&
2286 size != BPF_REG_SIZE) {
2287 verbose(env, "attempt to corrupt spilled pointer on stack\n");
2288 return -EACCES;
2289 }
17a52670 2290
f4d7e40a 2291 cur = env->cur_state->frame[env->cur_state->curframe];
f7cf25b2
AS
2292 if (value_regno >= 0)
2293 reg = &cur->regs[value_regno];
17a52670 2294
5689d49b 2295 if (reg && size == BPF_REG_SIZE && register_is_bounded(reg) &&
2c78ee89 2296 !register_is_null(reg) && env->bpf_capable) {
b5dc0163
AS
2297 if (dst_reg != BPF_REG_FP) {
2298 /* The backtracking logic can only recognize explicit
2299 * stack slot address like [fp - 8]. Other spill of
2300 * scalar via different register has to be conervative.
2301 * Backtrack from here and mark all registers as precise
2302 * that contributed into 'reg' being a constant.
2303 */
2304 err = mark_chain_precision(env, value_regno);
2305 if (err)
2306 return err;
2307 }
f7cf25b2
AS
2308 save_register_state(state, spi, reg);
2309 } else if (reg && is_spillable_regtype(reg->type)) {
17a52670 2310 /* register containing pointer is being spilled into stack */
9c399760 2311 if (size != BPF_REG_SIZE) {
f7cf25b2 2312 verbose_linfo(env, insn_idx, "; ");
61bd5218 2313 verbose(env, "invalid size of register spill\n");
17a52670
AS
2314 return -EACCES;
2315 }
2316
f7cf25b2 2317 if (state != cur && reg->type == PTR_TO_STACK) {
f4d7e40a
AS
2318 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
2319 return -EINVAL;
2320 }
2321
2c78ee89 2322 if (!env->bypass_spec_v4) {
f7cf25b2 2323 bool sanitize = false;
17a52670 2324
f7cf25b2
AS
2325 if (state->stack[spi].slot_type[0] == STACK_SPILL &&
2326 register_is_const(&state->stack[spi].spilled_ptr))
2327 sanitize = true;
2328 for (i = 0; i < BPF_REG_SIZE; i++)
2329 if (state->stack[spi].slot_type[i] == STACK_MISC) {
2330 sanitize = true;
2331 break;
2332 }
2333 if (sanitize) {
af86ca4e
AS
2334 int *poff = &env->insn_aux_data[insn_idx].sanitize_stack_off;
2335 int soff = (-spi - 1) * BPF_REG_SIZE;
2336
2337 /* detected reuse of integer stack slot with a pointer
2338 * which means either llvm is reusing stack slot or
2339 * an attacker is trying to exploit CVE-2018-3639
2340 * (speculative store bypass)
2341 * Have to sanitize that slot with preemptive
2342 * store of zero.
2343 */
2344 if (*poff && *poff != soff) {
2345 /* disallow programs where single insn stores
2346 * into two different stack slots, since verifier
2347 * cannot sanitize them
2348 */
2349 verbose(env,
2350 "insn %d cannot access two stack slots fp%d and fp%d",
2351 insn_idx, *poff, soff);
2352 return -EINVAL;
2353 }
2354 *poff = soff;
2355 }
af86ca4e 2356 }
f7cf25b2 2357 save_register_state(state, spi, reg);
9c399760 2358 } else {
cc2b14d5
AS
2359 u8 type = STACK_MISC;
2360
679c782d
EC
2361 /* regular write of data into stack destroys any spilled ptr */
2362 state->stack[spi].spilled_ptr.type = NOT_INIT;
0bae2d4d
JW
2363 /* Mark slots as STACK_MISC if they belonged to spilled ptr. */
2364 if (state->stack[spi].slot_type[0] == STACK_SPILL)
2365 for (i = 0; i < BPF_REG_SIZE; i++)
2366 state->stack[spi].slot_type[i] = STACK_MISC;
9c399760 2367
cc2b14d5
AS
2368 /* only mark the slot as written if all 8 bytes were written
2369 * otherwise read propagation may incorrectly stop too soon
2370 * when stack slots are partially written.
2371 * This heuristic means that read propagation will be
2372 * conservative, since it will add reg_live_read marks
2373 * to stack slots all the way to first state when programs
2374 * writes+reads less than 8 bytes
2375 */
2376 if (size == BPF_REG_SIZE)
2377 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
2378
2379 /* when we zero initialize stack slots mark them as such */
b5dc0163
AS
2380 if (reg && register_is_null(reg)) {
2381 /* backtracking doesn't work for STACK_ZERO yet. */
2382 err = mark_chain_precision(env, value_regno);
2383 if (err)
2384 return err;
cc2b14d5 2385 type = STACK_ZERO;
b5dc0163 2386 }
cc2b14d5 2387
0bae2d4d 2388 /* Mark slots affected by this stack write. */
9c399760 2389 for (i = 0; i < size; i++)
638f5b90 2390 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
cc2b14d5 2391 type;
17a52670
AS
2392 }
2393 return 0;
2394}
2395
61bd5218 2396static int check_stack_read(struct bpf_verifier_env *env,
f4d7e40a
AS
2397 struct bpf_func_state *reg_state /* func where register points to */,
2398 int off, int size, int value_regno)
17a52670 2399{
f4d7e40a
AS
2400 struct bpf_verifier_state *vstate = env->cur_state;
2401 struct bpf_func_state *state = vstate->frame[vstate->curframe];
638f5b90 2402 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
f7cf25b2 2403 struct bpf_reg_state *reg;
638f5b90 2404 u8 *stype;
17a52670 2405
f4d7e40a 2406 if (reg_state->allocated_stack <= slot) {
638f5b90
AS
2407 verbose(env, "invalid read from stack off %d+0 size %d\n",
2408 off, size);
2409 return -EACCES;
2410 }
f4d7e40a 2411 stype = reg_state->stack[spi].slot_type;
f7cf25b2 2412 reg = &reg_state->stack[spi].spilled_ptr;
17a52670 2413
638f5b90 2414 if (stype[0] == STACK_SPILL) {
9c399760 2415 if (size != BPF_REG_SIZE) {
f7cf25b2
AS
2416 if (reg->type != SCALAR_VALUE) {
2417 verbose_linfo(env, env->insn_idx, "; ");
2418 verbose(env, "invalid size of register fill\n");
2419 return -EACCES;
2420 }
2421 if (value_regno >= 0) {
2422 mark_reg_unknown(env, state->regs, value_regno);
2423 state->regs[value_regno].live |= REG_LIVE_WRITTEN;
2424 }
2425 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
2426 return 0;
17a52670 2427 }
9c399760 2428 for (i = 1; i < BPF_REG_SIZE; i++) {
638f5b90 2429 if (stype[(slot - i) % BPF_REG_SIZE] != STACK_SPILL) {
61bd5218 2430 verbose(env, "corrupted spill memory\n");
17a52670
AS
2431 return -EACCES;
2432 }
2433 }
2434
dc503a8a 2435 if (value_regno >= 0) {
17a52670 2436 /* restore register state from stack */
f7cf25b2 2437 state->regs[value_regno] = *reg;
2f18f62e
AS
2438 /* mark reg as written since spilled pointer state likely
2439 * has its liveness marks cleared by is_state_visited()
2440 * which resets stack/reg liveness for state transitions
2441 */
2442 state->regs[value_regno].live |= REG_LIVE_WRITTEN;
6e7e63cb
JH
2443 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
2444 /* If value_regno==-1, the caller is asking us whether
2445 * it is acceptable to use this value as a SCALAR_VALUE
2446 * (e.g. for XADD).
2447 * We must not allow unprivileged callers to do that
2448 * with spilled pointers.
2449 */
2450 verbose(env, "leaking pointer from stack off %d\n",
2451 off);
2452 return -EACCES;
dc503a8a 2453 }
f7cf25b2 2454 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
17a52670 2455 } else {
cc2b14d5
AS
2456 int zeros = 0;
2457
17a52670 2458 for (i = 0; i < size; i++) {
cc2b14d5
AS
2459 if (stype[(slot - i) % BPF_REG_SIZE] == STACK_MISC)
2460 continue;
2461 if (stype[(slot - i) % BPF_REG_SIZE] == STACK_ZERO) {
2462 zeros++;
2463 continue;
17a52670 2464 }
cc2b14d5
AS
2465 verbose(env, "invalid read from stack off %d+%d size %d\n",
2466 off, i, size);
2467 return -EACCES;
2468 }
f7cf25b2 2469 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
cc2b14d5
AS
2470 if (value_regno >= 0) {
2471 if (zeros == size) {
2472 /* any size read into register is zero extended,
2473 * so the whole register == const_zero
2474 */
2475 __mark_reg_const_zero(&state->regs[value_regno]);
b5dc0163
AS
2476 /* backtracking doesn't support STACK_ZERO yet,
2477 * so mark it precise here, so that later
2478 * backtracking can stop here.
2479 * Backtracking may not need this if this register
2480 * doesn't participate in pointer adjustment.
2481 * Forward propagation of precise flag is not
2482 * necessary either. This mark is only to stop
2483 * backtracking. Any register that contributed
2484 * to const 0 was marked precise before spill.
2485 */
2486 state->regs[value_regno].precise = true;
cc2b14d5
AS
2487 } else {
2488 /* have read misc data from the stack */
2489 mark_reg_unknown(env, state->regs, value_regno);
2490 }
2491 state->regs[value_regno].live |= REG_LIVE_WRITTEN;
17a52670 2492 }
17a52670 2493 }
f7cf25b2 2494 return 0;
17a52670
AS
2495}
2496
e4298d25
DB
2497static int check_stack_access(struct bpf_verifier_env *env,
2498 const struct bpf_reg_state *reg,
2499 int off, int size)
2500{
2501 /* Stack accesses must be at a fixed offset, so that we
2502 * can determine what type of data were returned. See
2503 * check_stack_read().
2504 */
2505 if (!tnum_is_const(reg->var_off)) {
2506 char tn_buf[48];
2507
2508 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
1fbd20f8 2509 verbose(env, "variable stack access var_off=%s off=%d size=%d\n",
e4298d25
DB
2510 tn_buf, off, size);
2511 return -EACCES;
2512 }
2513
2514 if (off >= 0 || off < -MAX_BPF_STACK) {
2515 verbose(env, "invalid stack off=%d size=%d\n", off, size);
2516 return -EACCES;
2517 }
2518
2519 return 0;
2520}
2521
591fe988
DB
2522static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
2523 int off, int size, enum bpf_access_type type)
2524{
2525 struct bpf_reg_state *regs = cur_regs(env);
2526 struct bpf_map *map = regs[regno].map_ptr;
2527 u32 cap = bpf_map_flags_to_cap(map);
2528
2529 if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
2530 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
2531 map->value_size, off, size);
2532 return -EACCES;
2533 }
2534
2535 if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
2536 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
2537 map->value_size, off, size);
2538 return -EACCES;
2539 }
2540
2541 return 0;
2542}
2543
457f4436
AN
2544/* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
2545static int __check_mem_access(struct bpf_verifier_env *env, int regno,
2546 int off, int size, u32 mem_size,
2547 bool zero_size_allowed)
17a52670 2548{
457f4436
AN
2549 bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
2550 struct bpf_reg_state *reg;
2551
2552 if (off >= 0 && size_ok && (u64)off + size <= mem_size)
2553 return 0;
17a52670 2554
457f4436
AN
2555 reg = &cur_regs(env)[regno];
2556 switch (reg->type) {
2557 case PTR_TO_MAP_VALUE:
61bd5218 2558 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
457f4436
AN
2559 mem_size, off, size);
2560 break;
2561 case PTR_TO_PACKET:
2562 case PTR_TO_PACKET_META:
2563 case PTR_TO_PACKET_END:
2564 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
2565 off, size, regno, reg->id, off, mem_size);
2566 break;
2567 case PTR_TO_MEM:
2568 default:
2569 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
2570 mem_size, off, size);
17a52670 2571 }
457f4436
AN
2572
2573 return -EACCES;
17a52670
AS
2574}
2575
457f4436
AN
2576/* check read/write into a memory region with possible variable offset */
2577static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
2578 int off, int size, u32 mem_size,
2579 bool zero_size_allowed)
dbcfe5f7 2580{
f4d7e40a
AS
2581 struct bpf_verifier_state *vstate = env->cur_state;
2582 struct bpf_func_state *state = vstate->frame[vstate->curframe];
dbcfe5f7
GB
2583 struct bpf_reg_state *reg = &state->regs[regno];
2584 int err;
2585
457f4436 2586 /* We may have adjusted the register pointing to memory region, so we
f1174f77
EC
2587 * need to try adding each of min_value and max_value to off
2588 * to make sure our theoretical access will be safe.
dbcfe5f7 2589 */
06ee7115 2590 if (env->log.level & BPF_LOG_LEVEL)
61bd5218 2591 print_verifier_state(env, state);
b7137c4e 2592
dbcfe5f7
GB
2593 /* The minimum value is only important with signed
2594 * comparisons where we can't assume the floor of a
2595 * value is 0. If we are using signed variables for our
2596 * index'es we need to make sure that whatever we use
2597 * will have a set floor within our range.
2598 */
b7137c4e
DB
2599 if (reg->smin_value < 0 &&
2600 (reg->smin_value == S64_MIN ||
2601 (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
2602 reg->smin_value + off < 0)) {
61bd5218 2603 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
dbcfe5f7
GB
2604 regno);
2605 return -EACCES;
2606 }
457f4436
AN
2607 err = __check_mem_access(env, regno, reg->smin_value + off, size,
2608 mem_size, zero_size_allowed);
dbcfe5f7 2609 if (err) {
457f4436 2610 verbose(env, "R%d min value is outside of the allowed memory range\n",
61bd5218 2611 regno);
dbcfe5f7
GB
2612 return err;
2613 }
2614
b03c9f9f
EC
2615 /* If we haven't set a max value then we need to bail since we can't be
2616 * sure we won't do bad things.
2617 * If reg->umax_value + off could overflow, treat that as unbounded too.
dbcfe5f7 2618 */
b03c9f9f 2619 if (reg->umax_value >= BPF_MAX_VAR_OFF) {
457f4436 2620 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
dbcfe5f7
GB
2621 regno);
2622 return -EACCES;
2623 }
457f4436
AN
2624 err = __check_mem_access(env, regno, reg->umax_value + off, size,
2625 mem_size, zero_size_allowed);
2626 if (err) {
2627 verbose(env, "R%d max value is outside of the allowed memory range\n",
61bd5218 2628 regno);
457f4436
AN
2629 return err;
2630 }
2631
2632 return 0;
2633}
d83525ca 2634
457f4436
AN
2635/* check read/write into a map element with possible variable offset */
2636static int check_map_access(struct bpf_verifier_env *env, u32 regno,
2637 int off, int size, bool zero_size_allowed)
2638{
2639 struct bpf_verifier_state *vstate = env->cur_state;
2640 struct bpf_func_state *state = vstate->frame[vstate->curframe];
2641 struct bpf_reg_state *reg = &state->regs[regno];
2642 struct bpf_map *map = reg->map_ptr;
2643 int err;
2644
2645 err = check_mem_region_access(env, regno, off, size, map->value_size,
2646 zero_size_allowed);
2647 if (err)
2648 return err;
2649
2650 if (map_value_has_spin_lock(map)) {
2651 u32 lock = map->spin_lock_off;
d83525ca
AS
2652
2653 /* if any part of struct bpf_spin_lock can be touched by
2654 * load/store reject this program.
2655 * To check that [x1, x2) overlaps with [y1, y2)
2656 * it is sufficient to check x1 < y2 && y1 < x2.
2657 */
2658 if (reg->smin_value + off < lock + sizeof(struct bpf_spin_lock) &&
2659 lock < reg->umax_value + off + size) {
2660 verbose(env, "bpf_spin_lock cannot be accessed directly by load/store\n");
2661 return -EACCES;
2662 }
2663 }
f1174f77 2664 return err;
dbcfe5f7
GB
2665}
2666
969bf05e
AS
2667#define MAX_PACKET_OFF 0xffff
2668
7e40781c
UP
2669static enum bpf_prog_type resolve_prog_type(struct bpf_prog *prog)
2670{
3aac1ead 2671 return prog->aux->dst_prog ? prog->aux->dst_prog->type : prog->type;
7e40781c
UP
2672}
2673
58e2af8b 2674static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
3a0af8fd
TG
2675 const struct bpf_call_arg_meta *meta,
2676 enum bpf_access_type t)
4acf6c0b 2677{
7e40781c
UP
2678 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
2679
2680 switch (prog_type) {
5d66fa7d 2681 /* Program types only with direct read access go here! */
3a0af8fd
TG
2682 case BPF_PROG_TYPE_LWT_IN:
2683 case BPF_PROG_TYPE_LWT_OUT:
004d4b27 2684 case BPF_PROG_TYPE_LWT_SEG6LOCAL:
2dbb9b9e 2685 case BPF_PROG_TYPE_SK_REUSEPORT:
5d66fa7d 2686 case BPF_PROG_TYPE_FLOW_DISSECTOR:
d5563d36 2687 case BPF_PROG_TYPE_CGROUP_SKB:
3a0af8fd
TG
2688 if (t == BPF_WRITE)
2689 return false;
8731745e 2690 fallthrough;
5d66fa7d
DB
2691
2692 /* Program types with direct read + write access go here! */
36bbef52
DB
2693 case BPF_PROG_TYPE_SCHED_CLS:
2694 case BPF_PROG_TYPE_SCHED_ACT:
4acf6c0b 2695 case BPF_PROG_TYPE_XDP:
3a0af8fd 2696 case BPF_PROG_TYPE_LWT_XMIT:
8a31db56 2697 case BPF_PROG_TYPE_SK_SKB:
4f738adb 2698 case BPF_PROG_TYPE_SK_MSG:
36bbef52
DB
2699 if (meta)
2700 return meta->pkt_access;
2701
2702 env->seen_direct_write = true;
4acf6c0b 2703 return true;
0d01da6a
SF
2704
2705 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
2706 if (t == BPF_WRITE)
2707 env->seen_direct_write = true;
2708
2709 return true;
2710
4acf6c0b
BB
2711 default:
2712 return false;
2713 }
2714}
2715
f1174f77 2716static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
9fd29c08 2717 int size, bool zero_size_allowed)
f1174f77 2718{
638f5b90 2719 struct bpf_reg_state *regs = cur_regs(env);
f1174f77
EC
2720 struct bpf_reg_state *reg = &regs[regno];
2721 int err;
2722
2723 /* We may have added a variable offset to the packet pointer; but any
2724 * reg->range we have comes after that. We are only checking the fixed
2725 * offset.
2726 */
2727
2728 /* We don't allow negative numbers, because we aren't tracking enough
2729 * detail to prove they're safe.
2730 */
b03c9f9f 2731 if (reg->smin_value < 0) {
61bd5218 2732 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
f1174f77
EC
2733 regno);
2734 return -EACCES;
2735 }
457f4436
AN
2736 err = __check_mem_access(env, regno, off, size, reg->range,
2737 zero_size_allowed);
f1174f77 2738 if (err) {
61bd5218 2739 verbose(env, "R%d offset is outside of the packet\n", regno);
f1174f77
EC
2740 return err;
2741 }
e647815a 2742
457f4436 2743 /* __check_mem_access has made sure "off + size - 1" is within u16.
e647815a
JW
2744 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
2745 * otherwise find_good_pkt_pointers would have refused to set range info
457f4436 2746 * that __check_mem_access would have rejected this pkt access.
e647815a
JW
2747 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
2748 */
2749 env->prog->aux->max_pkt_offset =
2750 max_t(u32, env->prog->aux->max_pkt_offset,
2751 off + reg->umax_value + size - 1);
2752
f1174f77
EC
2753 return err;
2754}
2755
2756/* check access to 'struct bpf_context' fields. Supports fixed offsets only */
31fd8581 2757static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
9e15db66
AS
2758 enum bpf_access_type t, enum bpf_reg_type *reg_type,
2759 u32 *btf_id)
17a52670 2760{
f96da094
DB
2761 struct bpf_insn_access_aux info = {
2762 .reg_type = *reg_type,
9e15db66 2763 .log = &env->log,
f96da094 2764 };
31fd8581 2765
4f9218aa 2766 if (env->ops->is_valid_access &&
5e43f899 2767 env->ops->is_valid_access(off, size, t, env->prog, &info)) {
f96da094
DB
2768 /* A non zero info.ctx_field_size indicates that this field is a
2769 * candidate for later verifier transformation to load the whole
2770 * field and then apply a mask when accessed with a narrower
2771 * access than actual ctx access size. A zero info.ctx_field_size
2772 * will only allow for whole field access and rejects any other
2773 * type of narrower access.
31fd8581 2774 */
23994631 2775 *reg_type = info.reg_type;
31fd8581 2776
b121b341 2777 if (*reg_type == PTR_TO_BTF_ID || *reg_type == PTR_TO_BTF_ID_OR_NULL)
9e15db66
AS
2778 *btf_id = info.btf_id;
2779 else
2780 env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
32bbe007
AS
2781 /* remember the offset of last byte accessed in ctx */
2782 if (env->prog->aux->max_ctx_offset < off + size)
2783 env->prog->aux->max_ctx_offset = off + size;
17a52670 2784 return 0;
32bbe007 2785 }
17a52670 2786
61bd5218 2787 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
17a52670
AS
2788 return -EACCES;
2789}
2790
d58e468b
PP
2791static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
2792 int size)
2793{
2794 if (size < 0 || off < 0 ||
2795 (u64)off + size > sizeof(struct bpf_flow_keys)) {
2796 verbose(env, "invalid access to flow keys off=%d size=%d\n",
2797 off, size);
2798 return -EACCES;
2799 }
2800 return 0;
2801}
2802
5f456649
MKL
2803static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
2804 u32 regno, int off, int size,
2805 enum bpf_access_type t)
c64b7983
JS
2806{
2807 struct bpf_reg_state *regs = cur_regs(env);
2808 struct bpf_reg_state *reg = &regs[regno];
5f456649 2809 struct bpf_insn_access_aux info = {};
46f8bc92 2810 bool valid;
c64b7983
JS
2811
2812 if (reg->smin_value < 0) {
2813 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
2814 regno);
2815 return -EACCES;
2816 }
2817
46f8bc92
MKL
2818 switch (reg->type) {
2819 case PTR_TO_SOCK_COMMON:
2820 valid = bpf_sock_common_is_valid_access(off, size, t, &info);
2821 break;
2822 case PTR_TO_SOCKET:
2823 valid = bpf_sock_is_valid_access(off, size, t, &info);
2824 break;
655a51e5
MKL
2825 case PTR_TO_TCP_SOCK:
2826 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
2827 break;
fada7fdc
JL
2828 case PTR_TO_XDP_SOCK:
2829 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
2830 break;
46f8bc92
MKL
2831 default:
2832 valid = false;
c64b7983
JS
2833 }
2834
5f456649 2835
46f8bc92
MKL
2836 if (valid) {
2837 env->insn_aux_data[insn_idx].ctx_field_size =
2838 info.ctx_field_size;
2839 return 0;
2840 }
2841
2842 verbose(env, "R%d invalid %s access off=%d size=%d\n",
2843 regno, reg_type_str[reg->type], off, size);
2844
2845 return -EACCES;
c64b7983
JS
2846}
2847
2a159c6f
DB
2848static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
2849{
2850 return cur_regs(env) + regno;
2851}
2852
4cabc5b1
DB
2853static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
2854{
2a159c6f 2855 return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
4cabc5b1
DB
2856}
2857
f37a8cb8
DB
2858static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
2859{
2a159c6f 2860 const struct bpf_reg_state *reg = reg_state(env, regno);
f37a8cb8 2861
46f8bc92
MKL
2862 return reg->type == PTR_TO_CTX;
2863}
2864
2865static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
2866{
2867 const struct bpf_reg_state *reg = reg_state(env, regno);
2868
2869 return type_is_sk_pointer(reg->type);
f37a8cb8
DB
2870}
2871
ca369602
DB
2872static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
2873{
2a159c6f 2874 const struct bpf_reg_state *reg = reg_state(env, regno);
ca369602
DB
2875
2876 return type_is_pkt_pointer(reg->type);
2877}
2878
4b5defde
DB
2879static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
2880{
2881 const struct bpf_reg_state *reg = reg_state(env, regno);
2882
2883 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
2884 return reg->type == PTR_TO_FLOW_KEYS;
2885}
2886
61bd5218
JK
2887static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
2888 const struct bpf_reg_state *reg,
d1174416 2889 int off, int size, bool strict)
969bf05e 2890{
f1174f77 2891 struct tnum reg_off;
e07b98d9 2892 int ip_align;
d1174416
DM
2893
2894 /* Byte size accesses are always allowed. */
2895 if (!strict || size == 1)
2896 return 0;
2897
e4eda884
DM
2898 /* For platforms that do not have a Kconfig enabling
2899 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
2900 * NET_IP_ALIGN is universally set to '2'. And on platforms
2901 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
2902 * to this code only in strict mode where we want to emulate
2903 * the NET_IP_ALIGN==2 checking. Therefore use an
2904 * unconditional IP align value of '2'.
e07b98d9 2905 */
e4eda884 2906 ip_align = 2;
f1174f77
EC
2907
2908 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
2909 if (!tnum_is_aligned(reg_off, size)) {
2910 char tn_buf[48];
2911
2912 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
61bd5218
JK
2913 verbose(env,
2914 "misaligned packet access off %d+%s+%d+%d size %d\n",
f1174f77 2915 ip_align, tn_buf, reg->off, off, size);
969bf05e
AS
2916 return -EACCES;
2917 }
79adffcd 2918
969bf05e
AS
2919 return 0;
2920}
2921
61bd5218
JK
2922static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
2923 const struct bpf_reg_state *reg,
f1174f77
EC
2924 const char *pointer_desc,
2925 int off, int size, bool strict)
79adffcd 2926{
f1174f77
EC
2927 struct tnum reg_off;
2928
2929 /* Byte size accesses are always allowed. */
2930 if (!strict || size == 1)
2931 return 0;
2932
2933 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
2934 if (!tnum_is_aligned(reg_off, size)) {
2935 char tn_buf[48];
2936
2937 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
61bd5218 2938 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
f1174f77 2939 pointer_desc, tn_buf, reg->off, off, size);
79adffcd
DB
2940 return -EACCES;
2941 }
2942
969bf05e
AS
2943 return 0;
2944}
2945
e07b98d9 2946static int check_ptr_alignment(struct bpf_verifier_env *env,
ca369602
DB
2947 const struct bpf_reg_state *reg, int off,
2948 int size, bool strict_alignment_once)
79adffcd 2949{
ca369602 2950 bool strict = env->strict_alignment || strict_alignment_once;
f1174f77 2951 const char *pointer_desc = "";
d1174416 2952
79adffcd
DB
2953 switch (reg->type) {
2954 case PTR_TO_PACKET:
de8f3a83
DB
2955 case PTR_TO_PACKET_META:
2956 /* Special case, because of NET_IP_ALIGN. Given metadata sits
2957 * right in front, treat it the very same way.
2958 */
61bd5218 2959 return check_pkt_ptr_alignment(env, reg, off, size, strict);
d58e468b
PP
2960 case PTR_TO_FLOW_KEYS:
2961 pointer_desc = "flow keys ";
2962 break;
f1174f77
EC
2963 case PTR_TO_MAP_VALUE:
2964 pointer_desc = "value ";
2965 break;
2966 case PTR_TO_CTX:
2967 pointer_desc = "context ";
2968 break;
2969 case PTR_TO_STACK:
2970 pointer_desc = "stack ";
a5ec6ae1
JH
2971 /* The stack spill tracking logic in check_stack_write()
2972 * and check_stack_read() relies on stack accesses being
2973 * aligned.
2974 */
2975 strict = true;
f1174f77 2976 break;
c64b7983
JS
2977 case PTR_TO_SOCKET:
2978 pointer_desc = "sock ";
2979 break;
46f8bc92
MKL
2980 case PTR_TO_SOCK_COMMON:
2981 pointer_desc = "sock_common ";
2982 break;
655a51e5
MKL
2983 case PTR_TO_TCP_SOCK:
2984 pointer_desc = "tcp_sock ";
2985 break;
fada7fdc
JL
2986 case PTR_TO_XDP_SOCK:
2987 pointer_desc = "xdp_sock ";
2988 break;
79adffcd 2989 default:
f1174f77 2990 break;
79adffcd 2991 }
61bd5218
JK
2992 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
2993 strict);
79adffcd
DB
2994}
2995
f4d7e40a
AS
2996static int update_stack_depth(struct bpf_verifier_env *env,
2997 const struct bpf_func_state *func,
2998 int off)
2999{
9c8105bd 3000 u16 stack = env->subprog_info[func->subprogno].stack_depth;
f4d7e40a
AS
3001
3002 if (stack >= -off)
3003 return 0;
3004
3005 /* update known max for given subprogram */
9c8105bd 3006 env->subprog_info[func->subprogno].stack_depth = -off;
70a87ffe
AS
3007 return 0;
3008}
f4d7e40a 3009
70a87ffe
AS
3010/* starting from main bpf function walk all instructions of the function
3011 * and recursively walk all callees that given function can call.
3012 * Ignore jump and exit insns.
3013 * Since recursion is prevented by check_cfg() this algorithm
3014 * only needs a local stack of MAX_CALL_FRAMES to remember callsites
3015 */
3016static int check_max_stack_depth(struct bpf_verifier_env *env)
3017{
9c8105bd
JW
3018 int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
3019 struct bpf_subprog_info *subprog = env->subprog_info;
70a87ffe 3020 struct bpf_insn *insn = env->prog->insnsi;
ebf7d1f5 3021 bool tail_call_reachable = false;
70a87ffe
AS
3022 int ret_insn[MAX_CALL_FRAMES];
3023 int ret_prog[MAX_CALL_FRAMES];
ebf7d1f5 3024 int j;
f4d7e40a 3025
70a87ffe 3026process_func:
7f6e4312
MF
3027 /* protect against potential stack overflow that might happen when
3028 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
3029 * depth for such case down to 256 so that the worst case scenario
3030 * would result in 8k stack size (32 which is tailcall limit * 256 =
3031 * 8k).
3032 *
3033 * To get the idea what might happen, see an example:
3034 * func1 -> sub rsp, 128
3035 * subfunc1 -> sub rsp, 256
3036 * tailcall1 -> add rsp, 256
3037 * func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
3038 * subfunc2 -> sub rsp, 64
3039 * subfunc22 -> sub rsp, 128
3040 * tailcall2 -> add rsp, 128
3041 * func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
3042 *
3043 * tailcall will unwind the current stack frame but it will not get rid
3044 * of caller's stack as shown on the example above.
3045 */
3046 if (idx && subprog[idx].has_tail_call && depth >= 256) {
3047 verbose(env,
3048 "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
3049 depth);
3050 return -EACCES;
3051 }
70a87ffe
AS
3052 /* round up to 32-bytes, since this is granularity
3053 * of interpreter stack size
3054 */
9c8105bd 3055 depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
70a87ffe 3056 if (depth > MAX_BPF_STACK) {
f4d7e40a 3057 verbose(env, "combined stack size of %d calls is %d. Too large\n",
70a87ffe 3058 frame + 1, depth);
f4d7e40a
AS
3059 return -EACCES;
3060 }
70a87ffe 3061continue_func:
4cb3d99c 3062 subprog_end = subprog[idx + 1].start;
70a87ffe
AS
3063 for (; i < subprog_end; i++) {
3064 if (insn[i].code != (BPF_JMP | BPF_CALL))
3065 continue;
3066 if (insn[i].src_reg != BPF_PSEUDO_CALL)
3067 continue;
3068 /* remember insn and function to return to */
3069 ret_insn[frame] = i + 1;
9c8105bd 3070 ret_prog[frame] = idx;
70a87ffe
AS
3071
3072 /* find the callee */
3073 i = i + insn[i].imm + 1;
9c8105bd
JW
3074 idx = find_subprog(env, i);
3075 if (idx < 0) {
70a87ffe
AS
3076 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
3077 i);
3078 return -EFAULT;
3079 }
ebf7d1f5
MF
3080
3081 if (subprog[idx].has_tail_call)
3082 tail_call_reachable = true;
3083
70a87ffe
AS
3084 frame++;
3085 if (frame >= MAX_CALL_FRAMES) {
927cb781
PC
3086 verbose(env, "the call stack of %d frames is too deep !\n",
3087 frame);
3088 return -E2BIG;
70a87ffe
AS
3089 }
3090 goto process_func;
3091 }
ebf7d1f5
MF
3092 /* if tail call got detected across bpf2bpf calls then mark each of the
3093 * currently present subprog frames as tail call reachable subprogs;
3094 * this info will be utilized by JIT so that we will be preserving the
3095 * tail call counter throughout bpf2bpf calls combined with tailcalls
3096 */
3097 if (tail_call_reachable)
3098 for (j = 0; j < frame; j++)
3099 subprog[ret_prog[j]].tail_call_reachable = true;
3100
70a87ffe
AS
3101 /* end of for() loop means the last insn of the 'subprog'
3102 * was reached. Doesn't matter whether it was JA or EXIT
3103 */
3104 if (frame == 0)
3105 return 0;
9c8105bd 3106 depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
70a87ffe
AS
3107 frame--;
3108 i = ret_insn[frame];
9c8105bd 3109 idx = ret_prog[frame];
70a87ffe 3110 goto continue_func;
f4d7e40a
AS
3111}
3112
19d28fbd 3113#ifndef CONFIG_BPF_JIT_ALWAYS_ON
1ea47e01
AS
3114static int get_callee_stack_depth(struct bpf_verifier_env *env,
3115 const struct bpf_insn *insn, int idx)
3116{
3117 int start = idx + insn->imm + 1, subprog;
3118
3119 subprog = find_subprog(env, start);
3120 if (subprog < 0) {
3121 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
3122 start);
3123 return -EFAULT;
3124 }
9c8105bd 3125 return env->subprog_info[subprog].stack_depth;
1ea47e01 3126}
19d28fbd 3127#endif
1ea47e01 3128
51c39bb1
AS
3129int check_ctx_reg(struct bpf_verifier_env *env,
3130 const struct bpf_reg_state *reg, int regno)
58990d1f
DB
3131{
3132 /* Access to ctx or passing it to a helper is only allowed in
3133 * its original, unmodified form.
3134 */
3135
3136 if (reg->off) {
3137 verbose(env, "dereference of modified ctx ptr R%d off=%d disallowed\n",
3138 regno, reg->off);
3139 return -EACCES;
3140 }
3141
3142 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3143 char tn_buf[48];
3144
3145 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3146 verbose(env, "variable ctx access var_off=%s disallowed\n", tn_buf);
3147 return -EACCES;
3148 }
3149
3150 return 0;
3151}
3152
afbf21dc
YS
3153static int __check_buffer_access(struct bpf_verifier_env *env,
3154 const char *buf_info,
3155 const struct bpf_reg_state *reg,
3156 int regno, int off, int size)
9df1c28b
MM
3157{
3158 if (off < 0) {
3159 verbose(env,
4fc00b79 3160 "R%d invalid %s buffer access: off=%d, size=%d\n",
afbf21dc 3161 regno, buf_info, off, size);
9df1c28b
MM
3162 return -EACCES;
3163 }
3164 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3165 char tn_buf[48];
3166
3167 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3168 verbose(env,
4fc00b79 3169 "R%d invalid variable buffer offset: off=%d, var_off=%s\n",
9df1c28b
MM
3170 regno, off, tn_buf);
3171 return -EACCES;
3172 }
afbf21dc
YS
3173
3174 return 0;
3175}
3176
3177static int check_tp_buffer_access(struct bpf_verifier_env *env,
3178 const struct bpf_reg_state *reg,
3179 int regno, int off, int size)
3180{
3181 int err;
3182
3183 err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
3184 if (err)
3185 return err;
3186
9df1c28b
MM
3187 if (off + size > env->prog->aux->max_tp_access)
3188 env->prog->aux->max_tp_access = off + size;
3189
3190 return 0;
3191}
3192
afbf21dc
YS
3193static int check_buffer_access(struct bpf_verifier_env *env,
3194 const struct bpf_reg_state *reg,
3195 int regno, int off, int size,
3196 bool zero_size_allowed,
3197 const char *buf_info,
3198 u32 *max_access)
3199{
3200 int err;
3201
3202 err = __check_buffer_access(env, buf_info, reg, regno, off, size);
3203 if (err)
3204 return err;
3205
3206 if (off + size > *max_access)
3207 *max_access = off + size;
3208
3209 return 0;
3210}
3211
3f50f132
JF
3212/* BPF architecture zero extends alu32 ops into 64-bit registesr */
3213static void zext_32_to_64(struct bpf_reg_state *reg)
3214{
3215 reg->var_off = tnum_subreg(reg->var_off);
3216 __reg_assign_32_into_64(reg);
3217}
9df1c28b 3218
0c17d1d2
JH
3219/* truncate register to smaller size (in bytes)
3220 * must be called with size < BPF_REG_SIZE
3221 */
3222static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
3223{
3224 u64 mask;
3225
3226 /* clear high bits in bit representation */
3227 reg->var_off = tnum_cast(reg->var_off, size);
3228
3229 /* fix arithmetic bounds */
3230 mask = ((u64)1 << (size * 8)) - 1;
3231 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
3232 reg->umin_value &= mask;
3233 reg->umax_value &= mask;
3234 } else {
3235 reg->umin_value = 0;
3236 reg->umax_value = mask;
3237 }
3238 reg->smin_value = reg->umin_value;
3239 reg->smax_value = reg->umax_value;
3f50f132
JF
3240
3241 /* If size is smaller than 32bit register the 32bit register
3242 * values are also truncated so we push 64-bit bounds into
3243 * 32-bit bounds. Above were truncated < 32-bits already.
3244 */
3245 if (size >= 4)
3246 return;
3247 __reg_combine_64_into_32(reg);
0c17d1d2
JH
3248}
3249
a23740ec
AN
3250static bool bpf_map_is_rdonly(const struct bpf_map *map)
3251{
3252 return (map->map_flags & BPF_F_RDONLY_PROG) && map->frozen;
3253}
3254
3255static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val)
3256{
3257 void *ptr;
3258 u64 addr;
3259 int err;
3260
3261 err = map->ops->map_direct_value_addr(map, &addr, off);
3262 if (err)
3263 return err;
2dedd7d2 3264 ptr = (void *)(long)addr + off;
a23740ec
AN
3265
3266 switch (size) {
3267 case sizeof(u8):
3268 *val = (u64)*(u8 *)ptr;
3269 break;
3270 case sizeof(u16):
3271 *val = (u64)*(u16 *)ptr;
3272 break;
3273 case sizeof(u32):
3274 *val = (u64)*(u32 *)ptr;
3275 break;
3276 case sizeof(u64):
3277 *val = *(u64 *)ptr;
3278 break;
3279 default:
3280 return -EINVAL;
3281 }
3282 return 0;
3283}
3284
9e15db66
AS
3285static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
3286 struct bpf_reg_state *regs,
3287 int regno, int off, int size,
3288 enum bpf_access_type atype,
3289 int value_regno)
3290{
3291 struct bpf_reg_state *reg = regs + regno;
3292 const struct btf_type *t = btf_type_by_id(btf_vmlinux, reg->btf_id);
3293 const char *tname = btf_name_by_offset(btf_vmlinux, t->name_off);
3294 u32 btf_id;
3295 int ret;
3296
9e15db66
AS
3297 if (off < 0) {
3298 verbose(env,
3299 "R%d is ptr_%s invalid negative access: off=%d\n",
3300 regno, tname, off);
3301 return -EACCES;
3302 }
3303 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3304 char tn_buf[48];
3305
3306 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3307 verbose(env,
3308 "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
3309 regno, tname, off, tn_buf);
3310 return -EACCES;
3311 }
3312
27ae7997
MKL
3313 if (env->ops->btf_struct_access) {
3314 ret = env->ops->btf_struct_access(&env->log, t, off, size,
3315 atype, &btf_id);
3316 } else {
3317 if (atype != BPF_READ) {
3318 verbose(env, "only read is supported\n");
3319 return -EACCES;
3320 }
3321
3322 ret = btf_struct_access(&env->log, t, off, size, atype,
3323 &btf_id);
3324 }
3325
9e15db66
AS
3326 if (ret < 0)
3327 return ret;
3328
41c48f3a
AI
3329 if (atype == BPF_READ && value_regno >= 0)
3330 mark_btf_ld_reg(env, regs, value_regno, ret, btf_id);
3331
3332 return 0;
3333}
3334
3335static int check_ptr_to_map_access(struct bpf_verifier_env *env,
3336 struct bpf_reg_state *regs,
3337 int regno, int off, int size,
3338 enum bpf_access_type atype,
3339 int value_regno)
3340{
3341 struct bpf_reg_state *reg = regs + regno;
3342 struct bpf_map *map = reg->map_ptr;
3343 const struct btf_type *t;
3344 const char *tname;
3345 u32 btf_id;
3346 int ret;
3347
3348 if (!btf_vmlinux) {
3349 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
3350 return -ENOTSUPP;
3351 }
3352
3353 if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
3354 verbose(env, "map_ptr access not supported for map type %d\n",
3355 map->map_type);
3356 return -ENOTSUPP;
3357 }
3358
3359 t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
3360 tname = btf_name_by_offset(btf_vmlinux, t->name_off);
3361
3362 if (!env->allow_ptr_to_map_access) {
3363 verbose(env,
3364 "%s access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
3365 tname);
3366 return -EPERM;
9e15db66 3367 }
27ae7997 3368
41c48f3a
AI
3369 if (off < 0) {
3370 verbose(env, "R%d is %s invalid negative access: off=%d\n",
3371 regno, tname, off);
3372 return -EACCES;
3373 }
3374
3375 if (atype != BPF_READ) {
3376 verbose(env, "only read from %s is supported\n", tname);
3377 return -EACCES;
3378 }
3379
3380 ret = btf_struct_access(&env->log, t, off, size, atype, &btf_id);
3381 if (ret < 0)
3382 return ret;
3383
3384 if (value_regno >= 0)
3385 mark_btf_ld_reg(env, regs, value_regno, ret, btf_id);
3386
9e15db66
AS
3387 return 0;
3388}
3389
41c48f3a 3390
17a52670
AS
3391/* check whether memory at (regno + off) is accessible for t = (read | write)
3392 * if t==write, value_regno is a register which value is stored into memory
3393 * if t==read, value_regno is a register which will receive the value from memory
3394 * if t==write && value_regno==-1, some unknown value is stored into memory
3395 * if t==read && value_regno==-1, don't care what we read from memory
3396 */
ca369602
DB
3397static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
3398 int off, int bpf_size, enum bpf_access_type t,
3399 int value_regno, bool strict_alignment_once)
17a52670 3400{
638f5b90
AS
3401 struct bpf_reg_state *regs = cur_regs(env);
3402 struct bpf_reg_state *reg = regs + regno;
f4d7e40a 3403 struct bpf_func_state *state;
17a52670
AS
3404 int size, err = 0;
3405
3406 size = bpf_size_to_bytes(bpf_size);
3407 if (size < 0)
3408 return size;
3409
f1174f77 3410 /* alignment checks will add in reg->off themselves */
ca369602 3411 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
969bf05e
AS
3412 if (err)
3413 return err;
17a52670 3414
f1174f77
EC
3415 /* for access checks, reg->off is just part of off */
3416 off += reg->off;
3417
3418 if (reg->type == PTR_TO_MAP_VALUE) {
1be7f75d
AS
3419 if (t == BPF_WRITE && value_regno >= 0 &&
3420 is_pointer_value(env, value_regno)) {
61bd5218 3421 verbose(env, "R%d leaks addr into map\n", value_regno);
1be7f75d
AS
3422 return -EACCES;
3423 }
591fe988
DB
3424 err = check_map_access_type(env, regno, off, size, t);
3425 if (err)
3426 return err;
9fd29c08 3427 err = check_map_access(env, regno, off, size, false);
a23740ec
AN
3428 if (!err && t == BPF_READ && value_regno >= 0) {
3429 struct bpf_map *map = reg->map_ptr;
3430
3431 /* if map is read-only, track its contents as scalars */
3432 if (tnum_is_const(reg->var_off) &&
3433 bpf_map_is_rdonly(map) &&
3434 map->ops->map_direct_value_addr) {
3435 int map_off = off + reg->var_off.value;
3436 u64 val = 0;
3437
3438 err = bpf_map_direct_read(map, map_off, size,
3439 &val);
3440 if (err)
3441 return err;
3442
3443 regs[value_regno].type = SCALAR_VALUE;
3444 __mark_reg_known(&regs[value_regno], val);
3445 } else {
3446 mark_reg_unknown(env, regs, value_regno);
3447 }
3448 }
457f4436
AN
3449 } else if (reg->type == PTR_TO_MEM) {
3450 if (t == BPF_WRITE && value_regno >= 0 &&
3451 is_pointer_value(env, value_regno)) {
3452 verbose(env, "R%d leaks addr into mem\n", value_regno);
3453 return -EACCES;
3454 }
3455 err = check_mem_region_access(env, regno, off, size,
3456 reg->mem_size, false);
3457 if (!err && t == BPF_READ && value_regno >= 0)
3458 mark_reg_unknown(env, regs, value_regno);
1a0dc1ac 3459 } else if (reg->type == PTR_TO_CTX) {
f1174f77 3460 enum bpf_reg_type reg_type = SCALAR_VALUE;
9e15db66 3461 u32 btf_id = 0;
19de99f7 3462
1be7f75d
AS
3463 if (t == BPF_WRITE && value_regno >= 0 &&
3464 is_pointer_value(env, value_regno)) {
61bd5218 3465 verbose(env, "R%d leaks addr into ctx\n", value_regno);
1be7f75d
AS
3466 return -EACCES;
3467 }
f1174f77 3468
58990d1f
DB
3469 err = check_ctx_reg(env, reg, regno);
3470 if (err < 0)
3471 return err;
3472
9e15db66
AS
3473 err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf_id);
3474 if (err)
3475 verbose_linfo(env, insn_idx, "; ");
969bf05e 3476 if (!err && t == BPF_READ && value_regno >= 0) {
f1174f77 3477 /* ctx access returns either a scalar, or a
de8f3a83
DB
3478 * PTR_TO_PACKET[_META,_END]. In the latter
3479 * case, we know the offset is zero.
f1174f77 3480 */
46f8bc92 3481 if (reg_type == SCALAR_VALUE) {
638f5b90 3482 mark_reg_unknown(env, regs, value_regno);
46f8bc92 3483 } else {
638f5b90 3484 mark_reg_known_zero(env, regs,
61bd5218 3485 value_regno);
46f8bc92
MKL
3486 if (reg_type_may_be_null(reg_type))
3487 regs[value_regno].id = ++env->id_gen;
5327ed3d
JW
3488 /* A load of ctx field could have different
3489 * actual load size with the one encoded in the
3490 * insn. When the dst is PTR, it is for sure not
3491 * a sub-register.
3492 */
3493 regs[value_regno].subreg_def = DEF_NOT_SUBREG;
b121b341
YS
3494 if (reg_type == PTR_TO_BTF_ID ||
3495 reg_type == PTR_TO_BTF_ID_OR_NULL)
9e15db66 3496 regs[value_regno].btf_id = btf_id;
46f8bc92 3497 }
638f5b90 3498 regs[value_regno].type = reg_type;
969bf05e 3499 }
17a52670 3500
f1174f77 3501 } else if (reg->type == PTR_TO_STACK) {
f1174f77 3502 off += reg->var_off.value;
e4298d25
DB
3503 err = check_stack_access(env, reg, off, size);
3504 if (err)
3505 return err;
8726679a 3506
f4d7e40a
AS
3507 state = func(env, reg);
3508 err = update_stack_depth(env, state, off);
3509 if (err)
3510 return err;
8726679a 3511
638f5b90 3512 if (t == BPF_WRITE)
61bd5218 3513 err = check_stack_write(env, state, off, size,
af86ca4e 3514 value_regno, insn_idx);
638f5b90 3515 else
61bd5218
JK
3516 err = check_stack_read(env, state, off, size,
3517 value_regno);
de8f3a83 3518 } else if (reg_is_pkt_pointer(reg)) {
3a0af8fd 3519 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
61bd5218 3520 verbose(env, "cannot write into packet\n");
969bf05e
AS
3521 return -EACCES;
3522 }
4acf6c0b
BB
3523 if (t == BPF_WRITE && value_regno >= 0 &&
3524 is_pointer_value(env, value_regno)) {
61bd5218
JK
3525 verbose(env, "R%d leaks addr into packet\n",
3526 value_regno);
4acf6c0b
BB
3527 return -EACCES;
3528 }
9fd29c08 3529 err = check_packet_access(env, regno, off, size, false);
969bf05e 3530 if (!err && t == BPF_READ && value_regno >= 0)
638f5b90 3531 mark_reg_unknown(env, regs, value_regno);
d58e468b
PP
3532 } else if (reg->type == PTR_TO_FLOW_KEYS) {
3533 if (t == BPF_WRITE && value_regno >= 0 &&
3534 is_pointer_value(env, value_regno)) {
3535 verbose(env, "R%d leaks addr into flow keys\n",
3536 value_regno);
3537 return -EACCES;
3538 }
3539
3540 err = check_flow_keys_access(env, off, size);
3541 if (!err && t == BPF_READ && value_regno >= 0)
3542 mark_reg_unknown(env, regs, value_regno);
46f8bc92 3543 } else if (type_is_sk_pointer(reg->type)) {
c64b7983 3544 if (t == BPF_WRITE) {
46f8bc92
MKL
3545 verbose(env, "R%d cannot write into %s\n",
3546 regno, reg_type_str[reg->type]);
c64b7983
JS
3547 return -EACCES;
3548 }
5f456649 3549 err = check_sock_access(env, insn_idx, regno, off, size, t);
c64b7983
JS
3550 if (!err && value_regno >= 0)
3551 mark_reg_unknown(env, regs, value_regno);
9df1c28b
MM
3552 } else if (reg->type == PTR_TO_TP_BUFFER) {
3553 err = check_tp_buffer_access(env, reg, regno, off, size);
3554 if (!err && t == BPF_READ && value_regno >= 0)
3555 mark_reg_unknown(env, regs, value_regno);
9e15db66
AS
3556 } else if (reg->type == PTR_TO_BTF_ID) {
3557 err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
3558 value_regno);
41c48f3a
AI
3559 } else if (reg->type == CONST_PTR_TO_MAP) {
3560 err = check_ptr_to_map_access(env, regs, regno, off, size, t,
3561 value_regno);
afbf21dc
YS
3562 } else if (reg->type == PTR_TO_RDONLY_BUF) {
3563 if (t == BPF_WRITE) {
3564 verbose(env, "R%d cannot write into %s\n",
3565 regno, reg_type_str[reg->type]);
3566 return -EACCES;
3567 }
f6dfbe31
CIK
3568 err = check_buffer_access(env, reg, regno, off, size, false,
3569 "rdonly",
afbf21dc
YS
3570 &env->prog->aux->max_rdonly_access);
3571 if (!err && value_regno >= 0)
3572 mark_reg_unknown(env, regs, value_regno);
3573 } else if (reg->type == PTR_TO_RDWR_BUF) {
f6dfbe31
CIK
3574 err = check_buffer_access(env, reg, regno, off, size, false,
3575 "rdwr",
afbf21dc
YS
3576 &env->prog->aux->max_rdwr_access);
3577 if (!err && t == BPF_READ && value_regno >= 0)
3578 mark_reg_unknown(env, regs, value_regno);
17a52670 3579 } else {
61bd5218
JK
3580 verbose(env, "R%d invalid mem access '%s'\n", regno,
3581 reg_type_str[reg->type]);
17a52670
AS
3582 return -EACCES;
3583 }
969bf05e 3584
f1174f77 3585 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
638f5b90 3586 regs[value_regno].type == SCALAR_VALUE) {
f1174f77 3587 /* b/h/w load zero-extends, mark upper bits as known 0 */
0c17d1d2 3588 coerce_reg_to_size(&regs[value_regno], size);
969bf05e 3589 }
17a52670
AS
3590 return err;
3591}
3592
31fd8581 3593static int check_xadd(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
17a52670 3594{
17a52670
AS
3595 int err;
3596
3597 if ((BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) ||
3598 insn->imm != 0) {
61bd5218 3599 verbose(env, "BPF_XADD uses reserved fields\n");
17a52670
AS
3600 return -EINVAL;
3601 }
3602
3603 /* check src1 operand */
dc503a8a 3604 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17a52670
AS
3605 if (err)
3606 return err;
3607
3608 /* check src2 operand */
dc503a8a 3609 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17a52670
AS
3610 if (err)
3611 return err;
3612
6bdf6abc 3613 if (is_pointer_value(env, insn->src_reg)) {
61bd5218 3614 verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
6bdf6abc
DB
3615 return -EACCES;
3616 }
3617
ca369602 3618 if (is_ctx_reg(env, insn->dst_reg) ||
4b5defde 3619 is_pkt_reg(env, insn->dst_reg) ||
46f8bc92
MKL
3620 is_flow_key_reg(env, insn->dst_reg) ||
3621 is_sk_reg(env, insn->dst_reg)) {
ca369602 3622 verbose(env, "BPF_XADD stores into R%d %s is not allowed\n",
2a159c6f
DB
3623 insn->dst_reg,
3624 reg_type_str[reg_state(env, insn->dst_reg)->type]);
f37a8cb8
DB
3625 return -EACCES;
3626 }
3627
17a52670 3628 /* check whether atomic_add can read the memory */
31fd8581 3629 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
ca369602 3630 BPF_SIZE(insn->code), BPF_READ, -1, true);
17a52670
AS
3631 if (err)
3632 return err;
3633
3634 /* check whether atomic_add can write into the same memory */
31fd8581 3635 return check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
ca369602 3636 BPF_SIZE(insn->code), BPF_WRITE, -1, true);
17a52670
AS
3637}
3638
2011fccf
AI
3639static int __check_stack_boundary(struct bpf_verifier_env *env, u32 regno,
3640 int off, int access_size,
3641 bool zero_size_allowed)
3642{
3643 struct bpf_reg_state *reg = reg_state(env, regno);
3644
3645 if (off >= 0 || off < -MAX_BPF_STACK || off + access_size > 0 ||
3646 access_size < 0 || (access_size == 0 && !zero_size_allowed)) {
3647 if (tnum_is_const(reg->var_off)) {
3648 verbose(env, "invalid stack type R%d off=%d access_size=%d\n",
3649 regno, off, access_size);
3650 } else {
3651 char tn_buf[48];
3652
3653 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3654 verbose(env, "invalid stack type R%d var_off=%s access_size=%d\n",
3655 regno, tn_buf, access_size);
3656 }
3657 return -EACCES;
3658 }
3659 return 0;
3660}
3661
17a52670
AS
3662/* when register 'regno' is passed into function that will read 'access_size'
3663 * bytes from that pointer, make sure that it's within stack boundary
f1174f77
EC
3664 * and all elements of stack are initialized.
3665 * Unlike most pointer bounds-checking functions, this one doesn't take an
3666 * 'off' argument, so it has to add in reg->off itself.
17a52670 3667 */
58e2af8b 3668static int check_stack_boundary(struct bpf_verifier_env *env, int regno,
435faee1
DB
3669 int access_size, bool zero_size_allowed,
3670 struct bpf_call_arg_meta *meta)
17a52670 3671{
2a159c6f 3672 struct bpf_reg_state *reg = reg_state(env, regno);
f4d7e40a 3673 struct bpf_func_state *state = func(env, reg);
f7cf25b2 3674 int err, min_off, max_off, i, j, slot, spi;
17a52670 3675
2011fccf
AI
3676 if (tnum_is_const(reg->var_off)) {
3677 min_off = max_off = reg->var_off.value + reg->off;
3678 err = __check_stack_boundary(env, regno, min_off, access_size,
3679 zero_size_allowed);
3680 if (err)
3681 return err;
3682 } else {
088ec26d
AI
3683 /* Variable offset is prohibited for unprivileged mode for
3684 * simplicity since it requires corresponding support in
3685 * Spectre masking for stack ALU.
3686 * See also retrieve_ptr_limit().
3687 */
2c78ee89 3688 if (!env->bypass_spec_v1) {
088ec26d 3689 char tn_buf[48];
f1174f77 3690
088ec26d
AI
3691 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3692 verbose(env, "R%d indirect variable offset stack access prohibited for !root, var_off=%s\n",
3693 regno, tn_buf);
3694 return -EACCES;
3695 }
f2bcd05e
AI
3696 /* Only initialized buffer on stack is allowed to be accessed
3697 * with variable offset. With uninitialized buffer it's hard to
3698 * guarantee that whole memory is marked as initialized on
3699 * helper return since specific bounds are unknown what may
3700 * cause uninitialized stack leaking.
3701 */
3702 if (meta && meta->raw_mode)
3703 meta = NULL;
3704
107c26a7
AI
3705 if (reg->smax_value >= BPF_MAX_VAR_OFF ||
3706 reg->smax_value <= -BPF_MAX_VAR_OFF) {
3707 verbose(env, "R%d unbounded indirect variable offset stack access\n",
3708 regno);
3709 return -EACCES;
3710 }
2011fccf 3711 min_off = reg->smin_value + reg->off;
107c26a7 3712 max_off = reg->smax_value + reg->off;
2011fccf
AI
3713 err = __check_stack_boundary(env, regno, min_off, access_size,
3714 zero_size_allowed);
107c26a7
AI
3715 if (err) {
3716 verbose(env, "R%d min value is outside of stack bound\n",
3717 regno);
2011fccf 3718 return err;
107c26a7 3719 }
2011fccf
AI
3720 err = __check_stack_boundary(env, regno, max_off, access_size,
3721 zero_size_allowed);
107c26a7
AI
3722 if (err) {
3723 verbose(env, "R%d max value is outside of stack bound\n",
3724 regno);
2011fccf 3725 return err;
107c26a7 3726 }
17a52670
AS
3727 }
3728
435faee1
DB
3729 if (meta && meta->raw_mode) {
3730 meta->access_size = access_size;
3731 meta->regno = regno;
3732 return 0;
3733 }
3734
2011fccf 3735 for (i = min_off; i < max_off + access_size; i++) {
cc2b14d5
AS
3736 u8 *stype;
3737
2011fccf 3738 slot = -i - 1;
638f5b90 3739 spi = slot / BPF_REG_SIZE;
cc2b14d5
AS
3740 if (state->allocated_stack <= slot)
3741 goto err;
3742 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
3743 if (*stype == STACK_MISC)
3744 goto mark;
3745 if (*stype == STACK_ZERO) {
3746 /* helper can write anything into the stack */
3747 *stype = STACK_MISC;
3748 goto mark;
17a52670 3749 }
1d68f22b
YS
3750
3751 if (state->stack[spi].slot_type[0] == STACK_SPILL &&
3752 state->stack[spi].spilled_ptr.type == PTR_TO_BTF_ID)
3753 goto mark;
3754
f7cf25b2
AS
3755 if (state->stack[spi].slot_type[0] == STACK_SPILL &&
3756 state->stack[spi].spilled_ptr.type == SCALAR_VALUE) {
f54c7898 3757 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
f7cf25b2
AS
3758 for (j = 0; j < BPF_REG_SIZE; j++)
3759 state->stack[spi].slot_type[j] = STACK_MISC;
3760 goto mark;
3761 }
3762
cc2b14d5 3763err:
2011fccf
AI
3764 if (tnum_is_const(reg->var_off)) {
3765 verbose(env, "invalid indirect read from stack off %d+%d size %d\n",
3766 min_off, i - min_off, access_size);
3767 } else {
3768 char tn_buf[48];
3769
3770 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3771 verbose(env, "invalid indirect read from stack var_off %s+%d size %d\n",
3772 tn_buf, i - min_off, access_size);
3773 }
cc2b14d5
AS
3774 return -EACCES;
3775mark:
3776 /* reading any byte out of 8-byte 'spill_slot' will cause
3777 * the whole slot to be marked as 'read'
3778 */
679c782d 3779 mark_reg_read(env, &state->stack[spi].spilled_ptr,
5327ed3d
JW
3780 state->stack[spi].spilled_ptr.parent,
3781 REG_LIVE_READ64);
17a52670 3782 }
2011fccf 3783 return update_stack_depth(env, state, min_off);
17a52670
AS
3784}
3785
06c1c049
GB
3786static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
3787 int access_size, bool zero_size_allowed,
3788 struct bpf_call_arg_meta *meta)
3789{
638f5b90 3790 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
06c1c049 3791
f1174f77 3792 switch (reg->type) {
06c1c049 3793 case PTR_TO_PACKET:
de8f3a83 3794 case PTR_TO_PACKET_META:
9fd29c08
YS
3795 return check_packet_access(env, regno, reg->off, access_size,
3796 zero_size_allowed);
06c1c049 3797 case PTR_TO_MAP_VALUE:
591fe988
DB
3798 if (check_map_access_type(env, regno, reg->off, access_size,
3799 meta && meta->raw_mode ? BPF_WRITE :
3800 BPF_READ))
3801 return -EACCES;
9fd29c08
YS
3802 return check_map_access(env, regno, reg->off, access_size,
3803 zero_size_allowed);
457f4436
AN
3804 case PTR_TO_MEM:
3805 return check_mem_region_access(env, regno, reg->off,
3806 access_size, reg->mem_size,
3807 zero_size_allowed);
afbf21dc
YS
3808 case PTR_TO_RDONLY_BUF:
3809 if (meta && meta->raw_mode)
3810 return -EACCES;
3811 return check_buffer_access(env, reg, regno, reg->off,
3812 access_size, zero_size_allowed,
3813 "rdonly",
3814 &env->prog->aux->max_rdonly_access);
3815 case PTR_TO_RDWR_BUF:
3816 return check_buffer_access(env, reg, regno, reg->off,
3817 access_size, zero_size_allowed,
3818 "rdwr",
3819 &env->prog->aux->max_rdwr_access);
0d004c02 3820 case PTR_TO_STACK:
06c1c049
GB
3821 return check_stack_boundary(env, regno, access_size,
3822 zero_size_allowed, meta);
0d004c02
LB
3823 default: /* scalar_value or invalid ptr */
3824 /* Allow zero-byte read from NULL, regardless of pointer type */
3825 if (zero_size_allowed && access_size == 0 &&
3826 register_is_null(reg))
3827 return 0;
3828
3829 verbose(env, "R%d type=%s expected=%s\n", regno,
3830 reg_type_str[reg->type],
3831 reg_type_str[PTR_TO_STACK]);
3832 return -EACCES;
06c1c049
GB
3833 }
3834}
3835
d83525ca
AS
3836/* Implementation details:
3837 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL
3838 * Two bpf_map_lookups (even with the same key) will have different reg->id.
3839 * For traditional PTR_TO_MAP_VALUE the verifier clears reg->id after
3840 * value_or_null->value transition, since the verifier only cares about
3841 * the range of access to valid map value pointer and doesn't care about actual
3842 * address of the map element.
3843 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
3844 * reg->id > 0 after value_or_null->value transition. By doing so
3845 * two bpf_map_lookups will be considered two different pointers that
3846 * point to different bpf_spin_locks.
3847 * The verifier allows taking only one bpf_spin_lock at a time to avoid
3848 * dead-locks.
3849 * Since only one bpf_spin_lock is allowed the checks are simpler than
3850 * reg_is_refcounted() logic. The verifier needs to remember only
3851 * one spin_lock instead of array of acquired_refs.
3852 * cur_state->active_spin_lock remembers which map value element got locked
3853 * and clears it after bpf_spin_unlock.
3854 */
3855static int process_spin_lock(struct bpf_verifier_env *env, int regno,
3856 bool is_lock)
3857{
3858 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
3859 struct bpf_verifier_state *cur = env->cur_state;
3860 bool is_const = tnum_is_const(reg->var_off);
3861 struct bpf_map *map = reg->map_ptr;
3862 u64 val = reg->var_off.value;
3863
d83525ca
AS
3864 if (!is_const) {
3865 verbose(env,
3866 "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
3867 regno);
3868 return -EINVAL;
3869 }
3870 if (!map->btf) {
3871 verbose(env,
3872 "map '%s' has to have BTF in order to use bpf_spin_lock\n",
3873 map->name);
3874 return -EINVAL;
3875 }
3876 if (!map_value_has_spin_lock(map)) {
3877 if (map->spin_lock_off == -E2BIG)
3878 verbose(env,
3879 "map '%s' has more than one 'struct bpf_spin_lock'\n",
3880 map->name);
3881 else if (map->spin_lock_off == -ENOENT)
3882 verbose(env,
3883 "map '%s' doesn't have 'struct bpf_spin_lock'\n",
3884 map->name);
3885 else
3886 verbose(env,
3887 "map '%s' is not a struct type or bpf_spin_lock is mangled\n",
3888 map->name);
3889 return -EINVAL;
3890 }
3891 if (map->spin_lock_off != val + reg->off) {
3892 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock'\n",
3893 val + reg->off);
3894 return -EINVAL;
3895 }
3896 if (is_lock) {
3897 if (cur->active_spin_lock) {
3898 verbose(env,
3899 "Locking two bpf_spin_locks are not allowed\n");
3900 return -EINVAL;
3901 }
3902 cur->active_spin_lock = reg->id;
3903 } else {
3904 if (!cur->active_spin_lock) {
3905 verbose(env, "bpf_spin_unlock without taking a lock\n");
3906 return -EINVAL;
3907 }
3908 if (cur->active_spin_lock != reg->id) {
3909 verbose(env, "bpf_spin_unlock of different lock\n");
3910 return -EINVAL;
3911 }
3912 cur->active_spin_lock = 0;
3913 }
3914 return 0;
3915}
3916
90133415
DB
3917static bool arg_type_is_mem_ptr(enum bpf_arg_type type)
3918{
3919 return type == ARG_PTR_TO_MEM ||
3920 type == ARG_PTR_TO_MEM_OR_NULL ||
3921 type == ARG_PTR_TO_UNINIT_MEM;
3922}
3923
3924static bool arg_type_is_mem_size(enum bpf_arg_type type)
3925{
3926 return type == ARG_CONST_SIZE ||
3927 type == ARG_CONST_SIZE_OR_ZERO;
3928}
3929
457f4436
AN
3930static bool arg_type_is_alloc_size(enum bpf_arg_type type)
3931{
3932 return type == ARG_CONST_ALLOC_SIZE_OR_ZERO;
3933}
3934
57c3bb72
AI
3935static bool arg_type_is_int_ptr(enum bpf_arg_type type)
3936{
3937 return type == ARG_PTR_TO_INT ||
3938 type == ARG_PTR_TO_LONG;
3939}
3940
3941static int int_ptr_type_to_size(enum bpf_arg_type type)
3942{
3943 if (type == ARG_PTR_TO_INT)
3944 return sizeof(u32);
3945 else if (type == ARG_PTR_TO_LONG)
3946 return sizeof(u64);
3947
3948 return -EINVAL;
3949}
3950
912f442c
LB
3951static int resolve_map_arg_type(struct bpf_verifier_env *env,
3952 const struct bpf_call_arg_meta *meta,
3953 enum bpf_arg_type *arg_type)
3954{
3955 if (!meta->map_ptr) {
3956 /* kernel subsystem misconfigured verifier */
3957 verbose(env, "invalid map_ptr to access map->type\n");
3958 return -EACCES;
3959 }
3960
3961 switch (meta->map_ptr->map_type) {
3962 case BPF_MAP_TYPE_SOCKMAP:
3963 case BPF_MAP_TYPE_SOCKHASH:
3964 if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
6550f2dd 3965 *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
912f442c
LB
3966 } else {
3967 verbose(env, "invalid arg_type for sockmap/sockhash\n");
3968 return -EINVAL;
3969 }
3970 break;
3971
3972 default:
3973 break;
3974 }
3975 return 0;
3976}
3977
f79e7ea5
LB
3978struct bpf_reg_types {
3979 const enum bpf_reg_type types[10];
1df8f55a 3980 u32 *btf_id;
f79e7ea5
LB
3981};
3982
3983static const struct bpf_reg_types map_key_value_types = {
3984 .types = {
3985 PTR_TO_STACK,
3986 PTR_TO_PACKET,
3987 PTR_TO_PACKET_META,
3988 PTR_TO_MAP_VALUE,
3989 },
3990};
3991
3992static const struct bpf_reg_types sock_types = {
3993 .types = {
3994 PTR_TO_SOCK_COMMON,
3995 PTR_TO_SOCKET,
3996 PTR_TO_TCP_SOCK,
3997 PTR_TO_XDP_SOCK,
3998 },
3999};
4000
49a2a4d4 4001#ifdef CONFIG_NET
1df8f55a
MKL
4002static const struct bpf_reg_types btf_id_sock_common_types = {
4003 .types = {
4004 PTR_TO_SOCK_COMMON,
4005 PTR_TO_SOCKET,
4006 PTR_TO_TCP_SOCK,
4007 PTR_TO_XDP_SOCK,
4008 PTR_TO_BTF_ID,
4009 },
4010 .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
4011};
49a2a4d4 4012#endif
1df8f55a 4013
f79e7ea5
LB
4014static const struct bpf_reg_types mem_types = {
4015 .types = {
4016 PTR_TO_STACK,
4017 PTR_TO_PACKET,
4018 PTR_TO_PACKET_META,
4019 PTR_TO_MAP_VALUE,
4020 PTR_TO_MEM,
4021 PTR_TO_RDONLY_BUF,
4022 PTR_TO_RDWR_BUF,
4023 },
4024};
4025
4026static const struct bpf_reg_types int_ptr_types = {
4027 .types = {
4028 PTR_TO_STACK,
4029 PTR_TO_PACKET,
4030 PTR_TO_PACKET_META,
4031 PTR_TO_MAP_VALUE,
4032 },
4033};
4034
4035static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
4036static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
4037static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
4038static const struct bpf_reg_types alloc_mem_types = { .types = { PTR_TO_MEM } };
4039static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
4040static const struct bpf_reg_types btf_ptr_types = { .types = { PTR_TO_BTF_ID } };
4041static const struct bpf_reg_types spin_lock_types = { .types = { PTR_TO_MAP_VALUE } };
eaa6bcb7 4042static const struct bpf_reg_types percpu_btf_ptr_types = { .types = { PTR_TO_PERCPU_BTF_ID } };
f79e7ea5 4043
0789e13b 4044static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
f79e7ea5
LB
4045 [ARG_PTR_TO_MAP_KEY] = &map_key_value_types,
4046 [ARG_PTR_TO_MAP_VALUE] = &map_key_value_types,
4047 [ARG_PTR_TO_UNINIT_MAP_VALUE] = &map_key_value_types,
4048 [ARG_PTR_TO_MAP_VALUE_OR_NULL] = &map_key_value_types,
4049 [ARG_CONST_SIZE] = &scalar_types,
4050 [ARG_CONST_SIZE_OR_ZERO] = &scalar_types,
4051 [ARG_CONST_ALLOC_SIZE_OR_ZERO] = &scalar_types,
4052 [ARG_CONST_MAP_PTR] = &const_map_ptr_types,
4053 [ARG_PTR_TO_CTX] = &context_types,
4054 [ARG_PTR_TO_CTX_OR_NULL] = &context_types,
4055 [ARG_PTR_TO_SOCK_COMMON] = &sock_types,
49a2a4d4 4056#ifdef CONFIG_NET
1df8f55a 4057 [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types,
49a2a4d4 4058#endif
f79e7ea5
LB
4059 [ARG_PTR_TO_SOCKET] = &fullsock_types,
4060 [ARG_PTR_TO_SOCKET_OR_NULL] = &fullsock_types,
4061 [ARG_PTR_TO_BTF_ID] = &btf_ptr_types,
4062 [ARG_PTR_TO_SPIN_LOCK] = &spin_lock_types,
4063 [ARG_PTR_TO_MEM] = &mem_types,
4064 [ARG_PTR_TO_MEM_OR_NULL] = &mem_types,
4065 [ARG_PTR_TO_UNINIT_MEM] = &mem_types,
4066 [ARG_PTR_TO_ALLOC_MEM] = &alloc_mem_types,
4067 [ARG_PTR_TO_ALLOC_MEM_OR_NULL] = &alloc_mem_types,
4068 [ARG_PTR_TO_INT] = &int_ptr_types,
4069 [ARG_PTR_TO_LONG] = &int_ptr_types,
eaa6bcb7 4070 [ARG_PTR_TO_PERCPU_BTF_ID] = &percpu_btf_ptr_types,
f79e7ea5
LB
4071};
4072
4073static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
a968d5e2
MKL
4074 enum bpf_arg_type arg_type,
4075 const u32 *arg_btf_id)
f79e7ea5
LB
4076{
4077 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4078 enum bpf_reg_type expected, type = reg->type;
a968d5e2 4079 const struct bpf_reg_types *compatible;
f79e7ea5
LB
4080 int i, j;
4081
a968d5e2
MKL
4082 compatible = compatible_reg_types[arg_type];
4083 if (!compatible) {
4084 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
4085 return -EFAULT;
4086 }
4087
f79e7ea5
LB
4088 for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
4089 expected = compatible->types[i];
4090 if (expected == NOT_INIT)
4091 break;
4092
4093 if (type == expected)
a968d5e2 4094 goto found;
f79e7ea5
LB
4095 }
4096
4097 verbose(env, "R%d type=%s expected=", regno, reg_type_str[type]);
4098 for (j = 0; j + 1 < i; j++)
4099 verbose(env, "%s, ", reg_type_str[compatible->types[j]]);
4100 verbose(env, "%s\n", reg_type_str[compatible->types[j]]);
4101 return -EACCES;
a968d5e2
MKL
4102
4103found:
4104 if (type == PTR_TO_BTF_ID) {
1df8f55a
MKL
4105 if (!arg_btf_id) {
4106 if (!compatible->btf_id) {
4107 verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
4108 return -EFAULT;
4109 }
4110 arg_btf_id = compatible->btf_id;
4111 }
4112
a968d5e2
MKL
4113 if (!btf_struct_ids_match(&env->log, reg->off, reg->btf_id,
4114 *arg_btf_id)) {
4115 verbose(env, "R%d is of type %s but %s is expected\n",
4116 regno, kernel_type_name(reg->btf_id),
4117 kernel_type_name(*arg_btf_id));
4118 return -EACCES;
4119 }
4120
4121 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4122 verbose(env, "R%d is a pointer to in-kernel struct with non-zero offset\n",
4123 regno);
4124 return -EACCES;
4125 }
4126 }
4127
4128 return 0;
f79e7ea5
LB
4129}
4130
af7ec138
YS
4131static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
4132 struct bpf_call_arg_meta *meta,
4133 const struct bpf_func_proto *fn)
17a52670 4134{
af7ec138 4135 u32 regno = BPF_REG_1 + arg;
638f5b90 4136 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
af7ec138 4137 enum bpf_arg_type arg_type = fn->arg_type[arg];
f79e7ea5 4138 enum bpf_reg_type type = reg->type;
17a52670
AS
4139 int err = 0;
4140
80f1d68c 4141 if (arg_type == ARG_DONTCARE)
17a52670
AS
4142 return 0;
4143
dc503a8a
EC
4144 err = check_reg_arg(env, regno, SRC_OP);
4145 if (err)
4146 return err;
17a52670 4147
1be7f75d
AS
4148 if (arg_type == ARG_ANYTHING) {
4149 if (is_pointer_value(env, regno)) {
61bd5218
JK
4150 verbose(env, "R%d leaks addr into helper function\n",
4151 regno);
1be7f75d
AS
4152 return -EACCES;
4153 }
80f1d68c 4154 return 0;
1be7f75d 4155 }
80f1d68c 4156
de8f3a83 4157 if (type_is_pkt_pointer(type) &&
3a0af8fd 4158 !may_access_direct_pkt_data(env, meta, BPF_READ)) {
61bd5218 4159 verbose(env, "helper access to the packet is not allowed\n");
6841de8b
AS
4160 return -EACCES;
4161 }
4162
912f442c
LB
4163 if (arg_type == ARG_PTR_TO_MAP_VALUE ||
4164 arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE ||
4165 arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL) {
4166 err = resolve_map_arg_type(env, meta, &arg_type);
4167 if (err)
4168 return err;
4169 }
4170
fd1b0d60
LB
4171 if (register_is_null(reg) && arg_type_may_be_null(arg_type))
4172 /* A NULL register has a SCALAR_VALUE type, so skip
4173 * type checking.
4174 */
4175 goto skip_type_check;
4176
a968d5e2 4177 err = check_reg_type(env, regno, arg_type, fn->arg_btf_id[arg]);
f79e7ea5
LB
4178 if (err)
4179 return err;
4180
a968d5e2 4181 if (type == PTR_TO_CTX) {
feec7040
LB
4182 err = check_ctx_reg(env, reg, regno);
4183 if (err < 0)
4184 return err;
d7b9454a
LB
4185 }
4186
fd1b0d60 4187skip_type_check:
02f7c958 4188 if (reg->ref_obj_id) {
457f4436
AN
4189 if (meta->ref_obj_id) {
4190 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
4191 regno, reg->ref_obj_id,
4192 meta->ref_obj_id);
4193 return -EFAULT;
4194 }
4195 meta->ref_obj_id = reg->ref_obj_id;
17a52670
AS
4196 }
4197
17a52670
AS
4198 if (arg_type == ARG_CONST_MAP_PTR) {
4199 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
33ff9823 4200 meta->map_ptr = reg->map_ptr;
17a52670
AS
4201 } else if (arg_type == ARG_PTR_TO_MAP_KEY) {
4202 /* bpf_map_xxx(..., map_ptr, ..., key) call:
4203 * check that [key, key + map->key_size) are within
4204 * stack limits and initialized
4205 */
33ff9823 4206 if (!meta->map_ptr) {
17a52670
AS
4207 /* in function declaration map_ptr must come before
4208 * map_key, so that it's verified and known before
4209 * we have to check map_key here. Otherwise it means
4210 * that kernel subsystem misconfigured verifier
4211 */
61bd5218 4212 verbose(env, "invalid map_ptr to access map->key\n");
17a52670
AS
4213 return -EACCES;
4214 }
d71962f3
PC
4215 err = check_helper_mem_access(env, regno,
4216 meta->map_ptr->key_size, false,
4217 NULL);
2ea864c5 4218 } else if (arg_type == ARG_PTR_TO_MAP_VALUE ||
6ac99e8f
MKL
4219 (arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL &&
4220 !register_is_null(reg)) ||
2ea864c5 4221 arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE) {
17a52670
AS
4222 /* bpf_map_xxx(..., map_ptr, ..., value) call:
4223 * check [value, value + map->value_size) validity
4224 */
33ff9823 4225 if (!meta->map_ptr) {
17a52670 4226 /* kernel subsystem misconfigured verifier */
61bd5218 4227 verbose(env, "invalid map_ptr to access map->value\n");
17a52670
AS
4228 return -EACCES;
4229 }
2ea864c5 4230 meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE);
d71962f3
PC
4231 err = check_helper_mem_access(env, regno,
4232 meta->map_ptr->value_size, false,
2ea864c5 4233 meta);
eaa6bcb7
HL
4234 } else if (arg_type == ARG_PTR_TO_PERCPU_BTF_ID) {
4235 if (!reg->btf_id) {
4236 verbose(env, "Helper has invalid btf_id in R%d\n", regno);
4237 return -EACCES;
4238 }
4239 meta->ret_btf_id = reg->btf_id;
c18f0b6a
LB
4240 } else if (arg_type == ARG_PTR_TO_SPIN_LOCK) {
4241 if (meta->func_id == BPF_FUNC_spin_lock) {
4242 if (process_spin_lock(env, regno, true))
4243 return -EACCES;
4244 } else if (meta->func_id == BPF_FUNC_spin_unlock) {
4245 if (process_spin_lock(env, regno, false))
4246 return -EACCES;
4247 } else {
4248 verbose(env, "verifier internal error\n");
4249 return -EFAULT;
4250 }
a2bbe7cc
LB
4251 } else if (arg_type_is_mem_ptr(arg_type)) {
4252 /* The access to this pointer is only checked when we hit the
4253 * next is_mem_size argument below.
4254 */
4255 meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MEM);
90133415 4256 } else if (arg_type_is_mem_size(arg_type)) {
39f19ebb 4257 bool zero_size_allowed = (arg_type == ARG_CONST_SIZE_OR_ZERO);
17a52670 4258
10060503
JF
4259 /* This is used to refine r0 return value bounds for helpers
4260 * that enforce this value as an upper bound on return values.
4261 * See do_refine_retval_range() for helpers that can refine
4262 * the return value. C type of helper is u32 so we pull register
4263 * bound from umax_value however, if negative verifier errors
4264 * out. Only upper bounds can be learned because retval is an
4265 * int type and negative retvals are allowed.
849fa506 4266 */
10060503 4267 meta->msize_max_value = reg->umax_value;
849fa506 4268
f1174f77
EC
4269 /* The register is SCALAR_VALUE; the access check
4270 * happens using its boundaries.
06c1c049 4271 */
f1174f77 4272 if (!tnum_is_const(reg->var_off))
06c1c049
GB
4273 /* For unprivileged variable accesses, disable raw
4274 * mode so that the program is required to
4275 * initialize all the memory that the helper could
4276 * just partially fill up.
4277 */
4278 meta = NULL;
4279
b03c9f9f 4280 if (reg->smin_value < 0) {
61bd5218 4281 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
f1174f77
EC
4282 regno);
4283 return -EACCES;
4284 }
06c1c049 4285
b03c9f9f 4286 if (reg->umin_value == 0) {
f1174f77
EC
4287 err = check_helper_mem_access(env, regno - 1, 0,
4288 zero_size_allowed,
4289 meta);
06c1c049
GB
4290 if (err)
4291 return err;
06c1c049 4292 }
f1174f77 4293
b03c9f9f 4294 if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
61bd5218 4295 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
f1174f77
EC
4296 regno);
4297 return -EACCES;
4298 }
4299 err = check_helper_mem_access(env, regno - 1,
b03c9f9f 4300 reg->umax_value,
f1174f77 4301 zero_size_allowed, meta);
b5dc0163
AS
4302 if (!err)
4303 err = mark_chain_precision(env, regno);
457f4436
AN
4304 } else if (arg_type_is_alloc_size(arg_type)) {
4305 if (!tnum_is_const(reg->var_off)) {
4306 verbose(env, "R%d unbounded size, use 'var &= const' or 'if (var < const)'\n",
4307 regno);
4308 return -EACCES;
4309 }
4310 meta->mem_size = reg->var_off.value;
57c3bb72
AI
4311 } else if (arg_type_is_int_ptr(arg_type)) {
4312 int size = int_ptr_type_to_size(arg_type);
4313
4314 err = check_helper_mem_access(env, regno, size, false, meta);
4315 if (err)
4316 return err;
4317 err = check_ptr_alignment(env, reg, 0, size, true);
17a52670
AS
4318 }
4319
4320 return err;
4321}
4322
0126240f
LB
4323static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
4324{
4325 enum bpf_attach_type eatype = env->prog->expected_attach_type;
7e40781c 4326 enum bpf_prog_type type = resolve_prog_type(env->prog);
0126240f
LB
4327
4328 if (func_id != BPF_FUNC_map_update_elem)
4329 return false;
4330
4331 /* It's not possible to get access to a locked struct sock in these
4332 * contexts, so updating is safe.
4333 */
4334 switch (type) {
4335 case BPF_PROG_TYPE_TRACING:
4336 if (eatype == BPF_TRACE_ITER)
4337 return true;
4338 break;
4339 case BPF_PROG_TYPE_SOCKET_FILTER:
4340 case BPF_PROG_TYPE_SCHED_CLS:
4341 case BPF_PROG_TYPE_SCHED_ACT:
4342 case BPF_PROG_TYPE_XDP:
4343 case BPF_PROG_TYPE_SK_REUSEPORT:
4344 case BPF_PROG_TYPE_FLOW_DISSECTOR:
4345 case BPF_PROG_TYPE_SK_LOOKUP:
4346 return true;
4347 default:
4348 break;
4349 }
4350
4351 verbose(env, "cannot update sockmap in this context\n");
4352 return false;
4353}
4354
e411901c
MF
4355static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
4356{
4357 return env->prog->jit_requested && IS_ENABLED(CONFIG_X86_64);
4358}
4359
61bd5218
JK
4360static int check_map_func_compatibility(struct bpf_verifier_env *env,
4361 struct bpf_map *map, int func_id)
35578d79 4362{
35578d79
KX
4363 if (!map)
4364 return 0;
4365
6aff67c8
AS
4366 /* We need a two way check, first is from map perspective ... */
4367 switch (map->map_type) {
4368 case BPF_MAP_TYPE_PROG_ARRAY:
4369 if (func_id != BPF_FUNC_tail_call)
4370 goto error;
4371 break;
4372 case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
4373 if (func_id != BPF_FUNC_perf_event_read &&
908432ca 4374 func_id != BPF_FUNC_perf_event_output &&
a7658e1a 4375 func_id != BPF_FUNC_skb_output &&
d831ee84
EC
4376 func_id != BPF_FUNC_perf_event_read_value &&
4377 func_id != BPF_FUNC_xdp_output)
6aff67c8
AS
4378 goto error;
4379 break;
457f4436
AN
4380 case BPF_MAP_TYPE_RINGBUF:
4381 if (func_id != BPF_FUNC_ringbuf_output &&
4382 func_id != BPF_FUNC_ringbuf_reserve &&
4383 func_id != BPF_FUNC_ringbuf_submit &&
4384 func_id != BPF_FUNC_ringbuf_discard &&
4385 func_id != BPF_FUNC_ringbuf_query)
4386 goto error;
4387 break;
6aff67c8
AS
4388 case BPF_MAP_TYPE_STACK_TRACE:
4389 if (func_id != BPF_FUNC_get_stackid)
4390 goto error;
4391 break;
4ed8ec52 4392 case BPF_MAP_TYPE_CGROUP_ARRAY:
60747ef4 4393 if (func_id != BPF_FUNC_skb_under_cgroup &&
60d20f91 4394 func_id != BPF_FUNC_current_task_under_cgroup)
4a482f34
MKL
4395 goto error;
4396 break;
cd339431 4397 case BPF_MAP_TYPE_CGROUP_STORAGE:
b741f163 4398 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
cd339431
RG
4399 if (func_id != BPF_FUNC_get_local_storage)
4400 goto error;
4401 break;
546ac1ff 4402 case BPF_MAP_TYPE_DEVMAP:
6f9d451a 4403 case BPF_MAP_TYPE_DEVMAP_HASH:
0cdbb4b0
THJ
4404 if (func_id != BPF_FUNC_redirect_map &&
4405 func_id != BPF_FUNC_map_lookup_elem)
546ac1ff
JF
4406 goto error;
4407 break;
fbfc504a
BT
4408 /* Restrict bpf side of cpumap and xskmap, open when use-cases
4409 * appear.
4410 */
6710e112
JDB
4411 case BPF_MAP_TYPE_CPUMAP:
4412 if (func_id != BPF_FUNC_redirect_map)
4413 goto error;
4414 break;
fada7fdc
JL
4415 case BPF_MAP_TYPE_XSKMAP:
4416 if (func_id != BPF_FUNC_redirect_map &&
4417 func_id != BPF_FUNC_map_lookup_elem)
4418 goto error;
4419 break;
56f668df 4420 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
bcc6b1b7 4421 case BPF_MAP_TYPE_HASH_OF_MAPS:
56f668df
MKL
4422 if (func_id != BPF_FUNC_map_lookup_elem)
4423 goto error;
16a43625 4424 break;
174a79ff
JF
4425 case BPF_MAP_TYPE_SOCKMAP:
4426 if (func_id != BPF_FUNC_sk_redirect_map &&
4427 func_id != BPF_FUNC_sock_map_update &&
4f738adb 4428 func_id != BPF_FUNC_map_delete_elem &&
9fed9000 4429 func_id != BPF_FUNC_msg_redirect_map &&
64d85290 4430 func_id != BPF_FUNC_sk_select_reuseport &&
0126240f
LB
4431 func_id != BPF_FUNC_map_lookup_elem &&
4432 !may_update_sockmap(env, func_id))
174a79ff
JF
4433 goto error;
4434 break;
81110384
JF
4435 case BPF_MAP_TYPE_SOCKHASH:
4436 if (func_id != BPF_FUNC_sk_redirect_hash &&
4437 func_id != BPF_FUNC_sock_hash_update &&
4438 func_id != BPF_FUNC_map_delete_elem &&
9fed9000 4439 func_id != BPF_FUNC_msg_redirect_hash &&
64d85290 4440 func_id != BPF_FUNC_sk_select_reuseport &&
0126240f
LB
4441 func_id != BPF_FUNC_map_lookup_elem &&
4442 !may_update_sockmap(env, func_id))
81110384
JF
4443 goto error;
4444 break;
2dbb9b9e
MKL
4445 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
4446 if (func_id != BPF_FUNC_sk_select_reuseport)
4447 goto error;
4448 break;
f1a2e44a
MV
4449 case BPF_MAP_TYPE_QUEUE:
4450 case BPF_MAP_TYPE_STACK:
4451 if (func_id != BPF_FUNC_map_peek_elem &&
4452 func_id != BPF_FUNC_map_pop_elem &&
4453 func_id != BPF_FUNC_map_push_elem)
4454 goto error;
4455 break;
6ac99e8f
MKL
4456 case BPF_MAP_TYPE_SK_STORAGE:
4457 if (func_id != BPF_FUNC_sk_storage_get &&
4458 func_id != BPF_FUNC_sk_storage_delete)
4459 goto error;
4460 break;
8ea63684
KS
4461 case BPF_MAP_TYPE_INODE_STORAGE:
4462 if (func_id != BPF_FUNC_inode_storage_get &&
4463 func_id != BPF_FUNC_inode_storage_delete)
4464 goto error;
4465 break;
6aff67c8
AS
4466 default:
4467 break;
4468 }
4469
4470 /* ... and second from the function itself. */
4471 switch (func_id) {
4472 case BPF_FUNC_tail_call:
4473 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
4474 goto error;
e411901c
MF
4475 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
4476 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
f4d7e40a
AS
4477 return -EINVAL;
4478 }
6aff67c8
AS
4479 break;
4480 case BPF_FUNC_perf_event_read:
4481 case BPF_FUNC_perf_event_output:
908432ca 4482 case BPF_FUNC_perf_event_read_value:
a7658e1a 4483 case BPF_FUNC_skb_output:
d831ee84 4484 case BPF_FUNC_xdp_output:
6aff67c8
AS
4485 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
4486 goto error;
4487 break;
4488 case BPF_FUNC_get_stackid:
4489 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
4490 goto error;
4491 break;
60d20f91 4492 case BPF_FUNC_current_task_under_cgroup:
747ea55e 4493 case BPF_FUNC_skb_under_cgroup:
4a482f34
MKL
4494 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
4495 goto error;
4496 break;
97f91a7c 4497 case BPF_FUNC_redirect_map:
9c270af3 4498 if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
6f9d451a 4499 map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
fbfc504a
BT
4500 map->map_type != BPF_MAP_TYPE_CPUMAP &&
4501 map->map_type != BPF_MAP_TYPE_XSKMAP)
97f91a7c
JF
4502 goto error;
4503 break;
174a79ff 4504 case BPF_FUNC_sk_redirect_map:
4f738adb 4505 case BPF_FUNC_msg_redirect_map:
81110384 4506 case BPF_FUNC_sock_map_update:
174a79ff
JF
4507 if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
4508 goto error;
4509 break;
81110384
JF
4510 case BPF_FUNC_sk_redirect_hash:
4511 case BPF_FUNC_msg_redirect_hash:
4512 case BPF_FUNC_sock_hash_update:
4513 if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
174a79ff
JF
4514 goto error;
4515 break;
cd339431 4516 case BPF_FUNC_get_local_storage:
b741f163
RG
4517 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
4518 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
cd339431
RG
4519 goto error;
4520 break;
2dbb9b9e 4521 case BPF_FUNC_sk_select_reuseport:
9fed9000
JS
4522 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
4523 map->map_type != BPF_MAP_TYPE_SOCKMAP &&
4524 map->map_type != BPF_MAP_TYPE_SOCKHASH)
2dbb9b9e
MKL
4525 goto error;
4526 break;
f1a2e44a
MV
4527 case BPF_FUNC_map_peek_elem:
4528 case BPF_FUNC_map_pop_elem:
4529 case BPF_FUNC_map_push_elem:
4530 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
4531 map->map_type != BPF_MAP_TYPE_STACK)
4532 goto error;
4533 break;
6ac99e8f
MKL
4534 case BPF_FUNC_sk_storage_get:
4535 case BPF_FUNC_sk_storage_delete:
4536 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
4537 goto error;
4538 break;
8ea63684
KS
4539 case BPF_FUNC_inode_storage_get:
4540 case BPF_FUNC_inode_storage_delete:
4541 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
4542 goto error;
4543 break;
6aff67c8
AS
4544 default:
4545 break;
35578d79
KX
4546 }
4547
4548 return 0;
6aff67c8 4549error:
61bd5218 4550 verbose(env, "cannot pass map_type %d into func %s#%d\n",
ebb676da 4551 map->map_type, func_id_name(func_id), func_id);
6aff67c8 4552 return -EINVAL;
35578d79
KX
4553}
4554
90133415 4555static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
435faee1
DB
4556{
4557 int count = 0;
4558
39f19ebb 4559 if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
435faee1 4560 count++;
39f19ebb 4561 if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
435faee1 4562 count++;
39f19ebb 4563 if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
435faee1 4564 count++;
39f19ebb 4565 if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
435faee1 4566 count++;
39f19ebb 4567 if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
435faee1
DB
4568 count++;
4569
90133415
DB
4570 /* We only support one arg being in raw mode at the moment,
4571 * which is sufficient for the helper functions we have
4572 * right now.
4573 */
4574 return count <= 1;
4575}
4576
4577static bool check_args_pair_invalid(enum bpf_arg_type arg_curr,
4578 enum bpf_arg_type arg_next)
4579{
4580 return (arg_type_is_mem_ptr(arg_curr) &&
4581 !arg_type_is_mem_size(arg_next)) ||
4582 (!arg_type_is_mem_ptr(arg_curr) &&
4583 arg_type_is_mem_size(arg_next));
4584}
4585
4586static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
4587{
4588 /* bpf_xxx(..., buf, len) call will access 'len'
4589 * bytes from memory 'buf'. Both arg types need
4590 * to be paired, so make sure there's no buggy
4591 * helper function specification.
4592 */
4593 if (arg_type_is_mem_size(fn->arg1_type) ||
4594 arg_type_is_mem_ptr(fn->arg5_type) ||
4595 check_args_pair_invalid(fn->arg1_type, fn->arg2_type) ||
4596 check_args_pair_invalid(fn->arg2_type, fn->arg3_type) ||
4597 check_args_pair_invalid(fn->arg3_type, fn->arg4_type) ||
4598 check_args_pair_invalid(fn->arg4_type, fn->arg5_type))
4599 return false;
4600
4601 return true;
4602}
4603
1b986589 4604static bool check_refcount_ok(const struct bpf_func_proto *fn, int func_id)
fd978bf7
JS
4605{
4606 int count = 0;
4607
1b986589 4608 if (arg_type_may_be_refcounted(fn->arg1_type))
fd978bf7 4609 count++;
1b986589 4610 if (arg_type_may_be_refcounted(fn->arg2_type))
fd978bf7 4611 count++;
1b986589 4612 if (arg_type_may_be_refcounted(fn->arg3_type))
fd978bf7 4613 count++;
1b986589 4614 if (arg_type_may_be_refcounted(fn->arg4_type))
fd978bf7 4615 count++;
1b986589 4616 if (arg_type_may_be_refcounted(fn->arg5_type))
fd978bf7
JS
4617 count++;
4618
1b986589
MKL
4619 /* A reference acquiring function cannot acquire
4620 * another refcounted ptr.
4621 */
64d85290 4622 if (may_be_acquire_function(func_id) && count)
1b986589
MKL
4623 return false;
4624
fd978bf7
JS
4625 /* We only support one arg being unreferenced at the moment,
4626 * which is sufficient for the helper functions we have right now.
4627 */
4628 return count <= 1;
4629}
4630
9436ef6e
LB
4631static bool check_btf_id_ok(const struct bpf_func_proto *fn)
4632{
4633 int i;
4634
1df8f55a 4635 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
9436ef6e
LB
4636 if (fn->arg_type[i] == ARG_PTR_TO_BTF_ID && !fn->arg_btf_id[i])
4637 return false;
4638
1df8f55a
MKL
4639 if (fn->arg_type[i] != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i])
4640 return false;
4641 }
4642
9436ef6e
LB
4643 return true;
4644}
4645
1b986589 4646static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
90133415
DB
4647{
4648 return check_raw_mode_ok(fn) &&
fd978bf7 4649 check_arg_pair_ok(fn) &&
9436ef6e 4650 check_btf_id_ok(fn) &&
1b986589 4651 check_refcount_ok(fn, func_id) ? 0 : -EINVAL;
435faee1
DB
4652}
4653
de8f3a83
DB
4654/* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
4655 * are now invalid, so turn them into unknown SCALAR_VALUE.
f1174f77 4656 */
f4d7e40a
AS
4657static void __clear_all_pkt_pointers(struct bpf_verifier_env *env,
4658 struct bpf_func_state *state)
969bf05e 4659{
58e2af8b 4660 struct bpf_reg_state *regs = state->regs, *reg;
969bf05e
AS
4661 int i;
4662
4663 for (i = 0; i < MAX_BPF_REG; i++)
de8f3a83 4664 if (reg_is_pkt_pointer_any(&regs[i]))
61bd5218 4665 mark_reg_unknown(env, regs, i);
969bf05e 4666
f3709f69
JS
4667 bpf_for_each_spilled_reg(i, state, reg) {
4668 if (!reg)
969bf05e 4669 continue;
de8f3a83 4670 if (reg_is_pkt_pointer_any(reg))
f54c7898 4671 __mark_reg_unknown(env, reg);
969bf05e
AS
4672 }
4673}
4674
f4d7e40a
AS
4675static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
4676{
4677 struct bpf_verifier_state *vstate = env->cur_state;
4678 int i;
4679
4680 for (i = 0; i <= vstate->curframe; i++)
4681 __clear_all_pkt_pointers(env, vstate->frame[i]);
4682}
4683
fd978bf7 4684static void release_reg_references(struct bpf_verifier_env *env,
1b986589
MKL
4685 struct bpf_func_state *state,
4686 int ref_obj_id)
fd978bf7
JS
4687{
4688 struct bpf_reg_state *regs = state->regs, *reg;
4689 int i;
4690
4691 for (i = 0; i < MAX_BPF_REG; i++)
1b986589 4692 if (regs[i].ref_obj_id == ref_obj_id)
fd978bf7
JS
4693 mark_reg_unknown(env, regs, i);
4694
4695 bpf_for_each_spilled_reg(i, state, reg) {
4696 if (!reg)
4697 continue;
1b986589 4698 if (reg->ref_obj_id == ref_obj_id)
f54c7898 4699 __mark_reg_unknown(env, reg);
fd978bf7
JS
4700 }
4701}
4702
4703/* The pointer with the specified id has released its reference to kernel
4704 * resources. Identify all copies of the same pointer and clear the reference.
4705 */
4706static int release_reference(struct bpf_verifier_env *env,
1b986589 4707 int ref_obj_id)
fd978bf7
JS
4708{
4709 struct bpf_verifier_state *vstate = env->cur_state;
1b986589 4710 int err;
fd978bf7
JS
4711 int i;
4712
1b986589
MKL
4713 err = release_reference_state(cur_func(env), ref_obj_id);
4714 if (err)
4715 return err;
4716
fd978bf7 4717 for (i = 0; i <= vstate->curframe; i++)
1b986589 4718 release_reg_references(env, vstate->frame[i], ref_obj_id);
fd978bf7 4719
1b986589 4720 return 0;
fd978bf7
JS
4721}
4722
51c39bb1
AS
4723static void clear_caller_saved_regs(struct bpf_verifier_env *env,
4724 struct bpf_reg_state *regs)
4725{
4726 int i;
4727
4728 /* after the call registers r0 - r5 were scratched */
4729 for (i = 0; i < CALLER_SAVED_REGS; i++) {
4730 mark_reg_not_init(env, regs, caller_saved[i]);
4731 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
4732 }
4733}
4734
f4d7e40a
AS
4735static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
4736 int *insn_idx)
4737{
4738 struct bpf_verifier_state *state = env->cur_state;
51c39bb1 4739 struct bpf_func_info_aux *func_info_aux;
f4d7e40a 4740 struct bpf_func_state *caller, *callee;
fd978bf7 4741 int i, err, subprog, target_insn;
51c39bb1 4742 bool is_global = false;
f4d7e40a 4743
aada9ce6 4744 if (state->curframe + 1 >= MAX_CALL_FRAMES) {
f4d7e40a 4745 verbose(env, "the call stack of %d frames is too deep\n",
aada9ce6 4746 state->curframe + 2);
f4d7e40a
AS
4747 return -E2BIG;
4748 }
4749
4750 target_insn = *insn_idx + insn->imm;
4751 subprog = find_subprog(env, target_insn + 1);
4752 if (subprog < 0) {
4753 verbose(env, "verifier bug. No program starts at insn %d\n",
4754 target_insn + 1);
4755 return -EFAULT;
4756 }
4757
4758 caller = state->frame[state->curframe];
4759 if (state->frame[state->curframe + 1]) {
4760 verbose(env, "verifier bug. Frame %d already allocated\n",
4761 state->curframe + 1);
4762 return -EFAULT;
4763 }
4764
51c39bb1
AS
4765 func_info_aux = env->prog->aux->func_info_aux;
4766 if (func_info_aux)
4767 is_global = func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
4768 err = btf_check_func_arg_match(env, subprog, caller->regs);
4769 if (err == -EFAULT)
4770 return err;
4771 if (is_global) {
4772 if (err) {
4773 verbose(env, "Caller passes invalid args into func#%d\n",
4774 subprog);
4775 return err;
4776 } else {
4777 if (env->log.level & BPF_LOG_LEVEL)
4778 verbose(env,
4779 "Func#%d is global and valid. Skipping.\n",
4780 subprog);
4781 clear_caller_saved_regs(env, caller->regs);
4782
4783 /* All global functions return SCALAR_VALUE */
4784 mark_reg_unknown(env, caller->regs, BPF_REG_0);
4785
4786 /* continue with next insn after call */
4787 return 0;
4788 }
4789 }
4790
f4d7e40a
AS
4791 callee = kzalloc(sizeof(*callee), GFP_KERNEL);
4792 if (!callee)
4793 return -ENOMEM;
4794 state->frame[state->curframe + 1] = callee;
4795
4796 /* callee cannot access r0, r6 - r9 for reading and has to write
4797 * into its own stack before reading from it.
4798 * callee can read/write into caller's stack
4799 */
4800 init_func_state(env, callee,
4801 /* remember the callsite, it will be used by bpf_exit */
4802 *insn_idx /* callsite */,
4803 state->curframe + 1 /* frameno within this callchain */,
f910cefa 4804 subprog /* subprog number within this prog */);
f4d7e40a 4805
fd978bf7
JS
4806 /* Transfer references to the callee */
4807 err = transfer_reference_state(callee, caller);
4808 if (err)
4809 return err;
4810
679c782d
EC
4811 /* copy r1 - r5 args that callee can access. The copy includes parent
4812 * pointers, which connects us up to the liveness chain
4813 */
f4d7e40a
AS
4814 for (i = BPF_REG_1; i <= BPF_REG_5; i++)
4815 callee->regs[i] = caller->regs[i];
4816
51c39bb1 4817 clear_caller_saved_regs(env, caller->regs);
f4d7e40a
AS
4818
4819 /* only increment it after check_reg_arg() finished */
4820 state->curframe++;
4821
4822 /* and go analyze first insn of the callee */
4823 *insn_idx = target_insn;
4824
06ee7115 4825 if (env->log.level & BPF_LOG_LEVEL) {
f4d7e40a
AS
4826 verbose(env, "caller:\n");
4827 print_verifier_state(env, caller);
4828 verbose(env, "callee:\n");
4829 print_verifier_state(env, callee);
4830 }
4831 return 0;
4832}
4833
4834static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
4835{
4836 struct bpf_verifier_state *state = env->cur_state;
4837 struct bpf_func_state *caller, *callee;
4838 struct bpf_reg_state *r0;
fd978bf7 4839 int err;
f4d7e40a
AS
4840
4841 callee = state->frame[state->curframe];
4842 r0 = &callee->regs[BPF_REG_0];
4843 if (r0->type == PTR_TO_STACK) {
4844 /* technically it's ok to return caller's stack pointer
4845 * (or caller's caller's pointer) back to the caller,
4846 * since these pointers are valid. Only current stack
4847 * pointer will be invalid as soon as function exits,
4848 * but let's be conservative
4849 */
4850 verbose(env, "cannot return stack pointer to the caller\n");
4851 return -EINVAL;
4852 }
4853
4854 state->curframe--;
4855 caller = state->frame[state->curframe];
4856 /* return to the caller whatever r0 had in the callee */
4857 caller->regs[BPF_REG_0] = *r0;
4858
fd978bf7
JS
4859 /* Transfer references to the caller */
4860 err = transfer_reference_state(caller, callee);
4861 if (err)
4862 return err;
4863
f4d7e40a 4864 *insn_idx = callee->callsite + 1;
06ee7115 4865 if (env->log.level & BPF_LOG_LEVEL) {
f4d7e40a
AS
4866 verbose(env, "returning from callee:\n");
4867 print_verifier_state(env, callee);
4868 verbose(env, "to caller at %d:\n", *insn_idx);
4869 print_verifier_state(env, caller);
4870 }
4871 /* clear everything in the callee */
4872 free_func_state(callee);
4873 state->frame[state->curframe + 1] = NULL;
4874 return 0;
4875}
4876
849fa506
YS
4877static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
4878 int func_id,
4879 struct bpf_call_arg_meta *meta)
4880{
4881 struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
4882
4883 if (ret_type != RET_INTEGER ||
4884 (func_id != BPF_FUNC_get_stack &&
47cc0ed5
DB
4885 func_id != BPF_FUNC_probe_read_str &&
4886 func_id != BPF_FUNC_probe_read_kernel_str &&
4887 func_id != BPF_FUNC_probe_read_user_str))
849fa506
YS
4888 return;
4889
10060503 4890 ret_reg->smax_value = meta->msize_max_value;
fa123ac0 4891 ret_reg->s32_max_value = meta->msize_max_value;
849fa506
YS
4892 __reg_deduce_bounds(ret_reg);
4893 __reg_bound_offset(ret_reg);
10060503 4894 __update_reg_bounds(ret_reg);
849fa506
YS
4895}
4896
c93552c4
DB
4897static int
4898record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
4899 int func_id, int insn_idx)
4900{
4901 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
591fe988 4902 struct bpf_map *map = meta->map_ptr;
c93552c4
DB
4903
4904 if (func_id != BPF_FUNC_tail_call &&
09772d92
DB
4905 func_id != BPF_FUNC_map_lookup_elem &&
4906 func_id != BPF_FUNC_map_update_elem &&
f1a2e44a
MV
4907 func_id != BPF_FUNC_map_delete_elem &&
4908 func_id != BPF_FUNC_map_push_elem &&
4909 func_id != BPF_FUNC_map_pop_elem &&
4910 func_id != BPF_FUNC_map_peek_elem)
c93552c4 4911 return 0;
09772d92 4912
591fe988 4913 if (map == NULL) {
c93552c4
DB
4914 verbose(env, "kernel subsystem misconfigured verifier\n");
4915 return -EINVAL;
4916 }
4917
591fe988
DB
4918 /* In case of read-only, some additional restrictions
4919 * need to be applied in order to prevent altering the
4920 * state of the map from program side.
4921 */
4922 if ((map->map_flags & BPF_F_RDONLY_PROG) &&
4923 (func_id == BPF_FUNC_map_delete_elem ||
4924 func_id == BPF_FUNC_map_update_elem ||
4925 func_id == BPF_FUNC_map_push_elem ||
4926 func_id == BPF_FUNC_map_pop_elem)) {
4927 verbose(env, "write into map forbidden\n");
4928 return -EACCES;
4929 }
4930
d2e4c1e6 4931 if (!BPF_MAP_PTR(aux->map_ptr_state))
c93552c4 4932 bpf_map_ptr_store(aux, meta->map_ptr,
2c78ee89 4933 !meta->map_ptr->bypass_spec_v1);
d2e4c1e6 4934 else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
c93552c4 4935 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
2c78ee89 4936 !meta->map_ptr->bypass_spec_v1);
c93552c4
DB
4937 return 0;
4938}
4939
d2e4c1e6
DB
4940static int
4941record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
4942 int func_id, int insn_idx)
4943{
4944 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
4945 struct bpf_reg_state *regs = cur_regs(env), *reg;
4946 struct bpf_map *map = meta->map_ptr;
4947 struct tnum range;
4948 u64 val;
cc52d914 4949 int err;
d2e4c1e6
DB
4950
4951 if (func_id != BPF_FUNC_tail_call)
4952 return 0;
4953 if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
4954 verbose(env, "kernel subsystem misconfigured verifier\n");
4955 return -EINVAL;
4956 }
4957
4958 range = tnum_range(0, map->max_entries - 1);
4959 reg = &regs[BPF_REG_3];
4960
4961 if (!register_is_const(reg) || !tnum_in(range, reg->var_off)) {
4962 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
4963 return 0;
4964 }
4965
cc52d914
DB
4966 err = mark_chain_precision(env, BPF_REG_3);
4967 if (err)
4968 return err;
4969
d2e4c1e6
DB
4970 val = reg->var_off.value;
4971 if (bpf_map_key_unseen(aux))
4972 bpf_map_key_store(aux, val);
4973 else if (!bpf_map_key_poisoned(aux) &&
4974 bpf_map_key_immediate(aux) != val)
4975 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
4976 return 0;
4977}
4978
fd978bf7
JS
4979static int check_reference_leak(struct bpf_verifier_env *env)
4980{
4981 struct bpf_func_state *state = cur_func(env);
4982 int i;
4983
4984 for (i = 0; i < state->acquired_refs; i++) {
4985 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
4986 state->refs[i].id, state->refs[i].insn_idx);
4987 }
4988 return state->acquired_refs ? -EINVAL : 0;
4989}
4990
f4d7e40a 4991static int check_helper_call(struct bpf_verifier_env *env, int func_id, int insn_idx)
17a52670 4992{
17a52670 4993 const struct bpf_func_proto *fn = NULL;
638f5b90 4994 struct bpf_reg_state *regs;
33ff9823 4995 struct bpf_call_arg_meta meta;
969bf05e 4996 bool changes_data;
17a52670
AS
4997 int i, err;
4998
4999 /* find function prototype */
5000 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
61bd5218
JK
5001 verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
5002 func_id);
17a52670
AS
5003 return -EINVAL;
5004 }
5005
00176a34 5006 if (env->ops->get_func_proto)
5e43f899 5007 fn = env->ops->get_func_proto(func_id, env->prog);
17a52670 5008 if (!fn) {
61bd5218
JK
5009 verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
5010 func_id);
17a52670
AS
5011 return -EINVAL;
5012 }
5013
5014 /* eBPF programs must be GPL compatible to use GPL-ed functions */
24701ece 5015 if (!env->prog->gpl_compatible && fn->gpl_only) {
3fe2867c 5016 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
17a52670
AS
5017 return -EINVAL;
5018 }
5019
eae2e83e
JO
5020 if (fn->allowed && !fn->allowed(env->prog)) {
5021 verbose(env, "helper call is not allowed in probe\n");
5022 return -EINVAL;
5023 }
5024
04514d13 5025 /* With LD_ABS/IND some JITs save/restore skb from r1. */
17bedab2 5026 changes_data = bpf_helper_changes_pkt_data(fn->func);
04514d13
DB
5027 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
5028 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
5029 func_id_name(func_id), func_id);
5030 return -EINVAL;
5031 }
969bf05e 5032
33ff9823 5033 memset(&meta, 0, sizeof(meta));
36bbef52 5034 meta.pkt_access = fn->pkt_access;
33ff9823 5035
1b986589 5036 err = check_func_proto(fn, func_id);
435faee1 5037 if (err) {
61bd5218 5038 verbose(env, "kernel subsystem misconfigured func %s#%d\n",
ebb676da 5039 func_id_name(func_id), func_id);
435faee1
DB
5040 return err;
5041 }
5042
d83525ca 5043 meta.func_id = func_id;
17a52670 5044 /* check args */
a7658e1a 5045 for (i = 0; i < 5; i++) {
af7ec138 5046 err = check_func_arg(env, i, &meta, fn);
a7658e1a
AS
5047 if (err)
5048 return err;
5049 }
17a52670 5050
c93552c4
DB
5051 err = record_func_map(env, &meta, func_id, insn_idx);
5052 if (err)
5053 return err;
5054
d2e4c1e6
DB
5055 err = record_func_key(env, &meta, func_id, insn_idx);
5056 if (err)
5057 return err;
5058
435faee1
DB
5059 /* Mark slots with STACK_MISC in case of raw mode, stack offset
5060 * is inferred from register state.
5061 */
5062 for (i = 0; i < meta.access_size; i++) {
ca369602
DB
5063 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
5064 BPF_WRITE, -1, false);
435faee1
DB
5065 if (err)
5066 return err;
5067 }
5068
fd978bf7
JS
5069 if (func_id == BPF_FUNC_tail_call) {
5070 err = check_reference_leak(env);
5071 if (err) {
5072 verbose(env, "tail_call would lead to reference leak\n");
5073 return err;
5074 }
5075 } else if (is_release_function(func_id)) {
1b986589 5076 err = release_reference(env, meta.ref_obj_id);
46f8bc92
MKL
5077 if (err) {
5078 verbose(env, "func %s#%d reference has not been acquired before\n",
5079 func_id_name(func_id), func_id);
fd978bf7 5080 return err;
46f8bc92 5081 }
fd978bf7
JS
5082 }
5083
638f5b90 5084 regs = cur_regs(env);
cd339431
RG
5085
5086 /* check that flags argument in get_local_storage(map, flags) is 0,
5087 * this is required because get_local_storage() can't return an error.
5088 */
5089 if (func_id == BPF_FUNC_get_local_storage &&
5090 !register_is_null(&regs[BPF_REG_2])) {
5091 verbose(env, "get_local_storage() doesn't support non-zero flags\n");
5092 return -EINVAL;
5093 }
5094
17a52670 5095 /* reset caller saved regs */
dc503a8a 5096 for (i = 0; i < CALLER_SAVED_REGS; i++) {
61bd5218 5097 mark_reg_not_init(env, regs, caller_saved[i]);
dc503a8a
EC
5098 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
5099 }
17a52670 5100
5327ed3d
JW
5101 /* helper call returns 64-bit value. */
5102 regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
5103
dc503a8a 5104 /* update return register (already marked as written above) */
17a52670 5105 if (fn->ret_type == RET_INTEGER) {
f1174f77 5106 /* sets type to SCALAR_VALUE */
61bd5218 5107 mark_reg_unknown(env, regs, BPF_REG_0);
17a52670
AS
5108 } else if (fn->ret_type == RET_VOID) {
5109 regs[BPF_REG_0].type = NOT_INIT;
3e6a4b3e
RG
5110 } else if (fn->ret_type == RET_PTR_TO_MAP_VALUE_OR_NULL ||
5111 fn->ret_type == RET_PTR_TO_MAP_VALUE) {
f1174f77 5112 /* There is no offset yet applied, variable or fixed */
61bd5218 5113 mark_reg_known_zero(env, regs, BPF_REG_0);
17a52670
AS
5114 /* remember map_ptr, so that check_map_access()
5115 * can check 'value_size' boundary of memory access
5116 * to map element returned from bpf_map_lookup_elem()
5117 */
33ff9823 5118 if (meta.map_ptr == NULL) {
61bd5218
JK
5119 verbose(env,
5120 "kernel subsystem misconfigured verifier\n");
17a52670
AS
5121 return -EINVAL;
5122 }
33ff9823 5123 regs[BPF_REG_0].map_ptr = meta.map_ptr;
4d31f301
DB
5124 if (fn->ret_type == RET_PTR_TO_MAP_VALUE) {
5125 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE;
e16d2f1a
AS
5126 if (map_value_has_spin_lock(meta.map_ptr))
5127 regs[BPF_REG_0].id = ++env->id_gen;
4d31f301
DB
5128 } else {
5129 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE_OR_NULL;
5130 regs[BPF_REG_0].id = ++env->id_gen;
5131 }
c64b7983
JS
5132 } else if (fn->ret_type == RET_PTR_TO_SOCKET_OR_NULL) {
5133 mark_reg_known_zero(env, regs, BPF_REG_0);
5134 regs[BPF_REG_0].type = PTR_TO_SOCKET_OR_NULL;
0f3adc28 5135 regs[BPF_REG_0].id = ++env->id_gen;
85a51f8c
LB
5136 } else if (fn->ret_type == RET_PTR_TO_SOCK_COMMON_OR_NULL) {
5137 mark_reg_known_zero(env, regs, BPF_REG_0);
5138 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON_OR_NULL;
5139 regs[BPF_REG_0].id = ++env->id_gen;
655a51e5
MKL
5140 } else if (fn->ret_type == RET_PTR_TO_TCP_SOCK_OR_NULL) {
5141 mark_reg_known_zero(env, regs, BPF_REG_0);
5142 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK_OR_NULL;
5143 regs[BPF_REG_0].id = ++env->id_gen;
457f4436
AN
5144 } else if (fn->ret_type == RET_PTR_TO_ALLOC_MEM_OR_NULL) {
5145 mark_reg_known_zero(env, regs, BPF_REG_0);
5146 regs[BPF_REG_0].type = PTR_TO_MEM_OR_NULL;
5147 regs[BPF_REG_0].id = ++env->id_gen;
5148 regs[BPF_REG_0].mem_size = meta.mem_size;
63d9b80d
HL
5149 } else if (fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID_OR_NULL ||
5150 fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID) {
eaa6bcb7
HL
5151 const struct btf_type *t;
5152
5153 mark_reg_known_zero(env, regs, BPF_REG_0);
5154 t = btf_type_skip_modifiers(btf_vmlinux, meta.ret_btf_id, NULL);
5155 if (!btf_type_is_struct(t)) {
5156 u32 tsize;
5157 const struct btf_type *ret;
5158 const char *tname;
5159
5160 /* resolve the type size of ksym. */
5161 ret = btf_resolve_size(btf_vmlinux, t, &tsize);
5162 if (IS_ERR(ret)) {
5163 tname = btf_name_by_offset(btf_vmlinux, t->name_off);
5164 verbose(env, "unable to resolve the size of type '%s': %ld\n",
5165 tname, PTR_ERR(ret));
5166 return -EINVAL;
5167 }
63d9b80d
HL
5168 regs[BPF_REG_0].type =
5169 fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID ?
5170 PTR_TO_MEM : PTR_TO_MEM_OR_NULL;
eaa6bcb7
HL
5171 regs[BPF_REG_0].mem_size = tsize;
5172 } else {
63d9b80d
HL
5173 regs[BPF_REG_0].type =
5174 fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID ?
5175 PTR_TO_BTF_ID : PTR_TO_BTF_ID_OR_NULL;
eaa6bcb7
HL
5176 regs[BPF_REG_0].btf_id = meta.ret_btf_id;
5177 }
af7ec138
YS
5178 } else if (fn->ret_type == RET_PTR_TO_BTF_ID_OR_NULL) {
5179 int ret_btf_id;
5180
5181 mark_reg_known_zero(env, regs, BPF_REG_0);
5182 regs[BPF_REG_0].type = PTR_TO_BTF_ID_OR_NULL;
5183 ret_btf_id = *fn->ret_btf_id;
5184 if (ret_btf_id == 0) {
5185 verbose(env, "invalid return type %d of func %s#%d\n",
5186 fn->ret_type, func_id_name(func_id), func_id);
5187 return -EINVAL;
5188 }
5189 regs[BPF_REG_0].btf_id = ret_btf_id;
17a52670 5190 } else {
61bd5218 5191 verbose(env, "unknown return type %d of func %s#%d\n",
ebb676da 5192 fn->ret_type, func_id_name(func_id), func_id);
17a52670
AS
5193 return -EINVAL;
5194 }
04fd61ab 5195
0f3adc28 5196 if (is_ptr_cast_function(func_id)) {
1b986589
MKL
5197 /* For release_reference() */
5198 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
64d85290 5199 } else if (is_acquire_function(func_id, meta.map_ptr)) {
0f3adc28
LB
5200 int id = acquire_reference_state(env, insn_idx);
5201
5202 if (id < 0)
5203 return id;
5204 /* For mark_ptr_or_null_reg() */
5205 regs[BPF_REG_0].id = id;
5206 /* For release_reference() */
5207 regs[BPF_REG_0].ref_obj_id = id;
5208 }
1b986589 5209
849fa506
YS
5210 do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
5211
61bd5218 5212 err = check_map_func_compatibility(env, meta.map_ptr, func_id);
35578d79
KX
5213 if (err)
5214 return err;
04fd61ab 5215
fa28dcb8
SL
5216 if ((func_id == BPF_FUNC_get_stack ||
5217 func_id == BPF_FUNC_get_task_stack) &&
5218 !env->prog->has_callchain_buf) {
c195651e
YS
5219 const char *err_str;
5220
5221#ifdef CONFIG_PERF_EVENTS
5222 err = get_callchain_buffers(sysctl_perf_event_max_stack);
5223 err_str = "cannot get callchain buffer for func %s#%d\n";
5224#else
5225 err = -ENOTSUPP;
5226 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
5227#endif
5228 if (err) {
5229 verbose(env, err_str, func_id_name(func_id), func_id);
5230 return err;
5231 }
5232
5233 env->prog->has_callchain_buf = true;
5234 }
5235
5d99cb2c
SL
5236 if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
5237 env->prog->call_get_stack = true;
5238
969bf05e
AS
5239 if (changes_data)
5240 clear_all_pkt_pointers(env);
5241 return 0;
5242}
5243
b03c9f9f
EC
5244static bool signed_add_overflows(s64 a, s64 b)
5245{
5246 /* Do the add in u64, where overflow is well-defined */
5247 s64 res = (s64)((u64)a + (u64)b);
5248
5249 if (b < 0)
5250 return res > a;
5251 return res < a;
5252}
5253
3f50f132
JF
5254static bool signed_add32_overflows(s64 a, s64 b)
5255{
5256 /* Do the add in u32, where overflow is well-defined */
5257 s32 res = (s32)((u32)a + (u32)b);
5258
5259 if (b < 0)
5260 return res > a;
5261 return res < a;
5262}
5263
5264static bool signed_sub_overflows(s32 a, s32 b)
b03c9f9f
EC
5265{
5266 /* Do the sub in u64, where overflow is well-defined */
5267 s64 res = (s64)((u64)a - (u64)b);
5268
5269 if (b < 0)
5270 return res < a;
5271 return res > a;
969bf05e
AS
5272}
5273
3f50f132
JF
5274static bool signed_sub32_overflows(s32 a, s32 b)
5275{
5276 /* Do the sub in u64, where overflow is well-defined */
5277 s32 res = (s32)((u32)a - (u32)b);
5278
5279 if (b < 0)
5280 return res < a;
5281 return res > a;
5282}
5283
bb7f0f98
AS
5284static bool check_reg_sane_offset(struct bpf_verifier_env *env,
5285 const struct bpf_reg_state *reg,
5286 enum bpf_reg_type type)
5287{
5288 bool known = tnum_is_const(reg->var_off);
5289 s64 val = reg->var_off.value;
5290 s64 smin = reg->smin_value;
5291
5292 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
5293 verbose(env, "math between %s pointer and %lld is not allowed\n",
5294 reg_type_str[type], val);
5295 return false;
5296 }
5297
5298 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
5299 verbose(env, "%s pointer offset %d is not allowed\n",
5300 reg_type_str[type], reg->off);
5301 return false;
5302 }
5303
5304 if (smin == S64_MIN) {
5305 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
5306 reg_type_str[type]);
5307 return false;
5308 }
5309
5310 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
5311 verbose(env, "value %lld makes %s pointer be out of bounds\n",
5312 smin, reg_type_str[type]);
5313 return false;
5314 }
5315
5316 return true;
5317}
5318
979d63d5
DB
5319static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
5320{
5321 return &env->insn_aux_data[env->insn_idx];
5322}
5323
5324static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
5325 u32 *ptr_limit, u8 opcode, bool off_is_neg)
5326{
5327 bool mask_to_left = (opcode == BPF_ADD && off_is_neg) ||
5328 (opcode == BPF_SUB && !off_is_neg);
5329 u32 off;
5330
5331 switch (ptr_reg->type) {
5332 case PTR_TO_STACK:
088ec26d
AI
5333 /* Indirect variable offset stack access is prohibited in
5334 * unprivileged mode so it's not handled here.
5335 */
979d63d5
DB
5336 off = ptr_reg->off + ptr_reg->var_off.value;
5337 if (mask_to_left)
5338 *ptr_limit = MAX_BPF_STACK + off;
5339 else
5340 *ptr_limit = -off;
5341 return 0;
5342 case PTR_TO_MAP_VALUE:
5343 if (mask_to_left) {
5344 *ptr_limit = ptr_reg->umax_value + ptr_reg->off;
5345 } else {
5346 off = ptr_reg->smin_value + ptr_reg->off;
5347 *ptr_limit = ptr_reg->map_ptr->value_size - off;
5348 }
5349 return 0;
5350 default:
5351 return -EINVAL;
5352 }
5353}
5354
d3bd7413
DB
5355static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
5356 const struct bpf_insn *insn)
5357{
2c78ee89 5358 return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
d3bd7413
DB
5359}
5360
5361static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
5362 u32 alu_state, u32 alu_limit)
5363{
5364 /* If we arrived here from different branches with different
5365 * state or limits to sanitize, then this won't work.
5366 */
5367 if (aux->alu_state &&
5368 (aux->alu_state != alu_state ||
5369 aux->alu_limit != alu_limit))
5370 return -EACCES;
5371
5372 /* Corresponding fixup done in fixup_bpf_calls(). */
5373 aux->alu_state = alu_state;
5374 aux->alu_limit = alu_limit;
5375 return 0;
5376}
5377
5378static int sanitize_val_alu(struct bpf_verifier_env *env,
5379 struct bpf_insn *insn)
5380{
5381 struct bpf_insn_aux_data *aux = cur_aux(env);
5382
5383 if (can_skip_alu_sanitation(env, insn))
5384 return 0;
5385
5386 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
5387}
5388
979d63d5
DB
5389static int sanitize_ptr_alu(struct bpf_verifier_env *env,
5390 struct bpf_insn *insn,
5391 const struct bpf_reg_state *ptr_reg,
5392 struct bpf_reg_state *dst_reg,
5393 bool off_is_neg)
5394{
5395 struct bpf_verifier_state *vstate = env->cur_state;
5396 struct bpf_insn_aux_data *aux = cur_aux(env);
5397 bool ptr_is_dst_reg = ptr_reg == dst_reg;
5398 u8 opcode = BPF_OP(insn->code);
5399 u32 alu_state, alu_limit;
5400 struct bpf_reg_state tmp;
5401 bool ret;
5402
d3bd7413 5403 if (can_skip_alu_sanitation(env, insn))
979d63d5
DB
5404 return 0;
5405
5406 /* We already marked aux for masking from non-speculative
5407 * paths, thus we got here in the first place. We only care
5408 * to explore bad access from here.
5409 */
5410 if (vstate->speculative)
5411 goto do_sim;
5412
5413 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
5414 alu_state |= ptr_is_dst_reg ?
5415 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
5416
5417 if (retrieve_ptr_limit(ptr_reg, &alu_limit, opcode, off_is_neg))
5418 return 0;
d3bd7413 5419 if (update_alu_sanitation_state(aux, alu_state, alu_limit))
979d63d5 5420 return -EACCES;
979d63d5
DB
5421do_sim:
5422 /* Simulate and find potential out-of-bounds access under
5423 * speculative execution from truncation as a result of
5424 * masking when off was not within expected range. If off
5425 * sits in dst, then we temporarily need to move ptr there
5426 * to simulate dst (== 0) +/-= ptr. Needed, for example,
5427 * for cases where we use K-based arithmetic in one direction
5428 * and truncated reg-based in the other in order to explore
5429 * bad access.
5430 */
5431 if (!ptr_is_dst_reg) {
5432 tmp = *dst_reg;
5433 *dst_reg = *ptr_reg;
5434 }
5435 ret = push_stack(env, env->insn_idx + 1, env->insn_idx, true);
0803278b 5436 if (!ptr_is_dst_reg && ret)
979d63d5
DB
5437 *dst_reg = tmp;
5438 return !ret ? -EFAULT : 0;
5439}
5440
f1174f77 5441/* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
f1174f77
EC
5442 * Caller should also handle BPF_MOV case separately.
5443 * If we return -EACCES, caller may want to try again treating pointer as a
5444 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks.
5445 */
5446static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
5447 struct bpf_insn *insn,
5448 const struct bpf_reg_state *ptr_reg,
5449 const struct bpf_reg_state *off_reg)
969bf05e 5450{
f4d7e40a
AS
5451 struct bpf_verifier_state *vstate = env->cur_state;
5452 struct bpf_func_state *state = vstate->frame[vstate->curframe];
5453 struct bpf_reg_state *regs = state->regs, *dst_reg;
f1174f77 5454 bool known = tnum_is_const(off_reg->var_off);
b03c9f9f
EC
5455 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
5456 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
5457 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
5458 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
9d7eceed 5459 u32 dst = insn->dst_reg, src = insn->src_reg;
969bf05e 5460 u8 opcode = BPF_OP(insn->code);
979d63d5 5461 int ret;
969bf05e 5462
f1174f77 5463 dst_reg = &regs[dst];
969bf05e 5464
6f16101e
DB
5465 if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
5466 smin_val > smax_val || umin_val > umax_val) {
5467 /* Taint dst register if offset had invalid bounds derived from
5468 * e.g. dead branches.
5469 */
f54c7898 5470 __mark_reg_unknown(env, dst_reg);
6f16101e 5471 return 0;
f1174f77
EC
5472 }
5473
5474 if (BPF_CLASS(insn->code) != BPF_ALU64) {
5475 /* 32-bit ALU ops on pointers produce (meaningless) scalars */
6c693541
YS
5476 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
5477 __mark_reg_unknown(env, dst_reg);
5478 return 0;
5479 }
5480
82abbf8d
AS
5481 verbose(env,
5482 "R%d 32-bit pointer arithmetic prohibited\n",
5483 dst);
f1174f77 5484 return -EACCES;
969bf05e
AS
5485 }
5486
aad2eeaf
JS
5487 switch (ptr_reg->type) {
5488 case PTR_TO_MAP_VALUE_OR_NULL:
5489 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
5490 dst, reg_type_str[ptr_reg->type]);
f1174f77 5491 return -EACCES;
aad2eeaf 5492 case CONST_PTR_TO_MAP:
7c696732
YS
5493 /* smin_val represents the known value */
5494 if (known && smin_val == 0 && opcode == BPF_ADD)
5495 break;
8731745e 5496 fallthrough;
aad2eeaf 5497 case PTR_TO_PACKET_END:
c64b7983
JS
5498 case PTR_TO_SOCKET:
5499 case PTR_TO_SOCKET_OR_NULL:
46f8bc92
MKL
5500 case PTR_TO_SOCK_COMMON:
5501 case PTR_TO_SOCK_COMMON_OR_NULL:
655a51e5
MKL
5502 case PTR_TO_TCP_SOCK:
5503 case PTR_TO_TCP_SOCK_OR_NULL:
fada7fdc 5504 case PTR_TO_XDP_SOCK:
aad2eeaf
JS
5505 verbose(env, "R%d pointer arithmetic on %s prohibited\n",
5506 dst, reg_type_str[ptr_reg->type]);
f1174f77 5507 return -EACCES;
9d7eceed
DB
5508 case PTR_TO_MAP_VALUE:
5509 if (!env->allow_ptr_leaks && !known && (smin_val < 0) != (smax_val < 0)) {
5510 verbose(env, "R%d has unknown scalar with mixed signed bounds, pointer arithmetic with it prohibited for !root\n",
5511 off_reg == dst_reg ? dst : src);
5512 return -EACCES;
5513 }
df561f66 5514 fallthrough;
aad2eeaf
JS
5515 default:
5516 break;
f1174f77
EC
5517 }
5518
5519 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
5520 * The id may be overwritten later if we create a new variable offset.
969bf05e 5521 */
f1174f77
EC
5522 dst_reg->type = ptr_reg->type;
5523 dst_reg->id = ptr_reg->id;
969bf05e 5524
bb7f0f98
AS
5525 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
5526 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
5527 return -EINVAL;
5528
3f50f132
JF
5529 /* pointer types do not carry 32-bit bounds at the moment. */
5530 __mark_reg32_unbounded(dst_reg);
5531
f1174f77
EC
5532 switch (opcode) {
5533 case BPF_ADD:
979d63d5
DB
5534 ret = sanitize_ptr_alu(env, insn, ptr_reg, dst_reg, smin_val < 0);
5535 if (ret < 0) {
5536 verbose(env, "R%d tried to add from different maps or paths\n", dst);
5537 return ret;
5538 }
f1174f77
EC
5539 /* We can take a fixed offset as long as it doesn't overflow
5540 * the s32 'off' field
969bf05e 5541 */
b03c9f9f
EC
5542 if (known && (ptr_reg->off + smin_val ==
5543 (s64)(s32)(ptr_reg->off + smin_val))) {
f1174f77 5544 /* pointer += K. Accumulate it into fixed offset */
b03c9f9f
EC
5545 dst_reg->smin_value = smin_ptr;
5546 dst_reg->smax_value = smax_ptr;
5547 dst_reg->umin_value = umin_ptr;
5548 dst_reg->umax_value = umax_ptr;
f1174f77 5549 dst_reg->var_off = ptr_reg->var_off;
b03c9f9f 5550 dst_reg->off = ptr_reg->off + smin_val;
0962590e 5551 dst_reg->raw = ptr_reg->raw;
f1174f77
EC
5552 break;
5553 }
f1174f77
EC
5554 /* A new variable offset is created. Note that off_reg->off
5555 * == 0, since it's a scalar.
5556 * dst_reg gets the pointer type and since some positive
5557 * integer value was added to the pointer, give it a new 'id'
5558 * if it's a PTR_TO_PACKET.
5559 * this creates a new 'base' pointer, off_reg (variable) gets
5560 * added into the variable offset, and we copy the fixed offset
5561 * from ptr_reg.
969bf05e 5562 */
b03c9f9f
EC
5563 if (signed_add_overflows(smin_ptr, smin_val) ||
5564 signed_add_overflows(smax_ptr, smax_val)) {
5565 dst_reg->smin_value = S64_MIN;
5566 dst_reg->smax_value = S64_MAX;
5567 } else {
5568 dst_reg->smin_value = smin_ptr + smin_val;
5569 dst_reg->smax_value = smax_ptr + smax_val;
5570 }
5571 if (umin_ptr + umin_val < umin_ptr ||
5572 umax_ptr + umax_val < umax_ptr) {
5573 dst_reg->umin_value = 0;
5574 dst_reg->umax_value = U64_MAX;
5575 } else {
5576 dst_reg->umin_value = umin_ptr + umin_val;
5577 dst_reg->umax_value = umax_ptr + umax_val;
5578 }
f1174f77
EC
5579 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
5580 dst_reg->off = ptr_reg->off;
0962590e 5581 dst_reg->raw = ptr_reg->raw;
de8f3a83 5582 if (reg_is_pkt_pointer(ptr_reg)) {
f1174f77
EC
5583 dst_reg->id = ++env->id_gen;
5584 /* something was added to pkt_ptr, set range to zero */
0962590e 5585 dst_reg->raw = 0;
f1174f77
EC
5586 }
5587 break;
5588 case BPF_SUB:
979d63d5
DB
5589 ret = sanitize_ptr_alu(env, insn, ptr_reg, dst_reg, smin_val < 0);
5590 if (ret < 0) {
5591 verbose(env, "R%d tried to sub from different maps or paths\n", dst);
5592 return ret;
5593 }
f1174f77
EC
5594 if (dst_reg == off_reg) {
5595 /* scalar -= pointer. Creates an unknown scalar */
82abbf8d
AS
5596 verbose(env, "R%d tried to subtract pointer from scalar\n",
5597 dst);
f1174f77
EC
5598 return -EACCES;
5599 }
5600 /* We don't allow subtraction from FP, because (according to
5601 * test_verifier.c test "invalid fp arithmetic", JITs might not
5602 * be able to deal with it.
969bf05e 5603 */
f1174f77 5604 if (ptr_reg->type == PTR_TO_STACK) {
82abbf8d
AS
5605 verbose(env, "R%d subtraction from stack pointer prohibited\n",
5606 dst);
f1174f77
EC
5607 return -EACCES;
5608 }
b03c9f9f
EC
5609 if (known && (ptr_reg->off - smin_val ==
5610 (s64)(s32)(ptr_reg->off - smin_val))) {
f1174f77 5611 /* pointer -= K. Subtract it from fixed offset */
b03c9f9f
EC
5612 dst_reg->smin_value = smin_ptr;
5613 dst_reg->smax_value = smax_ptr;
5614 dst_reg->umin_value = umin_ptr;
5615 dst_reg->umax_value = umax_ptr;
f1174f77
EC
5616 dst_reg->var_off = ptr_reg->var_off;
5617 dst_reg->id = ptr_reg->id;
b03c9f9f 5618 dst_reg->off = ptr_reg->off - smin_val;
0962590e 5619 dst_reg->raw = ptr_reg->raw;
f1174f77
EC
5620 break;
5621 }
f1174f77
EC
5622 /* A new variable offset is created. If the subtrahend is known
5623 * nonnegative, then any reg->range we had before is still good.
969bf05e 5624 */
b03c9f9f
EC
5625 if (signed_sub_overflows(smin_ptr, smax_val) ||
5626 signed_sub_overflows(smax_ptr, smin_val)) {
5627 /* Overflow possible, we know nothing */
5628 dst_reg->smin_value = S64_MIN;
5629 dst_reg->smax_value = S64_MAX;
5630 } else {
5631 dst_reg->smin_value = smin_ptr - smax_val;
5632 dst_reg->smax_value = smax_ptr - smin_val;
5633 }
5634 if (umin_ptr < umax_val) {
5635 /* Overflow possible, we know nothing */
5636 dst_reg->umin_value = 0;
5637 dst_reg->umax_value = U64_MAX;
5638 } else {
5639 /* Cannot overflow (as long as bounds are consistent) */
5640 dst_reg->umin_value = umin_ptr - umax_val;
5641 dst_reg->umax_value = umax_ptr - umin_val;
5642 }
f1174f77
EC
5643 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
5644 dst_reg->off = ptr_reg->off;
0962590e 5645 dst_reg->raw = ptr_reg->raw;
de8f3a83 5646 if (reg_is_pkt_pointer(ptr_reg)) {
f1174f77
EC
5647 dst_reg->id = ++env->id_gen;
5648 /* something was added to pkt_ptr, set range to zero */
b03c9f9f 5649 if (smin_val < 0)
0962590e 5650 dst_reg->raw = 0;
43188702 5651 }
f1174f77
EC
5652 break;
5653 case BPF_AND:
5654 case BPF_OR:
5655 case BPF_XOR:
82abbf8d
AS
5656 /* bitwise ops on pointers are troublesome, prohibit. */
5657 verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
5658 dst, bpf_alu_string[opcode >> 4]);
f1174f77
EC
5659 return -EACCES;
5660 default:
5661 /* other operators (e.g. MUL,LSH) produce non-pointer results */
82abbf8d
AS
5662 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
5663 dst, bpf_alu_string[opcode >> 4]);
f1174f77 5664 return -EACCES;
43188702
JF
5665 }
5666
bb7f0f98
AS
5667 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
5668 return -EINVAL;
5669
b03c9f9f
EC
5670 __update_reg_bounds(dst_reg);
5671 __reg_deduce_bounds(dst_reg);
5672 __reg_bound_offset(dst_reg);
0d6303db
DB
5673
5674 /* For unprivileged we require that resulting offset must be in bounds
5675 * in order to be able to sanitize access later on.
5676 */
2c78ee89 5677 if (!env->bypass_spec_v1) {
e4298d25
DB
5678 if (dst_reg->type == PTR_TO_MAP_VALUE &&
5679 check_map_access(env, dst, dst_reg->off, 1, false)) {
5680 verbose(env, "R%d pointer arithmetic of map value goes out of range, "
5681 "prohibited for !root\n", dst);
5682 return -EACCES;
5683 } else if (dst_reg->type == PTR_TO_STACK &&
5684 check_stack_access(env, dst_reg, dst_reg->off +
5685 dst_reg->var_off.value, 1)) {
5686 verbose(env, "R%d stack pointer arithmetic goes out of range, "
5687 "prohibited for !root\n", dst);
5688 return -EACCES;
5689 }
0d6303db
DB
5690 }
5691
43188702
JF
5692 return 0;
5693}
5694
3f50f132
JF
5695static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
5696 struct bpf_reg_state *src_reg)
5697{
5698 s32 smin_val = src_reg->s32_min_value;
5699 s32 smax_val = src_reg->s32_max_value;
5700 u32 umin_val = src_reg->u32_min_value;
5701 u32 umax_val = src_reg->u32_max_value;
5702
5703 if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
5704 signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
5705 dst_reg->s32_min_value = S32_MIN;
5706 dst_reg->s32_max_value = S32_MAX;
5707 } else {
5708 dst_reg->s32_min_value += smin_val;
5709 dst_reg->s32_max_value += smax_val;
5710 }
5711 if (dst_reg->u32_min_value + umin_val < umin_val ||
5712 dst_reg->u32_max_value + umax_val < umax_val) {
5713 dst_reg->u32_min_value = 0;
5714 dst_reg->u32_max_value = U32_MAX;
5715 } else {
5716 dst_reg->u32_min_value += umin_val;
5717 dst_reg->u32_max_value += umax_val;
5718 }
5719}
5720
07cd2631
JF
5721static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
5722 struct bpf_reg_state *src_reg)
5723{
5724 s64 smin_val = src_reg->smin_value;
5725 s64 smax_val = src_reg->smax_value;
5726 u64 umin_val = src_reg->umin_value;
5727 u64 umax_val = src_reg->umax_value;
5728
5729 if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
5730 signed_add_overflows(dst_reg->smax_value, smax_val)) {
5731 dst_reg->smin_value = S64_MIN;
5732 dst_reg->smax_value = S64_MAX;
5733 } else {
5734 dst_reg->smin_value += smin_val;
5735 dst_reg->smax_value += smax_val;
5736 }
5737 if (dst_reg->umin_value + umin_val < umin_val ||
5738 dst_reg->umax_value + umax_val < umax_val) {
5739 dst_reg->umin_value = 0;
5740 dst_reg->umax_value = U64_MAX;
5741 } else {
5742 dst_reg->umin_value += umin_val;
5743 dst_reg->umax_value += umax_val;
5744 }
3f50f132
JF
5745}
5746
5747static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
5748 struct bpf_reg_state *src_reg)
5749{
5750 s32 smin_val = src_reg->s32_min_value;
5751 s32 smax_val = src_reg->s32_max_value;
5752 u32 umin_val = src_reg->u32_min_value;
5753 u32 umax_val = src_reg->u32_max_value;
5754
5755 if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
5756 signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
5757 /* Overflow possible, we know nothing */
5758 dst_reg->s32_min_value = S32_MIN;
5759 dst_reg->s32_max_value = S32_MAX;
5760 } else {
5761 dst_reg->s32_min_value -= smax_val;
5762 dst_reg->s32_max_value -= smin_val;
5763 }
5764 if (dst_reg->u32_min_value < umax_val) {
5765 /* Overflow possible, we know nothing */
5766 dst_reg->u32_min_value = 0;
5767 dst_reg->u32_max_value = U32_MAX;
5768 } else {
5769 /* Cannot overflow (as long as bounds are consistent) */
5770 dst_reg->u32_min_value -= umax_val;
5771 dst_reg->u32_max_value -= umin_val;
5772 }
07cd2631
JF
5773}
5774
5775static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
5776 struct bpf_reg_state *src_reg)
5777{
5778 s64 smin_val = src_reg->smin_value;
5779 s64 smax_val = src_reg->smax_value;
5780 u64 umin_val = src_reg->umin_value;
5781 u64 umax_val = src_reg->umax_value;
5782
5783 if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
5784 signed_sub_overflows(dst_reg->smax_value, smin_val)) {
5785 /* Overflow possible, we know nothing */
5786 dst_reg->smin_value = S64_MIN;
5787 dst_reg->smax_value = S64_MAX;
5788 } else {
5789 dst_reg->smin_value -= smax_val;
5790 dst_reg->smax_value -= smin_val;
5791 }
5792 if (dst_reg->umin_value < umax_val) {
5793 /* Overflow possible, we know nothing */
5794 dst_reg->umin_value = 0;
5795 dst_reg->umax_value = U64_MAX;
5796 } else {
5797 /* Cannot overflow (as long as bounds are consistent) */
5798 dst_reg->umin_value -= umax_val;
5799 dst_reg->umax_value -= umin_val;
5800 }
3f50f132
JF
5801}
5802
5803static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
5804 struct bpf_reg_state *src_reg)
5805{
5806 s32 smin_val = src_reg->s32_min_value;
5807 u32 umin_val = src_reg->u32_min_value;
5808 u32 umax_val = src_reg->u32_max_value;
5809
5810 if (smin_val < 0 || dst_reg->s32_min_value < 0) {
5811 /* Ain't nobody got time to multiply that sign */
5812 __mark_reg32_unbounded(dst_reg);
5813 return;
5814 }
5815 /* Both values are positive, so we can work with unsigned and
5816 * copy the result to signed (unless it exceeds S32_MAX).
5817 */
5818 if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
5819 /* Potential overflow, we know nothing */
5820 __mark_reg32_unbounded(dst_reg);
5821 return;
5822 }
5823 dst_reg->u32_min_value *= umin_val;
5824 dst_reg->u32_max_value *= umax_val;
5825 if (dst_reg->u32_max_value > S32_MAX) {
5826 /* Overflow possible, we know nothing */
5827 dst_reg->s32_min_value = S32_MIN;
5828 dst_reg->s32_max_value = S32_MAX;
5829 } else {
5830 dst_reg->s32_min_value = dst_reg->u32_min_value;
5831 dst_reg->s32_max_value = dst_reg->u32_max_value;
5832 }
07cd2631
JF
5833}
5834
5835static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
5836 struct bpf_reg_state *src_reg)
5837{
5838 s64 smin_val = src_reg->smin_value;
5839 u64 umin_val = src_reg->umin_value;
5840 u64 umax_val = src_reg->umax_value;
5841
07cd2631
JF
5842 if (smin_val < 0 || dst_reg->smin_value < 0) {
5843 /* Ain't nobody got time to multiply that sign */
3f50f132 5844 __mark_reg64_unbounded(dst_reg);
07cd2631
JF
5845 return;
5846 }
5847 /* Both values are positive, so we can work with unsigned and
5848 * copy the result to signed (unless it exceeds S64_MAX).
5849 */
5850 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
5851 /* Potential overflow, we know nothing */
3f50f132 5852 __mark_reg64_unbounded(dst_reg);
07cd2631
JF
5853 return;
5854 }
5855 dst_reg->umin_value *= umin_val;
5856 dst_reg->umax_value *= umax_val;
5857 if (dst_reg->umax_value > S64_MAX) {
5858 /* Overflow possible, we know nothing */
5859 dst_reg->smin_value = S64_MIN;
5860 dst_reg->smax_value = S64_MAX;
5861 } else {
5862 dst_reg->smin_value = dst_reg->umin_value;
5863 dst_reg->smax_value = dst_reg->umax_value;
5864 }
5865}
5866
3f50f132
JF
5867static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
5868 struct bpf_reg_state *src_reg)
5869{
5870 bool src_known = tnum_subreg_is_const(src_reg->var_off);
5871 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
5872 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
5873 s32 smin_val = src_reg->s32_min_value;
5874 u32 umax_val = src_reg->u32_max_value;
5875
5876 /* Assuming scalar64_min_max_and will be called so its safe
5877 * to skip updating register for known 32-bit case.
5878 */
5879 if (src_known && dst_known)
5880 return;
5881
5882 /* We get our minimum from the var_off, since that's inherently
5883 * bitwise. Our maximum is the minimum of the operands' maxima.
5884 */
5885 dst_reg->u32_min_value = var32_off.value;
5886 dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
5887 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
5888 /* Lose signed bounds when ANDing negative numbers,
5889 * ain't nobody got time for that.
5890 */
5891 dst_reg->s32_min_value = S32_MIN;
5892 dst_reg->s32_max_value = S32_MAX;
5893 } else {
5894 /* ANDing two positives gives a positive, so safe to
5895 * cast result into s64.
5896 */
5897 dst_reg->s32_min_value = dst_reg->u32_min_value;
5898 dst_reg->s32_max_value = dst_reg->u32_max_value;
5899 }
5900
5901}
5902
07cd2631
JF
5903static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
5904 struct bpf_reg_state *src_reg)
5905{
3f50f132
JF
5906 bool src_known = tnum_is_const(src_reg->var_off);
5907 bool dst_known = tnum_is_const(dst_reg->var_off);
07cd2631
JF
5908 s64 smin_val = src_reg->smin_value;
5909 u64 umax_val = src_reg->umax_value;
5910
3f50f132 5911 if (src_known && dst_known) {
4fbb38a3 5912 __mark_reg_known(dst_reg, dst_reg->var_off.value);
3f50f132
JF
5913 return;
5914 }
5915
07cd2631
JF
5916 /* We get our minimum from the var_off, since that's inherently
5917 * bitwise. Our maximum is the minimum of the operands' maxima.
5918 */
07cd2631
JF
5919 dst_reg->umin_value = dst_reg->var_off.value;
5920 dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
5921 if (dst_reg->smin_value < 0 || smin_val < 0) {
5922 /* Lose signed bounds when ANDing negative numbers,
5923 * ain't nobody got time for that.
5924 */
5925 dst_reg->smin_value = S64_MIN;
5926 dst_reg->smax_value = S64_MAX;
5927 } else {
5928 /* ANDing two positives gives a positive, so safe to
5929 * cast result into s64.
5930 */
5931 dst_reg->smin_value = dst_reg->umin_value;
5932 dst_reg->smax_value = dst_reg->umax_value;
5933 }
5934 /* We may learn something more from the var_off */
5935 __update_reg_bounds(dst_reg);
5936}
5937
3f50f132
JF
5938static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
5939 struct bpf_reg_state *src_reg)
5940{
5941 bool src_known = tnum_subreg_is_const(src_reg->var_off);
5942 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
5943 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
5b9fbeb7
DB
5944 s32 smin_val = src_reg->s32_min_value;
5945 u32 umin_val = src_reg->u32_min_value;
3f50f132
JF
5946
5947 /* Assuming scalar64_min_max_or will be called so it is safe
5948 * to skip updating register for known case.
5949 */
5950 if (src_known && dst_known)
5951 return;
5952
5953 /* We get our maximum from the var_off, and our minimum is the
5954 * maximum of the operands' minima
5955 */
5956 dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
5957 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
5958 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
5959 /* Lose signed bounds when ORing negative numbers,
5960 * ain't nobody got time for that.
5961 */
5962 dst_reg->s32_min_value = S32_MIN;
5963 dst_reg->s32_max_value = S32_MAX;
5964 } else {
5965 /* ORing two positives gives a positive, so safe to
5966 * cast result into s64.
5967 */
5b9fbeb7
DB
5968 dst_reg->s32_min_value = dst_reg->u32_min_value;
5969 dst_reg->s32_max_value = dst_reg->u32_max_value;
3f50f132
JF
5970 }
5971}
5972
07cd2631
JF
5973static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
5974 struct bpf_reg_state *src_reg)
5975{
3f50f132
JF
5976 bool src_known = tnum_is_const(src_reg->var_off);
5977 bool dst_known = tnum_is_const(dst_reg->var_off);
07cd2631
JF
5978 s64 smin_val = src_reg->smin_value;
5979 u64 umin_val = src_reg->umin_value;
5980
3f50f132 5981 if (src_known && dst_known) {
4fbb38a3 5982 __mark_reg_known(dst_reg, dst_reg->var_off.value);
3f50f132
JF
5983 return;
5984 }
5985
07cd2631
JF
5986 /* We get our maximum from the var_off, and our minimum is the
5987 * maximum of the operands' minima
5988 */
07cd2631
JF
5989 dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
5990 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
5991 if (dst_reg->smin_value < 0 || smin_val < 0) {
5992 /* Lose signed bounds when ORing negative numbers,
5993 * ain't nobody got time for that.
5994 */
5995 dst_reg->smin_value = S64_MIN;
5996 dst_reg->smax_value = S64_MAX;
5997 } else {
5998 /* ORing two positives gives a positive, so safe to
5999 * cast result into s64.
6000 */
6001 dst_reg->smin_value = dst_reg->umin_value;
6002 dst_reg->smax_value = dst_reg->umax_value;
6003 }
6004 /* We may learn something more from the var_off */
6005 __update_reg_bounds(dst_reg);
6006}
6007
2921c90d
YS
6008static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
6009 struct bpf_reg_state *src_reg)
6010{
6011 bool src_known = tnum_subreg_is_const(src_reg->var_off);
6012 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
6013 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
6014 s32 smin_val = src_reg->s32_min_value;
6015
6016 /* Assuming scalar64_min_max_xor will be called so it is safe
6017 * to skip updating register for known case.
6018 */
6019 if (src_known && dst_known)
6020 return;
6021
6022 /* We get both minimum and maximum from the var32_off. */
6023 dst_reg->u32_min_value = var32_off.value;
6024 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
6025
6026 if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
6027 /* XORing two positive sign numbers gives a positive,
6028 * so safe to cast u32 result into s32.
6029 */
6030 dst_reg->s32_min_value = dst_reg->u32_min_value;
6031 dst_reg->s32_max_value = dst_reg->u32_max_value;
6032 } else {
6033 dst_reg->s32_min_value = S32_MIN;
6034 dst_reg->s32_max_value = S32_MAX;
6035 }
6036}
6037
6038static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
6039 struct bpf_reg_state *src_reg)
6040{
6041 bool src_known = tnum_is_const(src_reg->var_off);
6042 bool dst_known = tnum_is_const(dst_reg->var_off);
6043 s64 smin_val = src_reg->smin_value;
6044
6045 if (src_known && dst_known) {
6046 /* dst_reg->var_off.value has been updated earlier */
6047 __mark_reg_known(dst_reg, dst_reg->var_off.value);
6048 return;
6049 }
6050
6051 /* We get both minimum and maximum from the var_off. */
6052 dst_reg->umin_value = dst_reg->var_off.value;
6053 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
6054
6055 if (dst_reg->smin_value >= 0 && smin_val >= 0) {
6056 /* XORing two positive sign numbers gives a positive,
6057 * so safe to cast u64 result into s64.
6058 */
6059 dst_reg->smin_value = dst_reg->umin_value;
6060 dst_reg->smax_value = dst_reg->umax_value;
6061 } else {
6062 dst_reg->smin_value = S64_MIN;
6063 dst_reg->smax_value = S64_MAX;
6064 }
6065
6066 __update_reg_bounds(dst_reg);
6067}
6068
3f50f132
JF
6069static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
6070 u64 umin_val, u64 umax_val)
07cd2631 6071{
07cd2631
JF
6072 /* We lose all sign bit information (except what we can pick
6073 * up from var_off)
6074 */
3f50f132
JF
6075 dst_reg->s32_min_value = S32_MIN;
6076 dst_reg->s32_max_value = S32_MAX;
6077 /* If we might shift our top bit out, then we know nothing */
6078 if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
6079 dst_reg->u32_min_value = 0;
6080 dst_reg->u32_max_value = U32_MAX;
6081 } else {
6082 dst_reg->u32_min_value <<= umin_val;
6083 dst_reg->u32_max_value <<= umax_val;
6084 }
6085}
6086
6087static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
6088 struct bpf_reg_state *src_reg)
6089{
6090 u32 umax_val = src_reg->u32_max_value;
6091 u32 umin_val = src_reg->u32_min_value;
6092 /* u32 alu operation will zext upper bits */
6093 struct tnum subreg = tnum_subreg(dst_reg->var_off);
6094
6095 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
6096 dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
6097 /* Not required but being careful mark reg64 bounds as unknown so
6098 * that we are forced to pick them up from tnum and zext later and
6099 * if some path skips this step we are still safe.
6100 */
6101 __mark_reg64_unbounded(dst_reg);
6102 __update_reg32_bounds(dst_reg);
6103}
6104
6105static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
6106 u64 umin_val, u64 umax_val)
6107{
6108 /* Special case <<32 because it is a common compiler pattern to sign
6109 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
6110 * positive we know this shift will also be positive so we can track
6111 * bounds correctly. Otherwise we lose all sign bit information except
6112 * what we can pick up from var_off. Perhaps we can generalize this
6113 * later to shifts of any length.
6114 */
6115 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
6116 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
6117 else
6118 dst_reg->smax_value = S64_MAX;
6119
6120 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
6121 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
6122 else
6123 dst_reg->smin_value = S64_MIN;
6124
07cd2631
JF
6125 /* If we might shift our top bit out, then we know nothing */
6126 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
6127 dst_reg->umin_value = 0;
6128 dst_reg->umax_value = U64_MAX;
6129 } else {
6130 dst_reg->umin_value <<= umin_val;
6131 dst_reg->umax_value <<= umax_val;
6132 }
3f50f132
JF
6133}
6134
6135static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
6136 struct bpf_reg_state *src_reg)
6137{
6138 u64 umax_val = src_reg->umax_value;
6139 u64 umin_val = src_reg->umin_value;
6140
6141 /* scalar64 calc uses 32bit unshifted bounds so must be called first */
6142 __scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
6143 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
6144
07cd2631
JF
6145 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
6146 /* We may learn something more from the var_off */
6147 __update_reg_bounds(dst_reg);
6148}
6149
3f50f132
JF
6150static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
6151 struct bpf_reg_state *src_reg)
6152{
6153 struct tnum subreg = tnum_subreg(dst_reg->var_off);
6154 u32 umax_val = src_reg->u32_max_value;
6155 u32 umin_val = src_reg->u32_min_value;
6156
6157 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
6158 * be negative, then either:
6159 * 1) src_reg might be zero, so the sign bit of the result is
6160 * unknown, so we lose our signed bounds
6161 * 2) it's known negative, thus the unsigned bounds capture the
6162 * signed bounds
6163 * 3) the signed bounds cross zero, so they tell us nothing
6164 * about the result
6165 * If the value in dst_reg is known nonnegative, then again the
6166 * unsigned bounts capture the signed bounds.
6167 * Thus, in all cases it suffices to blow away our signed bounds
6168 * and rely on inferring new ones from the unsigned bounds and
6169 * var_off of the result.
6170 */
6171 dst_reg->s32_min_value = S32_MIN;
6172 dst_reg->s32_max_value = S32_MAX;
6173
6174 dst_reg->var_off = tnum_rshift(subreg, umin_val);
6175 dst_reg->u32_min_value >>= umax_val;
6176 dst_reg->u32_max_value >>= umin_val;
6177
6178 __mark_reg64_unbounded(dst_reg);
6179 __update_reg32_bounds(dst_reg);
6180}
6181
07cd2631
JF
6182static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
6183 struct bpf_reg_state *src_reg)
6184{
6185 u64 umax_val = src_reg->umax_value;
6186 u64 umin_val = src_reg->umin_value;
6187
6188 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
6189 * be negative, then either:
6190 * 1) src_reg might be zero, so the sign bit of the result is
6191 * unknown, so we lose our signed bounds
6192 * 2) it's known negative, thus the unsigned bounds capture the
6193 * signed bounds
6194 * 3) the signed bounds cross zero, so they tell us nothing
6195 * about the result
6196 * If the value in dst_reg is known nonnegative, then again the
6197 * unsigned bounts capture the signed bounds.
6198 * Thus, in all cases it suffices to blow away our signed bounds
6199 * and rely on inferring new ones from the unsigned bounds and
6200 * var_off of the result.
6201 */
6202 dst_reg->smin_value = S64_MIN;
6203 dst_reg->smax_value = S64_MAX;
6204 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
6205 dst_reg->umin_value >>= umax_val;
6206 dst_reg->umax_value >>= umin_val;
3f50f132
JF
6207
6208 /* Its not easy to operate on alu32 bounds here because it depends
6209 * on bits being shifted in. Take easy way out and mark unbounded
6210 * so we can recalculate later from tnum.
6211 */
6212 __mark_reg32_unbounded(dst_reg);
07cd2631
JF
6213 __update_reg_bounds(dst_reg);
6214}
6215
3f50f132
JF
6216static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
6217 struct bpf_reg_state *src_reg)
07cd2631 6218{
3f50f132 6219 u64 umin_val = src_reg->u32_min_value;
07cd2631
JF
6220
6221 /* Upon reaching here, src_known is true and
6222 * umax_val is equal to umin_val.
6223 */
3f50f132
JF
6224 dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
6225 dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
07cd2631 6226
3f50f132
JF
6227 dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
6228
6229 /* blow away the dst_reg umin_value/umax_value and rely on
6230 * dst_reg var_off to refine the result.
6231 */
6232 dst_reg->u32_min_value = 0;
6233 dst_reg->u32_max_value = U32_MAX;
6234
6235 __mark_reg64_unbounded(dst_reg);
6236 __update_reg32_bounds(dst_reg);
6237}
6238
6239static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
6240 struct bpf_reg_state *src_reg)
6241{
6242 u64 umin_val = src_reg->umin_value;
6243
6244 /* Upon reaching here, src_known is true and umax_val is equal
6245 * to umin_val.
6246 */
6247 dst_reg->smin_value >>= umin_val;
6248 dst_reg->smax_value >>= umin_val;
6249
6250 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
07cd2631
JF
6251
6252 /* blow away the dst_reg umin_value/umax_value and rely on
6253 * dst_reg var_off to refine the result.
6254 */
6255 dst_reg->umin_value = 0;
6256 dst_reg->umax_value = U64_MAX;
3f50f132
JF
6257
6258 /* Its not easy to operate on alu32 bounds here because it depends
6259 * on bits being shifted in from upper 32-bits. Take easy way out
6260 * and mark unbounded so we can recalculate later from tnum.
6261 */
6262 __mark_reg32_unbounded(dst_reg);
07cd2631
JF
6263 __update_reg_bounds(dst_reg);
6264}
6265
468f6eaf
JH
6266/* WARNING: This function does calculations on 64-bit values, but the actual
6267 * execution may occur on 32-bit values. Therefore, things like bitshifts
6268 * need extra checks in the 32-bit case.
6269 */
f1174f77
EC
6270static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
6271 struct bpf_insn *insn,
6272 struct bpf_reg_state *dst_reg,
6273 struct bpf_reg_state src_reg)
969bf05e 6274{
638f5b90 6275 struct bpf_reg_state *regs = cur_regs(env);
48461135 6276 u8 opcode = BPF_OP(insn->code);
b0b3fb67 6277 bool src_known;
b03c9f9f
EC
6278 s64 smin_val, smax_val;
6279 u64 umin_val, umax_val;
3f50f132
JF
6280 s32 s32_min_val, s32_max_val;
6281 u32 u32_min_val, u32_max_val;
468f6eaf 6282 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
d3bd7413
DB
6283 u32 dst = insn->dst_reg;
6284 int ret;
3f50f132 6285 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
b799207e 6286
b03c9f9f
EC
6287 smin_val = src_reg.smin_value;
6288 smax_val = src_reg.smax_value;
6289 umin_val = src_reg.umin_value;
6290 umax_val = src_reg.umax_value;
f23cc643 6291
3f50f132
JF
6292 s32_min_val = src_reg.s32_min_value;
6293 s32_max_val = src_reg.s32_max_value;
6294 u32_min_val = src_reg.u32_min_value;
6295 u32_max_val = src_reg.u32_max_value;
6296
6297 if (alu32) {
6298 src_known = tnum_subreg_is_const(src_reg.var_off);
3f50f132
JF
6299 if ((src_known &&
6300 (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
6301 s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
6302 /* Taint dst register if offset had invalid bounds
6303 * derived from e.g. dead branches.
6304 */
6305 __mark_reg_unknown(env, dst_reg);
6306 return 0;
6307 }
6308 } else {
6309 src_known = tnum_is_const(src_reg.var_off);
3f50f132
JF
6310 if ((src_known &&
6311 (smin_val != smax_val || umin_val != umax_val)) ||
6312 smin_val > smax_val || umin_val > umax_val) {
6313 /* Taint dst register if offset had invalid bounds
6314 * derived from e.g. dead branches.
6315 */
6316 __mark_reg_unknown(env, dst_reg);
6317 return 0;
6318 }
6f16101e
DB
6319 }
6320
bb7f0f98
AS
6321 if (!src_known &&
6322 opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
f54c7898 6323 __mark_reg_unknown(env, dst_reg);
bb7f0f98
AS
6324 return 0;
6325 }
6326
3f50f132
JF
6327 /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
6328 * There are two classes of instructions: The first class we track both
6329 * alu32 and alu64 sign/unsigned bounds independently this provides the
6330 * greatest amount of precision when alu operations are mixed with jmp32
6331 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
6332 * and BPF_OR. This is possible because these ops have fairly easy to
6333 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
6334 * See alu32 verifier tests for examples. The second class of
6335 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
6336 * with regards to tracking sign/unsigned bounds because the bits may
6337 * cross subreg boundaries in the alu64 case. When this happens we mark
6338 * the reg unbounded in the subreg bound space and use the resulting
6339 * tnum to calculate an approximation of the sign/unsigned bounds.
6340 */
48461135
JB
6341 switch (opcode) {
6342 case BPF_ADD:
d3bd7413
DB
6343 ret = sanitize_val_alu(env, insn);
6344 if (ret < 0) {
6345 verbose(env, "R%d tried to add from different pointers or scalars\n", dst);
6346 return ret;
6347 }
3f50f132 6348 scalar32_min_max_add(dst_reg, &src_reg);
07cd2631 6349 scalar_min_max_add(dst_reg, &src_reg);
3f50f132 6350 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
48461135
JB
6351 break;
6352 case BPF_SUB:
d3bd7413
DB
6353 ret = sanitize_val_alu(env, insn);
6354 if (ret < 0) {
6355 verbose(env, "R%d tried to sub from different pointers or scalars\n", dst);
6356 return ret;
6357 }
3f50f132 6358 scalar32_min_max_sub(dst_reg, &src_reg);
07cd2631 6359 scalar_min_max_sub(dst_reg, &src_reg);
3f50f132 6360 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
48461135
JB
6361 break;
6362 case BPF_MUL:
3f50f132
JF
6363 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
6364 scalar32_min_max_mul(dst_reg, &src_reg);
07cd2631 6365 scalar_min_max_mul(dst_reg, &src_reg);
48461135
JB
6366 break;
6367 case BPF_AND:
3f50f132
JF
6368 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
6369 scalar32_min_max_and(dst_reg, &src_reg);
07cd2631 6370 scalar_min_max_and(dst_reg, &src_reg);
f1174f77
EC
6371 break;
6372 case BPF_OR:
3f50f132
JF
6373 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
6374 scalar32_min_max_or(dst_reg, &src_reg);
07cd2631 6375 scalar_min_max_or(dst_reg, &src_reg);
48461135 6376 break;
2921c90d
YS
6377 case BPF_XOR:
6378 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
6379 scalar32_min_max_xor(dst_reg, &src_reg);
6380 scalar_min_max_xor(dst_reg, &src_reg);
6381 break;
48461135 6382 case BPF_LSH:
468f6eaf
JH
6383 if (umax_val >= insn_bitness) {
6384 /* Shifts greater than 31 or 63 are undefined.
6385 * This includes shifts by a negative number.
b03c9f9f 6386 */
61bd5218 6387 mark_reg_unknown(env, regs, insn->dst_reg);
f1174f77
EC
6388 break;
6389 }
3f50f132
JF
6390 if (alu32)
6391 scalar32_min_max_lsh(dst_reg, &src_reg);
6392 else
6393 scalar_min_max_lsh(dst_reg, &src_reg);
48461135
JB
6394 break;
6395 case BPF_RSH:
468f6eaf
JH
6396 if (umax_val >= insn_bitness) {
6397 /* Shifts greater than 31 or 63 are undefined.
6398 * This includes shifts by a negative number.
b03c9f9f 6399 */
61bd5218 6400 mark_reg_unknown(env, regs, insn->dst_reg);
f1174f77
EC
6401 break;
6402 }
3f50f132
JF
6403 if (alu32)
6404 scalar32_min_max_rsh(dst_reg, &src_reg);
6405 else
6406 scalar_min_max_rsh(dst_reg, &src_reg);
48461135 6407 break;
9cbe1f5a
YS
6408 case BPF_ARSH:
6409 if (umax_val >= insn_bitness) {
6410 /* Shifts greater than 31 or 63 are undefined.
6411 * This includes shifts by a negative number.
6412 */
6413 mark_reg_unknown(env, regs, insn->dst_reg);
6414 break;
6415 }
3f50f132
JF
6416 if (alu32)
6417 scalar32_min_max_arsh(dst_reg, &src_reg);
6418 else
6419 scalar_min_max_arsh(dst_reg, &src_reg);
9cbe1f5a 6420 break;
48461135 6421 default:
61bd5218 6422 mark_reg_unknown(env, regs, insn->dst_reg);
48461135
JB
6423 break;
6424 }
6425
3f50f132
JF
6426 /* ALU32 ops are zero extended into 64bit register */
6427 if (alu32)
6428 zext_32_to_64(dst_reg);
468f6eaf 6429
294f2fc6 6430 __update_reg_bounds(dst_reg);
b03c9f9f
EC
6431 __reg_deduce_bounds(dst_reg);
6432 __reg_bound_offset(dst_reg);
f1174f77
EC
6433 return 0;
6434}
6435
6436/* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
6437 * and var_off.
6438 */
6439static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
6440 struct bpf_insn *insn)
6441{
f4d7e40a
AS
6442 struct bpf_verifier_state *vstate = env->cur_state;
6443 struct bpf_func_state *state = vstate->frame[vstate->curframe];
6444 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
f1174f77
EC
6445 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
6446 u8 opcode = BPF_OP(insn->code);
b5dc0163 6447 int err;
f1174f77
EC
6448
6449 dst_reg = &regs[insn->dst_reg];
f1174f77
EC
6450 src_reg = NULL;
6451 if (dst_reg->type != SCALAR_VALUE)
6452 ptr_reg = dst_reg;
75748837
AS
6453 else
6454 /* Make sure ID is cleared otherwise dst_reg min/max could be
6455 * incorrectly propagated into other registers by find_equal_scalars()
6456 */
6457 dst_reg->id = 0;
f1174f77
EC
6458 if (BPF_SRC(insn->code) == BPF_X) {
6459 src_reg = &regs[insn->src_reg];
f1174f77
EC
6460 if (src_reg->type != SCALAR_VALUE) {
6461 if (dst_reg->type != SCALAR_VALUE) {
6462 /* Combining two pointers by any ALU op yields
82abbf8d
AS
6463 * an arbitrary scalar. Disallow all math except
6464 * pointer subtraction
f1174f77 6465 */
dd066823 6466 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
82abbf8d
AS
6467 mark_reg_unknown(env, regs, insn->dst_reg);
6468 return 0;
f1174f77 6469 }
82abbf8d
AS
6470 verbose(env, "R%d pointer %s pointer prohibited\n",
6471 insn->dst_reg,
6472 bpf_alu_string[opcode >> 4]);
6473 return -EACCES;
f1174f77
EC
6474 } else {
6475 /* scalar += pointer
6476 * This is legal, but we have to reverse our
6477 * src/dest handling in computing the range
6478 */
b5dc0163
AS
6479 err = mark_chain_precision(env, insn->dst_reg);
6480 if (err)
6481 return err;
82abbf8d
AS
6482 return adjust_ptr_min_max_vals(env, insn,
6483 src_reg, dst_reg);
f1174f77
EC
6484 }
6485 } else if (ptr_reg) {
6486 /* pointer += scalar */
b5dc0163
AS
6487 err = mark_chain_precision(env, insn->src_reg);
6488 if (err)
6489 return err;
82abbf8d
AS
6490 return adjust_ptr_min_max_vals(env, insn,
6491 dst_reg, src_reg);
f1174f77
EC
6492 }
6493 } else {
6494 /* Pretend the src is a reg with a known value, since we only
6495 * need to be able to read from this state.
6496 */
6497 off_reg.type = SCALAR_VALUE;
b03c9f9f 6498 __mark_reg_known(&off_reg, insn->imm);
f1174f77 6499 src_reg = &off_reg;
82abbf8d
AS
6500 if (ptr_reg) /* pointer += K */
6501 return adjust_ptr_min_max_vals(env, insn,
6502 ptr_reg, src_reg);
f1174f77
EC
6503 }
6504
6505 /* Got here implies adding two SCALAR_VALUEs */
6506 if (WARN_ON_ONCE(ptr_reg)) {
f4d7e40a 6507 print_verifier_state(env, state);
61bd5218 6508 verbose(env, "verifier internal error: unexpected ptr_reg\n");
f1174f77
EC
6509 return -EINVAL;
6510 }
6511 if (WARN_ON(!src_reg)) {
f4d7e40a 6512 print_verifier_state(env, state);
61bd5218 6513 verbose(env, "verifier internal error: no src_reg\n");
f1174f77
EC
6514 return -EINVAL;
6515 }
6516 return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
48461135
JB
6517}
6518
17a52670 6519/* check validity of 32-bit and 64-bit arithmetic operations */
58e2af8b 6520static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
17a52670 6521{
638f5b90 6522 struct bpf_reg_state *regs = cur_regs(env);
17a52670
AS
6523 u8 opcode = BPF_OP(insn->code);
6524 int err;
6525
6526 if (opcode == BPF_END || opcode == BPF_NEG) {
6527 if (opcode == BPF_NEG) {
6528 if (BPF_SRC(insn->code) != 0 ||
6529 insn->src_reg != BPF_REG_0 ||
6530 insn->off != 0 || insn->imm != 0) {
61bd5218 6531 verbose(env, "BPF_NEG uses reserved fields\n");
17a52670
AS
6532 return -EINVAL;
6533 }
6534 } else {
6535 if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
e67b8a68
EC
6536 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
6537 BPF_CLASS(insn->code) == BPF_ALU64) {
61bd5218 6538 verbose(env, "BPF_END uses reserved fields\n");
17a52670
AS
6539 return -EINVAL;
6540 }
6541 }
6542
6543 /* check src operand */
dc503a8a 6544 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17a52670
AS
6545 if (err)
6546 return err;
6547
1be7f75d 6548 if (is_pointer_value(env, insn->dst_reg)) {
61bd5218 6549 verbose(env, "R%d pointer arithmetic prohibited\n",
1be7f75d
AS
6550 insn->dst_reg);
6551 return -EACCES;
6552 }
6553
17a52670 6554 /* check dest operand */
dc503a8a 6555 err = check_reg_arg(env, insn->dst_reg, DST_OP);
17a52670
AS
6556 if (err)
6557 return err;
6558
6559 } else if (opcode == BPF_MOV) {
6560
6561 if (BPF_SRC(insn->code) == BPF_X) {
6562 if (insn->imm != 0 || insn->off != 0) {
61bd5218 6563 verbose(env, "BPF_MOV uses reserved fields\n");
17a52670
AS
6564 return -EINVAL;
6565 }
6566
6567 /* check src operand */
dc503a8a 6568 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17a52670
AS
6569 if (err)
6570 return err;
6571 } else {
6572 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
61bd5218 6573 verbose(env, "BPF_MOV uses reserved fields\n");
17a52670
AS
6574 return -EINVAL;
6575 }
6576 }
6577
fbeb1603
AF
6578 /* check dest operand, mark as required later */
6579 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
17a52670
AS
6580 if (err)
6581 return err;
6582
6583 if (BPF_SRC(insn->code) == BPF_X) {
e434b8cd
JW
6584 struct bpf_reg_state *src_reg = regs + insn->src_reg;
6585 struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
6586
17a52670
AS
6587 if (BPF_CLASS(insn->code) == BPF_ALU64) {
6588 /* case: R1 = R2
6589 * copy register state to dest reg
6590 */
75748837
AS
6591 if (src_reg->type == SCALAR_VALUE && !src_reg->id)
6592 /* Assign src and dst registers the same ID
6593 * that will be used by find_equal_scalars()
6594 * to propagate min/max range.
6595 */
6596 src_reg->id = ++env->id_gen;
e434b8cd
JW
6597 *dst_reg = *src_reg;
6598 dst_reg->live |= REG_LIVE_WRITTEN;
5327ed3d 6599 dst_reg->subreg_def = DEF_NOT_SUBREG;
17a52670 6600 } else {
f1174f77 6601 /* R1 = (u32) R2 */
1be7f75d 6602 if (is_pointer_value(env, insn->src_reg)) {
61bd5218
JK
6603 verbose(env,
6604 "R%d partial copy of pointer\n",
1be7f75d
AS
6605 insn->src_reg);
6606 return -EACCES;
e434b8cd
JW
6607 } else if (src_reg->type == SCALAR_VALUE) {
6608 *dst_reg = *src_reg;
75748837
AS
6609 /* Make sure ID is cleared otherwise
6610 * dst_reg min/max could be incorrectly
6611 * propagated into src_reg by find_equal_scalars()
6612 */
6613 dst_reg->id = 0;
e434b8cd 6614 dst_reg->live |= REG_LIVE_WRITTEN;
5327ed3d 6615 dst_reg->subreg_def = env->insn_idx + 1;
e434b8cd
JW
6616 } else {
6617 mark_reg_unknown(env, regs,
6618 insn->dst_reg);
1be7f75d 6619 }
3f50f132 6620 zext_32_to_64(dst_reg);
17a52670
AS
6621 }
6622 } else {
6623 /* case: R = imm
6624 * remember the value we stored into this reg
6625 */
fbeb1603
AF
6626 /* clear any state __mark_reg_known doesn't set */
6627 mark_reg_unknown(env, regs, insn->dst_reg);
f1174f77 6628 regs[insn->dst_reg].type = SCALAR_VALUE;
95a762e2
JH
6629 if (BPF_CLASS(insn->code) == BPF_ALU64) {
6630 __mark_reg_known(regs + insn->dst_reg,
6631 insn->imm);
6632 } else {
6633 __mark_reg_known(regs + insn->dst_reg,
6634 (u32)insn->imm);
6635 }
17a52670
AS
6636 }
6637
6638 } else if (opcode > BPF_END) {
61bd5218 6639 verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
17a52670
AS
6640 return -EINVAL;
6641
6642 } else { /* all other ALU ops: and, sub, xor, add, ... */
6643
17a52670
AS
6644 if (BPF_SRC(insn->code) == BPF_X) {
6645 if (insn->imm != 0 || insn->off != 0) {
61bd5218 6646 verbose(env, "BPF_ALU uses reserved fields\n");
17a52670
AS
6647 return -EINVAL;
6648 }
6649 /* check src1 operand */
dc503a8a 6650 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17a52670
AS
6651 if (err)
6652 return err;
6653 } else {
6654 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
61bd5218 6655 verbose(env, "BPF_ALU uses reserved fields\n");
17a52670
AS
6656 return -EINVAL;
6657 }
6658 }
6659
6660 /* check src2 operand */
dc503a8a 6661 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17a52670
AS
6662 if (err)
6663 return err;
6664
6665 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
6666 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
61bd5218 6667 verbose(env, "div by zero\n");
17a52670
AS
6668 return -EINVAL;
6669 }
6670
229394e8
RV
6671 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
6672 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
6673 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
6674
6675 if (insn->imm < 0 || insn->imm >= size) {
61bd5218 6676 verbose(env, "invalid shift %d\n", insn->imm);
229394e8
RV
6677 return -EINVAL;
6678 }
6679 }
6680
1a0dc1ac 6681 /* check dest operand */
dc503a8a 6682 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
1a0dc1ac
AS
6683 if (err)
6684 return err;
6685
f1174f77 6686 return adjust_reg_min_max_vals(env, insn);
17a52670
AS
6687 }
6688
6689 return 0;
6690}
6691
c6a9efa1
PC
6692static void __find_good_pkt_pointers(struct bpf_func_state *state,
6693 struct bpf_reg_state *dst_reg,
6694 enum bpf_reg_type type, u16 new_range)
6695{
6696 struct bpf_reg_state *reg;
6697 int i;
6698
6699 for (i = 0; i < MAX_BPF_REG; i++) {
6700 reg = &state->regs[i];
6701 if (reg->type == type && reg->id == dst_reg->id)
6702 /* keep the maximum range already checked */
6703 reg->range = max(reg->range, new_range);
6704 }
6705
6706 bpf_for_each_spilled_reg(i, state, reg) {
6707 if (!reg)
6708 continue;
6709 if (reg->type == type && reg->id == dst_reg->id)
6710 reg->range = max(reg->range, new_range);
6711 }
6712}
6713
f4d7e40a 6714static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
de8f3a83 6715 struct bpf_reg_state *dst_reg,
f8ddadc4 6716 enum bpf_reg_type type,
fb2a311a 6717 bool range_right_open)
969bf05e 6718{
fb2a311a 6719 u16 new_range;
c6a9efa1 6720 int i;
2d2be8ca 6721
fb2a311a
DB
6722 if (dst_reg->off < 0 ||
6723 (dst_reg->off == 0 && range_right_open))
f1174f77
EC
6724 /* This doesn't give us any range */
6725 return;
6726
b03c9f9f
EC
6727 if (dst_reg->umax_value > MAX_PACKET_OFF ||
6728 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
f1174f77
EC
6729 /* Risk of overflow. For instance, ptr + (1<<63) may be less
6730 * than pkt_end, but that's because it's also less than pkt.
6731 */
6732 return;
6733
fb2a311a
DB
6734 new_range = dst_reg->off;
6735 if (range_right_open)
6736 new_range--;
6737
6738 /* Examples for register markings:
2d2be8ca 6739 *
fb2a311a 6740 * pkt_data in dst register:
2d2be8ca
DB
6741 *
6742 * r2 = r3;
6743 * r2 += 8;
6744 * if (r2 > pkt_end) goto <handle exception>
6745 * <access okay>
6746 *
b4e432f1
DB
6747 * r2 = r3;
6748 * r2 += 8;
6749 * if (r2 < pkt_end) goto <access okay>
6750 * <handle exception>
6751 *
2d2be8ca
DB
6752 * Where:
6753 * r2 == dst_reg, pkt_end == src_reg
6754 * r2=pkt(id=n,off=8,r=0)
6755 * r3=pkt(id=n,off=0,r=0)
6756 *
fb2a311a 6757 * pkt_data in src register:
2d2be8ca
DB
6758 *
6759 * r2 = r3;
6760 * r2 += 8;
6761 * if (pkt_end >= r2) goto <access okay>
6762 * <handle exception>
6763 *
b4e432f1
DB
6764 * r2 = r3;
6765 * r2 += 8;
6766 * if (pkt_end <= r2) goto <handle exception>
6767 * <access okay>
6768 *
2d2be8ca
DB
6769 * Where:
6770 * pkt_end == dst_reg, r2 == src_reg
6771 * r2=pkt(id=n,off=8,r=0)
6772 * r3=pkt(id=n,off=0,r=0)
6773 *
6774 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
fb2a311a
DB
6775 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
6776 * and [r3, r3 + 8-1) respectively is safe to access depending on
6777 * the check.
969bf05e 6778 */
2d2be8ca 6779
f1174f77
EC
6780 /* If our ids match, then we must have the same max_value. And we
6781 * don't care about the other reg's fixed offset, since if it's too big
6782 * the range won't allow anything.
6783 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
6784 */
c6a9efa1
PC
6785 for (i = 0; i <= vstate->curframe; i++)
6786 __find_good_pkt_pointers(vstate->frame[i], dst_reg, type,
6787 new_range);
969bf05e
AS
6788}
6789
3f50f132 6790static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
4f7b3e82 6791{
3f50f132
JF
6792 struct tnum subreg = tnum_subreg(reg->var_off);
6793 s32 sval = (s32)val;
a72dafaf 6794
3f50f132
JF
6795 switch (opcode) {
6796 case BPF_JEQ:
6797 if (tnum_is_const(subreg))
6798 return !!tnum_equals_const(subreg, val);
6799 break;
6800 case BPF_JNE:
6801 if (tnum_is_const(subreg))
6802 return !tnum_equals_const(subreg, val);
6803 break;
6804 case BPF_JSET:
6805 if ((~subreg.mask & subreg.value) & val)
6806 return 1;
6807 if (!((subreg.mask | subreg.value) & val))
6808 return 0;
6809 break;
6810 case BPF_JGT:
6811 if (reg->u32_min_value > val)
6812 return 1;
6813 else if (reg->u32_max_value <= val)
6814 return 0;
6815 break;
6816 case BPF_JSGT:
6817 if (reg->s32_min_value > sval)
6818 return 1;
6819 else if (reg->s32_max_value < sval)
6820 return 0;
6821 break;
6822 case BPF_JLT:
6823 if (reg->u32_max_value < val)
6824 return 1;
6825 else if (reg->u32_min_value >= val)
6826 return 0;
6827 break;
6828 case BPF_JSLT:
6829 if (reg->s32_max_value < sval)
6830 return 1;
6831 else if (reg->s32_min_value >= sval)
6832 return 0;
6833 break;
6834 case BPF_JGE:
6835 if (reg->u32_min_value >= val)
6836 return 1;
6837 else if (reg->u32_max_value < val)
6838 return 0;
6839 break;
6840 case BPF_JSGE:
6841 if (reg->s32_min_value >= sval)
6842 return 1;
6843 else if (reg->s32_max_value < sval)
6844 return 0;
6845 break;
6846 case BPF_JLE:
6847 if (reg->u32_max_value <= val)
6848 return 1;
6849 else if (reg->u32_min_value > val)
6850 return 0;
6851 break;
6852 case BPF_JSLE:
6853 if (reg->s32_max_value <= sval)
6854 return 1;
6855 else if (reg->s32_min_value > sval)
6856 return 0;
6857 break;
6858 }
4f7b3e82 6859
3f50f132
JF
6860 return -1;
6861}
092ed096 6862
3f50f132
JF
6863
6864static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
6865{
6866 s64 sval = (s64)val;
a72dafaf 6867
4f7b3e82
AS
6868 switch (opcode) {
6869 case BPF_JEQ:
6870 if (tnum_is_const(reg->var_off))
6871 return !!tnum_equals_const(reg->var_off, val);
6872 break;
6873 case BPF_JNE:
6874 if (tnum_is_const(reg->var_off))
6875 return !tnum_equals_const(reg->var_off, val);
6876 break;
960ea056
JK
6877 case BPF_JSET:
6878 if ((~reg->var_off.mask & reg->var_off.value) & val)
6879 return 1;
6880 if (!((reg->var_off.mask | reg->var_off.value) & val))
6881 return 0;
6882 break;
4f7b3e82
AS
6883 case BPF_JGT:
6884 if (reg->umin_value > val)
6885 return 1;
6886 else if (reg->umax_value <= val)
6887 return 0;
6888 break;
6889 case BPF_JSGT:
a72dafaf 6890 if (reg->smin_value > sval)
4f7b3e82 6891 return 1;
a72dafaf 6892 else if (reg->smax_value < sval)
4f7b3e82
AS
6893 return 0;
6894 break;
6895 case BPF_JLT:
6896 if (reg->umax_value < val)
6897 return 1;
6898 else if (reg->umin_value >= val)
6899 return 0;
6900 break;
6901 case BPF_JSLT:
a72dafaf 6902 if (reg->smax_value < sval)
4f7b3e82 6903 return 1;
a72dafaf 6904 else if (reg->smin_value >= sval)
4f7b3e82
AS
6905 return 0;
6906 break;
6907 case BPF_JGE:
6908 if (reg->umin_value >= val)
6909 return 1;
6910 else if (reg->umax_value < val)
6911 return 0;
6912 break;
6913 case BPF_JSGE:
a72dafaf 6914 if (reg->smin_value >= sval)
4f7b3e82 6915 return 1;
a72dafaf 6916 else if (reg->smax_value < sval)
4f7b3e82
AS
6917 return 0;
6918 break;
6919 case BPF_JLE:
6920 if (reg->umax_value <= val)
6921 return 1;
6922 else if (reg->umin_value > val)
6923 return 0;
6924 break;
6925 case BPF_JSLE:
a72dafaf 6926 if (reg->smax_value <= sval)
4f7b3e82 6927 return 1;
a72dafaf 6928 else if (reg->smin_value > sval)
4f7b3e82
AS
6929 return 0;
6930 break;
6931 }
6932
6933 return -1;
6934}
6935
3f50f132
JF
6936/* compute branch direction of the expression "if (reg opcode val) goto target;"
6937 * and return:
6938 * 1 - branch will be taken and "goto target" will be executed
6939 * 0 - branch will not be taken and fall-through to next insn
6940 * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
6941 * range [0,10]
604dca5e 6942 */
3f50f132
JF
6943static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
6944 bool is_jmp32)
604dca5e 6945{
cac616db
JF
6946 if (__is_pointer_value(false, reg)) {
6947 if (!reg_type_not_null(reg->type))
6948 return -1;
6949
6950 /* If pointer is valid tests against zero will fail so we can
6951 * use this to direct branch taken.
6952 */
6953 if (val != 0)
6954 return -1;
6955
6956 switch (opcode) {
6957 case BPF_JEQ:
6958 return 0;
6959 case BPF_JNE:
6960 return 1;
6961 default:
6962 return -1;
6963 }
6964 }
604dca5e 6965
3f50f132
JF
6966 if (is_jmp32)
6967 return is_branch32_taken(reg, val, opcode);
6968 return is_branch64_taken(reg, val, opcode);
604dca5e
JH
6969}
6970
48461135
JB
6971/* Adjusts the register min/max values in the case that the dst_reg is the
6972 * variable register that we are working on, and src_reg is a constant or we're
6973 * simply doing a BPF_K check.
f1174f77 6974 * In JEQ/JNE cases we also adjust the var_off values.
48461135
JB
6975 */
6976static void reg_set_min_max(struct bpf_reg_state *true_reg,
3f50f132
JF
6977 struct bpf_reg_state *false_reg,
6978 u64 val, u32 val32,
092ed096 6979 u8 opcode, bool is_jmp32)
48461135 6980{
3f50f132
JF
6981 struct tnum false_32off = tnum_subreg(false_reg->var_off);
6982 struct tnum false_64off = false_reg->var_off;
6983 struct tnum true_32off = tnum_subreg(true_reg->var_off);
6984 struct tnum true_64off = true_reg->var_off;
6985 s64 sval = (s64)val;
6986 s32 sval32 = (s32)val32;
a72dafaf 6987
f1174f77
EC
6988 /* If the dst_reg is a pointer, we can't learn anything about its
6989 * variable offset from the compare (unless src_reg were a pointer into
6990 * the same object, but we don't bother with that.
6991 * Since false_reg and true_reg have the same type by construction, we
6992 * only need to check one of them for pointerness.
6993 */
6994 if (__is_pointer_value(false, false_reg))
6995 return;
4cabc5b1 6996
48461135
JB
6997 switch (opcode) {
6998 case BPF_JEQ:
48461135 6999 case BPF_JNE:
a72dafaf
JW
7000 {
7001 struct bpf_reg_state *reg =
7002 opcode == BPF_JEQ ? true_reg : false_reg;
7003
7004 /* For BPF_JEQ, if this is false we know nothing Jon Snow, but
7005 * if it is true we know the value for sure. Likewise for
7006 * BPF_JNE.
48461135 7007 */
3f50f132
JF
7008 if (is_jmp32)
7009 __mark_reg32_known(reg, val32);
7010 else
092ed096 7011 __mark_reg_known(reg, val);
48461135 7012 break;
a72dafaf 7013 }
960ea056 7014 case BPF_JSET:
3f50f132
JF
7015 if (is_jmp32) {
7016 false_32off = tnum_and(false_32off, tnum_const(~val32));
7017 if (is_power_of_2(val32))
7018 true_32off = tnum_or(true_32off,
7019 tnum_const(val32));
7020 } else {
7021 false_64off = tnum_and(false_64off, tnum_const(~val));
7022 if (is_power_of_2(val))
7023 true_64off = tnum_or(true_64off,
7024 tnum_const(val));
7025 }
960ea056 7026 break;
48461135 7027 case BPF_JGE:
a72dafaf
JW
7028 case BPF_JGT:
7029 {
3f50f132
JF
7030 if (is_jmp32) {
7031 u32 false_umax = opcode == BPF_JGT ? val32 : val32 - 1;
7032 u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
7033
7034 false_reg->u32_max_value = min(false_reg->u32_max_value,
7035 false_umax);
7036 true_reg->u32_min_value = max(true_reg->u32_min_value,
7037 true_umin);
7038 } else {
7039 u64 false_umax = opcode == BPF_JGT ? val : val - 1;
7040 u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
7041
7042 false_reg->umax_value = min(false_reg->umax_value, false_umax);
7043 true_reg->umin_value = max(true_reg->umin_value, true_umin);
7044 }
b03c9f9f 7045 break;
a72dafaf 7046 }
48461135 7047 case BPF_JSGE:
a72dafaf
JW
7048 case BPF_JSGT:
7049 {
3f50f132
JF
7050 if (is_jmp32) {
7051 s32 false_smax = opcode == BPF_JSGT ? sval32 : sval32 - 1;
7052 s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
a72dafaf 7053
3f50f132
JF
7054 false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
7055 true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
7056 } else {
7057 s64 false_smax = opcode == BPF_JSGT ? sval : sval - 1;
7058 s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
7059
7060 false_reg->smax_value = min(false_reg->smax_value, false_smax);
7061 true_reg->smin_value = max(true_reg->smin_value, true_smin);
7062 }
48461135 7063 break;
a72dafaf 7064 }
b4e432f1 7065 case BPF_JLE:
a72dafaf
JW
7066 case BPF_JLT:
7067 {
3f50f132
JF
7068 if (is_jmp32) {
7069 u32 false_umin = opcode == BPF_JLT ? val32 : val32 + 1;
7070 u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
7071
7072 false_reg->u32_min_value = max(false_reg->u32_min_value,
7073 false_umin);
7074 true_reg->u32_max_value = min(true_reg->u32_max_value,
7075 true_umax);
7076 } else {
7077 u64 false_umin = opcode == BPF_JLT ? val : val + 1;
7078 u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
7079
7080 false_reg->umin_value = max(false_reg->umin_value, false_umin);
7081 true_reg->umax_value = min(true_reg->umax_value, true_umax);
7082 }
b4e432f1 7083 break;
a72dafaf 7084 }
b4e432f1 7085 case BPF_JSLE:
a72dafaf
JW
7086 case BPF_JSLT:
7087 {
3f50f132
JF
7088 if (is_jmp32) {
7089 s32 false_smin = opcode == BPF_JSLT ? sval32 : sval32 + 1;
7090 s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
a72dafaf 7091
3f50f132
JF
7092 false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
7093 true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
7094 } else {
7095 s64 false_smin = opcode == BPF_JSLT ? sval : sval + 1;
7096 s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
7097
7098 false_reg->smin_value = max(false_reg->smin_value, false_smin);
7099 true_reg->smax_value = min(true_reg->smax_value, true_smax);
7100 }
b4e432f1 7101 break;
a72dafaf 7102 }
48461135 7103 default:
0fc31b10 7104 return;
48461135
JB
7105 }
7106
3f50f132
JF
7107 if (is_jmp32) {
7108 false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
7109 tnum_subreg(false_32off));
7110 true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
7111 tnum_subreg(true_32off));
7112 __reg_combine_32_into_64(false_reg);
7113 __reg_combine_32_into_64(true_reg);
7114 } else {
7115 false_reg->var_off = false_64off;
7116 true_reg->var_off = true_64off;
7117 __reg_combine_64_into_32(false_reg);
7118 __reg_combine_64_into_32(true_reg);
7119 }
48461135
JB
7120}
7121
f1174f77
EC
7122/* Same as above, but for the case that dst_reg holds a constant and src_reg is
7123 * the variable reg.
48461135
JB
7124 */
7125static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
3f50f132
JF
7126 struct bpf_reg_state *false_reg,
7127 u64 val, u32 val32,
092ed096 7128 u8 opcode, bool is_jmp32)
48461135 7129{
0fc31b10
JH
7130 /* How can we transform "a <op> b" into "b <op> a"? */
7131 static const u8 opcode_flip[16] = {
7132 /* these stay the same */
7133 [BPF_JEQ >> 4] = BPF_JEQ,
7134 [BPF_JNE >> 4] = BPF_JNE,
7135 [BPF_JSET >> 4] = BPF_JSET,
7136 /* these swap "lesser" and "greater" (L and G in the opcodes) */
7137 [BPF_JGE >> 4] = BPF_JLE,
7138 [BPF_JGT >> 4] = BPF_JLT,
7139 [BPF_JLE >> 4] = BPF_JGE,
7140 [BPF_JLT >> 4] = BPF_JGT,
7141 [BPF_JSGE >> 4] = BPF_JSLE,
7142 [BPF_JSGT >> 4] = BPF_JSLT,
7143 [BPF_JSLE >> 4] = BPF_JSGE,
7144 [BPF_JSLT >> 4] = BPF_JSGT
7145 };
7146 opcode = opcode_flip[opcode >> 4];
7147 /* This uses zero as "not present in table"; luckily the zero opcode,
7148 * BPF_JA, can't get here.
b03c9f9f 7149 */
0fc31b10 7150 if (opcode)
3f50f132 7151 reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
f1174f77
EC
7152}
7153
7154/* Regs are known to be equal, so intersect their min/max/var_off */
7155static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
7156 struct bpf_reg_state *dst_reg)
7157{
b03c9f9f
EC
7158 src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
7159 dst_reg->umin_value);
7160 src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
7161 dst_reg->umax_value);
7162 src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
7163 dst_reg->smin_value);
7164 src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
7165 dst_reg->smax_value);
f1174f77
EC
7166 src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
7167 dst_reg->var_off);
b03c9f9f
EC
7168 /* We might have learned new bounds from the var_off. */
7169 __update_reg_bounds(src_reg);
7170 __update_reg_bounds(dst_reg);
7171 /* We might have learned something about the sign bit. */
7172 __reg_deduce_bounds(src_reg);
7173 __reg_deduce_bounds(dst_reg);
7174 /* We might have learned some bits from the bounds. */
7175 __reg_bound_offset(src_reg);
7176 __reg_bound_offset(dst_reg);
7177 /* Intersecting with the old var_off might have improved our bounds
7178 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
7179 * then new var_off is (0; 0x7f...fc) which improves our umax.
7180 */
7181 __update_reg_bounds(src_reg);
7182 __update_reg_bounds(dst_reg);
f1174f77
EC
7183}
7184
7185static void reg_combine_min_max(struct bpf_reg_state *true_src,
7186 struct bpf_reg_state *true_dst,
7187 struct bpf_reg_state *false_src,
7188 struct bpf_reg_state *false_dst,
7189 u8 opcode)
7190{
7191 switch (opcode) {
7192 case BPF_JEQ:
7193 __reg_combine_min_max(true_src, true_dst);
7194 break;
7195 case BPF_JNE:
7196 __reg_combine_min_max(false_src, false_dst);
b03c9f9f 7197 break;
4cabc5b1 7198 }
48461135
JB
7199}
7200
fd978bf7
JS
7201static void mark_ptr_or_null_reg(struct bpf_func_state *state,
7202 struct bpf_reg_state *reg, u32 id,
840b9615 7203 bool is_null)
57a09bf0 7204{
840b9615 7205 if (reg_type_may_be_null(reg->type) && reg->id == id) {
f1174f77
EC
7206 /* Old offset (both fixed and variable parts) should
7207 * have been known-zero, because we don't allow pointer
7208 * arithmetic on pointers that might be NULL.
7209 */
b03c9f9f
EC
7210 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value ||
7211 !tnum_equals_const(reg->var_off, 0) ||
f1174f77 7212 reg->off)) {
b03c9f9f
EC
7213 __mark_reg_known_zero(reg);
7214 reg->off = 0;
f1174f77
EC
7215 }
7216 if (is_null) {
7217 reg->type = SCALAR_VALUE;
840b9615 7218 } else if (reg->type == PTR_TO_MAP_VALUE_OR_NULL) {
64d85290
JS
7219 const struct bpf_map *map = reg->map_ptr;
7220
7221 if (map->inner_map_meta) {
840b9615 7222 reg->type = CONST_PTR_TO_MAP;
64d85290
JS
7223 reg->map_ptr = map->inner_map_meta;
7224 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
fada7fdc 7225 reg->type = PTR_TO_XDP_SOCK;
64d85290
JS
7226 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
7227 map->map_type == BPF_MAP_TYPE_SOCKHASH) {
7228 reg->type = PTR_TO_SOCKET;
840b9615
JS
7229 } else {
7230 reg->type = PTR_TO_MAP_VALUE;
7231 }
c64b7983
JS
7232 } else if (reg->type == PTR_TO_SOCKET_OR_NULL) {
7233 reg->type = PTR_TO_SOCKET;
46f8bc92
MKL
7234 } else if (reg->type == PTR_TO_SOCK_COMMON_OR_NULL) {
7235 reg->type = PTR_TO_SOCK_COMMON;
655a51e5
MKL
7236 } else if (reg->type == PTR_TO_TCP_SOCK_OR_NULL) {
7237 reg->type = PTR_TO_TCP_SOCK;
b121b341
YS
7238 } else if (reg->type == PTR_TO_BTF_ID_OR_NULL) {
7239 reg->type = PTR_TO_BTF_ID;
457f4436
AN
7240 } else if (reg->type == PTR_TO_MEM_OR_NULL) {
7241 reg->type = PTR_TO_MEM;
afbf21dc
YS
7242 } else if (reg->type == PTR_TO_RDONLY_BUF_OR_NULL) {
7243 reg->type = PTR_TO_RDONLY_BUF;
7244 } else if (reg->type == PTR_TO_RDWR_BUF_OR_NULL) {
7245 reg->type = PTR_TO_RDWR_BUF;
56f668df 7246 }
1b986589
MKL
7247 if (is_null) {
7248 /* We don't need id and ref_obj_id from this point
7249 * onwards anymore, thus we should better reset it,
7250 * so that state pruning has chances to take effect.
7251 */
7252 reg->id = 0;
7253 reg->ref_obj_id = 0;
7254 } else if (!reg_may_point_to_spin_lock(reg)) {
7255 /* For not-NULL ptr, reg->ref_obj_id will be reset
7256 * in release_reg_references().
7257 *
7258 * reg->id is still used by spin_lock ptr. Other
7259 * than spin_lock ptr type, reg->id can be reset.
fd978bf7
JS
7260 */
7261 reg->id = 0;
56f668df 7262 }
57a09bf0
TG
7263 }
7264}
7265
c6a9efa1
PC
7266static void __mark_ptr_or_null_regs(struct bpf_func_state *state, u32 id,
7267 bool is_null)
7268{
7269 struct bpf_reg_state *reg;
7270 int i;
7271
7272 for (i = 0; i < MAX_BPF_REG; i++)
7273 mark_ptr_or_null_reg(state, &state->regs[i], id, is_null);
7274
7275 bpf_for_each_spilled_reg(i, state, reg) {
7276 if (!reg)
7277 continue;
7278 mark_ptr_or_null_reg(state, reg, id, is_null);
7279 }
7280}
7281
57a09bf0
TG
7282/* The logic is similar to find_good_pkt_pointers(), both could eventually
7283 * be folded together at some point.
7284 */
840b9615
JS
7285static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
7286 bool is_null)
57a09bf0 7287{
f4d7e40a 7288 struct bpf_func_state *state = vstate->frame[vstate->curframe];
c6a9efa1 7289 struct bpf_reg_state *regs = state->regs;
1b986589 7290 u32 ref_obj_id = regs[regno].ref_obj_id;
a08dd0da 7291 u32 id = regs[regno].id;
c6a9efa1 7292 int i;
57a09bf0 7293
1b986589
MKL
7294 if (ref_obj_id && ref_obj_id == id && is_null)
7295 /* regs[regno] is in the " == NULL" branch.
7296 * No one could have freed the reference state before
7297 * doing the NULL check.
7298 */
7299 WARN_ON_ONCE(release_reference_state(state, id));
fd978bf7 7300
c6a9efa1
PC
7301 for (i = 0; i <= vstate->curframe; i++)
7302 __mark_ptr_or_null_regs(vstate->frame[i], id, is_null);
57a09bf0
TG
7303}
7304
5beca081
DB
7305static bool try_match_pkt_pointers(const struct bpf_insn *insn,
7306 struct bpf_reg_state *dst_reg,
7307 struct bpf_reg_state *src_reg,
7308 struct bpf_verifier_state *this_branch,
7309 struct bpf_verifier_state *other_branch)
7310{
7311 if (BPF_SRC(insn->code) != BPF_X)
7312 return false;
7313
092ed096
JW
7314 /* Pointers are always 64-bit. */
7315 if (BPF_CLASS(insn->code) == BPF_JMP32)
7316 return false;
7317
5beca081
DB
7318 switch (BPF_OP(insn->code)) {
7319 case BPF_JGT:
7320 if ((dst_reg->type == PTR_TO_PACKET &&
7321 src_reg->type == PTR_TO_PACKET_END) ||
7322 (dst_reg->type == PTR_TO_PACKET_META &&
7323 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
7324 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
7325 find_good_pkt_pointers(this_branch, dst_reg,
7326 dst_reg->type, false);
7327 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
7328 src_reg->type == PTR_TO_PACKET) ||
7329 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
7330 src_reg->type == PTR_TO_PACKET_META)) {
7331 /* pkt_end > pkt_data', pkt_data > pkt_meta' */
7332 find_good_pkt_pointers(other_branch, src_reg,
7333 src_reg->type, true);
7334 } else {
7335 return false;
7336 }
7337 break;
7338 case BPF_JLT:
7339 if ((dst_reg->type == PTR_TO_PACKET &&
7340 src_reg->type == PTR_TO_PACKET_END) ||
7341 (dst_reg->type == PTR_TO_PACKET_META &&
7342 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
7343 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
7344 find_good_pkt_pointers(other_branch, dst_reg,
7345 dst_reg->type, true);
7346 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
7347 src_reg->type == PTR_TO_PACKET) ||
7348 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
7349 src_reg->type == PTR_TO_PACKET_META)) {
7350 /* pkt_end < pkt_data', pkt_data > pkt_meta' */
7351 find_good_pkt_pointers(this_branch, src_reg,
7352 src_reg->type, false);
7353 } else {
7354 return false;
7355 }
7356 break;
7357 case BPF_JGE:
7358 if ((dst_reg->type == PTR_TO_PACKET &&
7359 src_reg->type == PTR_TO_PACKET_END) ||
7360 (dst_reg->type == PTR_TO_PACKET_META &&
7361 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
7362 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
7363 find_good_pkt_pointers(this_branch, dst_reg,
7364 dst_reg->type, true);
7365 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
7366 src_reg->type == PTR_TO_PACKET) ||
7367 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
7368 src_reg->type == PTR_TO_PACKET_META)) {
7369 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
7370 find_good_pkt_pointers(other_branch, src_reg,
7371 src_reg->type, false);
7372 } else {
7373 return false;
7374 }
7375 break;
7376 case BPF_JLE:
7377 if ((dst_reg->type == PTR_TO_PACKET &&
7378 src_reg->type == PTR_TO_PACKET_END) ||
7379 (dst_reg->type == PTR_TO_PACKET_META &&
7380 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
7381 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
7382 find_good_pkt_pointers(other_branch, dst_reg,
7383 dst_reg->type, false);
7384 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
7385 src_reg->type == PTR_TO_PACKET) ||
7386 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
7387 src_reg->type == PTR_TO_PACKET_META)) {
7388 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
7389 find_good_pkt_pointers(this_branch, src_reg,
7390 src_reg->type, true);
7391 } else {
7392 return false;
7393 }
7394 break;
7395 default:
7396 return false;
7397 }
7398
7399 return true;
7400}
7401
75748837
AS
7402static void find_equal_scalars(struct bpf_verifier_state *vstate,
7403 struct bpf_reg_state *known_reg)
7404{
7405 struct bpf_func_state *state;
7406 struct bpf_reg_state *reg;
7407 int i, j;
7408
7409 for (i = 0; i <= vstate->curframe; i++) {
7410 state = vstate->frame[i];
7411 for (j = 0; j < MAX_BPF_REG; j++) {
7412 reg = &state->regs[j];
7413 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
7414 *reg = *known_reg;
7415 }
7416
7417 bpf_for_each_spilled_reg(j, state, reg) {
7418 if (!reg)
7419 continue;
7420 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
7421 *reg = *known_reg;
7422 }
7423 }
7424}
7425
58e2af8b 7426static int check_cond_jmp_op(struct bpf_verifier_env *env,
17a52670
AS
7427 struct bpf_insn *insn, int *insn_idx)
7428{
f4d7e40a
AS
7429 struct bpf_verifier_state *this_branch = env->cur_state;
7430 struct bpf_verifier_state *other_branch;
7431 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
fb8d251e 7432 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
17a52670 7433 u8 opcode = BPF_OP(insn->code);
092ed096 7434 bool is_jmp32;
fb8d251e 7435 int pred = -1;
17a52670
AS
7436 int err;
7437
092ed096
JW
7438 /* Only conditional jumps are expected to reach here. */
7439 if (opcode == BPF_JA || opcode > BPF_JSLE) {
7440 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
17a52670
AS
7441 return -EINVAL;
7442 }
7443
7444 if (BPF_SRC(insn->code) == BPF_X) {
7445 if (insn->imm != 0) {
092ed096 7446 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
17a52670
AS
7447 return -EINVAL;
7448 }
7449
7450 /* check src1 operand */
dc503a8a 7451 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17a52670
AS
7452 if (err)
7453 return err;
1be7f75d
AS
7454
7455 if (is_pointer_value(env, insn->src_reg)) {
61bd5218 7456 verbose(env, "R%d pointer comparison prohibited\n",
1be7f75d
AS
7457 insn->src_reg);
7458 return -EACCES;
7459 }
fb8d251e 7460 src_reg = &regs[insn->src_reg];
17a52670
AS
7461 } else {
7462 if (insn->src_reg != BPF_REG_0) {
092ed096 7463 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
17a52670
AS
7464 return -EINVAL;
7465 }
7466 }
7467
7468 /* check src2 operand */
dc503a8a 7469 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17a52670
AS
7470 if (err)
7471 return err;
7472
1a0dc1ac 7473 dst_reg = &regs[insn->dst_reg];
092ed096 7474 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
1a0dc1ac 7475
3f50f132
JF
7476 if (BPF_SRC(insn->code) == BPF_K) {
7477 pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
7478 } else if (src_reg->type == SCALAR_VALUE &&
7479 is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
7480 pred = is_branch_taken(dst_reg,
7481 tnum_subreg(src_reg->var_off).value,
7482 opcode,
7483 is_jmp32);
7484 } else if (src_reg->type == SCALAR_VALUE &&
7485 !is_jmp32 && tnum_is_const(src_reg->var_off)) {
7486 pred = is_branch_taken(dst_reg,
7487 src_reg->var_off.value,
7488 opcode,
7489 is_jmp32);
7490 }
7491
b5dc0163 7492 if (pred >= 0) {
cac616db
JF
7493 /* If we get here with a dst_reg pointer type it is because
7494 * above is_branch_taken() special cased the 0 comparison.
7495 */
7496 if (!__is_pointer_value(false, dst_reg))
7497 err = mark_chain_precision(env, insn->dst_reg);
b5dc0163
AS
7498 if (BPF_SRC(insn->code) == BPF_X && !err)
7499 err = mark_chain_precision(env, insn->src_reg);
7500 if (err)
7501 return err;
7502 }
fb8d251e
AS
7503 if (pred == 1) {
7504 /* only follow the goto, ignore fall-through */
7505 *insn_idx += insn->off;
7506 return 0;
7507 } else if (pred == 0) {
7508 /* only follow fall-through branch, since
7509 * that's where the program will go
7510 */
7511 return 0;
17a52670
AS
7512 }
7513
979d63d5
DB
7514 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
7515 false);
17a52670
AS
7516 if (!other_branch)
7517 return -EFAULT;
f4d7e40a 7518 other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
17a52670 7519
48461135
JB
7520 /* detect if we are comparing against a constant value so we can adjust
7521 * our min/max values for our dst register.
f1174f77
EC
7522 * this is only legit if both are scalars (or pointers to the same
7523 * object, I suppose, but we don't support that right now), because
7524 * otherwise the different base pointers mean the offsets aren't
7525 * comparable.
48461135
JB
7526 */
7527 if (BPF_SRC(insn->code) == BPF_X) {
092ed096 7528 struct bpf_reg_state *src_reg = &regs[insn->src_reg];
092ed096 7529
f1174f77 7530 if (dst_reg->type == SCALAR_VALUE &&
092ed096
JW
7531 src_reg->type == SCALAR_VALUE) {
7532 if (tnum_is_const(src_reg->var_off) ||
3f50f132
JF
7533 (is_jmp32 &&
7534 tnum_is_const(tnum_subreg(src_reg->var_off))))
f4d7e40a 7535 reg_set_min_max(&other_branch_regs[insn->dst_reg],
092ed096 7536 dst_reg,
3f50f132
JF
7537 src_reg->var_off.value,
7538 tnum_subreg(src_reg->var_off).value,
092ed096
JW
7539 opcode, is_jmp32);
7540 else if (tnum_is_const(dst_reg->var_off) ||
3f50f132
JF
7541 (is_jmp32 &&
7542 tnum_is_const(tnum_subreg(dst_reg->var_off))))
f4d7e40a 7543 reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
092ed096 7544 src_reg,
3f50f132
JF
7545 dst_reg->var_off.value,
7546 tnum_subreg(dst_reg->var_off).value,
092ed096
JW
7547 opcode, is_jmp32);
7548 else if (!is_jmp32 &&
7549 (opcode == BPF_JEQ || opcode == BPF_JNE))
f1174f77 7550 /* Comparing for equality, we can combine knowledge */
f4d7e40a
AS
7551 reg_combine_min_max(&other_branch_regs[insn->src_reg],
7552 &other_branch_regs[insn->dst_reg],
092ed096 7553 src_reg, dst_reg, opcode);
75748837
AS
7554 if (src_reg->id) {
7555 find_equal_scalars(this_branch, src_reg);
7556 find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
7557 }
7558
f1174f77
EC
7559 }
7560 } else if (dst_reg->type == SCALAR_VALUE) {
f4d7e40a 7561 reg_set_min_max(&other_branch_regs[insn->dst_reg],
3f50f132
JF
7562 dst_reg, insn->imm, (u32)insn->imm,
7563 opcode, is_jmp32);
48461135
JB
7564 }
7565
75748837
AS
7566 if (dst_reg->type == SCALAR_VALUE && dst_reg->id) {
7567 find_equal_scalars(this_branch, dst_reg);
7568 find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
7569 }
7570
092ed096
JW
7571 /* detect if R == 0 where R is returned from bpf_map_lookup_elem().
7572 * NOTE: these optimizations below are related with pointer comparison
7573 * which will never be JMP32.
7574 */
7575 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
1a0dc1ac 7576 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
840b9615
JS
7577 reg_type_may_be_null(dst_reg->type)) {
7578 /* Mark all identical registers in each branch as either
57a09bf0
TG
7579 * safe or unknown depending R == 0 or R != 0 conditional.
7580 */
840b9615
JS
7581 mark_ptr_or_null_regs(this_branch, insn->dst_reg,
7582 opcode == BPF_JNE);
7583 mark_ptr_or_null_regs(other_branch, insn->dst_reg,
7584 opcode == BPF_JEQ);
5beca081
DB
7585 } else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
7586 this_branch, other_branch) &&
7587 is_pointer_value(env, insn->dst_reg)) {
61bd5218
JK
7588 verbose(env, "R%d pointer comparison prohibited\n",
7589 insn->dst_reg);
1be7f75d 7590 return -EACCES;
17a52670 7591 }
06ee7115 7592 if (env->log.level & BPF_LOG_LEVEL)
f4d7e40a 7593 print_verifier_state(env, this_branch->frame[this_branch->curframe]);
17a52670
AS
7594 return 0;
7595}
7596
17a52670 7597/* verify BPF_LD_IMM64 instruction */
58e2af8b 7598static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
17a52670 7599{
d8eca5bb 7600 struct bpf_insn_aux_data *aux = cur_aux(env);
638f5b90 7601 struct bpf_reg_state *regs = cur_regs(env);
4976b718 7602 struct bpf_reg_state *dst_reg;
d8eca5bb 7603 struct bpf_map *map;
17a52670
AS
7604 int err;
7605
7606 if (BPF_SIZE(insn->code) != BPF_DW) {
61bd5218 7607 verbose(env, "invalid BPF_LD_IMM insn\n");
17a52670
AS
7608 return -EINVAL;
7609 }
7610 if (insn->off != 0) {
61bd5218 7611 verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
17a52670
AS
7612 return -EINVAL;
7613 }
7614
dc503a8a 7615 err = check_reg_arg(env, insn->dst_reg, DST_OP);
17a52670
AS
7616 if (err)
7617 return err;
7618
4976b718 7619 dst_reg = &regs[insn->dst_reg];
6b173873 7620 if (insn->src_reg == 0) {
6b173873
JK
7621 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
7622
4976b718 7623 dst_reg->type = SCALAR_VALUE;
b03c9f9f 7624 __mark_reg_known(&regs[insn->dst_reg], imm);
17a52670 7625 return 0;
6b173873 7626 }
17a52670 7627
4976b718
HL
7628 if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
7629 mark_reg_known_zero(env, regs, insn->dst_reg);
7630
7631 dst_reg->type = aux->btf_var.reg_type;
7632 switch (dst_reg->type) {
7633 case PTR_TO_MEM:
7634 dst_reg->mem_size = aux->btf_var.mem_size;
7635 break;
7636 case PTR_TO_BTF_ID:
eaa6bcb7 7637 case PTR_TO_PERCPU_BTF_ID:
4976b718
HL
7638 dst_reg->btf_id = aux->btf_var.btf_id;
7639 break;
7640 default:
7641 verbose(env, "bpf verifier is misconfigured\n");
7642 return -EFAULT;
7643 }
7644 return 0;
7645 }
7646
d8eca5bb
DB
7647 map = env->used_maps[aux->map_index];
7648 mark_reg_known_zero(env, regs, insn->dst_reg);
4976b718 7649 dst_reg->map_ptr = map;
d8eca5bb
DB
7650
7651 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE) {
4976b718
HL
7652 dst_reg->type = PTR_TO_MAP_VALUE;
7653 dst_reg->off = aux->map_off;
d8eca5bb 7654 if (map_value_has_spin_lock(map))
4976b718 7655 dst_reg->id = ++env->id_gen;
d8eca5bb 7656 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD) {
4976b718 7657 dst_reg->type = CONST_PTR_TO_MAP;
d8eca5bb
DB
7658 } else {
7659 verbose(env, "bpf verifier is misconfigured\n");
7660 return -EINVAL;
7661 }
17a52670 7662
17a52670
AS
7663 return 0;
7664}
7665
96be4325
DB
7666static bool may_access_skb(enum bpf_prog_type type)
7667{
7668 switch (type) {
7669 case BPF_PROG_TYPE_SOCKET_FILTER:
7670 case BPF_PROG_TYPE_SCHED_CLS:
94caee8c 7671 case BPF_PROG_TYPE_SCHED_ACT:
96be4325
DB
7672 return true;
7673 default:
7674 return false;
7675 }
7676}
7677
ddd872bc
AS
7678/* verify safety of LD_ABS|LD_IND instructions:
7679 * - they can only appear in the programs where ctx == skb
7680 * - since they are wrappers of function calls, they scratch R1-R5 registers,
7681 * preserve R6-R9, and store return value into R0
7682 *
7683 * Implicit input:
7684 * ctx == skb == R6 == CTX
7685 *
7686 * Explicit input:
7687 * SRC == any register
7688 * IMM == 32-bit immediate
7689 *
7690 * Output:
7691 * R0 - 8/16/32-bit skb data converted to cpu endianness
7692 */
58e2af8b 7693static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
ddd872bc 7694{
638f5b90 7695 struct bpf_reg_state *regs = cur_regs(env);
6d4f151a 7696 static const int ctx_reg = BPF_REG_6;
ddd872bc 7697 u8 mode = BPF_MODE(insn->code);
ddd872bc
AS
7698 int i, err;
7699
7e40781c 7700 if (!may_access_skb(resolve_prog_type(env->prog))) {
61bd5218 7701 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
ddd872bc
AS
7702 return -EINVAL;
7703 }
7704
e0cea7ce
DB
7705 if (!env->ops->gen_ld_abs) {
7706 verbose(env, "bpf verifier is misconfigured\n");
7707 return -EINVAL;
7708 }
7709
ddd872bc 7710 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
d82bccc6 7711 BPF_SIZE(insn->code) == BPF_DW ||
ddd872bc 7712 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
61bd5218 7713 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
ddd872bc
AS
7714 return -EINVAL;
7715 }
7716
7717 /* check whether implicit source operand (register R6) is readable */
6d4f151a 7718 err = check_reg_arg(env, ctx_reg, SRC_OP);
ddd872bc
AS
7719 if (err)
7720 return err;
7721
fd978bf7
JS
7722 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
7723 * gen_ld_abs() may terminate the program at runtime, leading to
7724 * reference leak.
7725 */
7726 err = check_reference_leak(env);
7727 if (err) {
7728 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
7729 return err;
7730 }
7731
d83525ca
AS
7732 if (env->cur_state->active_spin_lock) {
7733 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
7734 return -EINVAL;
7735 }
7736
6d4f151a 7737 if (regs[ctx_reg].type != PTR_TO_CTX) {
61bd5218
JK
7738 verbose(env,
7739 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
ddd872bc
AS
7740 return -EINVAL;
7741 }
7742
7743 if (mode == BPF_IND) {
7744 /* check explicit source operand */
dc503a8a 7745 err = check_reg_arg(env, insn->src_reg, SRC_OP);
ddd872bc
AS
7746 if (err)
7747 return err;
7748 }
7749
6d4f151a
DB
7750 err = check_ctx_reg(env, &regs[ctx_reg], ctx_reg);
7751 if (err < 0)
7752 return err;
7753
ddd872bc 7754 /* reset caller saved regs to unreadable */
dc503a8a 7755 for (i = 0; i < CALLER_SAVED_REGS; i++) {
61bd5218 7756 mark_reg_not_init(env, regs, caller_saved[i]);
dc503a8a
EC
7757 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
7758 }
ddd872bc
AS
7759
7760 /* mark destination R0 register as readable, since it contains
dc503a8a
EC
7761 * the value fetched from the packet.
7762 * Already marked as written above.
ddd872bc 7763 */
61bd5218 7764 mark_reg_unknown(env, regs, BPF_REG_0);
5327ed3d
JW
7765 /* ld_abs load up to 32-bit skb data. */
7766 regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
ddd872bc
AS
7767 return 0;
7768}
7769
390ee7e2
AS
7770static int check_return_code(struct bpf_verifier_env *env)
7771{
5cf1e914 7772 struct tnum enforce_attach_type_range = tnum_unknown;
27ae7997 7773 const struct bpf_prog *prog = env->prog;
390ee7e2
AS
7774 struct bpf_reg_state *reg;
7775 struct tnum range = tnum_range(0, 1);
7e40781c 7776 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
27ae7997
MKL
7777 int err;
7778
9e4e01df 7779 /* LSM and struct_ops func-ptr's return type could be "void" */
7e40781c
UP
7780 if ((prog_type == BPF_PROG_TYPE_STRUCT_OPS ||
7781 prog_type == BPF_PROG_TYPE_LSM) &&
27ae7997
MKL
7782 !prog->aux->attach_func_proto->type)
7783 return 0;
7784
7785 /* eBPF calling convetion is such that R0 is used
7786 * to return the value from eBPF program.
7787 * Make sure that it's readable at this time
7788 * of bpf_exit, which means that program wrote
7789 * something into it earlier
7790 */
7791 err = check_reg_arg(env, BPF_REG_0, SRC_OP);
7792 if (err)
7793 return err;
7794
7795 if (is_pointer_value(env, BPF_REG_0)) {
7796 verbose(env, "R0 leaks addr as return value\n");
7797 return -EACCES;
7798 }
390ee7e2 7799
7e40781c 7800 switch (prog_type) {
983695fa
DB
7801 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
7802 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
1b66d253
DB
7803 env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
7804 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
7805 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
7806 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
7807 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
983695fa 7808 range = tnum_range(1, 1);
ed4ed404 7809 break;
390ee7e2 7810 case BPF_PROG_TYPE_CGROUP_SKB:
5cf1e914 7811 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
7812 range = tnum_range(0, 3);
7813 enforce_attach_type_range = tnum_range(2, 3);
7814 }
ed4ed404 7815 break;
390ee7e2
AS
7816 case BPF_PROG_TYPE_CGROUP_SOCK:
7817 case BPF_PROG_TYPE_SOCK_OPS:
ebc614f6 7818 case BPF_PROG_TYPE_CGROUP_DEVICE:
7b146ceb 7819 case BPF_PROG_TYPE_CGROUP_SYSCTL:
0d01da6a 7820 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
390ee7e2 7821 break;
15ab09bd
AS
7822 case BPF_PROG_TYPE_RAW_TRACEPOINT:
7823 if (!env->prog->aux->attach_btf_id)
7824 return 0;
7825 range = tnum_const(0);
7826 break;
15d83c4d 7827 case BPF_PROG_TYPE_TRACING:
e92888c7
YS
7828 switch (env->prog->expected_attach_type) {
7829 case BPF_TRACE_FENTRY:
7830 case BPF_TRACE_FEXIT:
7831 range = tnum_const(0);
7832 break;
7833 case BPF_TRACE_RAW_TP:
7834 case BPF_MODIFY_RETURN:
15d83c4d 7835 return 0;
2ec0616e
DB
7836 case BPF_TRACE_ITER:
7837 break;
e92888c7
YS
7838 default:
7839 return -ENOTSUPP;
7840 }
15d83c4d 7841 break;
e9ddbb77
JS
7842 case BPF_PROG_TYPE_SK_LOOKUP:
7843 range = tnum_range(SK_DROP, SK_PASS);
7844 break;
e92888c7
YS
7845 case BPF_PROG_TYPE_EXT:
7846 /* freplace program can return anything as its return value
7847 * depends on the to-be-replaced kernel func or bpf program.
7848 */
390ee7e2
AS
7849 default:
7850 return 0;
7851 }
7852
638f5b90 7853 reg = cur_regs(env) + BPF_REG_0;
390ee7e2 7854 if (reg->type != SCALAR_VALUE) {
61bd5218 7855 verbose(env, "At program exit the register R0 is not a known value (%s)\n",
390ee7e2
AS
7856 reg_type_str[reg->type]);
7857 return -EINVAL;
7858 }
7859
7860 if (!tnum_in(range, reg->var_off)) {
5cf1e914 7861 char tn_buf[48];
7862
61bd5218 7863 verbose(env, "At program exit the register R0 ");
390ee7e2 7864 if (!tnum_is_unknown(reg->var_off)) {
390ee7e2 7865 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
61bd5218 7866 verbose(env, "has value %s", tn_buf);
390ee7e2 7867 } else {
61bd5218 7868 verbose(env, "has unknown scalar value");
390ee7e2 7869 }
5cf1e914 7870 tnum_strn(tn_buf, sizeof(tn_buf), range);
983695fa 7871 verbose(env, " should have been in %s\n", tn_buf);
390ee7e2
AS
7872 return -EINVAL;
7873 }
5cf1e914 7874
7875 if (!tnum_is_unknown(enforce_attach_type_range) &&
7876 tnum_in(enforce_attach_type_range, reg->var_off))
7877 env->prog->enforce_expected_attach_type = 1;
390ee7e2
AS
7878 return 0;
7879}
7880
475fb78f
AS
7881/* non-recursive DFS pseudo code
7882 * 1 procedure DFS-iterative(G,v):
7883 * 2 label v as discovered
7884 * 3 let S be a stack
7885 * 4 S.push(v)
7886 * 5 while S is not empty
7887 * 6 t <- S.pop()
7888 * 7 if t is what we're looking for:
7889 * 8 return t
7890 * 9 for all edges e in G.adjacentEdges(t) do
7891 * 10 if edge e is already labelled
7892 * 11 continue with the next edge
7893 * 12 w <- G.adjacentVertex(t,e)
7894 * 13 if vertex w is not discovered and not explored
7895 * 14 label e as tree-edge
7896 * 15 label w as discovered
7897 * 16 S.push(w)
7898 * 17 continue at 5
7899 * 18 else if vertex w is discovered
7900 * 19 label e as back-edge
7901 * 20 else
7902 * 21 // vertex w is explored
7903 * 22 label e as forward- or cross-edge
7904 * 23 label t as explored
7905 * 24 S.pop()
7906 *
7907 * convention:
7908 * 0x10 - discovered
7909 * 0x11 - discovered and fall-through edge labelled
7910 * 0x12 - discovered and fall-through and branch edges labelled
7911 * 0x20 - explored
7912 */
7913
7914enum {
7915 DISCOVERED = 0x10,
7916 EXPLORED = 0x20,
7917 FALLTHROUGH = 1,
7918 BRANCH = 2,
7919};
7920
dc2a4ebc
AS
7921static u32 state_htab_size(struct bpf_verifier_env *env)
7922{
7923 return env->prog->len;
7924}
7925
5d839021
AS
7926static struct bpf_verifier_state_list **explored_state(
7927 struct bpf_verifier_env *env,
7928 int idx)
7929{
dc2a4ebc
AS
7930 struct bpf_verifier_state *cur = env->cur_state;
7931 struct bpf_func_state *state = cur->frame[cur->curframe];
7932
7933 return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
5d839021
AS
7934}
7935
7936static void init_explored_state(struct bpf_verifier_env *env, int idx)
7937{
a8f500af 7938 env->insn_aux_data[idx].prune_point = true;
5d839021 7939}
f1bca824 7940
475fb78f
AS
7941/* t, w, e - match pseudo-code above:
7942 * t - index of current instruction
7943 * w - next instruction
7944 * e - edge
7945 */
2589726d
AS
7946static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
7947 bool loop_ok)
475fb78f 7948{
7df737e9
AS
7949 int *insn_stack = env->cfg.insn_stack;
7950 int *insn_state = env->cfg.insn_state;
7951
475fb78f
AS
7952 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
7953 return 0;
7954
7955 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
7956 return 0;
7957
7958 if (w < 0 || w >= env->prog->len) {
d9762e84 7959 verbose_linfo(env, t, "%d: ", t);
61bd5218 7960 verbose(env, "jump out of range from insn %d to %d\n", t, w);
475fb78f
AS
7961 return -EINVAL;
7962 }
7963
f1bca824
AS
7964 if (e == BRANCH)
7965 /* mark branch target for state pruning */
5d839021 7966 init_explored_state(env, w);
f1bca824 7967
475fb78f
AS
7968 if (insn_state[w] == 0) {
7969 /* tree-edge */
7970 insn_state[t] = DISCOVERED | e;
7971 insn_state[w] = DISCOVERED;
7df737e9 7972 if (env->cfg.cur_stack >= env->prog->len)
475fb78f 7973 return -E2BIG;
7df737e9 7974 insn_stack[env->cfg.cur_stack++] = w;
475fb78f
AS
7975 return 1;
7976 } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
2c78ee89 7977 if (loop_ok && env->bpf_capable)
2589726d 7978 return 0;
d9762e84
MKL
7979 verbose_linfo(env, t, "%d: ", t);
7980 verbose_linfo(env, w, "%d: ", w);
61bd5218 7981 verbose(env, "back-edge from insn %d to %d\n", t, w);
475fb78f
AS
7982 return -EINVAL;
7983 } else if (insn_state[w] == EXPLORED) {
7984 /* forward- or cross-edge */
7985 insn_state[t] = DISCOVERED | e;
7986 } else {
61bd5218 7987 verbose(env, "insn state internal bug\n");
475fb78f
AS
7988 return -EFAULT;
7989 }
7990 return 0;
7991}
7992
7993/* non-recursive depth-first-search to detect loops in BPF program
7994 * loop == back-edge in directed graph
7995 */
58e2af8b 7996static int check_cfg(struct bpf_verifier_env *env)
475fb78f
AS
7997{
7998 struct bpf_insn *insns = env->prog->insnsi;
7999 int insn_cnt = env->prog->len;
7df737e9 8000 int *insn_stack, *insn_state;
475fb78f
AS
8001 int ret = 0;
8002 int i, t;
8003
7df737e9 8004 insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
475fb78f
AS
8005 if (!insn_state)
8006 return -ENOMEM;
8007
7df737e9 8008 insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
475fb78f 8009 if (!insn_stack) {
71dde681 8010 kvfree(insn_state);
475fb78f
AS
8011 return -ENOMEM;
8012 }
8013
8014 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
8015 insn_stack[0] = 0; /* 0 is the first instruction */
7df737e9 8016 env->cfg.cur_stack = 1;
475fb78f
AS
8017
8018peek_stack:
7df737e9 8019 if (env->cfg.cur_stack == 0)
475fb78f 8020 goto check_state;
7df737e9 8021 t = insn_stack[env->cfg.cur_stack - 1];
475fb78f 8022
092ed096
JW
8023 if (BPF_CLASS(insns[t].code) == BPF_JMP ||
8024 BPF_CLASS(insns[t].code) == BPF_JMP32) {
475fb78f
AS
8025 u8 opcode = BPF_OP(insns[t].code);
8026
8027 if (opcode == BPF_EXIT) {
8028 goto mark_explored;
8029 } else if (opcode == BPF_CALL) {
2589726d 8030 ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
475fb78f
AS
8031 if (ret == 1)
8032 goto peek_stack;
8033 else if (ret < 0)
8034 goto err_free;
07016151 8035 if (t + 1 < insn_cnt)
5d839021 8036 init_explored_state(env, t + 1);
cc8b0b92 8037 if (insns[t].src_reg == BPF_PSEUDO_CALL) {
5d839021 8038 init_explored_state(env, t);
2589726d
AS
8039 ret = push_insn(t, t + insns[t].imm + 1, BRANCH,
8040 env, false);
cc8b0b92
AS
8041 if (ret == 1)
8042 goto peek_stack;
8043 else if (ret < 0)
8044 goto err_free;
8045 }
475fb78f
AS
8046 } else if (opcode == BPF_JA) {
8047 if (BPF_SRC(insns[t].code) != BPF_K) {
8048 ret = -EINVAL;
8049 goto err_free;
8050 }
8051 /* unconditional jump with single edge */
8052 ret = push_insn(t, t + insns[t].off + 1,
2589726d 8053 FALLTHROUGH, env, true);
475fb78f
AS
8054 if (ret == 1)
8055 goto peek_stack;
8056 else if (ret < 0)
8057 goto err_free;
b5dc0163
AS
8058 /* unconditional jmp is not a good pruning point,
8059 * but it's marked, since backtracking needs
8060 * to record jmp history in is_state_visited().
8061 */
8062 init_explored_state(env, t + insns[t].off + 1);
f1bca824
AS
8063 /* tell verifier to check for equivalent states
8064 * after every call and jump
8065 */
c3de6317 8066 if (t + 1 < insn_cnt)
5d839021 8067 init_explored_state(env, t + 1);
475fb78f
AS
8068 } else {
8069 /* conditional jump with two edges */
5d839021 8070 init_explored_state(env, t);
2589726d 8071 ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
475fb78f
AS
8072 if (ret == 1)
8073 goto peek_stack;
8074 else if (ret < 0)
8075 goto err_free;
8076
2589726d 8077 ret = push_insn(t, t + insns[t].off + 1, BRANCH, env, true);
475fb78f
AS
8078 if (ret == 1)
8079 goto peek_stack;
8080 else if (ret < 0)
8081 goto err_free;
8082 }
8083 } else {
8084 /* all other non-branch instructions with single
8085 * fall-through edge
8086 */
2589726d 8087 ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
475fb78f
AS
8088 if (ret == 1)
8089 goto peek_stack;
8090 else if (ret < 0)
8091 goto err_free;
8092 }
8093
8094mark_explored:
8095 insn_state[t] = EXPLORED;
7df737e9 8096 if (env->cfg.cur_stack-- <= 0) {
61bd5218 8097 verbose(env, "pop stack internal bug\n");
475fb78f
AS
8098 ret = -EFAULT;
8099 goto err_free;
8100 }
8101 goto peek_stack;
8102
8103check_state:
8104 for (i = 0; i < insn_cnt; i++) {
8105 if (insn_state[i] != EXPLORED) {
61bd5218 8106 verbose(env, "unreachable insn %d\n", i);
475fb78f
AS
8107 ret = -EINVAL;
8108 goto err_free;
8109 }
8110 }
8111 ret = 0; /* cfg looks good */
8112
8113err_free:
71dde681
AS
8114 kvfree(insn_state);
8115 kvfree(insn_stack);
7df737e9 8116 env->cfg.insn_state = env->cfg.insn_stack = NULL;
475fb78f
AS
8117 return ret;
8118}
8119
09b28d76
AS
8120static int check_abnormal_return(struct bpf_verifier_env *env)
8121{
8122 int i;
8123
8124 for (i = 1; i < env->subprog_cnt; i++) {
8125 if (env->subprog_info[i].has_ld_abs) {
8126 verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
8127 return -EINVAL;
8128 }
8129 if (env->subprog_info[i].has_tail_call) {
8130 verbose(env, "tail_call is not allowed in subprogs without BTF\n");
8131 return -EINVAL;
8132 }
8133 }
8134 return 0;
8135}
8136
838e9690
YS
8137/* The minimum supported BTF func info size */
8138#define MIN_BPF_FUNCINFO_SIZE 8
8139#define MAX_FUNCINFO_REC_SIZE 252
8140
c454a46b
MKL
8141static int check_btf_func(struct bpf_verifier_env *env,
8142 const union bpf_attr *attr,
8143 union bpf_attr __user *uattr)
838e9690 8144{
09b28d76 8145 const struct btf_type *type, *func_proto, *ret_type;
d0b2818e 8146 u32 i, nfuncs, urec_size, min_size;
838e9690 8147 u32 krec_size = sizeof(struct bpf_func_info);
c454a46b 8148 struct bpf_func_info *krecord;
8c1b6e69 8149 struct bpf_func_info_aux *info_aux = NULL;
c454a46b
MKL
8150 struct bpf_prog *prog;
8151 const struct btf *btf;
838e9690 8152 void __user *urecord;
d0b2818e 8153 u32 prev_offset = 0;
09b28d76 8154 bool scalar_return;
e7ed83d6 8155 int ret = -ENOMEM;
838e9690
YS
8156
8157 nfuncs = attr->func_info_cnt;
09b28d76
AS
8158 if (!nfuncs) {
8159 if (check_abnormal_return(env))
8160 return -EINVAL;
838e9690 8161 return 0;
09b28d76 8162 }
838e9690
YS
8163
8164 if (nfuncs != env->subprog_cnt) {
8165 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
8166 return -EINVAL;
8167 }
8168
8169 urec_size = attr->func_info_rec_size;
8170 if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
8171 urec_size > MAX_FUNCINFO_REC_SIZE ||
8172 urec_size % sizeof(u32)) {
8173 verbose(env, "invalid func info rec size %u\n", urec_size);
8174 return -EINVAL;
8175 }
8176
c454a46b
MKL
8177 prog = env->prog;
8178 btf = prog->aux->btf;
838e9690
YS
8179
8180 urecord = u64_to_user_ptr(attr->func_info);
8181 min_size = min_t(u32, krec_size, urec_size);
8182
ba64e7d8 8183 krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
c454a46b
MKL
8184 if (!krecord)
8185 return -ENOMEM;
8c1b6e69
AS
8186 info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
8187 if (!info_aux)
8188 goto err_free;
ba64e7d8 8189
838e9690
YS
8190 for (i = 0; i < nfuncs; i++) {
8191 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
8192 if (ret) {
8193 if (ret == -E2BIG) {
8194 verbose(env, "nonzero tailing record in func info");
8195 /* set the size kernel expects so loader can zero
8196 * out the rest of the record.
8197 */
8198 if (put_user(min_size, &uattr->func_info_rec_size))
8199 ret = -EFAULT;
8200 }
c454a46b 8201 goto err_free;
838e9690
YS
8202 }
8203
ba64e7d8 8204 if (copy_from_user(&krecord[i], urecord, min_size)) {
838e9690 8205 ret = -EFAULT;
c454a46b 8206 goto err_free;
838e9690
YS
8207 }
8208
d30d42e0 8209 /* check insn_off */
09b28d76 8210 ret = -EINVAL;
838e9690 8211 if (i == 0) {
d30d42e0 8212 if (krecord[i].insn_off) {
838e9690 8213 verbose(env,
d30d42e0
MKL
8214 "nonzero insn_off %u for the first func info record",
8215 krecord[i].insn_off);
c454a46b 8216 goto err_free;
838e9690 8217 }
d30d42e0 8218 } else if (krecord[i].insn_off <= prev_offset) {
838e9690
YS
8219 verbose(env,
8220 "same or smaller insn offset (%u) than previous func info record (%u)",
d30d42e0 8221 krecord[i].insn_off, prev_offset);
c454a46b 8222 goto err_free;
838e9690
YS
8223 }
8224
d30d42e0 8225 if (env->subprog_info[i].start != krecord[i].insn_off) {
838e9690 8226 verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
c454a46b 8227 goto err_free;
838e9690
YS
8228 }
8229
8230 /* check type_id */
ba64e7d8 8231 type = btf_type_by_id(btf, krecord[i].type_id);
51c39bb1 8232 if (!type || !btf_type_is_func(type)) {
838e9690 8233 verbose(env, "invalid type id %d in func info",
ba64e7d8 8234 krecord[i].type_id);
c454a46b 8235 goto err_free;
838e9690 8236 }
51c39bb1 8237 info_aux[i].linkage = BTF_INFO_VLEN(type->info);
09b28d76
AS
8238
8239 func_proto = btf_type_by_id(btf, type->type);
8240 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
8241 /* btf_func_check() already verified it during BTF load */
8242 goto err_free;
8243 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
8244 scalar_return =
8245 btf_type_is_small_int(ret_type) || btf_type_is_enum(ret_type);
8246 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
8247 verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
8248 goto err_free;
8249 }
8250 if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
8251 verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
8252 goto err_free;
8253 }
8254
d30d42e0 8255 prev_offset = krecord[i].insn_off;
838e9690
YS
8256 urecord += urec_size;
8257 }
8258
ba64e7d8
YS
8259 prog->aux->func_info = krecord;
8260 prog->aux->func_info_cnt = nfuncs;
8c1b6e69 8261 prog->aux->func_info_aux = info_aux;
838e9690
YS
8262 return 0;
8263
c454a46b 8264err_free:
ba64e7d8 8265 kvfree(krecord);
8c1b6e69 8266 kfree(info_aux);
838e9690
YS
8267 return ret;
8268}
8269
ba64e7d8
YS
8270static void adjust_btf_func(struct bpf_verifier_env *env)
8271{
8c1b6e69 8272 struct bpf_prog_aux *aux = env->prog->aux;
ba64e7d8
YS
8273 int i;
8274
8c1b6e69 8275 if (!aux->func_info)
ba64e7d8
YS
8276 return;
8277
8278 for (i = 0; i < env->subprog_cnt; i++)
8c1b6e69 8279 aux->func_info[i].insn_off = env->subprog_info[i].start;
ba64e7d8
YS
8280}
8281
c454a46b
MKL
8282#define MIN_BPF_LINEINFO_SIZE (offsetof(struct bpf_line_info, line_col) + \
8283 sizeof(((struct bpf_line_info *)(0))->line_col))
8284#define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE
8285
8286static int check_btf_line(struct bpf_verifier_env *env,
8287 const union bpf_attr *attr,
8288 union bpf_attr __user *uattr)
8289{
8290 u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
8291 struct bpf_subprog_info *sub;
8292 struct bpf_line_info *linfo;
8293 struct bpf_prog *prog;
8294 const struct btf *btf;
8295 void __user *ulinfo;
8296 int err;
8297
8298 nr_linfo = attr->line_info_cnt;
8299 if (!nr_linfo)
8300 return 0;
8301
8302 rec_size = attr->line_info_rec_size;
8303 if (rec_size < MIN_BPF_LINEINFO_SIZE ||
8304 rec_size > MAX_LINEINFO_REC_SIZE ||
8305 rec_size & (sizeof(u32) - 1))
8306 return -EINVAL;
8307
8308 /* Need to zero it in case the userspace may
8309 * pass in a smaller bpf_line_info object.
8310 */
8311 linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
8312 GFP_KERNEL | __GFP_NOWARN);
8313 if (!linfo)
8314 return -ENOMEM;
8315
8316 prog = env->prog;
8317 btf = prog->aux->btf;
8318
8319 s = 0;
8320 sub = env->subprog_info;
8321 ulinfo = u64_to_user_ptr(attr->line_info);
8322 expected_size = sizeof(struct bpf_line_info);
8323 ncopy = min_t(u32, expected_size, rec_size);
8324 for (i = 0; i < nr_linfo; i++) {
8325 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
8326 if (err) {
8327 if (err == -E2BIG) {
8328 verbose(env, "nonzero tailing record in line_info");
8329 if (put_user(expected_size,
8330 &uattr->line_info_rec_size))
8331 err = -EFAULT;
8332 }
8333 goto err_free;
8334 }
8335
8336 if (copy_from_user(&linfo[i], ulinfo, ncopy)) {
8337 err = -EFAULT;
8338 goto err_free;
8339 }
8340
8341 /*
8342 * Check insn_off to ensure
8343 * 1) strictly increasing AND
8344 * 2) bounded by prog->len
8345 *
8346 * The linfo[0].insn_off == 0 check logically falls into
8347 * the later "missing bpf_line_info for func..." case
8348 * because the first linfo[0].insn_off must be the
8349 * first sub also and the first sub must have
8350 * subprog_info[0].start == 0.
8351 */
8352 if ((i && linfo[i].insn_off <= prev_offset) ||
8353 linfo[i].insn_off >= prog->len) {
8354 verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
8355 i, linfo[i].insn_off, prev_offset,
8356 prog->len);
8357 err = -EINVAL;
8358 goto err_free;
8359 }
8360
fdbaa0be
MKL
8361 if (!prog->insnsi[linfo[i].insn_off].code) {
8362 verbose(env,
8363 "Invalid insn code at line_info[%u].insn_off\n",
8364 i);
8365 err = -EINVAL;
8366 goto err_free;
8367 }
8368
23127b33
MKL
8369 if (!btf_name_by_offset(btf, linfo[i].line_off) ||
8370 !btf_name_by_offset(btf, linfo[i].file_name_off)) {
c454a46b
MKL
8371 verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
8372 err = -EINVAL;
8373 goto err_free;
8374 }
8375
8376 if (s != env->subprog_cnt) {
8377 if (linfo[i].insn_off == sub[s].start) {
8378 sub[s].linfo_idx = i;
8379 s++;
8380 } else if (sub[s].start < linfo[i].insn_off) {
8381 verbose(env, "missing bpf_line_info for func#%u\n", s);
8382 err = -EINVAL;
8383 goto err_free;
8384 }
8385 }
8386
8387 prev_offset = linfo[i].insn_off;
8388 ulinfo += rec_size;
8389 }
8390
8391 if (s != env->subprog_cnt) {
8392 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
8393 env->subprog_cnt - s, s);
8394 err = -EINVAL;
8395 goto err_free;
8396 }
8397
8398 prog->aux->linfo = linfo;
8399 prog->aux->nr_linfo = nr_linfo;
8400
8401 return 0;
8402
8403err_free:
8404 kvfree(linfo);
8405 return err;
8406}
8407
8408static int check_btf_info(struct bpf_verifier_env *env,
8409 const union bpf_attr *attr,
8410 union bpf_attr __user *uattr)
8411{
8412 struct btf *btf;
8413 int err;
8414
09b28d76
AS
8415 if (!attr->func_info_cnt && !attr->line_info_cnt) {
8416 if (check_abnormal_return(env))
8417 return -EINVAL;
c454a46b 8418 return 0;
09b28d76 8419 }
c454a46b
MKL
8420
8421 btf = btf_get_by_fd(attr->prog_btf_fd);
8422 if (IS_ERR(btf))
8423 return PTR_ERR(btf);
8424 env->prog->aux->btf = btf;
8425
8426 err = check_btf_func(env, attr, uattr);
8427 if (err)
8428 return err;
8429
8430 err = check_btf_line(env, attr, uattr);
8431 if (err)
8432 return err;
8433
8434 return 0;
ba64e7d8
YS
8435}
8436
f1174f77
EC
8437/* check %cur's range satisfies %old's */
8438static bool range_within(struct bpf_reg_state *old,
8439 struct bpf_reg_state *cur)
8440{
b03c9f9f
EC
8441 return old->umin_value <= cur->umin_value &&
8442 old->umax_value >= cur->umax_value &&
8443 old->smin_value <= cur->smin_value &&
8444 old->smax_value >= cur->smax_value;
f1174f77
EC
8445}
8446
8447/* Maximum number of register states that can exist at once */
8448#define ID_MAP_SIZE (MAX_BPF_REG + MAX_BPF_STACK / BPF_REG_SIZE)
8449struct idpair {
8450 u32 old;
8451 u32 cur;
8452};
8453
8454/* If in the old state two registers had the same id, then they need to have
8455 * the same id in the new state as well. But that id could be different from
8456 * the old state, so we need to track the mapping from old to new ids.
8457 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
8458 * regs with old id 5 must also have new id 9 for the new state to be safe. But
8459 * regs with a different old id could still have new id 9, we don't care about
8460 * that.
8461 * So we look through our idmap to see if this old id has been seen before. If
8462 * so, we require the new id to match; otherwise, we add the id pair to the map.
969bf05e 8463 */
f1174f77 8464static bool check_ids(u32 old_id, u32 cur_id, struct idpair *idmap)
969bf05e 8465{
f1174f77 8466 unsigned int i;
969bf05e 8467
f1174f77
EC
8468 for (i = 0; i < ID_MAP_SIZE; i++) {
8469 if (!idmap[i].old) {
8470 /* Reached an empty slot; haven't seen this id before */
8471 idmap[i].old = old_id;
8472 idmap[i].cur = cur_id;
8473 return true;
8474 }
8475 if (idmap[i].old == old_id)
8476 return idmap[i].cur == cur_id;
8477 }
8478 /* We ran out of idmap slots, which should be impossible */
8479 WARN_ON_ONCE(1);
8480 return false;
8481}
8482
9242b5f5
AS
8483static void clean_func_state(struct bpf_verifier_env *env,
8484 struct bpf_func_state *st)
8485{
8486 enum bpf_reg_liveness live;
8487 int i, j;
8488
8489 for (i = 0; i < BPF_REG_FP; i++) {
8490 live = st->regs[i].live;
8491 /* liveness must not touch this register anymore */
8492 st->regs[i].live |= REG_LIVE_DONE;
8493 if (!(live & REG_LIVE_READ))
8494 /* since the register is unused, clear its state
8495 * to make further comparison simpler
8496 */
f54c7898 8497 __mark_reg_not_init(env, &st->regs[i]);
9242b5f5
AS
8498 }
8499
8500 for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
8501 live = st->stack[i].spilled_ptr.live;
8502 /* liveness must not touch this stack slot anymore */
8503 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
8504 if (!(live & REG_LIVE_READ)) {
f54c7898 8505 __mark_reg_not_init(env, &st->stack[i].spilled_ptr);
9242b5f5
AS
8506 for (j = 0; j < BPF_REG_SIZE; j++)
8507 st->stack[i].slot_type[j] = STACK_INVALID;
8508 }
8509 }
8510}
8511
8512static void clean_verifier_state(struct bpf_verifier_env *env,
8513 struct bpf_verifier_state *st)
8514{
8515 int i;
8516
8517 if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
8518 /* all regs in this state in all frames were already marked */
8519 return;
8520
8521 for (i = 0; i <= st->curframe; i++)
8522 clean_func_state(env, st->frame[i]);
8523}
8524
8525/* the parentage chains form a tree.
8526 * the verifier states are added to state lists at given insn and
8527 * pushed into state stack for future exploration.
8528 * when the verifier reaches bpf_exit insn some of the verifer states
8529 * stored in the state lists have their final liveness state already,
8530 * but a lot of states will get revised from liveness point of view when
8531 * the verifier explores other branches.
8532 * Example:
8533 * 1: r0 = 1
8534 * 2: if r1 == 100 goto pc+1
8535 * 3: r0 = 2
8536 * 4: exit
8537 * when the verifier reaches exit insn the register r0 in the state list of
8538 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
8539 * of insn 2 and goes exploring further. At the insn 4 it will walk the
8540 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
8541 *
8542 * Since the verifier pushes the branch states as it sees them while exploring
8543 * the program the condition of walking the branch instruction for the second
8544 * time means that all states below this branch were already explored and
8545 * their final liveness markes are already propagated.
8546 * Hence when the verifier completes the search of state list in is_state_visited()
8547 * we can call this clean_live_states() function to mark all liveness states
8548 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
8549 * will not be used.
8550 * This function also clears the registers and stack for states that !READ
8551 * to simplify state merging.
8552 *
8553 * Important note here that walking the same branch instruction in the callee
8554 * doesn't meant that the states are DONE. The verifier has to compare
8555 * the callsites
8556 */
8557static void clean_live_states(struct bpf_verifier_env *env, int insn,
8558 struct bpf_verifier_state *cur)
8559{
8560 struct bpf_verifier_state_list *sl;
8561 int i;
8562
5d839021 8563 sl = *explored_state(env, insn);
a8f500af 8564 while (sl) {
2589726d
AS
8565 if (sl->state.branches)
8566 goto next;
dc2a4ebc
AS
8567 if (sl->state.insn_idx != insn ||
8568 sl->state.curframe != cur->curframe)
9242b5f5
AS
8569 goto next;
8570 for (i = 0; i <= cur->curframe; i++)
8571 if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
8572 goto next;
8573 clean_verifier_state(env, &sl->state);
8574next:
8575 sl = sl->next;
8576 }
8577}
8578
f1174f77 8579/* Returns true if (rold safe implies rcur safe) */
1b688a19
EC
8580static bool regsafe(struct bpf_reg_state *rold, struct bpf_reg_state *rcur,
8581 struct idpair *idmap)
f1174f77 8582{
f4d7e40a
AS
8583 bool equal;
8584
dc503a8a
EC
8585 if (!(rold->live & REG_LIVE_READ))
8586 /* explored state didn't use this */
8587 return true;
8588
679c782d 8589 equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, parent)) == 0;
f4d7e40a
AS
8590
8591 if (rold->type == PTR_TO_STACK)
8592 /* two stack pointers are equal only if they're pointing to
8593 * the same stack frame, since fp-8 in foo != fp-8 in bar
8594 */
8595 return equal && rold->frameno == rcur->frameno;
8596
8597 if (equal)
969bf05e
AS
8598 return true;
8599
f1174f77
EC
8600 if (rold->type == NOT_INIT)
8601 /* explored state can't have used this */
969bf05e 8602 return true;
f1174f77
EC
8603 if (rcur->type == NOT_INIT)
8604 return false;
8605 switch (rold->type) {
8606 case SCALAR_VALUE:
8607 if (rcur->type == SCALAR_VALUE) {
b5dc0163
AS
8608 if (!rold->precise && !rcur->precise)
8609 return true;
f1174f77
EC
8610 /* new val must satisfy old val knowledge */
8611 return range_within(rold, rcur) &&
8612 tnum_in(rold->var_off, rcur->var_off);
8613 } else {
179d1c56
JH
8614 /* We're trying to use a pointer in place of a scalar.
8615 * Even if the scalar was unbounded, this could lead to
8616 * pointer leaks because scalars are allowed to leak
8617 * while pointers are not. We could make this safe in
8618 * special cases if root is calling us, but it's
8619 * probably not worth the hassle.
f1174f77 8620 */
179d1c56 8621 return false;
f1174f77
EC
8622 }
8623 case PTR_TO_MAP_VALUE:
1b688a19
EC
8624 /* If the new min/max/var_off satisfy the old ones and
8625 * everything else matches, we are OK.
d83525ca
AS
8626 * 'id' is not compared, since it's only used for maps with
8627 * bpf_spin_lock inside map element and in such cases if
8628 * the rest of the prog is valid for one map element then
8629 * it's valid for all map elements regardless of the key
8630 * used in bpf_map_lookup()
1b688a19
EC
8631 */
8632 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
8633 range_within(rold, rcur) &&
8634 tnum_in(rold->var_off, rcur->var_off);
f1174f77
EC
8635 case PTR_TO_MAP_VALUE_OR_NULL:
8636 /* a PTR_TO_MAP_VALUE could be safe to use as a
8637 * PTR_TO_MAP_VALUE_OR_NULL into the same map.
8638 * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
8639 * checked, doing so could have affected others with the same
8640 * id, and we can't check for that because we lost the id when
8641 * we converted to a PTR_TO_MAP_VALUE.
8642 */
8643 if (rcur->type != PTR_TO_MAP_VALUE_OR_NULL)
8644 return false;
8645 if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
8646 return false;
8647 /* Check our ids match any regs they're supposed to */
8648 return check_ids(rold->id, rcur->id, idmap);
de8f3a83 8649 case PTR_TO_PACKET_META:
f1174f77 8650 case PTR_TO_PACKET:
de8f3a83 8651 if (rcur->type != rold->type)
f1174f77
EC
8652 return false;
8653 /* We must have at least as much range as the old ptr
8654 * did, so that any accesses which were safe before are
8655 * still safe. This is true even if old range < old off,
8656 * since someone could have accessed through (ptr - k), or
8657 * even done ptr -= k in a register, to get a safe access.
8658 */
8659 if (rold->range > rcur->range)
8660 return false;
8661 /* If the offsets don't match, we can't trust our alignment;
8662 * nor can we be sure that we won't fall out of range.
8663 */
8664 if (rold->off != rcur->off)
8665 return false;
8666 /* id relations must be preserved */
8667 if (rold->id && !check_ids(rold->id, rcur->id, idmap))
8668 return false;
8669 /* new val must satisfy old val knowledge */
8670 return range_within(rold, rcur) &&
8671 tnum_in(rold->var_off, rcur->var_off);
8672 case PTR_TO_CTX:
8673 case CONST_PTR_TO_MAP:
f1174f77 8674 case PTR_TO_PACKET_END:
d58e468b 8675 case PTR_TO_FLOW_KEYS:
c64b7983
JS
8676 case PTR_TO_SOCKET:
8677 case PTR_TO_SOCKET_OR_NULL:
46f8bc92
MKL
8678 case PTR_TO_SOCK_COMMON:
8679 case PTR_TO_SOCK_COMMON_OR_NULL:
655a51e5
MKL
8680 case PTR_TO_TCP_SOCK:
8681 case PTR_TO_TCP_SOCK_OR_NULL:
fada7fdc 8682 case PTR_TO_XDP_SOCK:
f1174f77
EC
8683 /* Only valid matches are exact, which memcmp() above
8684 * would have accepted
8685 */
8686 default:
8687 /* Don't know what's going on, just say it's not safe */
8688 return false;
8689 }
969bf05e 8690
f1174f77
EC
8691 /* Shouldn't get here; if we do, say it's not safe */
8692 WARN_ON_ONCE(1);
969bf05e
AS
8693 return false;
8694}
8695
f4d7e40a
AS
8696static bool stacksafe(struct bpf_func_state *old,
8697 struct bpf_func_state *cur,
638f5b90
AS
8698 struct idpair *idmap)
8699{
8700 int i, spi;
8701
638f5b90
AS
8702 /* walk slots of the explored stack and ignore any additional
8703 * slots in the current stack, since explored(safe) state
8704 * didn't use them
8705 */
8706 for (i = 0; i < old->allocated_stack; i++) {
8707 spi = i / BPF_REG_SIZE;
8708
b233920c
AS
8709 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
8710 i += BPF_REG_SIZE - 1;
cc2b14d5 8711 /* explored state didn't use this */
fd05e57b 8712 continue;
b233920c 8713 }
cc2b14d5 8714
638f5b90
AS
8715 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
8716 continue;
19e2dbb7
AS
8717
8718 /* explored stack has more populated slots than current stack
8719 * and these slots were used
8720 */
8721 if (i >= cur->allocated_stack)
8722 return false;
8723
cc2b14d5
AS
8724 /* if old state was safe with misc data in the stack
8725 * it will be safe with zero-initialized stack.
8726 * The opposite is not true
8727 */
8728 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
8729 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
8730 continue;
638f5b90
AS
8731 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
8732 cur->stack[spi].slot_type[i % BPF_REG_SIZE])
8733 /* Ex: old explored (safe) state has STACK_SPILL in
b8c1a309 8734 * this stack slot, but current has STACK_MISC ->
638f5b90
AS
8735 * this verifier states are not equivalent,
8736 * return false to continue verification of this path
8737 */
8738 return false;
8739 if (i % BPF_REG_SIZE)
8740 continue;
8741 if (old->stack[spi].slot_type[0] != STACK_SPILL)
8742 continue;
8743 if (!regsafe(&old->stack[spi].spilled_ptr,
8744 &cur->stack[spi].spilled_ptr,
8745 idmap))
8746 /* when explored and current stack slot are both storing
8747 * spilled registers, check that stored pointers types
8748 * are the same as well.
8749 * Ex: explored safe path could have stored
8750 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
8751 * but current path has stored:
8752 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
8753 * such verifier states are not equivalent.
8754 * return false to continue verification of this path
8755 */
8756 return false;
8757 }
8758 return true;
8759}
8760
fd978bf7
JS
8761static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur)
8762{
8763 if (old->acquired_refs != cur->acquired_refs)
8764 return false;
8765 return !memcmp(old->refs, cur->refs,
8766 sizeof(*old->refs) * old->acquired_refs);
8767}
8768
f1bca824
AS
8769/* compare two verifier states
8770 *
8771 * all states stored in state_list are known to be valid, since
8772 * verifier reached 'bpf_exit' instruction through them
8773 *
8774 * this function is called when verifier exploring different branches of
8775 * execution popped from the state stack. If it sees an old state that has
8776 * more strict register state and more strict stack state then this execution
8777 * branch doesn't need to be explored further, since verifier already
8778 * concluded that more strict state leads to valid finish.
8779 *
8780 * Therefore two states are equivalent if register state is more conservative
8781 * and explored stack state is more conservative than the current one.
8782 * Example:
8783 * explored current
8784 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
8785 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
8786 *
8787 * In other words if current stack state (one being explored) has more
8788 * valid slots than old one that already passed validation, it means
8789 * the verifier can stop exploring and conclude that current state is valid too
8790 *
8791 * Similarly with registers. If explored state has register type as invalid
8792 * whereas register type in current state is meaningful, it means that
8793 * the current state will reach 'bpf_exit' instruction safely
8794 */
f4d7e40a
AS
8795static bool func_states_equal(struct bpf_func_state *old,
8796 struct bpf_func_state *cur)
f1bca824 8797{
f1174f77
EC
8798 struct idpair *idmap;
8799 bool ret = false;
f1bca824
AS
8800 int i;
8801
f1174f77
EC
8802 idmap = kcalloc(ID_MAP_SIZE, sizeof(struct idpair), GFP_KERNEL);
8803 /* If we failed to allocate the idmap, just say it's not safe */
8804 if (!idmap)
1a0dc1ac 8805 return false;
f1174f77
EC
8806
8807 for (i = 0; i < MAX_BPF_REG; i++) {
1b688a19 8808 if (!regsafe(&old->regs[i], &cur->regs[i], idmap))
f1174f77 8809 goto out_free;
f1bca824
AS
8810 }
8811
638f5b90
AS
8812 if (!stacksafe(old, cur, idmap))
8813 goto out_free;
fd978bf7
JS
8814
8815 if (!refsafe(old, cur))
8816 goto out_free;
f1174f77
EC
8817 ret = true;
8818out_free:
8819 kfree(idmap);
8820 return ret;
f1bca824
AS
8821}
8822
f4d7e40a
AS
8823static bool states_equal(struct bpf_verifier_env *env,
8824 struct bpf_verifier_state *old,
8825 struct bpf_verifier_state *cur)
8826{
8827 int i;
8828
8829 if (old->curframe != cur->curframe)
8830 return false;
8831
979d63d5
DB
8832 /* Verification state from speculative execution simulation
8833 * must never prune a non-speculative execution one.
8834 */
8835 if (old->speculative && !cur->speculative)
8836 return false;
8837
d83525ca
AS
8838 if (old->active_spin_lock != cur->active_spin_lock)
8839 return false;
8840
f4d7e40a
AS
8841 /* for states to be equal callsites have to be the same
8842 * and all frame states need to be equivalent
8843 */
8844 for (i = 0; i <= old->curframe; i++) {
8845 if (old->frame[i]->callsite != cur->frame[i]->callsite)
8846 return false;
8847 if (!func_states_equal(old->frame[i], cur->frame[i]))
8848 return false;
8849 }
8850 return true;
8851}
8852
5327ed3d
JW
8853/* Return 0 if no propagation happened. Return negative error code if error
8854 * happened. Otherwise, return the propagated bit.
8855 */
55e7f3b5
JW
8856static int propagate_liveness_reg(struct bpf_verifier_env *env,
8857 struct bpf_reg_state *reg,
8858 struct bpf_reg_state *parent_reg)
8859{
5327ed3d
JW
8860 u8 parent_flag = parent_reg->live & REG_LIVE_READ;
8861 u8 flag = reg->live & REG_LIVE_READ;
55e7f3b5
JW
8862 int err;
8863
5327ed3d
JW
8864 /* When comes here, read flags of PARENT_REG or REG could be any of
8865 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
8866 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
8867 */
8868 if (parent_flag == REG_LIVE_READ64 ||
8869 /* Or if there is no read flag from REG. */
8870 !flag ||
8871 /* Or if the read flag from REG is the same as PARENT_REG. */
8872 parent_flag == flag)
55e7f3b5
JW
8873 return 0;
8874
5327ed3d 8875 err = mark_reg_read(env, reg, parent_reg, flag);
55e7f3b5
JW
8876 if (err)
8877 return err;
8878
5327ed3d 8879 return flag;
55e7f3b5
JW
8880}
8881
8e9cd9ce 8882/* A write screens off any subsequent reads; but write marks come from the
f4d7e40a
AS
8883 * straight-line code between a state and its parent. When we arrive at an
8884 * equivalent state (jump target or such) we didn't arrive by the straight-line
8885 * code, so read marks in the state must propagate to the parent regardless
8886 * of the state's write marks. That's what 'parent == state->parent' comparison
679c782d 8887 * in mark_reg_read() is for.
8e9cd9ce 8888 */
f4d7e40a
AS
8889static int propagate_liveness(struct bpf_verifier_env *env,
8890 const struct bpf_verifier_state *vstate,
8891 struct bpf_verifier_state *vparent)
dc503a8a 8892{
3f8cafa4 8893 struct bpf_reg_state *state_reg, *parent_reg;
f4d7e40a 8894 struct bpf_func_state *state, *parent;
3f8cafa4 8895 int i, frame, err = 0;
dc503a8a 8896
f4d7e40a
AS
8897 if (vparent->curframe != vstate->curframe) {
8898 WARN(1, "propagate_live: parent frame %d current frame %d\n",
8899 vparent->curframe, vstate->curframe);
8900 return -EFAULT;
8901 }
dc503a8a
EC
8902 /* Propagate read liveness of registers... */
8903 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
83d16312 8904 for (frame = 0; frame <= vstate->curframe; frame++) {
3f8cafa4
JW
8905 parent = vparent->frame[frame];
8906 state = vstate->frame[frame];
8907 parent_reg = parent->regs;
8908 state_reg = state->regs;
83d16312
JK
8909 /* We don't need to worry about FP liveness, it's read-only */
8910 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
55e7f3b5
JW
8911 err = propagate_liveness_reg(env, &state_reg[i],
8912 &parent_reg[i]);
5327ed3d 8913 if (err < 0)
3f8cafa4 8914 return err;
5327ed3d
JW
8915 if (err == REG_LIVE_READ64)
8916 mark_insn_zext(env, &parent_reg[i]);
dc503a8a 8917 }
f4d7e40a 8918
1b04aee7 8919 /* Propagate stack slots. */
f4d7e40a
AS
8920 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
8921 i < parent->allocated_stack / BPF_REG_SIZE; i++) {
3f8cafa4
JW
8922 parent_reg = &parent->stack[i].spilled_ptr;
8923 state_reg = &state->stack[i].spilled_ptr;
55e7f3b5
JW
8924 err = propagate_liveness_reg(env, state_reg,
8925 parent_reg);
5327ed3d 8926 if (err < 0)
3f8cafa4 8927 return err;
dc503a8a
EC
8928 }
8929 }
5327ed3d 8930 return 0;
dc503a8a
EC
8931}
8932
a3ce685d
AS
8933/* find precise scalars in the previous equivalent state and
8934 * propagate them into the current state
8935 */
8936static int propagate_precision(struct bpf_verifier_env *env,
8937 const struct bpf_verifier_state *old)
8938{
8939 struct bpf_reg_state *state_reg;
8940 struct bpf_func_state *state;
8941 int i, err = 0;
8942
8943 state = old->frame[old->curframe];
8944 state_reg = state->regs;
8945 for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
8946 if (state_reg->type != SCALAR_VALUE ||
8947 !state_reg->precise)
8948 continue;
8949 if (env->log.level & BPF_LOG_LEVEL2)
8950 verbose(env, "propagating r%d\n", i);
8951 err = mark_chain_precision(env, i);
8952 if (err < 0)
8953 return err;
8954 }
8955
8956 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
8957 if (state->stack[i].slot_type[0] != STACK_SPILL)
8958 continue;
8959 state_reg = &state->stack[i].spilled_ptr;
8960 if (state_reg->type != SCALAR_VALUE ||
8961 !state_reg->precise)
8962 continue;
8963 if (env->log.level & BPF_LOG_LEVEL2)
8964 verbose(env, "propagating fp%d\n",
8965 (-i - 1) * BPF_REG_SIZE);
8966 err = mark_chain_precision_stack(env, i);
8967 if (err < 0)
8968 return err;
8969 }
8970 return 0;
8971}
8972
2589726d
AS
8973static bool states_maybe_looping(struct bpf_verifier_state *old,
8974 struct bpf_verifier_state *cur)
8975{
8976 struct bpf_func_state *fold, *fcur;
8977 int i, fr = cur->curframe;
8978
8979 if (old->curframe != fr)
8980 return false;
8981
8982 fold = old->frame[fr];
8983 fcur = cur->frame[fr];
8984 for (i = 0; i < MAX_BPF_REG; i++)
8985 if (memcmp(&fold->regs[i], &fcur->regs[i],
8986 offsetof(struct bpf_reg_state, parent)))
8987 return false;
8988 return true;
8989}
8990
8991
58e2af8b 8992static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
f1bca824 8993{
58e2af8b 8994 struct bpf_verifier_state_list *new_sl;
9f4686c4 8995 struct bpf_verifier_state_list *sl, **pprev;
679c782d 8996 struct bpf_verifier_state *cur = env->cur_state, *new;
ceefbc96 8997 int i, j, err, states_cnt = 0;
10d274e8 8998 bool add_new_state = env->test_state_freq ? true : false;
f1bca824 8999
b5dc0163 9000 cur->last_insn_idx = env->prev_insn_idx;
a8f500af 9001 if (!env->insn_aux_data[insn_idx].prune_point)
f1bca824
AS
9002 /* this 'insn_idx' instruction wasn't marked, so we will not
9003 * be doing state search here
9004 */
9005 return 0;
9006
2589726d
AS
9007 /* bpf progs typically have pruning point every 4 instructions
9008 * http://vger.kernel.org/bpfconf2019.html#session-1
9009 * Do not add new state for future pruning if the verifier hasn't seen
9010 * at least 2 jumps and at least 8 instructions.
9011 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
9012 * In tests that amounts to up to 50% reduction into total verifier
9013 * memory consumption and 20% verifier time speedup.
9014 */
9015 if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
9016 env->insn_processed - env->prev_insn_processed >= 8)
9017 add_new_state = true;
9018
a8f500af
AS
9019 pprev = explored_state(env, insn_idx);
9020 sl = *pprev;
9021
9242b5f5
AS
9022 clean_live_states(env, insn_idx, cur);
9023
a8f500af 9024 while (sl) {
dc2a4ebc
AS
9025 states_cnt++;
9026 if (sl->state.insn_idx != insn_idx)
9027 goto next;
2589726d
AS
9028 if (sl->state.branches) {
9029 if (states_maybe_looping(&sl->state, cur) &&
9030 states_equal(env, &sl->state, cur)) {
9031 verbose_linfo(env, insn_idx, "; ");
9032 verbose(env, "infinite loop detected at insn %d\n", insn_idx);
9033 return -EINVAL;
9034 }
9035 /* if the verifier is processing a loop, avoid adding new state
9036 * too often, since different loop iterations have distinct
9037 * states and may not help future pruning.
9038 * This threshold shouldn't be too low to make sure that
9039 * a loop with large bound will be rejected quickly.
9040 * The most abusive loop will be:
9041 * r1 += 1
9042 * if r1 < 1000000 goto pc-2
9043 * 1M insn_procssed limit / 100 == 10k peak states.
9044 * This threshold shouldn't be too high either, since states
9045 * at the end of the loop are likely to be useful in pruning.
9046 */
9047 if (env->jmps_processed - env->prev_jmps_processed < 20 &&
9048 env->insn_processed - env->prev_insn_processed < 100)
9049 add_new_state = false;
9050 goto miss;
9051 }
638f5b90 9052 if (states_equal(env, &sl->state, cur)) {
9f4686c4 9053 sl->hit_cnt++;
f1bca824 9054 /* reached equivalent register/stack state,
dc503a8a
EC
9055 * prune the search.
9056 * Registers read by the continuation are read by us.
8e9cd9ce
EC
9057 * If we have any write marks in env->cur_state, they
9058 * will prevent corresponding reads in the continuation
9059 * from reaching our parent (an explored_state). Our
9060 * own state will get the read marks recorded, but
9061 * they'll be immediately forgotten as we're pruning
9062 * this state and will pop a new one.
f1bca824 9063 */
f4d7e40a 9064 err = propagate_liveness(env, &sl->state, cur);
a3ce685d
AS
9065
9066 /* if previous state reached the exit with precision and
9067 * current state is equivalent to it (except precsion marks)
9068 * the precision needs to be propagated back in
9069 * the current state.
9070 */
9071 err = err ? : push_jmp_history(env, cur);
9072 err = err ? : propagate_precision(env, &sl->state);
f4d7e40a
AS
9073 if (err)
9074 return err;
f1bca824 9075 return 1;
dc503a8a 9076 }
2589726d
AS
9077miss:
9078 /* when new state is not going to be added do not increase miss count.
9079 * Otherwise several loop iterations will remove the state
9080 * recorded earlier. The goal of these heuristics is to have
9081 * states from some iterations of the loop (some in the beginning
9082 * and some at the end) to help pruning.
9083 */
9084 if (add_new_state)
9085 sl->miss_cnt++;
9f4686c4
AS
9086 /* heuristic to determine whether this state is beneficial
9087 * to keep checking from state equivalence point of view.
9088 * Higher numbers increase max_states_per_insn and verification time,
9089 * but do not meaningfully decrease insn_processed.
9090 */
9091 if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
9092 /* the state is unlikely to be useful. Remove it to
9093 * speed up verification
9094 */
9095 *pprev = sl->next;
9096 if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
2589726d
AS
9097 u32 br = sl->state.branches;
9098
9099 WARN_ONCE(br,
9100 "BUG live_done but branches_to_explore %d\n",
9101 br);
9f4686c4
AS
9102 free_verifier_state(&sl->state, false);
9103 kfree(sl);
9104 env->peak_states--;
9105 } else {
9106 /* cannot free this state, since parentage chain may
9107 * walk it later. Add it for free_list instead to
9108 * be freed at the end of verification
9109 */
9110 sl->next = env->free_list;
9111 env->free_list = sl;
9112 }
9113 sl = *pprev;
9114 continue;
9115 }
dc2a4ebc 9116next:
9f4686c4
AS
9117 pprev = &sl->next;
9118 sl = *pprev;
f1bca824
AS
9119 }
9120
06ee7115
AS
9121 if (env->max_states_per_insn < states_cnt)
9122 env->max_states_per_insn = states_cnt;
9123
2c78ee89 9124 if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
b5dc0163 9125 return push_jmp_history(env, cur);
ceefbc96 9126
2589726d 9127 if (!add_new_state)
b5dc0163 9128 return push_jmp_history(env, cur);
ceefbc96 9129
2589726d
AS
9130 /* There were no equivalent states, remember the current one.
9131 * Technically the current state is not proven to be safe yet,
f4d7e40a 9132 * but it will either reach outer most bpf_exit (which means it's safe)
2589726d 9133 * or it will be rejected. When there are no loops the verifier won't be
f4d7e40a 9134 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
2589726d
AS
9135 * again on the way to bpf_exit.
9136 * When looping the sl->state.branches will be > 0 and this state
9137 * will not be considered for equivalence until branches == 0.
f1bca824 9138 */
638f5b90 9139 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
f1bca824
AS
9140 if (!new_sl)
9141 return -ENOMEM;
06ee7115
AS
9142 env->total_states++;
9143 env->peak_states++;
2589726d
AS
9144 env->prev_jmps_processed = env->jmps_processed;
9145 env->prev_insn_processed = env->insn_processed;
f1bca824
AS
9146
9147 /* add new state to the head of linked list */
679c782d
EC
9148 new = &new_sl->state;
9149 err = copy_verifier_state(new, cur);
1969db47 9150 if (err) {
679c782d 9151 free_verifier_state(new, false);
1969db47
AS
9152 kfree(new_sl);
9153 return err;
9154 }
dc2a4ebc 9155 new->insn_idx = insn_idx;
2589726d
AS
9156 WARN_ONCE(new->branches != 1,
9157 "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
b5dc0163 9158
2589726d 9159 cur->parent = new;
b5dc0163
AS
9160 cur->first_insn_idx = insn_idx;
9161 clear_jmp_history(cur);
5d839021
AS
9162 new_sl->next = *explored_state(env, insn_idx);
9163 *explored_state(env, insn_idx) = new_sl;
7640ead9
JK
9164 /* connect new state to parentage chain. Current frame needs all
9165 * registers connected. Only r6 - r9 of the callers are alive (pushed
9166 * to the stack implicitly by JITs) so in callers' frames connect just
9167 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
9168 * the state of the call instruction (with WRITTEN set), and r0 comes
9169 * from callee with its full parentage chain, anyway.
9170 */
8e9cd9ce
EC
9171 /* clear write marks in current state: the writes we did are not writes
9172 * our child did, so they don't screen off its reads from us.
9173 * (There are no read marks in current state, because reads always mark
9174 * their parent and current state never has children yet. Only
9175 * explored_states can get read marks.)
9176 */
eea1c227
AS
9177 for (j = 0; j <= cur->curframe; j++) {
9178 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
9179 cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
9180 for (i = 0; i < BPF_REG_FP; i++)
9181 cur->frame[j]->regs[i].live = REG_LIVE_NONE;
9182 }
f4d7e40a
AS
9183
9184 /* all stack frames are accessible from callee, clear them all */
9185 for (j = 0; j <= cur->curframe; j++) {
9186 struct bpf_func_state *frame = cur->frame[j];
679c782d 9187 struct bpf_func_state *newframe = new->frame[j];
f4d7e40a 9188
679c782d 9189 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
cc2b14d5 9190 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
679c782d
EC
9191 frame->stack[i].spilled_ptr.parent =
9192 &newframe->stack[i].spilled_ptr;
9193 }
f4d7e40a 9194 }
f1bca824
AS
9195 return 0;
9196}
9197
c64b7983
JS
9198/* Return true if it's OK to have the same insn return a different type. */
9199static bool reg_type_mismatch_ok(enum bpf_reg_type type)
9200{
9201 switch (type) {
9202 case PTR_TO_CTX:
9203 case PTR_TO_SOCKET:
9204 case PTR_TO_SOCKET_OR_NULL:
46f8bc92
MKL
9205 case PTR_TO_SOCK_COMMON:
9206 case PTR_TO_SOCK_COMMON_OR_NULL:
655a51e5
MKL
9207 case PTR_TO_TCP_SOCK:
9208 case PTR_TO_TCP_SOCK_OR_NULL:
fada7fdc 9209 case PTR_TO_XDP_SOCK:
2a02759e 9210 case PTR_TO_BTF_ID:
b121b341 9211 case PTR_TO_BTF_ID_OR_NULL:
c64b7983
JS
9212 return false;
9213 default:
9214 return true;
9215 }
9216}
9217
9218/* If an instruction was previously used with particular pointer types, then we
9219 * need to be careful to avoid cases such as the below, where it may be ok
9220 * for one branch accessing the pointer, but not ok for the other branch:
9221 *
9222 * R1 = sock_ptr
9223 * goto X;
9224 * ...
9225 * R1 = some_other_valid_ptr;
9226 * goto X;
9227 * ...
9228 * R2 = *(u32 *)(R1 + 0);
9229 */
9230static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
9231{
9232 return src != prev && (!reg_type_mismatch_ok(src) ||
9233 !reg_type_mismatch_ok(prev));
9234}
9235
58e2af8b 9236static int do_check(struct bpf_verifier_env *env)
17a52670 9237{
6f8a57cc 9238 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
51c39bb1 9239 struct bpf_verifier_state *state = env->cur_state;
17a52670 9240 struct bpf_insn *insns = env->prog->insnsi;
638f5b90 9241 struct bpf_reg_state *regs;
06ee7115 9242 int insn_cnt = env->prog->len;
17a52670 9243 bool do_print_state = false;
b5dc0163 9244 int prev_insn_idx = -1;
17a52670 9245
17a52670
AS
9246 for (;;) {
9247 struct bpf_insn *insn;
9248 u8 class;
9249 int err;
9250
b5dc0163 9251 env->prev_insn_idx = prev_insn_idx;
c08435ec 9252 if (env->insn_idx >= insn_cnt) {
61bd5218 9253 verbose(env, "invalid insn idx %d insn_cnt %d\n",
c08435ec 9254 env->insn_idx, insn_cnt);
17a52670
AS
9255 return -EFAULT;
9256 }
9257
c08435ec 9258 insn = &insns[env->insn_idx];
17a52670
AS
9259 class = BPF_CLASS(insn->code);
9260
06ee7115 9261 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
61bd5218
JK
9262 verbose(env,
9263 "BPF program is too large. Processed %d insn\n",
06ee7115 9264 env->insn_processed);
17a52670
AS
9265 return -E2BIG;
9266 }
9267
c08435ec 9268 err = is_state_visited(env, env->insn_idx);
f1bca824
AS
9269 if (err < 0)
9270 return err;
9271 if (err == 1) {
9272 /* found equivalent state, can prune the search */
06ee7115 9273 if (env->log.level & BPF_LOG_LEVEL) {
f1bca824 9274 if (do_print_state)
979d63d5
DB
9275 verbose(env, "\nfrom %d to %d%s: safe\n",
9276 env->prev_insn_idx, env->insn_idx,
9277 env->cur_state->speculative ?
9278 " (speculative execution)" : "");
f1bca824 9279 else
c08435ec 9280 verbose(env, "%d: safe\n", env->insn_idx);
f1bca824
AS
9281 }
9282 goto process_bpf_exit;
9283 }
9284
c3494801
AS
9285 if (signal_pending(current))
9286 return -EAGAIN;
9287
3c2ce60b
DB
9288 if (need_resched())
9289 cond_resched();
9290
06ee7115
AS
9291 if (env->log.level & BPF_LOG_LEVEL2 ||
9292 (env->log.level & BPF_LOG_LEVEL && do_print_state)) {
9293 if (env->log.level & BPF_LOG_LEVEL2)
c08435ec 9294 verbose(env, "%d:", env->insn_idx);
c5fc9692 9295 else
979d63d5
DB
9296 verbose(env, "\nfrom %d to %d%s:",
9297 env->prev_insn_idx, env->insn_idx,
9298 env->cur_state->speculative ?
9299 " (speculative execution)" : "");
f4d7e40a 9300 print_verifier_state(env, state->frame[state->curframe]);
17a52670
AS
9301 do_print_state = false;
9302 }
9303
06ee7115 9304 if (env->log.level & BPF_LOG_LEVEL) {
7105e828
DB
9305 const struct bpf_insn_cbs cbs = {
9306 .cb_print = verbose,
abe08840 9307 .private_data = env,
7105e828
DB
9308 };
9309
c08435ec
DB
9310 verbose_linfo(env, env->insn_idx, "; ");
9311 verbose(env, "%d: ", env->insn_idx);
abe08840 9312 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
17a52670
AS
9313 }
9314
cae1927c 9315 if (bpf_prog_is_dev_bound(env->prog->aux)) {
c08435ec
DB
9316 err = bpf_prog_offload_verify_insn(env, env->insn_idx,
9317 env->prev_insn_idx);
cae1927c
JK
9318 if (err)
9319 return err;
9320 }
13a27dfc 9321
638f5b90 9322 regs = cur_regs(env);
51c39bb1 9323 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
b5dc0163 9324 prev_insn_idx = env->insn_idx;
fd978bf7 9325
17a52670 9326 if (class == BPF_ALU || class == BPF_ALU64) {
1be7f75d 9327 err = check_alu_op(env, insn);
17a52670
AS
9328 if (err)
9329 return err;
9330
9331 } else if (class == BPF_LDX) {
3df126f3 9332 enum bpf_reg_type *prev_src_type, src_reg_type;
9bac3d6d
AS
9333
9334 /* check for reserved fields is already done */
9335
17a52670 9336 /* check src operand */
dc503a8a 9337 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17a52670
AS
9338 if (err)
9339 return err;
9340
dc503a8a 9341 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
17a52670
AS
9342 if (err)
9343 return err;
9344
725f9dcd
AS
9345 src_reg_type = regs[insn->src_reg].type;
9346
17a52670
AS
9347 /* check that memory (src_reg + off) is readable,
9348 * the state of dst_reg will be updated by this func
9349 */
c08435ec
DB
9350 err = check_mem_access(env, env->insn_idx, insn->src_reg,
9351 insn->off, BPF_SIZE(insn->code),
9352 BPF_READ, insn->dst_reg, false);
17a52670
AS
9353 if (err)
9354 return err;
9355
c08435ec 9356 prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type;
3df126f3
JK
9357
9358 if (*prev_src_type == NOT_INIT) {
9bac3d6d
AS
9359 /* saw a valid insn
9360 * dst_reg = *(u32 *)(src_reg + off)
3df126f3 9361 * save type to validate intersecting paths
9bac3d6d 9362 */
3df126f3 9363 *prev_src_type = src_reg_type;
9bac3d6d 9364
c64b7983 9365 } else if (reg_type_mismatch(src_reg_type, *prev_src_type)) {
9bac3d6d
AS
9366 /* ABuser program is trying to use the same insn
9367 * dst_reg = *(u32*) (src_reg + off)
9368 * with different pointer types:
9369 * src_reg == ctx in one branch and
9370 * src_reg == stack|map in some other branch.
9371 * Reject it.
9372 */
61bd5218 9373 verbose(env, "same insn cannot be used with different pointers\n");
9bac3d6d
AS
9374 return -EINVAL;
9375 }
9376
17a52670 9377 } else if (class == BPF_STX) {
3df126f3 9378 enum bpf_reg_type *prev_dst_type, dst_reg_type;
d691f9e8 9379
17a52670 9380 if (BPF_MODE(insn->code) == BPF_XADD) {
c08435ec 9381 err = check_xadd(env, env->insn_idx, insn);
17a52670
AS
9382 if (err)
9383 return err;
c08435ec 9384 env->insn_idx++;
17a52670
AS
9385 continue;
9386 }
9387
17a52670 9388 /* check src1 operand */
dc503a8a 9389 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17a52670
AS
9390 if (err)
9391 return err;
9392 /* check src2 operand */
dc503a8a 9393 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17a52670
AS
9394 if (err)
9395 return err;
9396
d691f9e8
AS
9397 dst_reg_type = regs[insn->dst_reg].type;
9398
17a52670 9399 /* check that memory (dst_reg + off) is writeable */
c08435ec
DB
9400 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
9401 insn->off, BPF_SIZE(insn->code),
9402 BPF_WRITE, insn->src_reg, false);
17a52670
AS
9403 if (err)
9404 return err;
9405
c08435ec 9406 prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type;
3df126f3
JK
9407
9408 if (*prev_dst_type == NOT_INIT) {
9409 *prev_dst_type = dst_reg_type;
c64b7983 9410 } else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) {
61bd5218 9411 verbose(env, "same insn cannot be used with different pointers\n");
d691f9e8
AS
9412 return -EINVAL;
9413 }
9414
17a52670
AS
9415 } else if (class == BPF_ST) {
9416 if (BPF_MODE(insn->code) != BPF_MEM ||
9417 insn->src_reg != BPF_REG_0) {
61bd5218 9418 verbose(env, "BPF_ST uses reserved fields\n");
17a52670
AS
9419 return -EINVAL;
9420 }
9421 /* check src operand */
dc503a8a 9422 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17a52670
AS
9423 if (err)
9424 return err;
9425
f37a8cb8 9426 if (is_ctx_reg(env, insn->dst_reg)) {
9d2be44a 9427 verbose(env, "BPF_ST stores into R%d %s is not allowed\n",
2a159c6f
DB
9428 insn->dst_reg,
9429 reg_type_str[reg_state(env, insn->dst_reg)->type]);
f37a8cb8
DB
9430 return -EACCES;
9431 }
9432
17a52670 9433 /* check that memory (dst_reg + off) is writeable */
c08435ec
DB
9434 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
9435 insn->off, BPF_SIZE(insn->code),
9436 BPF_WRITE, -1, false);
17a52670
AS
9437 if (err)
9438 return err;
9439
092ed096 9440 } else if (class == BPF_JMP || class == BPF_JMP32) {
17a52670
AS
9441 u8 opcode = BPF_OP(insn->code);
9442
2589726d 9443 env->jmps_processed++;
17a52670
AS
9444 if (opcode == BPF_CALL) {
9445 if (BPF_SRC(insn->code) != BPF_K ||
9446 insn->off != 0 ||
f4d7e40a
AS
9447 (insn->src_reg != BPF_REG_0 &&
9448 insn->src_reg != BPF_PSEUDO_CALL) ||
092ed096
JW
9449 insn->dst_reg != BPF_REG_0 ||
9450 class == BPF_JMP32) {
61bd5218 9451 verbose(env, "BPF_CALL uses reserved fields\n");
17a52670
AS
9452 return -EINVAL;
9453 }
9454
d83525ca
AS
9455 if (env->cur_state->active_spin_lock &&
9456 (insn->src_reg == BPF_PSEUDO_CALL ||
9457 insn->imm != BPF_FUNC_spin_unlock)) {
9458 verbose(env, "function calls are not allowed while holding a lock\n");
9459 return -EINVAL;
9460 }
f4d7e40a 9461 if (insn->src_reg == BPF_PSEUDO_CALL)
c08435ec 9462 err = check_func_call(env, insn, &env->insn_idx);
f4d7e40a 9463 else
c08435ec 9464 err = check_helper_call(env, insn->imm, env->insn_idx);
17a52670
AS
9465 if (err)
9466 return err;
9467
9468 } else if (opcode == BPF_JA) {
9469 if (BPF_SRC(insn->code) != BPF_K ||
9470 insn->imm != 0 ||
9471 insn->src_reg != BPF_REG_0 ||
092ed096
JW
9472 insn->dst_reg != BPF_REG_0 ||
9473 class == BPF_JMP32) {
61bd5218 9474 verbose(env, "BPF_JA uses reserved fields\n");
17a52670
AS
9475 return -EINVAL;
9476 }
9477
c08435ec 9478 env->insn_idx += insn->off + 1;
17a52670
AS
9479 continue;
9480
9481 } else if (opcode == BPF_EXIT) {
9482 if (BPF_SRC(insn->code) != BPF_K ||
9483 insn->imm != 0 ||
9484 insn->src_reg != BPF_REG_0 ||
092ed096
JW
9485 insn->dst_reg != BPF_REG_0 ||
9486 class == BPF_JMP32) {
61bd5218 9487 verbose(env, "BPF_EXIT uses reserved fields\n");
17a52670
AS
9488 return -EINVAL;
9489 }
9490
d83525ca
AS
9491 if (env->cur_state->active_spin_lock) {
9492 verbose(env, "bpf_spin_unlock is missing\n");
9493 return -EINVAL;
9494 }
9495
f4d7e40a
AS
9496 if (state->curframe) {
9497 /* exit from nested function */
c08435ec 9498 err = prepare_func_exit(env, &env->insn_idx);
f4d7e40a
AS
9499 if (err)
9500 return err;
9501 do_print_state = true;
9502 continue;
9503 }
9504
fd978bf7
JS
9505 err = check_reference_leak(env);
9506 if (err)
9507 return err;
9508
390ee7e2
AS
9509 err = check_return_code(env);
9510 if (err)
9511 return err;
f1bca824 9512process_bpf_exit:
2589726d 9513 update_branch_counts(env, env->cur_state);
b5dc0163 9514 err = pop_stack(env, &prev_insn_idx,
6f8a57cc 9515 &env->insn_idx, pop_log);
638f5b90
AS
9516 if (err < 0) {
9517 if (err != -ENOENT)
9518 return err;
17a52670
AS
9519 break;
9520 } else {
9521 do_print_state = true;
9522 continue;
9523 }
9524 } else {
c08435ec 9525 err = check_cond_jmp_op(env, insn, &env->insn_idx);
17a52670
AS
9526 if (err)
9527 return err;
9528 }
9529 } else if (class == BPF_LD) {
9530 u8 mode = BPF_MODE(insn->code);
9531
9532 if (mode == BPF_ABS || mode == BPF_IND) {
ddd872bc
AS
9533 err = check_ld_abs(env, insn);
9534 if (err)
9535 return err;
9536
17a52670
AS
9537 } else if (mode == BPF_IMM) {
9538 err = check_ld_imm(env, insn);
9539 if (err)
9540 return err;
9541
c08435ec 9542 env->insn_idx++;
51c39bb1 9543 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
17a52670 9544 } else {
61bd5218 9545 verbose(env, "invalid BPF_LD mode\n");
17a52670
AS
9546 return -EINVAL;
9547 }
9548 } else {
61bd5218 9549 verbose(env, "unknown insn class %d\n", class);
17a52670
AS
9550 return -EINVAL;
9551 }
9552
c08435ec 9553 env->insn_idx++;
17a52670
AS
9554 }
9555
9556 return 0;
9557}
9558
4976b718
HL
9559/* replace pseudo btf_id with kernel symbol address */
9560static int check_pseudo_btf_id(struct bpf_verifier_env *env,
9561 struct bpf_insn *insn,
9562 struct bpf_insn_aux_data *aux)
9563{
eaa6bcb7
HL
9564 u32 datasec_id, type, id = insn->imm;
9565 const struct btf_var_secinfo *vsi;
9566 const struct btf_type *datasec;
4976b718
HL
9567 const struct btf_type *t;
9568 const char *sym_name;
eaa6bcb7 9569 bool percpu = false;
4976b718 9570 u64 addr;
eaa6bcb7 9571 int i;
4976b718
HL
9572
9573 if (!btf_vmlinux) {
9574 verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
9575 return -EINVAL;
9576 }
9577
9578 if (insn[1].imm != 0) {
9579 verbose(env, "reserved field (insn[1].imm) is used in pseudo_btf_id ldimm64 insn.\n");
9580 return -EINVAL;
9581 }
9582
9583 t = btf_type_by_id(btf_vmlinux, id);
9584 if (!t) {
9585 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
9586 return -ENOENT;
9587 }
9588
9589 if (!btf_type_is_var(t)) {
9590 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR.\n",
9591 id);
9592 return -EINVAL;
9593 }
9594
9595 sym_name = btf_name_by_offset(btf_vmlinux, t->name_off);
9596 addr = kallsyms_lookup_name(sym_name);
9597 if (!addr) {
9598 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
9599 sym_name);
9600 return -ENOENT;
9601 }
9602
eaa6bcb7
HL
9603 datasec_id = btf_find_by_name_kind(btf_vmlinux, ".data..percpu",
9604 BTF_KIND_DATASEC);
9605 if (datasec_id > 0) {
9606 datasec = btf_type_by_id(btf_vmlinux, datasec_id);
9607 for_each_vsi(i, datasec, vsi) {
9608 if (vsi->type == id) {
9609 percpu = true;
9610 break;
9611 }
9612 }
9613 }
9614
4976b718
HL
9615 insn[0].imm = (u32)addr;
9616 insn[1].imm = addr >> 32;
9617
9618 type = t->type;
9619 t = btf_type_skip_modifiers(btf_vmlinux, type, NULL);
eaa6bcb7
HL
9620 if (percpu) {
9621 aux->btf_var.reg_type = PTR_TO_PERCPU_BTF_ID;
9622 aux->btf_var.btf_id = type;
9623 } else if (!btf_type_is_struct(t)) {
4976b718
HL
9624 const struct btf_type *ret;
9625 const char *tname;
9626 u32 tsize;
9627
9628 /* resolve the type size of ksym. */
9629 ret = btf_resolve_size(btf_vmlinux, t, &tsize);
9630 if (IS_ERR(ret)) {
9631 tname = btf_name_by_offset(btf_vmlinux, t->name_off);
9632 verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
9633 tname, PTR_ERR(ret));
9634 return -EINVAL;
9635 }
9636 aux->btf_var.reg_type = PTR_TO_MEM;
9637 aux->btf_var.mem_size = tsize;
9638 } else {
9639 aux->btf_var.reg_type = PTR_TO_BTF_ID;
9640 aux->btf_var.btf_id = type;
9641 }
9642 return 0;
9643}
9644
56f668df
MKL
9645static int check_map_prealloc(struct bpf_map *map)
9646{
9647 return (map->map_type != BPF_MAP_TYPE_HASH &&
bcc6b1b7
MKL
9648 map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
9649 map->map_type != BPF_MAP_TYPE_HASH_OF_MAPS) ||
56f668df
MKL
9650 !(map->map_flags & BPF_F_NO_PREALLOC);
9651}
9652
d83525ca
AS
9653static bool is_tracing_prog_type(enum bpf_prog_type type)
9654{
9655 switch (type) {
9656 case BPF_PROG_TYPE_KPROBE:
9657 case BPF_PROG_TYPE_TRACEPOINT:
9658 case BPF_PROG_TYPE_PERF_EVENT:
9659 case BPF_PROG_TYPE_RAW_TRACEPOINT:
9660 return true;
9661 default:
9662 return false;
9663 }
9664}
9665
94dacdbd
TG
9666static bool is_preallocated_map(struct bpf_map *map)
9667{
9668 if (!check_map_prealloc(map))
9669 return false;
9670 if (map->inner_map_meta && !check_map_prealloc(map->inner_map_meta))
9671 return false;
9672 return true;
9673}
9674
61bd5218
JK
9675static int check_map_prog_compatibility(struct bpf_verifier_env *env,
9676 struct bpf_map *map,
fdc15d38
AS
9677 struct bpf_prog *prog)
9678
9679{
7e40781c 9680 enum bpf_prog_type prog_type = resolve_prog_type(prog);
94dacdbd
TG
9681 /*
9682 * Validate that trace type programs use preallocated hash maps.
9683 *
9684 * For programs attached to PERF events this is mandatory as the
9685 * perf NMI can hit any arbitrary code sequence.
9686 *
9687 * All other trace types using preallocated hash maps are unsafe as
9688 * well because tracepoint or kprobes can be inside locked regions
9689 * of the memory allocator or at a place where a recursion into the
9690 * memory allocator would see inconsistent state.
9691 *
2ed905c5
TG
9692 * On RT enabled kernels run-time allocation of all trace type
9693 * programs is strictly prohibited due to lock type constraints. On
9694 * !RT kernels it is allowed for backwards compatibility reasons for
9695 * now, but warnings are emitted so developers are made aware of
9696 * the unsafety and can fix their programs before this is enforced.
56f668df 9697 */
7e40781c
UP
9698 if (is_tracing_prog_type(prog_type) && !is_preallocated_map(map)) {
9699 if (prog_type == BPF_PROG_TYPE_PERF_EVENT) {
61bd5218 9700 verbose(env, "perf_event programs can only use preallocated hash map\n");
56f668df
MKL
9701 return -EINVAL;
9702 }
2ed905c5
TG
9703 if (IS_ENABLED(CONFIG_PREEMPT_RT)) {
9704 verbose(env, "trace type programs can only use preallocated hash map\n");
9705 return -EINVAL;
9706 }
94dacdbd
TG
9707 WARN_ONCE(1, "trace type BPF program uses run-time allocation\n");
9708 verbose(env, "trace type programs with run-time allocated hash maps are unsafe. Switch to preallocated hash maps.\n");
fdc15d38 9709 }
a3884572 9710
7e40781c
UP
9711 if ((is_tracing_prog_type(prog_type) ||
9712 prog_type == BPF_PROG_TYPE_SOCKET_FILTER) &&
d83525ca
AS
9713 map_value_has_spin_lock(map)) {
9714 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
9715 return -EINVAL;
9716 }
9717
a3884572 9718 if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) &&
09728266 9719 !bpf_offload_prog_map_match(prog, map)) {
a3884572
JK
9720 verbose(env, "offload device mismatch between prog and map\n");
9721 return -EINVAL;
9722 }
9723
85d33df3
MKL
9724 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
9725 verbose(env, "bpf_struct_ops map cannot be used in prog\n");
9726 return -EINVAL;
9727 }
9728
1e6c62a8
AS
9729 if (prog->aux->sleepable)
9730 switch (map->map_type) {
9731 case BPF_MAP_TYPE_HASH:
9732 case BPF_MAP_TYPE_LRU_HASH:
9733 case BPF_MAP_TYPE_ARRAY:
9734 if (!is_preallocated_map(map)) {
9735 verbose(env,
9736 "Sleepable programs can only use preallocated hash maps\n");
9737 return -EINVAL;
9738 }
9739 break;
9740 default:
9741 verbose(env,
9742 "Sleepable programs can only use array and hash maps\n");
9743 return -EINVAL;
9744 }
9745
fdc15d38
AS
9746 return 0;
9747}
9748
b741f163
RG
9749static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
9750{
9751 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
9752 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
9753}
9754
4976b718
HL
9755/* find and rewrite pseudo imm in ld_imm64 instructions:
9756 *
9757 * 1. if it accesses map FD, replace it with actual map pointer.
9758 * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
9759 *
9760 * NOTE: btf_vmlinux is required for converting pseudo btf_id.
0246e64d 9761 */
4976b718 9762static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
0246e64d
AS
9763{
9764 struct bpf_insn *insn = env->prog->insnsi;
9765 int insn_cnt = env->prog->len;
fdc15d38 9766 int i, j, err;
0246e64d 9767
f1f7714e 9768 err = bpf_prog_calc_tag(env->prog);
aafe6ae9
DB
9769 if (err)
9770 return err;
9771
0246e64d 9772 for (i = 0; i < insn_cnt; i++, insn++) {
9bac3d6d 9773 if (BPF_CLASS(insn->code) == BPF_LDX &&
d691f9e8 9774 (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
61bd5218 9775 verbose(env, "BPF_LDX uses reserved fields\n");
9bac3d6d
AS
9776 return -EINVAL;
9777 }
9778
d691f9e8
AS
9779 if (BPF_CLASS(insn->code) == BPF_STX &&
9780 ((BPF_MODE(insn->code) != BPF_MEM &&
9781 BPF_MODE(insn->code) != BPF_XADD) || insn->imm != 0)) {
61bd5218 9782 verbose(env, "BPF_STX uses reserved fields\n");
d691f9e8
AS
9783 return -EINVAL;
9784 }
9785
0246e64d 9786 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
d8eca5bb 9787 struct bpf_insn_aux_data *aux;
0246e64d
AS
9788 struct bpf_map *map;
9789 struct fd f;
d8eca5bb 9790 u64 addr;
0246e64d
AS
9791
9792 if (i == insn_cnt - 1 || insn[1].code != 0 ||
9793 insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
9794 insn[1].off != 0) {
61bd5218 9795 verbose(env, "invalid bpf_ld_imm64 insn\n");
0246e64d
AS
9796 return -EINVAL;
9797 }
9798
d8eca5bb 9799 if (insn[0].src_reg == 0)
0246e64d
AS
9800 /* valid generic load 64-bit imm */
9801 goto next_insn;
9802
4976b718
HL
9803 if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
9804 aux = &env->insn_aux_data[i];
9805 err = check_pseudo_btf_id(env, insn, aux);
9806 if (err)
9807 return err;
9808 goto next_insn;
9809 }
9810
d8eca5bb
DB
9811 /* In final convert_pseudo_ld_imm64() step, this is
9812 * converted into regular 64-bit imm load insn.
9813 */
9814 if ((insn[0].src_reg != BPF_PSEUDO_MAP_FD &&
9815 insn[0].src_reg != BPF_PSEUDO_MAP_VALUE) ||
9816 (insn[0].src_reg == BPF_PSEUDO_MAP_FD &&
9817 insn[1].imm != 0)) {
9818 verbose(env,
9819 "unrecognized bpf_ld_imm64 insn\n");
0246e64d
AS
9820 return -EINVAL;
9821 }
9822
20182390 9823 f = fdget(insn[0].imm);
c2101297 9824 map = __bpf_map_get(f);
0246e64d 9825 if (IS_ERR(map)) {
61bd5218 9826 verbose(env, "fd %d is not pointing to valid bpf_map\n",
20182390 9827 insn[0].imm);
0246e64d
AS
9828 return PTR_ERR(map);
9829 }
9830
61bd5218 9831 err = check_map_prog_compatibility(env, map, env->prog);
fdc15d38
AS
9832 if (err) {
9833 fdput(f);
9834 return err;
9835 }
9836
d8eca5bb
DB
9837 aux = &env->insn_aux_data[i];
9838 if (insn->src_reg == BPF_PSEUDO_MAP_FD) {
9839 addr = (unsigned long)map;
9840 } else {
9841 u32 off = insn[1].imm;
9842
9843 if (off >= BPF_MAX_VAR_OFF) {
9844 verbose(env, "direct value offset of %u is not allowed\n", off);
9845 fdput(f);
9846 return -EINVAL;
9847 }
9848
9849 if (!map->ops->map_direct_value_addr) {
9850 verbose(env, "no direct value access support for this map type\n");
9851 fdput(f);
9852 return -EINVAL;
9853 }
9854
9855 err = map->ops->map_direct_value_addr(map, &addr, off);
9856 if (err) {
9857 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
9858 map->value_size, off);
9859 fdput(f);
9860 return err;
9861 }
9862
9863 aux->map_off = off;
9864 addr += off;
9865 }
9866
9867 insn[0].imm = (u32)addr;
9868 insn[1].imm = addr >> 32;
0246e64d
AS
9869
9870 /* check whether we recorded this map already */
d8eca5bb 9871 for (j = 0; j < env->used_map_cnt; j++) {
0246e64d 9872 if (env->used_maps[j] == map) {
d8eca5bb 9873 aux->map_index = j;
0246e64d
AS
9874 fdput(f);
9875 goto next_insn;
9876 }
d8eca5bb 9877 }
0246e64d
AS
9878
9879 if (env->used_map_cnt >= MAX_USED_MAPS) {
9880 fdput(f);
9881 return -E2BIG;
9882 }
9883
0246e64d
AS
9884 /* hold the map. If the program is rejected by verifier,
9885 * the map will be released by release_maps() or it
9886 * will be used by the valid program until it's unloaded
ab7f5bf0 9887 * and all maps are released in free_used_maps()
0246e64d 9888 */
1e0bd5a0 9889 bpf_map_inc(map);
d8eca5bb
DB
9890
9891 aux->map_index = env->used_map_cnt;
92117d84
AS
9892 env->used_maps[env->used_map_cnt++] = map;
9893
b741f163 9894 if (bpf_map_is_cgroup_storage(map) &&
e4730423 9895 bpf_cgroup_storage_assign(env->prog->aux, map)) {
b741f163 9896 verbose(env, "only one cgroup storage of each type is allowed\n");
de9cbbaa
RG
9897 fdput(f);
9898 return -EBUSY;
9899 }
9900
0246e64d
AS
9901 fdput(f);
9902next_insn:
9903 insn++;
9904 i++;
5e581dad
DB
9905 continue;
9906 }
9907
9908 /* Basic sanity check before we invest more work here. */
9909 if (!bpf_opcode_in_insntable(insn->code)) {
9910 verbose(env, "unknown opcode %02x\n", insn->code);
9911 return -EINVAL;
0246e64d
AS
9912 }
9913 }
9914
9915 /* now all pseudo BPF_LD_IMM64 instructions load valid
9916 * 'struct bpf_map *' into a register instead of user map_fd.
9917 * These pointers will be used later by verifier to validate map access.
9918 */
9919 return 0;
9920}
9921
9922/* drop refcnt of maps used by the rejected program */
58e2af8b 9923static void release_maps(struct bpf_verifier_env *env)
0246e64d 9924{
a2ea0746
DB
9925 __bpf_free_used_maps(env->prog->aux, env->used_maps,
9926 env->used_map_cnt);
0246e64d
AS
9927}
9928
9929/* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
58e2af8b 9930static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
0246e64d
AS
9931{
9932 struct bpf_insn *insn = env->prog->insnsi;
9933 int insn_cnt = env->prog->len;
9934 int i;
9935
9936 for (i = 0; i < insn_cnt; i++, insn++)
9937 if (insn->code == (BPF_LD | BPF_IMM | BPF_DW))
9938 insn->src_reg = 0;
9939}
9940
8041902d
AS
9941/* single env->prog->insni[off] instruction was replaced with the range
9942 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying
9943 * [0, off) and [off, end) to new locations, so the patched range stays zero
9944 */
b325fbca
JW
9945static int adjust_insn_aux_data(struct bpf_verifier_env *env,
9946 struct bpf_prog *new_prog, u32 off, u32 cnt)
8041902d
AS
9947{
9948 struct bpf_insn_aux_data *new_data, *old_data = env->insn_aux_data;
b325fbca
JW
9949 struct bpf_insn *insn = new_prog->insnsi;
9950 u32 prog_len;
c131187d 9951 int i;
8041902d 9952
b325fbca
JW
9953 /* aux info at OFF always needs adjustment, no matter fast path
9954 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
9955 * original insn at old prog.
9956 */
9957 old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
9958
8041902d
AS
9959 if (cnt == 1)
9960 return 0;
b325fbca 9961 prog_len = new_prog->len;
fad953ce
KC
9962 new_data = vzalloc(array_size(prog_len,
9963 sizeof(struct bpf_insn_aux_data)));
8041902d
AS
9964 if (!new_data)
9965 return -ENOMEM;
9966 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
9967 memcpy(new_data + off + cnt - 1, old_data + off,
9968 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
b325fbca 9969 for (i = off; i < off + cnt - 1; i++) {
51c39bb1 9970 new_data[i].seen = env->pass_cnt;
b325fbca
JW
9971 new_data[i].zext_dst = insn_has_def32(env, insn + i);
9972 }
8041902d
AS
9973 env->insn_aux_data = new_data;
9974 vfree(old_data);
9975 return 0;
9976}
9977
cc8b0b92
AS
9978static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
9979{
9980 int i;
9981
9982 if (len == 1)
9983 return;
4cb3d99c
JW
9984 /* NOTE: fake 'exit' subprog should be updated as well. */
9985 for (i = 0; i <= env->subprog_cnt; i++) {
afd59424 9986 if (env->subprog_info[i].start <= off)
cc8b0b92 9987 continue;
9c8105bd 9988 env->subprog_info[i].start += len - 1;
cc8b0b92
AS
9989 }
9990}
9991
a748c697
MF
9992static void adjust_poke_descs(struct bpf_prog *prog, u32 len)
9993{
9994 struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
9995 int i, sz = prog->aux->size_poke_tab;
9996 struct bpf_jit_poke_descriptor *desc;
9997
9998 for (i = 0; i < sz; i++) {
9999 desc = &tab[i];
10000 desc->insn_idx += len - 1;
10001 }
10002}
10003
8041902d
AS
10004static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
10005 const struct bpf_insn *patch, u32 len)
10006{
10007 struct bpf_prog *new_prog;
10008
10009 new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
4f73379e
AS
10010 if (IS_ERR(new_prog)) {
10011 if (PTR_ERR(new_prog) == -ERANGE)
10012 verbose(env,
10013 "insn %d cannot be patched due to 16-bit range\n",
10014 env->insn_aux_data[off].orig_idx);
8041902d 10015 return NULL;
4f73379e 10016 }
b325fbca 10017 if (adjust_insn_aux_data(env, new_prog, off, len))
8041902d 10018 return NULL;
cc8b0b92 10019 adjust_subprog_starts(env, off, len);
a748c697 10020 adjust_poke_descs(new_prog, len);
8041902d
AS
10021 return new_prog;
10022}
10023
52875a04
JK
10024static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
10025 u32 off, u32 cnt)
10026{
10027 int i, j;
10028
10029 /* find first prog starting at or after off (first to remove) */
10030 for (i = 0; i < env->subprog_cnt; i++)
10031 if (env->subprog_info[i].start >= off)
10032 break;
10033 /* find first prog starting at or after off + cnt (first to stay) */
10034 for (j = i; j < env->subprog_cnt; j++)
10035 if (env->subprog_info[j].start >= off + cnt)
10036 break;
10037 /* if j doesn't start exactly at off + cnt, we are just removing
10038 * the front of previous prog
10039 */
10040 if (env->subprog_info[j].start != off + cnt)
10041 j--;
10042
10043 if (j > i) {
10044 struct bpf_prog_aux *aux = env->prog->aux;
10045 int move;
10046
10047 /* move fake 'exit' subprog as well */
10048 move = env->subprog_cnt + 1 - j;
10049
10050 memmove(env->subprog_info + i,
10051 env->subprog_info + j,
10052 sizeof(*env->subprog_info) * move);
10053 env->subprog_cnt -= j - i;
10054
10055 /* remove func_info */
10056 if (aux->func_info) {
10057 move = aux->func_info_cnt - j;
10058
10059 memmove(aux->func_info + i,
10060 aux->func_info + j,
10061 sizeof(*aux->func_info) * move);
10062 aux->func_info_cnt -= j - i;
10063 /* func_info->insn_off is set after all code rewrites,
10064 * in adjust_btf_func() - no need to adjust
10065 */
10066 }
10067 } else {
10068 /* convert i from "first prog to remove" to "first to adjust" */
10069 if (env->subprog_info[i].start == off)
10070 i++;
10071 }
10072
10073 /* update fake 'exit' subprog as well */
10074 for (; i <= env->subprog_cnt; i++)
10075 env->subprog_info[i].start -= cnt;
10076
10077 return 0;
10078}
10079
10080static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
10081 u32 cnt)
10082{
10083 struct bpf_prog *prog = env->prog;
10084 u32 i, l_off, l_cnt, nr_linfo;
10085 struct bpf_line_info *linfo;
10086
10087 nr_linfo = prog->aux->nr_linfo;
10088 if (!nr_linfo)
10089 return 0;
10090
10091 linfo = prog->aux->linfo;
10092
10093 /* find first line info to remove, count lines to be removed */
10094 for (i = 0; i < nr_linfo; i++)
10095 if (linfo[i].insn_off >= off)
10096 break;
10097
10098 l_off = i;
10099 l_cnt = 0;
10100 for (; i < nr_linfo; i++)
10101 if (linfo[i].insn_off < off + cnt)
10102 l_cnt++;
10103 else
10104 break;
10105
10106 /* First live insn doesn't match first live linfo, it needs to "inherit"
10107 * last removed linfo. prog is already modified, so prog->len == off
10108 * means no live instructions after (tail of the program was removed).
10109 */
10110 if (prog->len != off && l_cnt &&
10111 (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
10112 l_cnt--;
10113 linfo[--i].insn_off = off + cnt;
10114 }
10115
10116 /* remove the line info which refer to the removed instructions */
10117 if (l_cnt) {
10118 memmove(linfo + l_off, linfo + i,
10119 sizeof(*linfo) * (nr_linfo - i));
10120
10121 prog->aux->nr_linfo -= l_cnt;
10122 nr_linfo = prog->aux->nr_linfo;
10123 }
10124
10125 /* pull all linfo[i].insn_off >= off + cnt in by cnt */
10126 for (i = l_off; i < nr_linfo; i++)
10127 linfo[i].insn_off -= cnt;
10128
10129 /* fix up all subprogs (incl. 'exit') which start >= off */
10130 for (i = 0; i <= env->subprog_cnt; i++)
10131 if (env->subprog_info[i].linfo_idx > l_off) {
10132 /* program may have started in the removed region but
10133 * may not be fully removed
10134 */
10135 if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
10136 env->subprog_info[i].linfo_idx -= l_cnt;
10137 else
10138 env->subprog_info[i].linfo_idx = l_off;
10139 }
10140
10141 return 0;
10142}
10143
10144static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
10145{
10146 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
10147 unsigned int orig_prog_len = env->prog->len;
10148 int err;
10149
08ca90af
JK
10150 if (bpf_prog_is_dev_bound(env->prog->aux))
10151 bpf_prog_offload_remove_insns(env, off, cnt);
10152
52875a04
JK
10153 err = bpf_remove_insns(env->prog, off, cnt);
10154 if (err)
10155 return err;
10156
10157 err = adjust_subprog_starts_after_remove(env, off, cnt);
10158 if (err)
10159 return err;
10160
10161 err = bpf_adj_linfo_after_remove(env, off, cnt);
10162 if (err)
10163 return err;
10164
10165 memmove(aux_data + off, aux_data + off + cnt,
10166 sizeof(*aux_data) * (orig_prog_len - off - cnt));
10167
10168 return 0;
10169}
10170
2a5418a1
DB
10171/* The verifier does more data flow analysis than llvm and will not
10172 * explore branches that are dead at run time. Malicious programs can
10173 * have dead code too. Therefore replace all dead at-run-time code
10174 * with 'ja -1'.
10175 *
10176 * Just nops are not optimal, e.g. if they would sit at the end of the
10177 * program and through another bug we would manage to jump there, then
10178 * we'd execute beyond program memory otherwise. Returning exception
10179 * code also wouldn't work since we can have subprogs where the dead
10180 * code could be located.
c131187d
AS
10181 */
10182static void sanitize_dead_code(struct bpf_verifier_env *env)
10183{
10184 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
2a5418a1 10185 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
c131187d
AS
10186 struct bpf_insn *insn = env->prog->insnsi;
10187 const int insn_cnt = env->prog->len;
10188 int i;
10189
10190 for (i = 0; i < insn_cnt; i++) {
10191 if (aux_data[i].seen)
10192 continue;
2a5418a1 10193 memcpy(insn + i, &trap, sizeof(trap));
c131187d
AS
10194 }
10195}
10196
e2ae4ca2
JK
10197static bool insn_is_cond_jump(u8 code)
10198{
10199 u8 op;
10200
092ed096
JW
10201 if (BPF_CLASS(code) == BPF_JMP32)
10202 return true;
10203
e2ae4ca2
JK
10204 if (BPF_CLASS(code) != BPF_JMP)
10205 return false;
10206
10207 op = BPF_OP(code);
10208 return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
10209}
10210
10211static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
10212{
10213 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
10214 struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
10215 struct bpf_insn *insn = env->prog->insnsi;
10216 const int insn_cnt = env->prog->len;
10217 int i;
10218
10219 for (i = 0; i < insn_cnt; i++, insn++) {
10220 if (!insn_is_cond_jump(insn->code))
10221 continue;
10222
10223 if (!aux_data[i + 1].seen)
10224 ja.off = insn->off;
10225 else if (!aux_data[i + 1 + insn->off].seen)
10226 ja.off = 0;
10227 else
10228 continue;
10229
08ca90af
JK
10230 if (bpf_prog_is_dev_bound(env->prog->aux))
10231 bpf_prog_offload_replace_insn(env, i, &ja);
10232
e2ae4ca2
JK
10233 memcpy(insn, &ja, sizeof(ja));
10234 }
10235}
10236
52875a04
JK
10237static int opt_remove_dead_code(struct bpf_verifier_env *env)
10238{
10239 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
10240 int insn_cnt = env->prog->len;
10241 int i, err;
10242
10243 for (i = 0; i < insn_cnt; i++) {
10244 int j;
10245
10246 j = 0;
10247 while (i + j < insn_cnt && !aux_data[i + j].seen)
10248 j++;
10249 if (!j)
10250 continue;
10251
10252 err = verifier_remove_insns(env, i, j);
10253 if (err)
10254 return err;
10255 insn_cnt = env->prog->len;
10256 }
10257
10258 return 0;
10259}
10260
a1b14abc
JK
10261static int opt_remove_nops(struct bpf_verifier_env *env)
10262{
10263 const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
10264 struct bpf_insn *insn = env->prog->insnsi;
10265 int insn_cnt = env->prog->len;
10266 int i, err;
10267
10268 for (i = 0; i < insn_cnt; i++) {
10269 if (memcmp(&insn[i], &ja, sizeof(ja)))
10270 continue;
10271
10272 err = verifier_remove_insns(env, i, 1);
10273 if (err)
10274 return err;
10275 insn_cnt--;
10276 i--;
10277 }
10278
10279 return 0;
10280}
10281
d6c2308c
JW
10282static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
10283 const union bpf_attr *attr)
a4b1d3c1 10284{
d6c2308c 10285 struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
a4b1d3c1 10286 struct bpf_insn_aux_data *aux = env->insn_aux_data;
d6c2308c 10287 int i, patch_len, delta = 0, len = env->prog->len;
a4b1d3c1 10288 struct bpf_insn *insns = env->prog->insnsi;
a4b1d3c1 10289 struct bpf_prog *new_prog;
d6c2308c 10290 bool rnd_hi32;
a4b1d3c1 10291
d6c2308c 10292 rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
a4b1d3c1 10293 zext_patch[1] = BPF_ZEXT_REG(0);
d6c2308c
JW
10294 rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
10295 rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
10296 rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
a4b1d3c1
JW
10297 for (i = 0; i < len; i++) {
10298 int adj_idx = i + delta;
10299 struct bpf_insn insn;
10300
d6c2308c
JW
10301 insn = insns[adj_idx];
10302 if (!aux[adj_idx].zext_dst) {
10303 u8 code, class;
10304 u32 imm_rnd;
10305
10306 if (!rnd_hi32)
10307 continue;
10308
10309 code = insn.code;
10310 class = BPF_CLASS(code);
10311 if (insn_no_def(&insn))
10312 continue;
10313
10314 /* NOTE: arg "reg" (the fourth one) is only used for
10315 * BPF_STX which has been ruled out in above
10316 * check, it is safe to pass NULL here.
10317 */
10318 if (is_reg64(env, &insn, insn.dst_reg, NULL, DST_OP)) {
10319 if (class == BPF_LD &&
10320 BPF_MODE(code) == BPF_IMM)
10321 i++;
10322 continue;
10323 }
10324
10325 /* ctx load could be transformed into wider load. */
10326 if (class == BPF_LDX &&
10327 aux[adj_idx].ptr_type == PTR_TO_CTX)
10328 continue;
10329
10330 imm_rnd = get_random_int();
10331 rnd_hi32_patch[0] = insn;
10332 rnd_hi32_patch[1].imm = imm_rnd;
10333 rnd_hi32_patch[3].dst_reg = insn.dst_reg;
10334 patch = rnd_hi32_patch;
10335 patch_len = 4;
10336 goto apply_patch_buffer;
10337 }
10338
10339 if (!bpf_jit_needs_zext())
a4b1d3c1
JW
10340 continue;
10341
a4b1d3c1
JW
10342 zext_patch[0] = insn;
10343 zext_patch[1].dst_reg = insn.dst_reg;
10344 zext_patch[1].src_reg = insn.dst_reg;
d6c2308c
JW
10345 patch = zext_patch;
10346 patch_len = 2;
10347apply_patch_buffer:
10348 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
a4b1d3c1
JW
10349 if (!new_prog)
10350 return -ENOMEM;
10351 env->prog = new_prog;
10352 insns = new_prog->insnsi;
10353 aux = env->insn_aux_data;
d6c2308c 10354 delta += patch_len - 1;
a4b1d3c1
JW
10355 }
10356
10357 return 0;
10358}
10359
c64b7983
JS
10360/* convert load instructions that access fields of a context type into a
10361 * sequence of instructions that access fields of the underlying structure:
10362 * struct __sk_buff -> struct sk_buff
10363 * struct bpf_sock_ops -> struct sock
9bac3d6d 10364 */
58e2af8b 10365static int convert_ctx_accesses(struct bpf_verifier_env *env)
9bac3d6d 10366{
00176a34 10367 const struct bpf_verifier_ops *ops = env->ops;
f96da094 10368 int i, cnt, size, ctx_field_size, delta = 0;
3df126f3 10369 const int insn_cnt = env->prog->len;
36bbef52 10370 struct bpf_insn insn_buf[16], *insn;
46f53a65 10371 u32 target_size, size_default, off;
9bac3d6d 10372 struct bpf_prog *new_prog;
d691f9e8 10373 enum bpf_access_type type;
f96da094 10374 bool is_narrower_load;
9bac3d6d 10375
b09928b9
DB
10376 if (ops->gen_prologue || env->seen_direct_write) {
10377 if (!ops->gen_prologue) {
10378 verbose(env, "bpf verifier is misconfigured\n");
10379 return -EINVAL;
10380 }
36bbef52
DB
10381 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
10382 env->prog);
10383 if (cnt >= ARRAY_SIZE(insn_buf)) {
61bd5218 10384 verbose(env, "bpf verifier is misconfigured\n");
36bbef52
DB
10385 return -EINVAL;
10386 } else if (cnt) {
8041902d 10387 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
36bbef52
DB
10388 if (!new_prog)
10389 return -ENOMEM;
8041902d 10390
36bbef52 10391 env->prog = new_prog;
3df126f3 10392 delta += cnt - 1;
36bbef52
DB
10393 }
10394 }
10395
c64b7983 10396 if (bpf_prog_is_dev_bound(env->prog->aux))
9bac3d6d
AS
10397 return 0;
10398
3df126f3 10399 insn = env->prog->insnsi + delta;
36bbef52 10400
9bac3d6d 10401 for (i = 0; i < insn_cnt; i++, insn++) {
c64b7983
JS
10402 bpf_convert_ctx_access_t convert_ctx_access;
10403
62c7989b
DB
10404 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
10405 insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
10406 insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
ea2e7ce5 10407 insn->code == (BPF_LDX | BPF_MEM | BPF_DW))
d691f9e8 10408 type = BPF_READ;
62c7989b
DB
10409 else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
10410 insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
10411 insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
ea2e7ce5 10412 insn->code == (BPF_STX | BPF_MEM | BPF_DW))
d691f9e8
AS
10413 type = BPF_WRITE;
10414 else
9bac3d6d
AS
10415 continue;
10416
af86ca4e
AS
10417 if (type == BPF_WRITE &&
10418 env->insn_aux_data[i + delta].sanitize_stack_off) {
10419 struct bpf_insn patch[] = {
10420 /* Sanitize suspicious stack slot with zero.
10421 * There are no memory dependencies for this store,
10422 * since it's only using frame pointer and immediate
10423 * constant of zero
10424 */
10425 BPF_ST_MEM(BPF_DW, BPF_REG_FP,
10426 env->insn_aux_data[i + delta].sanitize_stack_off,
10427 0),
10428 /* the original STX instruction will immediately
10429 * overwrite the same stack slot with appropriate value
10430 */
10431 *insn,
10432 };
10433
10434 cnt = ARRAY_SIZE(patch);
10435 new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
10436 if (!new_prog)
10437 return -ENOMEM;
10438
10439 delta += cnt - 1;
10440 env->prog = new_prog;
10441 insn = new_prog->insnsi + i + delta;
10442 continue;
10443 }
10444
c64b7983
JS
10445 switch (env->insn_aux_data[i + delta].ptr_type) {
10446 case PTR_TO_CTX:
10447 if (!ops->convert_ctx_access)
10448 continue;
10449 convert_ctx_access = ops->convert_ctx_access;
10450 break;
10451 case PTR_TO_SOCKET:
46f8bc92 10452 case PTR_TO_SOCK_COMMON:
c64b7983
JS
10453 convert_ctx_access = bpf_sock_convert_ctx_access;
10454 break;
655a51e5
MKL
10455 case PTR_TO_TCP_SOCK:
10456 convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
10457 break;
fada7fdc
JL
10458 case PTR_TO_XDP_SOCK:
10459 convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
10460 break;
2a02759e 10461 case PTR_TO_BTF_ID:
27ae7997
MKL
10462 if (type == BPF_READ) {
10463 insn->code = BPF_LDX | BPF_PROBE_MEM |
10464 BPF_SIZE((insn)->code);
10465 env->prog->aux->num_exentries++;
7e40781c 10466 } else if (resolve_prog_type(env->prog) != BPF_PROG_TYPE_STRUCT_OPS) {
2a02759e
AS
10467 verbose(env, "Writes through BTF pointers are not allowed\n");
10468 return -EINVAL;
10469 }
2a02759e 10470 continue;
c64b7983 10471 default:
9bac3d6d 10472 continue;
c64b7983 10473 }
9bac3d6d 10474
31fd8581 10475 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
f96da094 10476 size = BPF_LDST_BYTES(insn);
31fd8581
YS
10477
10478 /* If the read access is a narrower load of the field,
10479 * convert to a 4/8-byte load, to minimum program type specific
10480 * convert_ctx_access changes. If conversion is successful,
10481 * we will apply proper mask to the result.
10482 */
f96da094 10483 is_narrower_load = size < ctx_field_size;
46f53a65
AI
10484 size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
10485 off = insn->off;
31fd8581 10486 if (is_narrower_load) {
f96da094
DB
10487 u8 size_code;
10488
10489 if (type == BPF_WRITE) {
61bd5218 10490 verbose(env, "bpf verifier narrow ctx access misconfigured\n");
f96da094
DB
10491 return -EINVAL;
10492 }
31fd8581 10493
f96da094 10494 size_code = BPF_H;
31fd8581
YS
10495 if (ctx_field_size == 4)
10496 size_code = BPF_W;
10497 else if (ctx_field_size == 8)
10498 size_code = BPF_DW;
f96da094 10499
bc23105c 10500 insn->off = off & ~(size_default - 1);
31fd8581
YS
10501 insn->code = BPF_LDX | BPF_MEM | size_code;
10502 }
f96da094
DB
10503
10504 target_size = 0;
c64b7983
JS
10505 cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
10506 &target_size);
f96da094
DB
10507 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
10508 (ctx_field_size && !target_size)) {
61bd5218 10509 verbose(env, "bpf verifier is misconfigured\n");
9bac3d6d
AS
10510 return -EINVAL;
10511 }
f96da094
DB
10512
10513 if (is_narrower_load && size < target_size) {
d895a0f1
IL
10514 u8 shift = bpf_ctx_narrow_access_offset(
10515 off, size, size_default) * 8;
46f53a65
AI
10516 if (ctx_field_size <= 4) {
10517 if (shift)
10518 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
10519 insn->dst_reg,
10520 shift);
31fd8581 10521 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
f96da094 10522 (1 << size * 8) - 1);
46f53a65
AI
10523 } else {
10524 if (shift)
10525 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
10526 insn->dst_reg,
10527 shift);
31fd8581 10528 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
e2f7fc0a 10529 (1ULL << size * 8) - 1);
46f53a65 10530 }
31fd8581 10531 }
9bac3d6d 10532
8041902d 10533 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
9bac3d6d
AS
10534 if (!new_prog)
10535 return -ENOMEM;
10536
3df126f3 10537 delta += cnt - 1;
9bac3d6d
AS
10538
10539 /* keep walking new program and skip insns we just inserted */
10540 env->prog = new_prog;
3df126f3 10541 insn = new_prog->insnsi + i + delta;
9bac3d6d
AS
10542 }
10543
10544 return 0;
10545}
10546
1c2a088a
AS
10547static int jit_subprogs(struct bpf_verifier_env *env)
10548{
10549 struct bpf_prog *prog = env->prog, **func, *tmp;
10550 int i, j, subprog_start, subprog_end = 0, len, subprog;
a748c697 10551 struct bpf_map *map_ptr;
7105e828 10552 struct bpf_insn *insn;
1c2a088a 10553 void *old_bpf_func;
c4c0bdc0 10554 int err, num_exentries;
1c2a088a 10555
f910cefa 10556 if (env->subprog_cnt <= 1)
1c2a088a
AS
10557 return 0;
10558
7105e828 10559 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
1c2a088a
AS
10560 if (insn->code != (BPF_JMP | BPF_CALL) ||
10561 insn->src_reg != BPF_PSEUDO_CALL)
10562 continue;
c7a89784
DB
10563 /* Upon error here we cannot fall back to interpreter but
10564 * need a hard reject of the program. Thus -EFAULT is
10565 * propagated in any case.
10566 */
1c2a088a
AS
10567 subprog = find_subprog(env, i + insn->imm + 1);
10568 if (subprog < 0) {
10569 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
10570 i + insn->imm + 1);
10571 return -EFAULT;
10572 }
10573 /* temporarily remember subprog id inside insn instead of
10574 * aux_data, since next loop will split up all insns into funcs
10575 */
f910cefa 10576 insn->off = subprog;
1c2a088a
AS
10577 /* remember original imm in case JIT fails and fallback
10578 * to interpreter will be needed
10579 */
10580 env->insn_aux_data[i].call_imm = insn->imm;
10581 /* point imm to __bpf_call_base+1 from JITs point of view */
10582 insn->imm = 1;
10583 }
10584
c454a46b
MKL
10585 err = bpf_prog_alloc_jited_linfo(prog);
10586 if (err)
10587 goto out_undo_insn;
10588
10589 err = -ENOMEM;
6396bb22 10590 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
1c2a088a 10591 if (!func)
c7a89784 10592 goto out_undo_insn;
1c2a088a 10593
f910cefa 10594 for (i = 0; i < env->subprog_cnt; i++) {
1c2a088a 10595 subprog_start = subprog_end;
4cb3d99c 10596 subprog_end = env->subprog_info[i + 1].start;
1c2a088a
AS
10597
10598 len = subprog_end - subprog_start;
492ecee8
AS
10599 /* BPF_PROG_RUN doesn't call subprogs directly,
10600 * hence main prog stats include the runtime of subprogs.
10601 * subprogs don't have IDs and not reachable via prog_get_next_id
10602 * func[i]->aux->stats will never be accessed and stays NULL
10603 */
10604 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
1c2a088a
AS
10605 if (!func[i])
10606 goto out_free;
10607 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
10608 len * sizeof(struct bpf_insn));
4f74d809 10609 func[i]->type = prog->type;
1c2a088a 10610 func[i]->len = len;
4f74d809
DB
10611 if (bpf_prog_calc_tag(func[i]))
10612 goto out_free;
1c2a088a 10613 func[i]->is_func = 1;
ba64e7d8
YS
10614 func[i]->aux->func_idx = i;
10615 /* the btf and func_info will be freed only at prog->aux */
10616 func[i]->aux->btf = prog->aux->btf;
10617 func[i]->aux->func_info = prog->aux->func_info;
10618
a748c697
MF
10619 for (j = 0; j < prog->aux->size_poke_tab; j++) {
10620 u32 insn_idx = prog->aux->poke_tab[j].insn_idx;
10621 int ret;
10622
10623 if (!(insn_idx >= subprog_start &&
10624 insn_idx <= subprog_end))
10625 continue;
10626
10627 ret = bpf_jit_add_poke_descriptor(func[i],
10628 &prog->aux->poke_tab[j]);
10629 if (ret < 0) {
10630 verbose(env, "adding tail call poke descriptor failed\n");
10631 goto out_free;
10632 }
10633
10634 func[i]->insnsi[insn_idx - subprog_start].imm = ret + 1;
10635
10636 map_ptr = func[i]->aux->poke_tab[ret].tail_call.map;
10637 ret = map_ptr->ops->map_poke_track(map_ptr, func[i]->aux);
10638 if (ret < 0) {
10639 verbose(env, "tracking tail call prog failed\n");
10640 goto out_free;
10641 }
10642 }
10643
1c2a088a
AS
10644 /* Use bpf_prog_F_tag to indicate functions in stack traces.
10645 * Long term would need debug info to populate names
10646 */
10647 func[i]->aux->name[0] = 'F';
9c8105bd 10648 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
1c2a088a 10649 func[i]->jit_requested = 1;
c454a46b
MKL
10650 func[i]->aux->linfo = prog->aux->linfo;
10651 func[i]->aux->nr_linfo = prog->aux->nr_linfo;
10652 func[i]->aux->jited_linfo = prog->aux->jited_linfo;
10653 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
c4c0bdc0
YS
10654 num_exentries = 0;
10655 insn = func[i]->insnsi;
10656 for (j = 0; j < func[i]->len; j++, insn++) {
10657 if (BPF_CLASS(insn->code) == BPF_LDX &&
10658 BPF_MODE(insn->code) == BPF_PROBE_MEM)
10659 num_exentries++;
10660 }
10661 func[i]->aux->num_exentries = num_exentries;
ebf7d1f5 10662 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
1c2a088a
AS
10663 func[i] = bpf_int_jit_compile(func[i]);
10664 if (!func[i]->jited) {
10665 err = -ENOTSUPP;
10666 goto out_free;
10667 }
10668 cond_resched();
10669 }
a748c697
MF
10670
10671 /* Untrack main program's aux structs so that during map_poke_run()
10672 * we will not stumble upon the unfilled poke descriptors; each
10673 * of the main program's poke descs got distributed across subprogs
10674 * and got tracked onto map, so we are sure that none of them will
10675 * be missed after the operation below
10676 */
10677 for (i = 0; i < prog->aux->size_poke_tab; i++) {
10678 map_ptr = prog->aux->poke_tab[i].tail_call.map;
10679
10680 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
10681 }
10682
1c2a088a
AS
10683 /* at this point all bpf functions were successfully JITed
10684 * now populate all bpf_calls with correct addresses and
10685 * run last pass of JIT
10686 */
f910cefa 10687 for (i = 0; i < env->subprog_cnt; i++) {
1c2a088a
AS
10688 insn = func[i]->insnsi;
10689 for (j = 0; j < func[i]->len; j++, insn++) {
10690 if (insn->code != (BPF_JMP | BPF_CALL) ||
10691 insn->src_reg != BPF_PSEUDO_CALL)
10692 continue;
10693 subprog = insn->off;
0d306c31
PB
10694 insn->imm = BPF_CAST_CALL(func[subprog]->bpf_func) -
10695 __bpf_call_base;
1c2a088a 10696 }
2162fed4
SD
10697
10698 /* we use the aux data to keep a list of the start addresses
10699 * of the JITed images for each function in the program
10700 *
10701 * for some architectures, such as powerpc64, the imm field
10702 * might not be large enough to hold the offset of the start
10703 * address of the callee's JITed image from __bpf_call_base
10704 *
10705 * in such cases, we can lookup the start address of a callee
10706 * by using its subprog id, available from the off field of
10707 * the call instruction, as an index for this list
10708 */
10709 func[i]->aux->func = func;
10710 func[i]->aux->func_cnt = env->subprog_cnt;
1c2a088a 10711 }
f910cefa 10712 for (i = 0; i < env->subprog_cnt; i++) {
1c2a088a
AS
10713 old_bpf_func = func[i]->bpf_func;
10714 tmp = bpf_int_jit_compile(func[i]);
10715 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
10716 verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
c7a89784 10717 err = -ENOTSUPP;
1c2a088a
AS
10718 goto out_free;
10719 }
10720 cond_resched();
10721 }
10722
10723 /* finally lock prog and jit images for all functions and
10724 * populate kallsysm
10725 */
f910cefa 10726 for (i = 0; i < env->subprog_cnt; i++) {
1c2a088a
AS
10727 bpf_prog_lock_ro(func[i]);
10728 bpf_prog_kallsyms_add(func[i]);
10729 }
7105e828
DB
10730
10731 /* Last step: make now unused interpreter insns from main
10732 * prog consistent for later dump requests, so they can
10733 * later look the same as if they were interpreted only.
10734 */
10735 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
7105e828
DB
10736 if (insn->code != (BPF_JMP | BPF_CALL) ||
10737 insn->src_reg != BPF_PSEUDO_CALL)
10738 continue;
10739 insn->off = env->insn_aux_data[i].call_imm;
10740 subprog = find_subprog(env, i + insn->off + 1);
dbecd738 10741 insn->imm = subprog;
7105e828
DB
10742 }
10743
1c2a088a
AS
10744 prog->jited = 1;
10745 prog->bpf_func = func[0]->bpf_func;
10746 prog->aux->func = func;
f910cefa 10747 prog->aux->func_cnt = env->subprog_cnt;
c454a46b 10748 bpf_prog_free_unused_jited_linfo(prog);
1c2a088a
AS
10749 return 0;
10750out_free:
a748c697
MF
10751 for (i = 0; i < env->subprog_cnt; i++) {
10752 if (!func[i])
10753 continue;
10754
10755 for (j = 0; j < func[i]->aux->size_poke_tab; j++) {
10756 map_ptr = func[i]->aux->poke_tab[j].tail_call.map;
10757 map_ptr->ops->map_poke_untrack(map_ptr, func[i]->aux);
10758 }
10759 bpf_jit_free(func[i]);
10760 }
1c2a088a 10761 kfree(func);
c7a89784 10762out_undo_insn:
1c2a088a
AS
10763 /* cleanup main prog to be interpreted */
10764 prog->jit_requested = 0;
10765 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
10766 if (insn->code != (BPF_JMP | BPF_CALL) ||
10767 insn->src_reg != BPF_PSEUDO_CALL)
10768 continue;
10769 insn->off = 0;
10770 insn->imm = env->insn_aux_data[i].call_imm;
10771 }
c454a46b 10772 bpf_prog_free_jited_linfo(prog);
1c2a088a
AS
10773 return err;
10774}
10775
1ea47e01
AS
10776static int fixup_call_args(struct bpf_verifier_env *env)
10777{
19d28fbd 10778#ifndef CONFIG_BPF_JIT_ALWAYS_ON
1ea47e01
AS
10779 struct bpf_prog *prog = env->prog;
10780 struct bpf_insn *insn = prog->insnsi;
10781 int i, depth;
19d28fbd 10782#endif
e4052d06 10783 int err = 0;
1ea47e01 10784
e4052d06
QM
10785 if (env->prog->jit_requested &&
10786 !bpf_prog_is_dev_bound(env->prog->aux)) {
19d28fbd
DM
10787 err = jit_subprogs(env);
10788 if (err == 0)
1c2a088a 10789 return 0;
c7a89784
DB
10790 if (err == -EFAULT)
10791 return err;
19d28fbd
DM
10792 }
10793#ifndef CONFIG_BPF_JIT_ALWAYS_ON
e411901c
MF
10794 if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
10795 /* When JIT fails the progs with bpf2bpf calls and tail_calls
10796 * have to be rejected, since interpreter doesn't support them yet.
10797 */
10798 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
10799 return -EINVAL;
10800 }
1ea47e01
AS
10801 for (i = 0; i < prog->len; i++, insn++) {
10802 if (insn->code != (BPF_JMP | BPF_CALL) ||
10803 insn->src_reg != BPF_PSEUDO_CALL)
10804 continue;
10805 depth = get_callee_stack_depth(env, insn, i);
10806 if (depth < 0)
10807 return depth;
10808 bpf_patch_call_args(insn, depth);
10809 }
19d28fbd
DM
10810 err = 0;
10811#endif
10812 return err;
1ea47e01
AS
10813}
10814
79741b3b 10815/* fixup insn->imm field of bpf_call instructions
81ed18ab 10816 * and inline eligible helpers as explicit sequence of BPF instructions
e245c5c6
AS
10817 *
10818 * this function is called after eBPF program passed verification
10819 */
79741b3b 10820static int fixup_bpf_calls(struct bpf_verifier_env *env)
e245c5c6 10821{
79741b3b 10822 struct bpf_prog *prog = env->prog;
d2e4c1e6 10823 bool expect_blinding = bpf_jit_blinding_enabled(prog);
79741b3b 10824 struct bpf_insn *insn = prog->insnsi;
e245c5c6 10825 const struct bpf_func_proto *fn;
79741b3b 10826 const int insn_cnt = prog->len;
09772d92 10827 const struct bpf_map_ops *ops;
c93552c4 10828 struct bpf_insn_aux_data *aux;
81ed18ab
AS
10829 struct bpf_insn insn_buf[16];
10830 struct bpf_prog *new_prog;
10831 struct bpf_map *map_ptr;
d2e4c1e6 10832 int i, ret, cnt, delta = 0;
e245c5c6 10833
79741b3b 10834 for (i = 0; i < insn_cnt; i++, insn++) {
f6b1b3bf
DB
10835 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
10836 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
10837 insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
68fda450 10838 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
f6b1b3bf
DB
10839 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
10840 struct bpf_insn mask_and_div[] = {
10841 BPF_MOV32_REG(insn->src_reg, insn->src_reg),
10842 /* Rx div 0 -> 0 */
10843 BPF_JMP_IMM(BPF_JNE, insn->src_reg, 0, 2),
10844 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
10845 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
10846 *insn,
10847 };
10848 struct bpf_insn mask_and_mod[] = {
10849 BPF_MOV32_REG(insn->src_reg, insn->src_reg),
10850 /* Rx mod 0 -> Rx */
10851 BPF_JMP_IMM(BPF_JEQ, insn->src_reg, 0, 1),
10852 *insn,
10853 };
10854 struct bpf_insn *patchlet;
10855
10856 if (insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
10857 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
10858 patchlet = mask_and_div + (is64 ? 1 : 0);
10859 cnt = ARRAY_SIZE(mask_and_div) - (is64 ? 1 : 0);
10860 } else {
10861 patchlet = mask_and_mod + (is64 ? 1 : 0);
10862 cnt = ARRAY_SIZE(mask_and_mod) - (is64 ? 1 : 0);
10863 }
10864
10865 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
68fda450
AS
10866 if (!new_prog)
10867 return -ENOMEM;
10868
10869 delta += cnt - 1;
10870 env->prog = prog = new_prog;
10871 insn = new_prog->insnsi + i + delta;
10872 continue;
10873 }
10874
e0cea7ce
DB
10875 if (BPF_CLASS(insn->code) == BPF_LD &&
10876 (BPF_MODE(insn->code) == BPF_ABS ||
10877 BPF_MODE(insn->code) == BPF_IND)) {
10878 cnt = env->ops->gen_ld_abs(insn, insn_buf);
10879 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
10880 verbose(env, "bpf verifier is misconfigured\n");
10881 return -EINVAL;
10882 }
10883
10884 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
10885 if (!new_prog)
10886 return -ENOMEM;
10887
10888 delta += cnt - 1;
10889 env->prog = prog = new_prog;
10890 insn = new_prog->insnsi + i + delta;
10891 continue;
10892 }
10893
979d63d5
DB
10894 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
10895 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
10896 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
10897 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
10898 struct bpf_insn insn_buf[16];
10899 struct bpf_insn *patch = &insn_buf[0];
10900 bool issrc, isneg;
10901 u32 off_reg;
10902
10903 aux = &env->insn_aux_data[i + delta];
3612af78
DB
10904 if (!aux->alu_state ||
10905 aux->alu_state == BPF_ALU_NON_POINTER)
979d63d5
DB
10906 continue;
10907
10908 isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
10909 issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
10910 BPF_ALU_SANITIZE_SRC;
10911
10912 off_reg = issrc ? insn->src_reg : insn->dst_reg;
10913 if (isneg)
10914 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
10915 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit - 1);
10916 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
10917 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
10918 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
10919 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
10920 if (issrc) {
10921 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX,
10922 off_reg);
10923 insn->src_reg = BPF_REG_AX;
10924 } else {
10925 *patch++ = BPF_ALU64_REG(BPF_AND, off_reg,
10926 BPF_REG_AX);
10927 }
10928 if (isneg)
10929 insn->code = insn->code == code_add ?
10930 code_sub : code_add;
10931 *patch++ = *insn;
10932 if (issrc && isneg)
10933 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
10934 cnt = patch - insn_buf;
10935
10936 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
10937 if (!new_prog)
10938 return -ENOMEM;
10939
10940 delta += cnt - 1;
10941 env->prog = prog = new_prog;
10942 insn = new_prog->insnsi + i + delta;
10943 continue;
10944 }
10945
79741b3b
AS
10946 if (insn->code != (BPF_JMP | BPF_CALL))
10947 continue;
cc8b0b92
AS
10948 if (insn->src_reg == BPF_PSEUDO_CALL)
10949 continue;
e245c5c6 10950
79741b3b
AS
10951 if (insn->imm == BPF_FUNC_get_route_realm)
10952 prog->dst_needed = 1;
10953 if (insn->imm == BPF_FUNC_get_prandom_u32)
10954 bpf_user_rnd_init_once();
9802d865
JB
10955 if (insn->imm == BPF_FUNC_override_return)
10956 prog->kprobe_override = 1;
79741b3b 10957 if (insn->imm == BPF_FUNC_tail_call) {
7b9f6da1
DM
10958 /* If we tail call into other programs, we
10959 * cannot make any assumptions since they can
10960 * be replaced dynamically during runtime in
10961 * the program array.
10962 */
10963 prog->cb_access = 1;
e411901c
MF
10964 if (!allow_tail_call_in_subprogs(env))
10965 prog->aux->stack_depth = MAX_BPF_STACK;
10966 prog->aux->max_pkt_offset = MAX_PACKET_OFF;
7b9f6da1 10967
79741b3b
AS
10968 /* mark bpf_tail_call as different opcode to avoid
10969 * conditional branch in the interpeter for every normal
10970 * call and to prevent accidental JITing by JIT compiler
10971 * that doesn't support bpf_tail_call yet
e245c5c6 10972 */
79741b3b 10973 insn->imm = 0;
71189fa9 10974 insn->code = BPF_JMP | BPF_TAIL_CALL;
b2157399 10975
c93552c4 10976 aux = &env->insn_aux_data[i + delta];
2c78ee89 10977 if (env->bpf_capable && !expect_blinding &&
cc52d914 10978 prog->jit_requested &&
d2e4c1e6
DB
10979 !bpf_map_key_poisoned(aux) &&
10980 !bpf_map_ptr_poisoned(aux) &&
10981 !bpf_map_ptr_unpriv(aux)) {
10982 struct bpf_jit_poke_descriptor desc = {
10983 .reason = BPF_POKE_REASON_TAIL_CALL,
10984 .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
10985 .tail_call.key = bpf_map_key_immediate(aux),
a748c697 10986 .insn_idx = i + delta,
d2e4c1e6
DB
10987 };
10988
10989 ret = bpf_jit_add_poke_descriptor(prog, &desc);
10990 if (ret < 0) {
10991 verbose(env, "adding tail call poke descriptor failed\n");
10992 return ret;
10993 }
10994
10995 insn->imm = ret + 1;
10996 continue;
10997 }
10998
c93552c4
DB
10999 if (!bpf_map_ptr_unpriv(aux))
11000 continue;
11001
b2157399
AS
11002 /* instead of changing every JIT dealing with tail_call
11003 * emit two extra insns:
11004 * if (index >= max_entries) goto out;
11005 * index &= array->index_mask;
11006 * to avoid out-of-bounds cpu speculation
11007 */
c93552c4 11008 if (bpf_map_ptr_poisoned(aux)) {
40950343 11009 verbose(env, "tail_call abusing map_ptr\n");
b2157399
AS
11010 return -EINVAL;
11011 }
c93552c4 11012
d2e4c1e6 11013 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
b2157399
AS
11014 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
11015 map_ptr->max_entries, 2);
11016 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
11017 container_of(map_ptr,
11018 struct bpf_array,
11019 map)->index_mask);
11020 insn_buf[2] = *insn;
11021 cnt = 3;
11022 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
11023 if (!new_prog)
11024 return -ENOMEM;
11025
11026 delta += cnt - 1;
11027 env->prog = prog = new_prog;
11028 insn = new_prog->insnsi + i + delta;
79741b3b
AS
11029 continue;
11030 }
e245c5c6 11031
89c63074 11032 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
09772d92
DB
11033 * and other inlining handlers are currently limited to 64 bit
11034 * only.
89c63074 11035 */
60b58afc 11036 if (prog->jit_requested && BITS_PER_LONG == 64 &&
09772d92
DB
11037 (insn->imm == BPF_FUNC_map_lookup_elem ||
11038 insn->imm == BPF_FUNC_map_update_elem ||
84430d42
DB
11039 insn->imm == BPF_FUNC_map_delete_elem ||
11040 insn->imm == BPF_FUNC_map_push_elem ||
11041 insn->imm == BPF_FUNC_map_pop_elem ||
11042 insn->imm == BPF_FUNC_map_peek_elem)) {
c93552c4
DB
11043 aux = &env->insn_aux_data[i + delta];
11044 if (bpf_map_ptr_poisoned(aux))
11045 goto patch_call_imm;
11046
d2e4c1e6 11047 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
09772d92
DB
11048 ops = map_ptr->ops;
11049 if (insn->imm == BPF_FUNC_map_lookup_elem &&
11050 ops->map_gen_lookup) {
11051 cnt = ops->map_gen_lookup(map_ptr, insn_buf);
4a8f87e6
DB
11052 if (cnt == -EOPNOTSUPP)
11053 goto patch_map_ops_generic;
11054 if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
09772d92
DB
11055 verbose(env, "bpf verifier is misconfigured\n");
11056 return -EINVAL;
11057 }
81ed18ab 11058
09772d92
DB
11059 new_prog = bpf_patch_insn_data(env, i + delta,
11060 insn_buf, cnt);
11061 if (!new_prog)
11062 return -ENOMEM;
81ed18ab 11063
09772d92
DB
11064 delta += cnt - 1;
11065 env->prog = prog = new_prog;
11066 insn = new_prog->insnsi + i + delta;
11067 continue;
11068 }
81ed18ab 11069
09772d92
DB
11070 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
11071 (void *(*)(struct bpf_map *map, void *key))NULL));
11072 BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
11073 (int (*)(struct bpf_map *map, void *key))NULL));
11074 BUILD_BUG_ON(!__same_type(ops->map_update_elem,
11075 (int (*)(struct bpf_map *map, void *key, void *value,
11076 u64 flags))NULL));
84430d42
DB
11077 BUILD_BUG_ON(!__same_type(ops->map_push_elem,
11078 (int (*)(struct bpf_map *map, void *value,
11079 u64 flags))NULL));
11080 BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
11081 (int (*)(struct bpf_map *map, void *value))NULL));
11082 BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
11083 (int (*)(struct bpf_map *map, void *value))NULL));
4a8f87e6 11084patch_map_ops_generic:
09772d92
DB
11085 switch (insn->imm) {
11086 case BPF_FUNC_map_lookup_elem:
11087 insn->imm = BPF_CAST_CALL(ops->map_lookup_elem) -
11088 __bpf_call_base;
11089 continue;
11090 case BPF_FUNC_map_update_elem:
11091 insn->imm = BPF_CAST_CALL(ops->map_update_elem) -
11092 __bpf_call_base;
11093 continue;
11094 case BPF_FUNC_map_delete_elem:
11095 insn->imm = BPF_CAST_CALL(ops->map_delete_elem) -
11096 __bpf_call_base;
11097 continue;
84430d42
DB
11098 case BPF_FUNC_map_push_elem:
11099 insn->imm = BPF_CAST_CALL(ops->map_push_elem) -
11100 __bpf_call_base;
11101 continue;
11102 case BPF_FUNC_map_pop_elem:
11103 insn->imm = BPF_CAST_CALL(ops->map_pop_elem) -
11104 __bpf_call_base;
11105 continue;
11106 case BPF_FUNC_map_peek_elem:
11107 insn->imm = BPF_CAST_CALL(ops->map_peek_elem) -
11108 __bpf_call_base;
11109 continue;
09772d92 11110 }
81ed18ab 11111
09772d92 11112 goto patch_call_imm;
81ed18ab
AS
11113 }
11114
5576b991
MKL
11115 if (prog->jit_requested && BITS_PER_LONG == 64 &&
11116 insn->imm == BPF_FUNC_jiffies64) {
11117 struct bpf_insn ld_jiffies_addr[2] = {
11118 BPF_LD_IMM64(BPF_REG_0,
11119 (unsigned long)&jiffies),
11120 };
11121
11122 insn_buf[0] = ld_jiffies_addr[0];
11123 insn_buf[1] = ld_jiffies_addr[1];
11124 insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
11125 BPF_REG_0, 0);
11126 cnt = 3;
11127
11128 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
11129 cnt);
11130 if (!new_prog)
11131 return -ENOMEM;
11132
11133 delta += cnt - 1;
11134 env->prog = prog = new_prog;
11135 insn = new_prog->insnsi + i + delta;
11136 continue;
11137 }
11138
81ed18ab 11139patch_call_imm:
5e43f899 11140 fn = env->ops->get_func_proto(insn->imm, env->prog);
79741b3b
AS
11141 /* all functions that have prototype and verifier allowed
11142 * programs to call them, must be real in-kernel functions
11143 */
11144 if (!fn->func) {
61bd5218
JK
11145 verbose(env,
11146 "kernel subsystem misconfigured func %s#%d\n",
79741b3b
AS
11147 func_id_name(insn->imm), insn->imm);
11148 return -EFAULT;
e245c5c6 11149 }
79741b3b 11150 insn->imm = fn->func - __bpf_call_base;
e245c5c6 11151 }
e245c5c6 11152
d2e4c1e6
DB
11153 /* Since poke tab is now finalized, publish aux to tracker. */
11154 for (i = 0; i < prog->aux->size_poke_tab; i++) {
11155 map_ptr = prog->aux->poke_tab[i].tail_call.map;
11156 if (!map_ptr->ops->map_poke_track ||
11157 !map_ptr->ops->map_poke_untrack ||
11158 !map_ptr->ops->map_poke_run) {
11159 verbose(env, "bpf verifier is misconfigured\n");
11160 return -EINVAL;
11161 }
11162
11163 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
11164 if (ret < 0) {
11165 verbose(env, "tracking tail call prog failed\n");
11166 return ret;
11167 }
11168 }
11169
79741b3b
AS
11170 return 0;
11171}
e245c5c6 11172
58e2af8b 11173static void free_states(struct bpf_verifier_env *env)
f1bca824 11174{
58e2af8b 11175 struct bpf_verifier_state_list *sl, *sln;
f1bca824
AS
11176 int i;
11177
9f4686c4
AS
11178 sl = env->free_list;
11179 while (sl) {
11180 sln = sl->next;
11181 free_verifier_state(&sl->state, false);
11182 kfree(sl);
11183 sl = sln;
11184 }
51c39bb1 11185 env->free_list = NULL;
9f4686c4 11186
f1bca824
AS
11187 if (!env->explored_states)
11188 return;
11189
dc2a4ebc 11190 for (i = 0; i < state_htab_size(env); i++) {
f1bca824
AS
11191 sl = env->explored_states[i];
11192
a8f500af
AS
11193 while (sl) {
11194 sln = sl->next;
11195 free_verifier_state(&sl->state, false);
11196 kfree(sl);
11197 sl = sln;
11198 }
51c39bb1 11199 env->explored_states[i] = NULL;
f1bca824 11200 }
51c39bb1 11201}
f1bca824 11202
51c39bb1
AS
11203/* The verifier is using insn_aux_data[] to store temporary data during
11204 * verification and to store information for passes that run after the
11205 * verification like dead code sanitization. do_check_common() for subprogram N
11206 * may analyze many other subprograms. sanitize_insn_aux_data() clears all
11207 * temporary data after do_check_common() finds that subprogram N cannot be
11208 * verified independently. pass_cnt counts the number of times
11209 * do_check_common() was run and insn->aux->seen tells the pass number
11210 * insn_aux_data was touched. These variables are compared to clear temporary
11211 * data from failed pass. For testing and experiments do_check_common() can be
11212 * run multiple times even when prior attempt to verify is unsuccessful.
11213 */
11214static void sanitize_insn_aux_data(struct bpf_verifier_env *env)
11215{
11216 struct bpf_insn *insn = env->prog->insnsi;
11217 struct bpf_insn_aux_data *aux;
11218 int i, class;
11219
11220 for (i = 0; i < env->prog->len; i++) {
11221 class = BPF_CLASS(insn[i].code);
11222 if (class != BPF_LDX && class != BPF_STX)
11223 continue;
11224 aux = &env->insn_aux_data[i];
11225 if (aux->seen != env->pass_cnt)
11226 continue;
11227 memset(aux, 0, offsetof(typeof(*aux), orig_idx));
11228 }
f1bca824
AS
11229}
11230
51c39bb1
AS
11231static int do_check_common(struct bpf_verifier_env *env, int subprog)
11232{
6f8a57cc 11233 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
51c39bb1
AS
11234 struct bpf_verifier_state *state;
11235 struct bpf_reg_state *regs;
11236 int ret, i;
11237
11238 env->prev_linfo = NULL;
11239 env->pass_cnt++;
11240
11241 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
11242 if (!state)
11243 return -ENOMEM;
11244 state->curframe = 0;
11245 state->speculative = false;
11246 state->branches = 1;
11247 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
11248 if (!state->frame[0]) {
11249 kfree(state);
11250 return -ENOMEM;
11251 }
11252 env->cur_state = state;
11253 init_func_state(env, state->frame[0],
11254 BPF_MAIN_FUNC /* callsite */,
11255 0 /* frameno */,
11256 subprog);
11257
11258 regs = state->frame[state->curframe]->regs;
be8704ff 11259 if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
51c39bb1
AS
11260 ret = btf_prepare_func_args(env, subprog, regs);
11261 if (ret)
11262 goto out;
11263 for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
11264 if (regs[i].type == PTR_TO_CTX)
11265 mark_reg_known_zero(env, regs, i);
11266 else if (regs[i].type == SCALAR_VALUE)
11267 mark_reg_unknown(env, regs, i);
11268 }
11269 } else {
11270 /* 1st arg to a function */
11271 regs[BPF_REG_1].type = PTR_TO_CTX;
11272 mark_reg_known_zero(env, regs, BPF_REG_1);
11273 ret = btf_check_func_arg_match(env, subprog, regs);
11274 if (ret == -EFAULT)
11275 /* unlikely verifier bug. abort.
11276 * ret == 0 and ret < 0 are sadly acceptable for
11277 * main() function due to backward compatibility.
11278 * Like socket filter program may be written as:
11279 * int bpf_prog(struct pt_regs *ctx)
11280 * and never dereference that ctx in the program.
11281 * 'struct pt_regs' is a type mismatch for socket
11282 * filter that should be using 'struct __sk_buff'.
11283 */
11284 goto out;
11285 }
11286
11287 ret = do_check(env);
11288out:
f59bbfc2
AS
11289 /* check for NULL is necessary, since cur_state can be freed inside
11290 * do_check() under memory pressure.
11291 */
11292 if (env->cur_state) {
11293 free_verifier_state(env->cur_state, true);
11294 env->cur_state = NULL;
11295 }
6f8a57cc
AN
11296 while (!pop_stack(env, NULL, NULL, false));
11297 if (!ret && pop_log)
11298 bpf_vlog_reset(&env->log, 0);
51c39bb1
AS
11299 free_states(env);
11300 if (ret)
11301 /* clean aux data in case subprog was rejected */
11302 sanitize_insn_aux_data(env);
11303 return ret;
11304}
11305
11306/* Verify all global functions in a BPF program one by one based on their BTF.
11307 * All global functions must pass verification. Otherwise the whole program is rejected.
11308 * Consider:
11309 * int bar(int);
11310 * int foo(int f)
11311 * {
11312 * return bar(f);
11313 * }
11314 * int bar(int b)
11315 * {
11316 * ...
11317 * }
11318 * foo() will be verified first for R1=any_scalar_value. During verification it
11319 * will be assumed that bar() already verified successfully and call to bar()
11320 * from foo() will be checked for type match only. Later bar() will be verified
11321 * independently to check that it's safe for R1=any_scalar_value.
11322 */
11323static int do_check_subprogs(struct bpf_verifier_env *env)
11324{
11325 struct bpf_prog_aux *aux = env->prog->aux;
11326 int i, ret;
11327
11328 if (!aux->func_info)
11329 return 0;
11330
11331 for (i = 1; i < env->subprog_cnt; i++) {
11332 if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
11333 continue;
11334 env->insn_idx = env->subprog_info[i].start;
11335 WARN_ON_ONCE(env->insn_idx == 0);
11336 ret = do_check_common(env, i);
11337 if (ret) {
11338 return ret;
11339 } else if (env->log.level & BPF_LOG_LEVEL) {
11340 verbose(env,
11341 "Func#%d is safe for any args that match its prototype\n",
11342 i);
11343 }
11344 }
11345 return 0;
11346}
11347
11348static int do_check_main(struct bpf_verifier_env *env)
11349{
11350 int ret;
11351
11352 env->insn_idx = 0;
11353 ret = do_check_common(env, 0);
11354 if (!ret)
11355 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
11356 return ret;
11357}
11358
11359
06ee7115
AS
11360static void print_verification_stats(struct bpf_verifier_env *env)
11361{
11362 int i;
11363
11364 if (env->log.level & BPF_LOG_STATS) {
11365 verbose(env, "verification time %lld usec\n",
11366 div_u64(env->verification_time, 1000));
11367 verbose(env, "stack depth ");
11368 for (i = 0; i < env->subprog_cnt; i++) {
11369 u32 depth = env->subprog_info[i].stack_depth;
11370
11371 verbose(env, "%d", depth);
11372 if (i + 1 < env->subprog_cnt)
11373 verbose(env, "+");
11374 }
11375 verbose(env, "\n");
11376 }
11377 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
11378 "total_states %d peak_states %d mark_read %d\n",
11379 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
11380 env->max_states_per_insn, env->total_states,
11381 env->peak_states, env->longest_mark_read_walk);
f1bca824
AS
11382}
11383
27ae7997
MKL
11384static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
11385{
11386 const struct btf_type *t, *func_proto;
11387 const struct bpf_struct_ops *st_ops;
11388 const struct btf_member *member;
11389 struct bpf_prog *prog = env->prog;
11390 u32 btf_id, member_idx;
11391 const char *mname;
11392
11393 btf_id = prog->aux->attach_btf_id;
11394 st_ops = bpf_struct_ops_find(btf_id);
11395 if (!st_ops) {
11396 verbose(env, "attach_btf_id %u is not a supported struct\n",
11397 btf_id);
11398 return -ENOTSUPP;
11399 }
11400
11401 t = st_ops->type;
11402 member_idx = prog->expected_attach_type;
11403 if (member_idx >= btf_type_vlen(t)) {
11404 verbose(env, "attach to invalid member idx %u of struct %s\n",
11405 member_idx, st_ops->name);
11406 return -EINVAL;
11407 }
11408
11409 member = &btf_type_member(t)[member_idx];
11410 mname = btf_name_by_offset(btf_vmlinux, member->name_off);
11411 func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
11412 NULL);
11413 if (!func_proto) {
11414 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
11415 mname, member_idx, st_ops->name);
11416 return -EINVAL;
11417 }
11418
11419 if (st_ops->check_member) {
11420 int err = st_ops->check_member(t, member);
11421
11422 if (err) {
11423 verbose(env, "attach to unsupported member %s of struct %s\n",
11424 mname, st_ops->name);
11425 return err;
11426 }
11427 }
11428
11429 prog->aux->attach_func_proto = func_proto;
11430 prog->aux->attach_func_name = mname;
11431 env->ops = st_ops->verifier_ops;
11432
11433 return 0;
11434}
6ba43b76
KS
11435#define SECURITY_PREFIX "security_"
11436
f7b12b6f 11437static int check_attach_modify_return(unsigned long addr, const char *func_name)
6ba43b76 11438{
69191754 11439 if (within_error_injection_list(addr) ||
f7b12b6f 11440 !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
6ba43b76 11441 return 0;
6ba43b76 11442
6ba43b76
KS
11443 return -EINVAL;
11444}
27ae7997 11445
1e6c62a8
AS
11446/* non exhaustive list of sleepable bpf_lsm_*() functions */
11447BTF_SET_START(btf_sleepable_lsm_hooks)
11448#ifdef CONFIG_BPF_LSM
1e6c62a8 11449BTF_ID(func, bpf_lsm_bprm_committed_creds)
29523c5e
AS
11450#else
11451BTF_ID_UNUSED
1e6c62a8
AS
11452#endif
11453BTF_SET_END(btf_sleepable_lsm_hooks)
11454
11455static int check_sleepable_lsm_hook(u32 btf_id)
11456{
11457 return btf_id_set_contains(&btf_sleepable_lsm_hooks, btf_id);
11458}
11459
11460/* list of non-sleepable functions that are otherwise on
11461 * ALLOW_ERROR_INJECTION list
11462 */
11463BTF_SET_START(btf_non_sleepable_error_inject)
11464/* Three functions below can be called from sleepable and non-sleepable context.
11465 * Assume non-sleepable from bpf safety point of view.
11466 */
11467BTF_ID(func, __add_to_page_cache_locked)
11468BTF_ID(func, should_fail_alloc_page)
11469BTF_ID(func, should_failslab)
11470BTF_SET_END(btf_non_sleepable_error_inject)
11471
11472static int check_non_sleepable_error_inject(u32 btf_id)
11473{
11474 return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
11475}
11476
f7b12b6f
THJ
11477int bpf_check_attach_target(struct bpf_verifier_log *log,
11478 const struct bpf_prog *prog,
11479 const struct bpf_prog *tgt_prog,
11480 u32 btf_id,
11481 struct bpf_attach_target_info *tgt_info)
38207291 11482{
be8704ff 11483 bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
f1b9509c 11484 const char prefix[] = "btf_trace_";
5b92a28a 11485 int ret = 0, subprog = -1, i;
38207291 11486 const struct btf_type *t;
5b92a28a 11487 bool conservative = true;
38207291 11488 const char *tname;
5b92a28a 11489 struct btf *btf;
f7b12b6f 11490 long addr = 0;
38207291 11491
f1b9509c 11492 if (!btf_id) {
efc68158 11493 bpf_log(log, "Tracing programs must provide btf_id\n");
f1b9509c
AS
11494 return -EINVAL;
11495 }
f7b12b6f 11496 btf = tgt_prog ? tgt_prog->aux->btf : btf_vmlinux;
5b92a28a 11497 if (!btf) {
efc68158 11498 bpf_log(log,
5b92a28a
AS
11499 "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
11500 return -EINVAL;
11501 }
11502 t = btf_type_by_id(btf, btf_id);
f1b9509c 11503 if (!t) {
efc68158 11504 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
f1b9509c
AS
11505 return -EINVAL;
11506 }
5b92a28a 11507 tname = btf_name_by_offset(btf, t->name_off);
f1b9509c 11508 if (!tname) {
efc68158 11509 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
f1b9509c
AS
11510 return -EINVAL;
11511 }
5b92a28a
AS
11512 if (tgt_prog) {
11513 struct bpf_prog_aux *aux = tgt_prog->aux;
11514
11515 for (i = 0; i < aux->func_info_cnt; i++)
11516 if (aux->func_info[i].type_id == btf_id) {
11517 subprog = i;
11518 break;
11519 }
11520 if (subprog == -1) {
efc68158 11521 bpf_log(log, "Subprog %s doesn't exist\n", tname);
5b92a28a
AS
11522 return -EINVAL;
11523 }
11524 conservative = aux->func_info_aux[subprog].unreliable;
be8704ff
AS
11525 if (prog_extension) {
11526 if (conservative) {
efc68158 11527 bpf_log(log,
be8704ff
AS
11528 "Cannot replace static functions\n");
11529 return -EINVAL;
11530 }
11531 if (!prog->jit_requested) {
efc68158 11532 bpf_log(log,
be8704ff
AS
11533 "Extension programs should be JITed\n");
11534 return -EINVAL;
11535 }
be8704ff
AS
11536 }
11537 if (!tgt_prog->jited) {
efc68158 11538 bpf_log(log, "Can attach to only JITed progs\n");
be8704ff
AS
11539 return -EINVAL;
11540 }
11541 if (tgt_prog->type == prog->type) {
11542 /* Cannot fentry/fexit another fentry/fexit program.
11543 * Cannot attach program extension to another extension.
11544 * It's ok to attach fentry/fexit to extension program.
11545 */
efc68158 11546 bpf_log(log, "Cannot recursively attach\n");
be8704ff
AS
11547 return -EINVAL;
11548 }
11549 if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
11550 prog_extension &&
11551 (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
11552 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
11553 /* Program extensions can extend all program types
11554 * except fentry/fexit. The reason is the following.
11555 * The fentry/fexit programs are used for performance
11556 * analysis, stats and can be attached to any program
11557 * type except themselves. When extension program is
11558 * replacing XDP function it is necessary to allow
11559 * performance analysis of all functions. Both original
11560 * XDP program and its program extension. Hence
11561 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
11562 * allowed. If extending of fentry/fexit was allowed it
11563 * would be possible to create long call chain
11564 * fentry->extension->fentry->extension beyond
11565 * reasonable stack size. Hence extending fentry is not
11566 * allowed.
11567 */
efc68158 11568 bpf_log(log, "Cannot extend fentry/fexit\n");
be8704ff
AS
11569 return -EINVAL;
11570 }
5b92a28a 11571 } else {
be8704ff 11572 if (prog_extension) {
efc68158 11573 bpf_log(log, "Cannot replace kernel functions\n");
be8704ff
AS
11574 return -EINVAL;
11575 }
5b92a28a 11576 }
f1b9509c
AS
11577
11578 switch (prog->expected_attach_type) {
11579 case BPF_TRACE_RAW_TP:
5b92a28a 11580 if (tgt_prog) {
efc68158 11581 bpf_log(log,
5b92a28a
AS
11582 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
11583 return -EINVAL;
11584 }
38207291 11585 if (!btf_type_is_typedef(t)) {
efc68158 11586 bpf_log(log, "attach_btf_id %u is not a typedef\n",
38207291
MKL
11587 btf_id);
11588 return -EINVAL;
11589 }
f1b9509c 11590 if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
efc68158 11591 bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
38207291
MKL
11592 btf_id, tname);
11593 return -EINVAL;
11594 }
11595 tname += sizeof(prefix) - 1;
5b92a28a 11596 t = btf_type_by_id(btf, t->type);
38207291
MKL
11597 if (!btf_type_is_ptr(t))
11598 /* should never happen in valid vmlinux build */
11599 return -EINVAL;
5b92a28a 11600 t = btf_type_by_id(btf, t->type);
38207291
MKL
11601 if (!btf_type_is_func_proto(t))
11602 /* should never happen in valid vmlinux build */
11603 return -EINVAL;
11604
f7b12b6f 11605 break;
15d83c4d
YS
11606 case BPF_TRACE_ITER:
11607 if (!btf_type_is_func(t)) {
efc68158 11608 bpf_log(log, "attach_btf_id %u is not a function\n",
15d83c4d
YS
11609 btf_id);
11610 return -EINVAL;
11611 }
11612 t = btf_type_by_id(btf, t->type);
11613 if (!btf_type_is_func_proto(t))
11614 return -EINVAL;
f7b12b6f
THJ
11615 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
11616 if (ret)
11617 return ret;
11618 break;
be8704ff
AS
11619 default:
11620 if (!prog_extension)
11621 return -EINVAL;
df561f66 11622 fallthrough;
ae240823 11623 case BPF_MODIFY_RETURN:
9e4e01df 11624 case BPF_LSM_MAC:
fec56f58
AS
11625 case BPF_TRACE_FENTRY:
11626 case BPF_TRACE_FEXIT:
11627 if (!btf_type_is_func(t)) {
efc68158 11628 bpf_log(log, "attach_btf_id %u is not a function\n",
fec56f58
AS
11629 btf_id);
11630 return -EINVAL;
11631 }
be8704ff 11632 if (prog_extension &&
efc68158 11633 btf_check_type_match(log, prog, btf, t))
be8704ff 11634 return -EINVAL;
5b92a28a 11635 t = btf_type_by_id(btf, t->type);
fec56f58
AS
11636 if (!btf_type_is_func_proto(t))
11637 return -EINVAL;
f7b12b6f 11638
4a1e7c0c
THJ
11639 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
11640 (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
11641 prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
11642 return -EINVAL;
11643
f7b12b6f 11644 if (tgt_prog && conservative)
5b92a28a 11645 t = NULL;
f7b12b6f
THJ
11646
11647 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
fec56f58 11648 if (ret < 0)
f7b12b6f
THJ
11649 return ret;
11650
5b92a28a 11651 if (tgt_prog) {
e9eeec58
YS
11652 if (subprog == 0)
11653 addr = (long) tgt_prog->bpf_func;
11654 else
11655 addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
5b92a28a
AS
11656 } else {
11657 addr = kallsyms_lookup_name(tname);
11658 if (!addr) {
efc68158 11659 bpf_log(log,
5b92a28a
AS
11660 "The address of function %s cannot be found\n",
11661 tname);
f7b12b6f 11662 return -ENOENT;
5b92a28a 11663 }
fec56f58 11664 }
18644cec 11665
1e6c62a8
AS
11666 if (prog->aux->sleepable) {
11667 ret = -EINVAL;
11668 switch (prog->type) {
11669 case BPF_PROG_TYPE_TRACING:
11670 /* fentry/fexit/fmod_ret progs can be sleepable only if they are
11671 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
11672 */
11673 if (!check_non_sleepable_error_inject(btf_id) &&
11674 within_error_injection_list(addr))
11675 ret = 0;
11676 break;
11677 case BPF_PROG_TYPE_LSM:
11678 /* LSM progs check that they are attached to bpf_lsm_*() funcs.
11679 * Only some of them are sleepable.
11680 */
11681 if (check_sleepable_lsm_hook(btf_id))
11682 ret = 0;
11683 break;
11684 default:
11685 break;
11686 }
f7b12b6f
THJ
11687 if (ret) {
11688 bpf_log(log, "%s is not sleepable\n", tname);
11689 return ret;
11690 }
1e6c62a8 11691 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
1af9270e 11692 if (tgt_prog) {
efc68158 11693 bpf_log(log, "can't modify return codes of BPF programs\n");
f7b12b6f
THJ
11694 return -EINVAL;
11695 }
11696 ret = check_attach_modify_return(addr, tname);
11697 if (ret) {
11698 bpf_log(log, "%s() is not modifiable\n", tname);
11699 return ret;
1af9270e 11700 }
18644cec 11701 }
f7b12b6f
THJ
11702
11703 break;
11704 }
11705 tgt_info->tgt_addr = addr;
11706 tgt_info->tgt_name = tname;
11707 tgt_info->tgt_type = t;
11708 return 0;
11709}
11710
11711static int check_attach_btf_id(struct bpf_verifier_env *env)
11712{
11713 struct bpf_prog *prog = env->prog;
3aac1ead 11714 struct bpf_prog *tgt_prog = prog->aux->dst_prog;
f7b12b6f
THJ
11715 struct bpf_attach_target_info tgt_info = {};
11716 u32 btf_id = prog->aux->attach_btf_id;
11717 struct bpf_trampoline *tr;
11718 int ret;
11719 u64 key;
11720
11721 if (prog->aux->sleepable && prog->type != BPF_PROG_TYPE_TRACING &&
11722 prog->type != BPF_PROG_TYPE_LSM) {
11723 verbose(env, "Only fentry/fexit/fmod_ret and lsm programs can be sleepable\n");
11724 return -EINVAL;
11725 }
11726
11727 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
11728 return check_struct_ops_btf_id(env);
11729
11730 if (prog->type != BPF_PROG_TYPE_TRACING &&
11731 prog->type != BPF_PROG_TYPE_LSM &&
11732 prog->type != BPF_PROG_TYPE_EXT)
11733 return 0;
11734
11735 ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
11736 if (ret)
fec56f58 11737 return ret;
f7b12b6f
THJ
11738
11739 if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
3aac1ead
THJ
11740 /* to make freplace equivalent to their targets, they need to
11741 * inherit env->ops and expected_attach_type for the rest of the
11742 * verification
11743 */
f7b12b6f
THJ
11744 env->ops = bpf_verifier_ops[tgt_prog->type];
11745 prog->expected_attach_type = tgt_prog->expected_attach_type;
11746 }
11747
11748 /* store info about the attachment target that will be used later */
11749 prog->aux->attach_func_proto = tgt_info.tgt_type;
11750 prog->aux->attach_func_name = tgt_info.tgt_name;
11751
4a1e7c0c
THJ
11752 if (tgt_prog) {
11753 prog->aux->saved_dst_prog_type = tgt_prog->type;
11754 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
11755 }
11756
f7b12b6f
THJ
11757 if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
11758 prog->aux->attach_btf_trace = true;
11759 return 0;
11760 } else if (prog->expected_attach_type == BPF_TRACE_ITER) {
11761 if (!bpf_iter_prog_supported(prog))
11762 return -EINVAL;
11763 return 0;
11764 }
11765
11766 if (prog->type == BPF_PROG_TYPE_LSM) {
11767 ret = bpf_lsm_verify_prog(&env->log, prog);
11768 if (ret < 0)
11769 return ret;
38207291 11770 }
f7b12b6f
THJ
11771
11772 key = bpf_trampoline_compute_key(tgt_prog, btf_id);
11773 tr = bpf_trampoline_get(key, &tgt_info);
11774 if (!tr)
11775 return -ENOMEM;
11776
3aac1ead 11777 prog->aux->dst_trampoline = tr;
f7b12b6f 11778 return 0;
38207291
MKL
11779}
11780
76654e67
AM
11781struct btf *bpf_get_btf_vmlinux(void)
11782{
11783 if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
11784 mutex_lock(&bpf_verifier_lock);
11785 if (!btf_vmlinux)
11786 btf_vmlinux = btf_parse_vmlinux();
11787 mutex_unlock(&bpf_verifier_lock);
11788 }
11789 return btf_vmlinux;
11790}
11791
838e9690
YS
11792int bpf_check(struct bpf_prog **prog, union bpf_attr *attr,
11793 union bpf_attr __user *uattr)
51580e79 11794{
06ee7115 11795 u64 start_time = ktime_get_ns();
58e2af8b 11796 struct bpf_verifier_env *env;
b9193c1b 11797 struct bpf_verifier_log *log;
9e4c24e7 11798 int i, len, ret = -EINVAL;
e2ae4ca2 11799 bool is_priv;
51580e79 11800
eba0c929
AB
11801 /* no program is valid */
11802 if (ARRAY_SIZE(bpf_verifier_ops) == 0)
11803 return -EINVAL;
11804
58e2af8b 11805 /* 'struct bpf_verifier_env' can be global, but since it's not small,
cbd35700
AS
11806 * allocate/free it every time bpf_check() is called
11807 */
58e2af8b 11808 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
cbd35700
AS
11809 if (!env)
11810 return -ENOMEM;
61bd5218 11811 log = &env->log;
cbd35700 11812
9e4c24e7 11813 len = (*prog)->len;
fad953ce 11814 env->insn_aux_data =
9e4c24e7 11815 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
3df126f3
JK
11816 ret = -ENOMEM;
11817 if (!env->insn_aux_data)
11818 goto err_free_env;
9e4c24e7
JK
11819 for (i = 0; i < len; i++)
11820 env->insn_aux_data[i].orig_idx = i;
9bac3d6d 11821 env->prog = *prog;
00176a34 11822 env->ops = bpf_verifier_ops[env->prog->type];
2c78ee89 11823 is_priv = bpf_capable();
0246e64d 11824
76654e67 11825 bpf_get_btf_vmlinux();
8580ac94 11826
cbd35700 11827 /* grab the mutex to protect few globals used by verifier */
45a73c17
AS
11828 if (!is_priv)
11829 mutex_lock(&bpf_verifier_lock);
cbd35700
AS
11830
11831 if (attr->log_level || attr->log_buf || attr->log_size) {
11832 /* user requested verbose verifier output
11833 * and supplied buffer to store the verification trace
11834 */
e7bf8249
JK
11835 log->level = attr->log_level;
11836 log->ubuf = (char __user *) (unsigned long) attr->log_buf;
11837 log->len_total = attr->log_size;
cbd35700
AS
11838
11839 ret = -EINVAL;
e7bf8249 11840 /* log attributes have to be sane */
7a9f5c65 11841 if (log->len_total < 128 || log->len_total > UINT_MAX >> 2 ||
06ee7115 11842 !log->level || !log->ubuf || log->level & ~BPF_LOG_MASK)
3df126f3 11843 goto err_unlock;
cbd35700 11844 }
1ad2f583 11845
8580ac94
AS
11846 if (IS_ERR(btf_vmlinux)) {
11847 /* Either gcc or pahole or kernel are broken. */
11848 verbose(env, "in-kernel BTF is malformed\n");
11849 ret = PTR_ERR(btf_vmlinux);
38207291 11850 goto skip_full_check;
8580ac94
AS
11851 }
11852
1ad2f583
DB
11853 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
11854 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
e07b98d9 11855 env->strict_alignment = true;
e9ee9efc
DM
11856 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
11857 env->strict_alignment = false;
cbd35700 11858
2c78ee89 11859 env->allow_ptr_leaks = bpf_allow_ptr_leaks();
41c48f3a 11860 env->allow_ptr_to_map_access = bpf_allow_ptr_to_map_access();
2c78ee89
AS
11861 env->bypass_spec_v1 = bpf_bypass_spec_v1();
11862 env->bypass_spec_v4 = bpf_bypass_spec_v4();
11863 env->bpf_capable = bpf_capable();
e2ae4ca2 11864
10d274e8
AS
11865 if (is_priv)
11866 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
11867
cae1927c 11868 if (bpf_prog_is_dev_bound(env->prog->aux)) {
a40a2632 11869 ret = bpf_prog_offload_verifier_prep(env->prog);
ab3f0063 11870 if (ret)
f4e3ec0d 11871 goto skip_full_check;
ab3f0063
JK
11872 }
11873
dc2a4ebc 11874 env->explored_states = kvcalloc(state_htab_size(env),
58e2af8b 11875 sizeof(struct bpf_verifier_state_list *),
f1bca824
AS
11876 GFP_USER);
11877 ret = -ENOMEM;
11878 if (!env->explored_states)
11879 goto skip_full_check;
11880
d9762e84 11881 ret = check_subprogs(env);
475fb78f
AS
11882 if (ret < 0)
11883 goto skip_full_check;
11884
c454a46b 11885 ret = check_btf_info(env, attr, uattr);
838e9690
YS
11886 if (ret < 0)
11887 goto skip_full_check;
11888
be8704ff
AS
11889 ret = check_attach_btf_id(env);
11890 if (ret)
11891 goto skip_full_check;
11892
4976b718
HL
11893 ret = resolve_pseudo_ldimm64(env);
11894 if (ret < 0)
11895 goto skip_full_check;
11896
d9762e84
MKL
11897 ret = check_cfg(env);
11898 if (ret < 0)
11899 goto skip_full_check;
11900
51c39bb1
AS
11901 ret = do_check_subprogs(env);
11902 ret = ret ?: do_check_main(env);
cbd35700 11903
c941ce9c
QM
11904 if (ret == 0 && bpf_prog_is_dev_bound(env->prog->aux))
11905 ret = bpf_prog_offload_finalize(env);
11906
0246e64d 11907skip_full_check:
51c39bb1 11908 kvfree(env->explored_states);
0246e64d 11909
c131187d 11910 if (ret == 0)
9b38c405 11911 ret = check_max_stack_depth(env);
c131187d 11912
9b38c405 11913 /* instruction rewrites happen after this point */
e2ae4ca2
JK
11914 if (is_priv) {
11915 if (ret == 0)
11916 opt_hard_wire_dead_code_branches(env);
52875a04
JK
11917 if (ret == 0)
11918 ret = opt_remove_dead_code(env);
a1b14abc
JK
11919 if (ret == 0)
11920 ret = opt_remove_nops(env);
52875a04
JK
11921 } else {
11922 if (ret == 0)
11923 sanitize_dead_code(env);
e2ae4ca2
JK
11924 }
11925
9bac3d6d
AS
11926 if (ret == 0)
11927 /* program is valid, convert *(u32*)(ctx + off) accesses */
11928 ret = convert_ctx_accesses(env);
11929
e245c5c6 11930 if (ret == 0)
79741b3b 11931 ret = fixup_bpf_calls(env);
e245c5c6 11932
a4b1d3c1
JW
11933 /* do 32-bit optimization after insn patching has done so those patched
11934 * insns could be handled correctly.
11935 */
d6c2308c
JW
11936 if (ret == 0 && !bpf_prog_is_dev_bound(env->prog->aux)) {
11937 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
11938 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
11939 : false;
a4b1d3c1
JW
11940 }
11941
1ea47e01
AS
11942 if (ret == 0)
11943 ret = fixup_call_args(env);
11944
06ee7115
AS
11945 env->verification_time = ktime_get_ns() - start_time;
11946 print_verification_stats(env);
11947
a2a7d570 11948 if (log->level && bpf_verifier_log_full(log))
cbd35700 11949 ret = -ENOSPC;
a2a7d570 11950 if (log->level && !log->ubuf) {
cbd35700 11951 ret = -EFAULT;
a2a7d570 11952 goto err_release_maps;
cbd35700
AS
11953 }
11954
0246e64d
AS
11955 if (ret == 0 && env->used_map_cnt) {
11956 /* if program passed verifier, update used_maps in bpf_prog_info */
9bac3d6d
AS
11957 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
11958 sizeof(env->used_maps[0]),
11959 GFP_KERNEL);
0246e64d 11960
9bac3d6d 11961 if (!env->prog->aux->used_maps) {
0246e64d 11962 ret = -ENOMEM;
a2a7d570 11963 goto err_release_maps;
0246e64d
AS
11964 }
11965
9bac3d6d 11966 memcpy(env->prog->aux->used_maps, env->used_maps,
0246e64d 11967 sizeof(env->used_maps[0]) * env->used_map_cnt);
9bac3d6d 11968 env->prog->aux->used_map_cnt = env->used_map_cnt;
0246e64d
AS
11969
11970 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
11971 * bpf_ld_imm64 instructions
11972 */
11973 convert_pseudo_ld_imm64(env);
11974 }
cbd35700 11975
ba64e7d8
YS
11976 if (ret == 0)
11977 adjust_btf_func(env);
11978
a2a7d570 11979err_release_maps:
9bac3d6d 11980 if (!env->prog->aux->used_maps)
0246e64d 11981 /* if we didn't copy map pointers into bpf_prog_info, release
ab7f5bf0 11982 * them now. Otherwise free_used_maps() will release them.
0246e64d
AS
11983 */
11984 release_maps(env);
03f87c0b
THJ
11985
11986 /* extension progs temporarily inherit the attach_type of their targets
11987 for verification purposes, so set it back to zero before returning
11988 */
11989 if (env->prog->type == BPF_PROG_TYPE_EXT)
11990 env->prog->expected_attach_type = 0;
11991
9bac3d6d 11992 *prog = env->prog;
3df126f3 11993err_unlock:
45a73c17
AS
11994 if (!is_priv)
11995 mutex_unlock(&bpf_verifier_lock);
3df126f3
JK
11996 vfree(env->insn_aux_data);
11997err_free_env:
11998 kfree(env);
51580e79
AS
11999 return ret;
12000}