]> git.proxmox.com Git - mirror_ubuntu-hirsute-kernel.git/blame - kernel/bpf/verifier.c
UBUNTU: SAUCE: Revert "UBUNTU: SAUCE: bpf: verifier: fix ALU32 bounds tracking with...
[mirror_ubuntu-hirsute-kernel.git] / kernel / bpf / verifier.c
CommitLineData
5b497af4 1// SPDX-License-Identifier: GPL-2.0-only
51580e79 2/* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com
969bf05e 3 * Copyright (c) 2016 Facebook
fd978bf7 4 * Copyright (c) 2018 Covalent IO, Inc. http://covalent.io
51580e79 5 */
838e9690 6#include <uapi/linux/btf.h>
51580e79
AS
7#include <linux/kernel.h>
8#include <linux/types.h>
9#include <linux/slab.h>
10#include <linux/bpf.h>
838e9690 11#include <linux/btf.h>
58e2af8b 12#include <linux/bpf_verifier.h>
51580e79
AS
13#include <linux/filter.h>
14#include <net/netlink.h>
15#include <linux/file.h>
16#include <linux/vmalloc.h>
ebb676da 17#include <linux/stringify.h>
cc8b0b92
AS
18#include <linux/bsearch.h>
19#include <linux/sort.h>
c195651e 20#include <linux/perf_event.h>
d9762e84 21#include <linux/ctype.h>
6ba43b76 22#include <linux/error-injection.h>
9e4e01df 23#include <linux/bpf_lsm.h>
1e6c62a8 24#include <linux/btf_ids.h>
51580e79 25
f4ac7e0b
JK
26#include "disasm.h"
27
00176a34 28static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
91cc1a99 29#define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
00176a34
JK
30 [_id] = & _name ## _verifier_ops,
31#define BPF_MAP_TYPE(_id, _ops)
f2e10bff 32#define BPF_LINK_TYPE(_id, _name)
00176a34
JK
33#include <linux/bpf_types.h>
34#undef BPF_PROG_TYPE
35#undef BPF_MAP_TYPE
f2e10bff 36#undef BPF_LINK_TYPE
00176a34
JK
37};
38
51580e79
AS
39/* bpf_check() is a static code analyzer that walks eBPF program
40 * instruction by instruction and updates register/stack state.
41 * All paths of conditional branches are analyzed until 'bpf_exit' insn.
42 *
43 * The first pass is depth-first-search to check that the program is a DAG.
44 * It rejects the following programs:
45 * - larger than BPF_MAXINSNS insns
46 * - if loop is present (detected via back-edge)
47 * - unreachable insns exist (shouldn't be a forest. program = one function)
48 * - out of bounds or malformed jumps
49 * The second pass is all possible path descent from the 1st insn.
50 * Since it's analyzing all pathes through the program, the length of the
eba38a96 51 * analysis is limited to 64k insn, which may be hit even if total number of
51580e79
AS
52 * insn is less then 4K, but there are too many branches that change stack/regs.
53 * Number of 'branches to be analyzed' is limited to 1k
54 *
55 * On entry to each instruction, each register has a type, and the instruction
56 * changes the types of the registers depending on instruction semantics.
57 * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
58 * copied to R1.
59 *
60 * All registers are 64-bit.
61 * R0 - return register
62 * R1-R5 argument passing registers
63 * R6-R9 callee saved registers
64 * R10 - frame pointer read-only
65 *
66 * At the start of BPF program the register R1 contains a pointer to bpf_context
67 * and has type PTR_TO_CTX.
68 *
69 * Verifier tracks arithmetic operations on pointers in case:
70 * BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
71 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
72 * 1st insn copies R10 (which has FRAME_PTR) type into R1
73 * and 2nd arithmetic instruction is pattern matched to recognize
74 * that it wants to construct a pointer to some element within stack.
75 * So after 2nd insn, the register R1 has type PTR_TO_STACK
76 * (and -20 constant is saved for further stack bounds checking).
77 * Meaning that this reg is a pointer to stack plus known immediate constant.
78 *
f1174f77 79 * Most of the time the registers have SCALAR_VALUE type, which
51580e79 80 * means the register has some value, but it's not a valid pointer.
f1174f77 81 * (like pointer plus pointer becomes SCALAR_VALUE type)
51580e79
AS
82 *
83 * When verifier sees load or store instructions the type of base register
c64b7983
JS
84 * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are
85 * four pointer types recognized by check_mem_access() function.
51580e79
AS
86 *
87 * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
88 * and the range of [ptr, ptr + map's value_size) is accessible.
89 *
90 * registers used to pass values to function calls are checked against
91 * function argument constraints.
92 *
93 * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
94 * It means that the register type passed to this function must be
95 * PTR_TO_STACK and it will be used inside the function as
96 * 'pointer to map element key'
97 *
98 * For example the argument constraints for bpf_map_lookup_elem():
99 * .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
100 * .arg1_type = ARG_CONST_MAP_PTR,
101 * .arg2_type = ARG_PTR_TO_MAP_KEY,
102 *
103 * ret_type says that this function returns 'pointer to map elem value or null'
104 * function expects 1st argument to be a const pointer to 'struct bpf_map' and
105 * 2nd argument should be a pointer to stack, which will be used inside
106 * the helper function as a pointer to map element key.
107 *
108 * On the kernel side the helper function looks like:
109 * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
110 * {
111 * struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
112 * void *key = (void *) (unsigned long) r2;
113 * void *value;
114 *
115 * here kernel can access 'key' and 'map' pointers safely, knowing that
116 * [key, key + map->key_size) bytes are valid and were initialized on
117 * the stack of eBPF program.
118 * }
119 *
120 * Corresponding eBPF program may look like:
121 * BPF_MOV64_REG(BPF_REG_2, BPF_REG_10), // after this insn R2 type is FRAME_PTR
122 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
123 * BPF_LD_MAP_FD(BPF_REG_1, map_fd), // after this insn R1 type is CONST_PTR_TO_MAP
124 * BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
125 * here verifier looks at prototype of map_lookup_elem() and sees:
126 * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
127 * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
128 *
129 * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
130 * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
131 * and were initialized prior to this call.
132 * If it's ok, then verifier allows this BPF_CALL insn and looks at
133 * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
134 * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
135 * returns ether pointer to map value or NULL.
136 *
137 * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
138 * insn, the register holding that pointer in the true branch changes state to
139 * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
140 * branch. See check_cond_jmp_op().
141 *
142 * After the call R0 is set to return type of the function and registers R1-R5
143 * are set to NOT_INIT to indicate that they are no longer readable.
fd978bf7
JS
144 *
145 * The following reference types represent a potential reference to a kernel
146 * resource which, after first being allocated, must be checked and freed by
147 * the BPF program:
148 * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET
149 *
150 * When the verifier sees a helper call return a reference type, it allocates a
151 * pointer id for the reference and stores it in the current function state.
152 * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into
153 * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type
154 * passes through a NULL-check conditional. For the branch wherein the state is
155 * changed to CONST_IMM, the verifier releases the reference.
6acc9b43
JS
156 *
157 * For each helper function that allocates a reference, such as
158 * bpf_sk_lookup_tcp(), there is a corresponding release function, such as
159 * bpf_sk_release(). When a reference type passes into the release function,
160 * the verifier also releases the reference. If any unchecked or unreleased
161 * reference remains at the end of the program, the verifier rejects it.
51580e79
AS
162 */
163
17a52670 164/* verifier_state + insn_idx are pushed to stack when branch is encountered */
58e2af8b 165struct bpf_verifier_stack_elem {
17a52670
AS
166 /* verifer state is 'st'
167 * before processing instruction 'insn_idx'
168 * and after processing instruction 'prev_insn_idx'
169 */
58e2af8b 170 struct bpf_verifier_state st;
17a52670
AS
171 int insn_idx;
172 int prev_insn_idx;
58e2af8b 173 struct bpf_verifier_stack_elem *next;
6f8a57cc
AN
174 /* length of verifier log at the time this state was pushed on stack */
175 u32 log_pos;
cbd35700
AS
176};
177
b285fcb7 178#define BPF_COMPLEXITY_LIMIT_JMP_SEQ 8192
ceefbc96 179#define BPF_COMPLEXITY_LIMIT_STATES 64
07016151 180
d2e4c1e6
DB
181#define BPF_MAP_KEY_POISON (1ULL << 63)
182#define BPF_MAP_KEY_SEEN (1ULL << 62)
183
c93552c4
DB
184#define BPF_MAP_PTR_UNPRIV 1UL
185#define BPF_MAP_PTR_POISON ((void *)((0xeB9FUL << 1) + \
186 POISON_POINTER_DELTA))
187#define BPF_MAP_PTR(X) ((struct bpf_map *)((X) & ~BPF_MAP_PTR_UNPRIV))
188
189static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux)
190{
d2e4c1e6 191 return BPF_MAP_PTR(aux->map_ptr_state) == BPF_MAP_PTR_POISON;
c93552c4
DB
192}
193
194static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux)
195{
d2e4c1e6 196 return aux->map_ptr_state & BPF_MAP_PTR_UNPRIV;
c93552c4
DB
197}
198
199static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
200 const struct bpf_map *map, bool unpriv)
201{
202 BUILD_BUG_ON((unsigned long)BPF_MAP_PTR_POISON & BPF_MAP_PTR_UNPRIV);
203 unpriv |= bpf_map_ptr_unpriv(aux);
d2e4c1e6
DB
204 aux->map_ptr_state = (unsigned long)map |
205 (unpriv ? BPF_MAP_PTR_UNPRIV : 0UL);
206}
207
208static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux)
209{
210 return aux->map_key_state & BPF_MAP_KEY_POISON;
211}
212
213static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux)
214{
215 return !(aux->map_key_state & BPF_MAP_KEY_SEEN);
216}
217
218static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux)
219{
220 return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON);
221}
222
223static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state)
224{
225 bool poisoned = bpf_map_key_poisoned(aux);
226
227 aux->map_key_state = state | BPF_MAP_KEY_SEEN |
228 (poisoned ? BPF_MAP_KEY_POISON : 0ULL);
c93552c4 229}
fad73a1a 230
33ff9823
DB
231struct bpf_call_arg_meta {
232 struct bpf_map *map_ptr;
435faee1 233 bool raw_mode;
36bbef52 234 bool pkt_access;
435faee1
DB
235 int regno;
236 int access_size;
457f4436 237 int mem_size;
10060503 238 u64 msize_max_value;
1b986589 239 int ref_obj_id;
d83525ca 240 int func_id;
22dc4a0f 241 struct btf *btf;
eaa6bcb7 242 u32 btf_id;
22dc4a0f 243 struct btf *ret_btf;
eaa6bcb7 244 u32 ret_btf_id;
33ff9823
DB
245};
246
8580ac94
AS
247struct btf *btf_vmlinux;
248
cbd35700
AS
249static DEFINE_MUTEX(bpf_verifier_lock);
250
d9762e84
MKL
251static const struct bpf_line_info *
252find_linfo(const struct bpf_verifier_env *env, u32 insn_off)
253{
254 const struct bpf_line_info *linfo;
255 const struct bpf_prog *prog;
256 u32 i, nr_linfo;
257
258 prog = env->prog;
259 nr_linfo = prog->aux->nr_linfo;
260
261 if (!nr_linfo || insn_off >= prog->len)
262 return NULL;
263
264 linfo = prog->aux->linfo;
265 for (i = 1; i < nr_linfo; i++)
266 if (insn_off < linfo[i].insn_off)
267 break;
268
269 return &linfo[i - 1];
270}
271
77d2e05a
MKL
272void bpf_verifier_vlog(struct bpf_verifier_log *log, const char *fmt,
273 va_list args)
cbd35700 274{
a2a7d570 275 unsigned int n;
cbd35700 276
a2a7d570 277 n = vscnprintf(log->kbuf, BPF_VERIFIER_TMP_LOG_SIZE, fmt, args);
a2a7d570
JK
278
279 WARN_ONCE(n >= BPF_VERIFIER_TMP_LOG_SIZE - 1,
280 "verifier log line truncated - local buffer too short\n");
281
282 n = min(log->len_total - log->len_used - 1, n);
283 log->kbuf[n] = '\0';
284
8580ac94
AS
285 if (log->level == BPF_LOG_KERNEL) {
286 pr_err("BPF:%s\n", log->kbuf);
287 return;
288 }
a2a7d570
JK
289 if (!copy_to_user(log->ubuf + log->len_used, log->kbuf, n + 1))
290 log->len_used += n;
291 else
292 log->ubuf = NULL;
cbd35700 293}
abe08840 294
6f8a57cc
AN
295static void bpf_vlog_reset(struct bpf_verifier_log *log, u32 new_pos)
296{
297 char zero = 0;
298
299 if (!bpf_verifier_log_needed(log))
300 return;
301
302 log->len_used = new_pos;
303 if (put_user(zero, log->ubuf + new_pos))
304 log->ubuf = NULL;
305}
306
abe08840
JO
307/* log_level controls verbosity level of eBPF verifier.
308 * bpf_verifier_log_write() is used to dump the verification trace to the log,
309 * so the user can figure out what's wrong with the program
430e68d1 310 */
abe08840
JO
311__printf(2, 3) void bpf_verifier_log_write(struct bpf_verifier_env *env,
312 const char *fmt, ...)
313{
314 va_list args;
315
77d2e05a
MKL
316 if (!bpf_verifier_log_needed(&env->log))
317 return;
318
abe08840 319 va_start(args, fmt);
77d2e05a 320 bpf_verifier_vlog(&env->log, fmt, args);
abe08840
JO
321 va_end(args);
322}
323EXPORT_SYMBOL_GPL(bpf_verifier_log_write);
324
325__printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
326{
77d2e05a 327 struct bpf_verifier_env *env = private_data;
abe08840
JO
328 va_list args;
329
77d2e05a
MKL
330 if (!bpf_verifier_log_needed(&env->log))
331 return;
332
abe08840 333 va_start(args, fmt);
77d2e05a 334 bpf_verifier_vlog(&env->log, fmt, args);
abe08840
JO
335 va_end(args);
336}
cbd35700 337
9e15db66
AS
338__printf(2, 3) void bpf_log(struct bpf_verifier_log *log,
339 const char *fmt, ...)
340{
341 va_list args;
342
343 if (!bpf_verifier_log_needed(log))
344 return;
345
346 va_start(args, fmt);
347 bpf_verifier_vlog(log, fmt, args);
348 va_end(args);
349}
350
d9762e84
MKL
351static const char *ltrim(const char *s)
352{
353 while (isspace(*s))
354 s++;
355
356 return s;
357}
358
359__printf(3, 4) static void verbose_linfo(struct bpf_verifier_env *env,
360 u32 insn_off,
361 const char *prefix_fmt, ...)
362{
363 const struct bpf_line_info *linfo;
364
365 if (!bpf_verifier_log_needed(&env->log))
366 return;
367
368 linfo = find_linfo(env, insn_off);
369 if (!linfo || linfo == env->prev_linfo)
370 return;
371
372 if (prefix_fmt) {
373 va_list args;
374
375 va_start(args, prefix_fmt);
376 bpf_verifier_vlog(&env->log, prefix_fmt, args);
377 va_end(args);
378 }
379
380 verbose(env, "%s\n",
381 ltrim(btf_name_by_offset(env->prog->aux->btf,
382 linfo->line_off)));
383
384 env->prev_linfo = linfo;
385}
386
de8f3a83
DB
387static bool type_is_pkt_pointer(enum bpf_reg_type type)
388{
389 return type == PTR_TO_PACKET ||
390 type == PTR_TO_PACKET_META;
391}
392
46f8bc92
MKL
393static bool type_is_sk_pointer(enum bpf_reg_type type)
394{
395 return type == PTR_TO_SOCKET ||
655a51e5 396 type == PTR_TO_SOCK_COMMON ||
fada7fdc
JL
397 type == PTR_TO_TCP_SOCK ||
398 type == PTR_TO_XDP_SOCK;
46f8bc92
MKL
399}
400
cac616db
JF
401static bool reg_type_not_null(enum bpf_reg_type type)
402{
403 return type == PTR_TO_SOCKET ||
404 type == PTR_TO_TCP_SOCK ||
405 type == PTR_TO_MAP_VALUE ||
01c66c48 406 type == PTR_TO_SOCK_COMMON;
cac616db
JF
407}
408
840b9615
JS
409static bool reg_type_may_be_null(enum bpf_reg_type type)
410{
fd978bf7 411 return type == PTR_TO_MAP_VALUE_OR_NULL ||
46f8bc92 412 type == PTR_TO_SOCKET_OR_NULL ||
655a51e5 413 type == PTR_TO_SOCK_COMMON_OR_NULL ||
b121b341 414 type == PTR_TO_TCP_SOCK_OR_NULL ||
457f4436 415 type == PTR_TO_BTF_ID_OR_NULL ||
afbf21dc
YS
416 type == PTR_TO_MEM_OR_NULL ||
417 type == PTR_TO_RDONLY_BUF_OR_NULL ||
418 type == PTR_TO_RDWR_BUF_OR_NULL;
fd978bf7
JS
419}
420
d83525ca
AS
421static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
422{
423 return reg->type == PTR_TO_MAP_VALUE &&
424 map_value_has_spin_lock(reg->map_ptr);
425}
426
cba368c1
MKL
427static bool reg_type_may_be_refcounted_or_null(enum bpf_reg_type type)
428{
429 return type == PTR_TO_SOCKET ||
430 type == PTR_TO_SOCKET_OR_NULL ||
431 type == PTR_TO_TCP_SOCK ||
457f4436
AN
432 type == PTR_TO_TCP_SOCK_OR_NULL ||
433 type == PTR_TO_MEM ||
434 type == PTR_TO_MEM_OR_NULL;
cba368c1
MKL
435}
436
1b986589 437static bool arg_type_may_be_refcounted(enum bpf_arg_type type)
fd978bf7 438{
1b986589 439 return type == ARG_PTR_TO_SOCK_COMMON;
fd978bf7
JS
440}
441
fd1b0d60
LB
442static bool arg_type_may_be_null(enum bpf_arg_type type)
443{
444 return type == ARG_PTR_TO_MAP_VALUE_OR_NULL ||
445 type == ARG_PTR_TO_MEM_OR_NULL ||
446 type == ARG_PTR_TO_CTX_OR_NULL ||
447 type == ARG_PTR_TO_SOCKET_OR_NULL ||
448 type == ARG_PTR_TO_ALLOC_MEM_OR_NULL;
449}
450
fd978bf7
JS
451/* Determine whether the function releases some resources allocated by another
452 * function call. The first reference type argument will be assumed to be
453 * released by release_reference().
454 */
455static bool is_release_function(enum bpf_func_id func_id)
456{
457f4436
AN
457 return func_id == BPF_FUNC_sk_release ||
458 func_id == BPF_FUNC_ringbuf_submit ||
459 func_id == BPF_FUNC_ringbuf_discard;
840b9615
JS
460}
461
64d85290 462static bool may_be_acquire_function(enum bpf_func_id func_id)
46f8bc92
MKL
463{
464 return func_id == BPF_FUNC_sk_lookup_tcp ||
edbf8c01 465 func_id == BPF_FUNC_sk_lookup_udp ||
64d85290 466 func_id == BPF_FUNC_skc_lookup_tcp ||
457f4436
AN
467 func_id == BPF_FUNC_map_lookup_elem ||
468 func_id == BPF_FUNC_ringbuf_reserve;
64d85290
JS
469}
470
471static bool is_acquire_function(enum bpf_func_id func_id,
472 const struct bpf_map *map)
473{
474 enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
475
476 if (func_id == BPF_FUNC_sk_lookup_tcp ||
477 func_id == BPF_FUNC_sk_lookup_udp ||
457f4436
AN
478 func_id == BPF_FUNC_skc_lookup_tcp ||
479 func_id == BPF_FUNC_ringbuf_reserve)
64d85290
JS
480 return true;
481
482 if (func_id == BPF_FUNC_map_lookup_elem &&
483 (map_type == BPF_MAP_TYPE_SOCKMAP ||
484 map_type == BPF_MAP_TYPE_SOCKHASH))
485 return true;
486
487 return false;
46f8bc92
MKL
488}
489
1b986589
MKL
490static bool is_ptr_cast_function(enum bpf_func_id func_id)
491{
492 return func_id == BPF_FUNC_tcp_sock ||
1df8f55a
MKL
493 func_id == BPF_FUNC_sk_fullsock ||
494 func_id == BPF_FUNC_skc_to_tcp_sock ||
495 func_id == BPF_FUNC_skc_to_tcp6_sock ||
496 func_id == BPF_FUNC_skc_to_udp6_sock ||
497 func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
498 func_id == BPF_FUNC_skc_to_tcp_request_sock;
1b986589
MKL
499}
500
17a52670
AS
501/* string representation of 'enum bpf_reg_type' */
502static const char * const reg_type_str[] = {
503 [NOT_INIT] = "?",
f1174f77 504 [SCALAR_VALUE] = "inv",
17a52670
AS
505 [PTR_TO_CTX] = "ctx",
506 [CONST_PTR_TO_MAP] = "map_ptr",
507 [PTR_TO_MAP_VALUE] = "map_value",
508 [PTR_TO_MAP_VALUE_OR_NULL] = "map_value_or_null",
17a52670 509 [PTR_TO_STACK] = "fp",
969bf05e 510 [PTR_TO_PACKET] = "pkt",
de8f3a83 511 [PTR_TO_PACKET_META] = "pkt_meta",
969bf05e 512 [PTR_TO_PACKET_END] = "pkt_end",
d58e468b 513 [PTR_TO_FLOW_KEYS] = "flow_keys",
c64b7983
JS
514 [PTR_TO_SOCKET] = "sock",
515 [PTR_TO_SOCKET_OR_NULL] = "sock_or_null",
46f8bc92
MKL
516 [PTR_TO_SOCK_COMMON] = "sock_common",
517 [PTR_TO_SOCK_COMMON_OR_NULL] = "sock_common_or_null",
655a51e5
MKL
518 [PTR_TO_TCP_SOCK] = "tcp_sock",
519 [PTR_TO_TCP_SOCK_OR_NULL] = "tcp_sock_or_null",
9df1c28b 520 [PTR_TO_TP_BUFFER] = "tp_buffer",
fada7fdc 521 [PTR_TO_XDP_SOCK] = "xdp_sock",
9e15db66 522 [PTR_TO_BTF_ID] = "ptr_",
b121b341 523 [PTR_TO_BTF_ID_OR_NULL] = "ptr_or_null_",
eaa6bcb7 524 [PTR_TO_PERCPU_BTF_ID] = "percpu_ptr_",
457f4436
AN
525 [PTR_TO_MEM] = "mem",
526 [PTR_TO_MEM_OR_NULL] = "mem_or_null",
afbf21dc
YS
527 [PTR_TO_RDONLY_BUF] = "rdonly_buf",
528 [PTR_TO_RDONLY_BUF_OR_NULL] = "rdonly_buf_or_null",
529 [PTR_TO_RDWR_BUF] = "rdwr_buf",
530 [PTR_TO_RDWR_BUF_OR_NULL] = "rdwr_buf_or_null",
17a52670
AS
531};
532
8efea21d
EC
533static char slot_type_char[] = {
534 [STACK_INVALID] = '?',
535 [STACK_SPILL] = 'r',
536 [STACK_MISC] = 'm',
537 [STACK_ZERO] = '0',
538};
539
4e92024a
AS
540static void print_liveness(struct bpf_verifier_env *env,
541 enum bpf_reg_liveness live)
542{
9242b5f5 543 if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE))
4e92024a
AS
544 verbose(env, "_");
545 if (live & REG_LIVE_READ)
546 verbose(env, "r");
547 if (live & REG_LIVE_WRITTEN)
548 verbose(env, "w");
9242b5f5
AS
549 if (live & REG_LIVE_DONE)
550 verbose(env, "D");
4e92024a
AS
551}
552
f4d7e40a
AS
553static struct bpf_func_state *func(struct bpf_verifier_env *env,
554 const struct bpf_reg_state *reg)
555{
556 struct bpf_verifier_state *cur = env->cur_state;
557
558 return cur->frame[reg->frameno];
559}
560
22dc4a0f 561static const char *kernel_type_name(const struct btf* btf, u32 id)
9e15db66 562{
22dc4a0f 563 return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off);
9e15db66
AS
564}
565
61bd5218 566static void print_verifier_state(struct bpf_verifier_env *env,
f4d7e40a 567 const struct bpf_func_state *state)
17a52670 568{
f4d7e40a 569 const struct bpf_reg_state *reg;
17a52670
AS
570 enum bpf_reg_type t;
571 int i;
572
f4d7e40a
AS
573 if (state->frameno)
574 verbose(env, " frame%d:", state->frameno);
17a52670 575 for (i = 0; i < MAX_BPF_REG; i++) {
1a0dc1ac
AS
576 reg = &state->regs[i];
577 t = reg->type;
17a52670
AS
578 if (t == NOT_INIT)
579 continue;
4e92024a
AS
580 verbose(env, " R%d", i);
581 print_liveness(env, reg->live);
582 verbose(env, "=%s", reg_type_str[t]);
b5dc0163
AS
583 if (t == SCALAR_VALUE && reg->precise)
584 verbose(env, "P");
f1174f77
EC
585 if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
586 tnum_is_const(reg->var_off)) {
587 /* reg->off should be 0 for SCALAR_VALUE */
61bd5218 588 verbose(env, "%lld", reg->var_off.value + reg->off);
f1174f77 589 } else {
eaa6bcb7
HL
590 if (t == PTR_TO_BTF_ID ||
591 t == PTR_TO_BTF_ID_OR_NULL ||
592 t == PTR_TO_PERCPU_BTF_ID)
22dc4a0f 593 verbose(env, "%s", kernel_type_name(reg->btf, reg->btf_id));
cba368c1
MKL
594 verbose(env, "(id=%d", reg->id);
595 if (reg_type_may_be_refcounted_or_null(t))
596 verbose(env, ",ref_obj_id=%d", reg->ref_obj_id);
f1174f77 597 if (t != SCALAR_VALUE)
61bd5218 598 verbose(env, ",off=%d", reg->off);
de8f3a83 599 if (type_is_pkt_pointer(t))
61bd5218 600 verbose(env, ",r=%d", reg->range);
f1174f77
EC
601 else if (t == CONST_PTR_TO_MAP ||
602 t == PTR_TO_MAP_VALUE ||
603 t == PTR_TO_MAP_VALUE_OR_NULL)
61bd5218 604 verbose(env, ",ks=%d,vs=%d",
f1174f77
EC
605 reg->map_ptr->key_size,
606 reg->map_ptr->value_size);
7d1238f2
EC
607 if (tnum_is_const(reg->var_off)) {
608 /* Typically an immediate SCALAR_VALUE, but
609 * could be a pointer whose offset is too big
610 * for reg->off
611 */
61bd5218 612 verbose(env, ",imm=%llx", reg->var_off.value);
7d1238f2
EC
613 } else {
614 if (reg->smin_value != reg->umin_value &&
615 reg->smin_value != S64_MIN)
61bd5218 616 verbose(env, ",smin_value=%lld",
7d1238f2
EC
617 (long long)reg->smin_value);
618 if (reg->smax_value != reg->umax_value &&
619 reg->smax_value != S64_MAX)
61bd5218 620 verbose(env, ",smax_value=%lld",
7d1238f2
EC
621 (long long)reg->smax_value);
622 if (reg->umin_value != 0)
61bd5218 623 verbose(env, ",umin_value=%llu",
7d1238f2
EC
624 (unsigned long long)reg->umin_value);
625 if (reg->umax_value != U64_MAX)
61bd5218 626 verbose(env, ",umax_value=%llu",
7d1238f2
EC
627 (unsigned long long)reg->umax_value);
628 if (!tnum_is_unknown(reg->var_off)) {
629 char tn_buf[48];
f1174f77 630
7d1238f2 631 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
61bd5218 632 verbose(env, ",var_off=%s", tn_buf);
7d1238f2 633 }
3f50f132
JF
634 if (reg->s32_min_value != reg->smin_value &&
635 reg->s32_min_value != S32_MIN)
636 verbose(env, ",s32_min_value=%d",
637 (int)(reg->s32_min_value));
638 if (reg->s32_max_value != reg->smax_value &&
639 reg->s32_max_value != S32_MAX)
640 verbose(env, ",s32_max_value=%d",
641 (int)(reg->s32_max_value));
642 if (reg->u32_min_value != reg->umin_value &&
643 reg->u32_min_value != U32_MIN)
644 verbose(env, ",u32_min_value=%d",
645 (int)(reg->u32_min_value));
646 if (reg->u32_max_value != reg->umax_value &&
647 reg->u32_max_value != U32_MAX)
648 verbose(env, ",u32_max_value=%d",
649 (int)(reg->u32_max_value));
f1174f77 650 }
61bd5218 651 verbose(env, ")");
f1174f77 652 }
17a52670 653 }
638f5b90 654 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
8efea21d
EC
655 char types_buf[BPF_REG_SIZE + 1];
656 bool valid = false;
657 int j;
658
659 for (j = 0; j < BPF_REG_SIZE; j++) {
660 if (state->stack[i].slot_type[j] != STACK_INVALID)
661 valid = true;
662 types_buf[j] = slot_type_char[
663 state->stack[i].slot_type[j]];
664 }
665 types_buf[BPF_REG_SIZE] = 0;
666 if (!valid)
667 continue;
668 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
669 print_liveness(env, state->stack[i].spilled_ptr.live);
b5dc0163
AS
670 if (state->stack[i].slot_type[0] == STACK_SPILL) {
671 reg = &state->stack[i].spilled_ptr;
672 t = reg->type;
673 verbose(env, "=%s", reg_type_str[t]);
674 if (t == SCALAR_VALUE && reg->precise)
675 verbose(env, "P");
676 if (t == SCALAR_VALUE && tnum_is_const(reg->var_off))
677 verbose(env, "%lld", reg->var_off.value + reg->off);
678 } else {
8efea21d 679 verbose(env, "=%s", types_buf);
b5dc0163 680 }
17a52670 681 }
fd978bf7
JS
682 if (state->acquired_refs && state->refs[0].id) {
683 verbose(env, " refs=%d", state->refs[0].id);
684 for (i = 1; i < state->acquired_refs; i++)
685 if (state->refs[i].id)
686 verbose(env, ",%d", state->refs[i].id);
687 }
61bd5218 688 verbose(env, "\n");
17a52670
AS
689}
690
84dbf350
JS
691#define COPY_STATE_FN(NAME, COUNT, FIELD, SIZE) \
692static int copy_##NAME##_state(struct bpf_func_state *dst, \
693 const struct bpf_func_state *src) \
694{ \
695 if (!src->FIELD) \
696 return 0; \
697 if (WARN_ON_ONCE(dst->COUNT < src->COUNT)) { \
698 /* internal bug, make state invalid to reject the program */ \
699 memset(dst, 0, sizeof(*dst)); \
700 return -EFAULT; \
701 } \
702 memcpy(dst->FIELD, src->FIELD, \
703 sizeof(*src->FIELD) * (src->COUNT / SIZE)); \
704 return 0; \
638f5b90 705}
fd978bf7
JS
706/* copy_reference_state() */
707COPY_STATE_FN(reference, acquired_refs, refs, 1)
84dbf350
JS
708/* copy_stack_state() */
709COPY_STATE_FN(stack, allocated_stack, stack, BPF_REG_SIZE)
710#undef COPY_STATE_FN
711
712#define REALLOC_STATE_FN(NAME, COUNT, FIELD, SIZE) \
713static int realloc_##NAME##_state(struct bpf_func_state *state, int size, \
714 bool copy_old) \
715{ \
716 u32 old_size = state->COUNT; \
717 struct bpf_##NAME##_state *new_##FIELD; \
718 int slot = size / SIZE; \
719 \
720 if (size <= old_size || !size) { \
721 if (copy_old) \
722 return 0; \
723 state->COUNT = slot * SIZE; \
724 if (!size && old_size) { \
725 kfree(state->FIELD); \
726 state->FIELD = NULL; \
727 } \
728 return 0; \
729 } \
730 new_##FIELD = kmalloc_array(slot, sizeof(struct bpf_##NAME##_state), \
731 GFP_KERNEL); \
732 if (!new_##FIELD) \
733 return -ENOMEM; \
734 if (copy_old) { \
735 if (state->FIELD) \
736 memcpy(new_##FIELD, state->FIELD, \
737 sizeof(*new_##FIELD) * (old_size / SIZE)); \
738 memset(new_##FIELD + old_size / SIZE, 0, \
739 sizeof(*new_##FIELD) * (size - old_size) / SIZE); \
740 } \
741 state->COUNT = slot * SIZE; \
742 kfree(state->FIELD); \
743 state->FIELD = new_##FIELD; \
744 return 0; \
745}
fd978bf7
JS
746/* realloc_reference_state() */
747REALLOC_STATE_FN(reference, acquired_refs, refs, 1)
84dbf350
JS
748/* realloc_stack_state() */
749REALLOC_STATE_FN(stack, allocated_stack, stack, BPF_REG_SIZE)
750#undef REALLOC_STATE_FN
638f5b90
AS
751
752/* do_check() starts with zero-sized stack in struct bpf_verifier_state to
753 * make it consume minimal amount of memory. check_stack_write() access from
f4d7e40a 754 * the program calls into realloc_func_state() to grow the stack size.
84dbf350
JS
755 * Note there is a non-zero 'parent' pointer inside bpf_verifier_state
756 * which realloc_stack_state() copies over. It points to previous
757 * bpf_verifier_state which is never reallocated.
638f5b90 758 */
fd978bf7
JS
759static int realloc_func_state(struct bpf_func_state *state, int stack_size,
760 int refs_size, bool copy_old)
638f5b90 761{
fd978bf7
JS
762 int err = realloc_reference_state(state, refs_size, copy_old);
763 if (err)
764 return err;
765 return realloc_stack_state(state, stack_size, copy_old);
766}
767
768/* Acquire a pointer id from the env and update the state->refs to include
769 * this new pointer reference.
770 * On success, returns a valid pointer id to associate with the register
771 * On failure, returns a negative errno.
638f5b90 772 */
fd978bf7 773static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
638f5b90 774{
fd978bf7
JS
775 struct bpf_func_state *state = cur_func(env);
776 int new_ofs = state->acquired_refs;
777 int id, err;
778
779 err = realloc_reference_state(state, state->acquired_refs + 1, true);
780 if (err)
781 return err;
782 id = ++env->id_gen;
783 state->refs[new_ofs].id = id;
784 state->refs[new_ofs].insn_idx = insn_idx;
638f5b90 785
fd978bf7
JS
786 return id;
787}
788
789/* release function corresponding to acquire_reference_state(). Idempotent. */
46f8bc92 790static int release_reference_state(struct bpf_func_state *state, int ptr_id)
fd978bf7
JS
791{
792 int i, last_idx;
793
fd978bf7
JS
794 last_idx = state->acquired_refs - 1;
795 for (i = 0; i < state->acquired_refs; i++) {
796 if (state->refs[i].id == ptr_id) {
797 if (last_idx && i != last_idx)
798 memcpy(&state->refs[i], &state->refs[last_idx],
799 sizeof(*state->refs));
800 memset(&state->refs[last_idx], 0, sizeof(*state->refs));
801 state->acquired_refs--;
638f5b90 802 return 0;
638f5b90 803 }
638f5b90 804 }
46f8bc92 805 return -EINVAL;
fd978bf7
JS
806}
807
808static int transfer_reference_state(struct bpf_func_state *dst,
809 struct bpf_func_state *src)
810{
811 int err = realloc_reference_state(dst, src->acquired_refs, false);
812 if (err)
813 return err;
814 err = copy_reference_state(dst, src);
815 if (err)
816 return err;
638f5b90
AS
817 return 0;
818}
819
f4d7e40a
AS
820static void free_func_state(struct bpf_func_state *state)
821{
5896351e
AS
822 if (!state)
823 return;
fd978bf7 824 kfree(state->refs);
f4d7e40a
AS
825 kfree(state->stack);
826 kfree(state);
827}
828
b5dc0163
AS
829static void clear_jmp_history(struct bpf_verifier_state *state)
830{
831 kfree(state->jmp_history);
832 state->jmp_history = NULL;
833 state->jmp_history_cnt = 0;
834}
835
1969db47
AS
836static void free_verifier_state(struct bpf_verifier_state *state,
837 bool free_self)
638f5b90 838{
f4d7e40a
AS
839 int i;
840
841 for (i = 0; i <= state->curframe; i++) {
842 free_func_state(state->frame[i]);
843 state->frame[i] = NULL;
844 }
b5dc0163 845 clear_jmp_history(state);
1969db47
AS
846 if (free_self)
847 kfree(state);
638f5b90
AS
848}
849
850/* copy verifier state from src to dst growing dst stack space
851 * when necessary to accommodate larger src stack
852 */
f4d7e40a
AS
853static int copy_func_state(struct bpf_func_state *dst,
854 const struct bpf_func_state *src)
638f5b90
AS
855{
856 int err;
857
fd978bf7
JS
858 err = realloc_func_state(dst, src->allocated_stack, src->acquired_refs,
859 false);
860 if (err)
861 return err;
862 memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
863 err = copy_reference_state(dst, src);
638f5b90
AS
864 if (err)
865 return err;
638f5b90
AS
866 return copy_stack_state(dst, src);
867}
868
f4d7e40a
AS
869static int copy_verifier_state(struct bpf_verifier_state *dst_state,
870 const struct bpf_verifier_state *src)
871{
872 struct bpf_func_state *dst;
b5dc0163 873 u32 jmp_sz = sizeof(struct bpf_idx_pair) * src->jmp_history_cnt;
f4d7e40a
AS
874 int i, err;
875
b5dc0163
AS
876 if (dst_state->jmp_history_cnt < src->jmp_history_cnt) {
877 kfree(dst_state->jmp_history);
878 dst_state->jmp_history = kmalloc(jmp_sz, GFP_USER);
879 if (!dst_state->jmp_history)
880 return -ENOMEM;
881 }
882 memcpy(dst_state->jmp_history, src->jmp_history, jmp_sz);
883 dst_state->jmp_history_cnt = src->jmp_history_cnt;
884
f4d7e40a
AS
885 /* if dst has more stack frames then src frame, free them */
886 for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
887 free_func_state(dst_state->frame[i]);
888 dst_state->frame[i] = NULL;
889 }
979d63d5 890 dst_state->speculative = src->speculative;
f4d7e40a 891 dst_state->curframe = src->curframe;
d83525ca 892 dst_state->active_spin_lock = src->active_spin_lock;
2589726d
AS
893 dst_state->branches = src->branches;
894 dst_state->parent = src->parent;
b5dc0163
AS
895 dst_state->first_insn_idx = src->first_insn_idx;
896 dst_state->last_insn_idx = src->last_insn_idx;
f4d7e40a
AS
897 for (i = 0; i <= src->curframe; i++) {
898 dst = dst_state->frame[i];
899 if (!dst) {
900 dst = kzalloc(sizeof(*dst), GFP_KERNEL);
901 if (!dst)
902 return -ENOMEM;
903 dst_state->frame[i] = dst;
904 }
905 err = copy_func_state(dst, src->frame[i]);
906 if (err)
907 return err;
908 }
909 return 0;
910}
911
2589726d
AS
912static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
913{
914 while (st) {
915 u32 br = --st->branches;
916
917 /* WARN_ON(br > 1) technically makes sense here,
918 * but see comment in push_stack(), hence:
919 */
920 WARN_ONCE((int)br < 0,
921 "BUG update_branch_counts:branches_to_explore=%d\n",
922 br);
923 if (br)
924 break;
925 st = st->parent;
926 }
927}
928
638f5b90 929static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
6f8a57cc 930 int *insn_idx, bool pop_log)
638f5b90
AS
931{
932 struct bpf_verifier_state *cur = env->cur_state;
933 struct bpf_verifier_stack_elem *elem, *head = env->head;
934 int err;
17a52670
AS
935
936 if (env->head == NULL)
638f5b90 937 return -ENOENT;
17a52670 938
638f5b90
AS
939 if (cur) {
940 err = copy_verifier_state(cur, &head->st);
941 if (err)
942 return err;
943 }
6f8a57cc
AN
944 if (pop_log)
945 bpf_vlog_reset(&env->log, head->log_pos);
638f5b90
AS
946 if (insn_idx)
947 *insn_idx = head->insn_idx;
17a52670 948 if (prev_insn_idx)
638f5b90
AS
949 *prev_insn_idx = head->prev_insn_idx;
950 elem = head->next;
1969db47 951 free_verifier_state(&head->st, false);
638f5b90 952 kfree(head);
17a52670
AS
953 env->head = elem;
954 env->stack_size--;
638f5b90 955 return 0;
17a52670
AS
956}
957
58e2af8b 958static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
979d63d5
DB
959 int insn_idx, int prev_insn_idx,
960 bool speculative)
17a52670 961{
638f5b90 962 struct bpf_verifier_state *cur = env->cur_state;
58e2af8b 963 struct bpf_verifier_stack_elem *elem;
638f5b90 964 int err;
17a52670 965
638f5b90 966 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
17a52670
AS
967 if (!elem)
968 goto err;
969
17a52670
AS
970 elem->insn_idx = insn_idx;
971 elem->prev_insn_idx = prev_insn_idx;
972 elem->next = env->head;
6f8a57cc 973 elem->log_pos = env->log.len_used;
17a52670
AS
974 env->head = elem;
975 env->stack_size++;
1969db47
AS
976 err = copy_verifier_state(&elem->st, cur);
977 if (err)
978 goto err;
979d63d5 979 elem->st.speculative |= speculative;
b285fcb7
AS
980 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
981 verbose(env, "The sequence of %d jumps is too complex.\n",
982 env->stack_size);
17a52670
AS
983 goto err;
984 }
2589726d
AS
985 if (elem->st.parent) {
986 ++elem->st.parent->branches;
987 /* WARN_ON(branches > 2) technically makes sense here,
988 * but
989 * 1. speculative states will bump 'branches' for non-branch
990 * instructions
991 * 2. is_state_visited() heuristics may decide not to create
992 * a new state for a sequence of branches and all such current
993 * and cloned states will be pointing to a single parent state
994 * which might have large 'branches' count.
995 */
996 }
17a52670
AS
997 return &elem->st;
998err:
5896351e
AS
999 free_verifier_state(env->cur_state, true);
1000 env->cur_state = NULL;
17a52670 1001 /* pop all elements and return */
6f8a57cc 1002 while (!pop_stack(env, NULL, NULL, false));
17a52670
AS
1003 return NULL;
1004}
1005
1006#define CALLER_SAVED_REGS 6
1007static const int caller_saved[CALLER_SAVED_REGS] = {
1008 BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
1009};
1010
f54c7898
DB
1011static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1012 struct bpf_reg_state *reg);
f1174f77 1013
e688c3db
AS
1014/* This helper doesn't clear reg->id */
1015static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
b03c9f9f 1016{
b03c9f9f
EC
1017 reg->var_off = tnum_const(imm);
1018 reg->smin_value = (s64)imm;
1019 reg->smax_value = (s64)imm;
1020 reg->umin_value = imm;
1021 reg->umax_value = imm;
3f50f132
JF
1022
1023 reg->s32_min_value = (s32)imm;
1024 reg->s32_max_value = (s32)imm;
1025 reg->u32_min_value = (u32)imm;
1026 reg->u32_max_value = (u32)imm;
1027}
1028
e688c3db
AS
1029/* Mark the unknown part of a register (variable offset or scalar value) as
1030 * known to have the value @imm.
1031 */
1032static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1033{
1034 /* Clear id, off, and union(map_ptr, range) */
1035 memset(((u8 *)reg) + sizeof(reg->type), 0,
1036 offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
1037 ___mark_reg_known(reg, imm);
1038}
1039
3f50f132
JF
1040static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1041{
1042 reg->var_off = tnum_const_subreg(reg->var_off, imm);
1043 reg->s32_min_value = (s32)imm;
1044 reg->s32_max_value = (s32)imm;
1045 reg->u32_min_value = (u32)imm;
1046 reg->u32_max_value = (u32)imm;
b03c9f9f
EC
1047}
1048
f1174f77
EC
1049/* Mark the 'variable offset' part of a register as zero. This should be
1050 * used only on registers holding a pointer type.
1051 */
1052static void __mark_reg_known_zero(struct bpf_reg_state *reg)
a9789ef9 1053{
b03c9f9f 1054 __mark_reg_known(reg, 0);
f1174f77 1055}
a9789ef9 1056
cc2b14d5
AS
1057static void __mark_reg_const_zero(struct bpf_reg_state *reg)
1058{
1059 __mark_reg_known(reg, 0);
cc2b14d5
AS
1060 reg->type = SCALAR_VALUE;
1061}
1062
61bd5218
JK
1063static void mark_reg_known_zero(struct bpf_verifier_env *env,
1064 struct bpf_reg_state *regs, u32 regno)
f1174f77
EC
1065{
1066 if (WARN_ON(regno >= MAX_BPF_REG)) {
61bd5218 1067 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
f1174f77
EC
1068 /* Something bad happened, let's kill all regs */
1069 for (regno = 0; regno < MAX_BPF_REG; regno++)
f54c7898 1070 __mark_reg_not_init(env, regs + regno);
f1174f77
EC
1071 return;
1072 }
1073 __mark_reg_known_zero(regs + regno);
1074}
1075
de8f3a83
DB
1076static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1077{
1078 return type_is_pkt_pointer(reg->type);
1079}
1080
1081static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
1082{
1083 return reg_is_pkt_pointer(reg) ||
1084 reg->type == PTR_TO_PACKET_END;
1085}
1086
1087/* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
1088static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
1089 enum bpf_reg_type which)
1090{
1091 /* The register can already have a range from prior markings.
1092 * This is fine as long as it hasn't been advanced from its
1093 * origin.
1094 */
1095 return reg->type == which &&
1096 reg->id == 0 &&
1097 reg->off == 0 &&
1098 tnum_equals_const(reg->var_off, 0);
1099}
1100
3f50f132
JF
1101/* Reset the min/max bounds of a register */
1102static void __mark_reg_unbounded(struct bpf_reg_state *reg)
1103{
1104 reg->smin_value = S64_MIN;
1105 reg->smax_value = S64_MAX;
1106 reg->umin_value = 0;
1107 reg->umax_value = U64_MAX;
1108
1109 reg->s32_min_value = S32_MIN;
1110 reg->s32_max_value = S32_MAX;
1111 reg->u32_min_value = 0;
1112 reg->u32_max_value = U32_MAX;
1113}
1114
1115static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
1116{
1117 reg->smin_value = S64_MIN;
1118 reg->smax_value = S64_MAX;
1119 reg->umin_value = 0;
1120 reg->umax_value = U64_MAX;
1121}
1122
1123static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
1124{
1125 reg->s32_min_value = S32_MIN;
1126 reg->s32_max_value = S32_MAX;
1127 reg->u32_min_value = 0;
1128 reg->u32_max_value = U32_MAX;
1129}
1130
1131static void __update_reg32_bounds(struct bpf_reg_state *reg)
1132{
1133 struct tnum var32_off = tnum_subreg(reg->var_off);
1134
1135 /* min signed is max(sign bit) | min(other bits) */
1136 reg->s32_min_value = max_t(s32, reg->s32_min_value,
1137 var32_off.value | (var32_off.mask & S32_MIN));
1138 /* max signed is min(sign bit) | max(other bits) */
1139 reg->s32_max_value = min_t(s32, reg->s32_max_value,
1140 var32_off.value | (var32_off.mask & S32_MAX));
1141 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
1142 reg->u32_max_value = min(reg->u32_max_value,
1143 (u32)(var32_off.value | var32_off.mask));
1144}
1145
1146static void __update_reg64_bounds(struct bpf_reg_state *reg)
b03c9f9f
EC
1147{
1148 /* min signed is max(sign bit) | min(other bits) */
1149 reg->smin_value = max_t(s64, reg->smin_value,
1150 reg->var_off.value | (reg->var_off.mask & S64_MIN));
1151 /* max signed is min(sign bit) | max(other bits) */
1152 reg->smax_value = min_t(s64, reg->smax_value,
1153 reg->var_off.value | (reg->var_off.mask & S64_MAX));
1154 reg->umin_value = max(reg->umin_value, reg->var_off.value);
1155 reg->umax_value = min(reg->umax_value,
1156 reg->var_off.value | reg->var_off.mask);
1157}
1158
3f50f132
JF
1159static void __update_reg_bounds(struct bpf_reg_state *reg)
1160{
1161 __update_reg32_bounds(reg);
1162 __update_reg64_bounds(reg);
1163}
1164
b03c9f9f 1165/* Uses signed min/max values to inform unsigned, and vice-versa */
3f50f132
JF
1166static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
1167{
1168 /* Learn sign from signed bounds.
1169 * If we cannot cross the sign boundary, then signed and unsigned bounds
1170 * are the same, so combine. This works even in the negative case, e.g.
1171 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1172 */
1173 if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) {
1174 reg->s32_min_value = reg->u32_min_value =
1175 max_t(u32, reg->s32_min_value, reg->u32_min_value);
1176 reg->s32_max_value = reg->u32_max_value =
1177 min_t(u32, reg->s32_max_value, reg->u32_max_value);
1178 return;
1179 }
1180 /* Learn sign from unsigned bounds. Signed bounds cross the sign
1181 * boundary, so we must be careful.
1182 */
1183 if ((s32)reg->u32_max_value >= 0) {
1184 /* Positive. We can't learn anything from the smin, but smax
1185 * is positive, hence safe.
1186 */
1187 reg->s32_min_value = reg->u32_min_value;
1188 reg->s32_max_value = reg->u32_max_value =
1189 min_t(u32, reg->s32_max_value, reg->u32_max_value);
1190 } else if ((s32)reg->u32_min_value < 0) {
1191 /* Negative. We can't learn anything from the smax, but smin
1192 * is negative, hence safe.
1193 */
1194 reg->s32_min_value = reg->u32_min_value =
1195 max_t(u32, reg->s32_min_value, reg->u32_min_value);
1196 reg->s32_max_value = reg->u32_max_value;
1197 }
1198}
1199
1200static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
b03c9f9f
EC
1201{
1202 /* Learn sign from signed bounds.
1203 * If we cannot cross the sign boundary, then signed and unsigned bounds
1204 * are the same, so combine. This works even in the negative case, e.g.
1205 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1206 */
1207 if (reg->smin_value >= 0 || reg->smax_value < 0) {
1208 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1209 reg->umin_value);
1210 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1211 reg->umax_value);
1212 return;
1213 }
1214 /* Learn sign from unsigned bounds. Signed bounds cross the sign
1215 * boundary, so we must be careful.
1216 */
1217 if ((s64)reg->umax_value >= 0) {
1218 /* Positive. We can't learn anything from the smin, but smax
1219 * is positive, hence safe.
1220 */
1221 reg->smin_value = reg->umin_value;
1222 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1223 reg->umax_value);
1224 } else if ((s64)reg->umin_value < 0) {
1225 /* Negative. We can't learn anything from the smax, but smin
1226 * is negative, hence safe.
1227 */
1228 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1229 reg->umin_value);
1230 reg->smax_value = reg->umax_value;
1231 }
1232}
1233
3f50f132
JF
1234static void __reg_deduce_bounds(struct bpf_reg_state *reg)
1235{
1236 __reg32_deduce_bounds(reg);
1237 __reg64_deduce_bounds(reg);
1238}
1239
b03c9f9f
EC
1240/* Attempts to improve var_off based on unsigned min/max information */
1241static void __reg_bound_offset(struct bpf_reg_state *reg)
1242{
3f50f132
JF
1243 struct tnum var64_off = tnum_intersect(reg->var_off,
1244 tnum_range(reg->umin_value,
1245 reg->umax_value));
1246 struct tnum var32_off = tnum_intersect(tnum_subreg(reg->var_off),
1247 tnum_range(reg->u32_min_value,
1248 reg->u32_max_value));
1249
1250 reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
b03c9f9f
EC
1251}
1252
3f50f132 1253static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
b03c9f9f 1254{
3f50f132
JF
1255 reg->umin_value = reg->u32_min_value;
1256 reg->umax_value = reg->u32_max_value;
1257 /* Attempt to pull 32-bit signed bounds into 64-bit bounds
1258 * but must be positive otherwise set to worse case bounds
1259 * and refine later from tnum.
1260 */
3a71dc36 1261 if (reg->s32_min_value >= 0 && reg->s32_max_value >= 0)
3f50f132
JF
1262 reg->smax_value = reg->s32_max_value;
1263 else
1264 reg->smax_value = U32_MAX;
3a71dc36
JF
1265 if (reg->s32_min_value >= 0)
1266 reg->smin_value = reg->s32_min_value;
1267 else
1268 reg->smin_value = 0;
3f50f132
JF
1269}
1270
1271static void __reg_combine_32_into_64(struct bpf_reg_state *reg)
1272{
1273 /* special case when 64-bit register has upper 32-bit register
1274 * zeroed. Typically happens after zext or <<32, >>32 sequence
1275 * allowing us to use 32-bit bounds directly,
1276 */
1277 if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) {
1278 __reg_assign_32_into_64(reg);
1279 } else {
1280 /* Otherwise the best we can do is push lower 32bit known and
1281 * unknown bits into register (var_off set from jmp logic)
1282 * then learn as much as possible from the 64-bit tnum
1283 * known and unknown bits. The previous smin/smax bounds are
1284 * invalid here because of jmp32 compare so mark them unknown
1285 * so they do not impact tnum bounds calculation.
1286 */
1287 __mark_reg64_unbounded(reg);
1288 __update_reg_bounds(reg);
1289 }
1290
1291 /* Intersecting with the old var_off might have improved our bounds
1292 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1293 * then new var_off is (0; 0x7f...fc) which improves our umax.
1294 */
1295 __reg_deduce_bounds(reg);
1296 __reg_bound_offset(reg);
1297 __update_reg_bounds(reg);
1298}
1299
1300static bool __reg64_bound_s32(s64 a)
1301{
b0270958 1302 return a > S32_MIN && a < S32_MAX;
3f50f132
JF
1303}
1304
1305static bool __reg64_bound_u32(u64 a)
1306{
e031f3fe 1307 return a > U32_MIN && a < U32_MAX;
3f50f132
JF
1308}
1309
1310static void __reg_combine_64_into_32(struct bpf_reg_state *reg)
1311{
1312 __mark_reg32_unbounded(reg);
1313
b0270958 1314 if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) {
3f50f132 1315 reg->s32_min_value = (s32)reg->smin_value;
3f50f132 1316 reg->s32_max_value = (s32)reg->smax_value;
b0270958 1317 }
e031f3fe 1318 if (__reg64_bound_u32(reg->umin_value) && __reg64_bound_u32(reg->umax_value)) {
3f50f132 1319 reg->u32_min_value = (u32)reg->umin_value;
3f50f132 1320 reg->u32_max_value = (u32)reg->umax_value;
e031f3fe 1321 }
3f50f132
JF
1322
1323 /* Intersecting with the old var_off might have improved our bounds
1324 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1325 * then new var_off is (0; 0x7f...fc) which improves our umax.
1326 */
1327 __reg_deduce_bounds(reg);
1328 __reg_bound_offset(reg);
1329 __update_reg_bounds(reg);
b03c9f9f
EC
1330}
1331
f1174f77 1332/* Mark a register as having a completely unknown (scalar) value. */
f54c7898
DB
1333static void __mark_reg_unknown(const struct bpf_verifier_env *env,
1334 struct bpf_reg_state *reg)
f1174f77 1335{
a9c676bc
AS
1336 /*
1337 * Clear type, id, off, and union(map_ptr, range) and
1338 * padding between 'type' and union
1339 */
1340 memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
f1174f77 1341 reg->type = SCALAR_VALUE;
f1174f77 1342 reg->var_off = tnum_unknown;
f4d7e40a 1343 reg->frameno = 0;
2c78ee89 1344 reg->precise = env->subprog_cnt > 1 || !env->bpf_capable;
b03c9f9f 1345 __mark_reg_unbounded(reg);
f1174f77
EC
1346}
1347
61bd5218
JK
1348static void mark_reg_unknown(struct bpf_verifier_env *env,
1349 struct bpf_reg_state *regs, u32 regno)
f1174f77
EC
1350{
1351 if (WARN_ON(regno >= MAX_BPF_REG)) {
61bd5218 1352 verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
19ceb417
AS
1353 /* Something bad happened, let's kill all regs except FP */
1354 for (regno = 0; regno < BPF_REG_FP; regno++)
f54c7898 1355 __mark_reg_not_init(env, regs + regno);
f1174f77
EC
1356 return;
1357 }
f54c7898 1358 __mark_reg_unknown(env, regs + regno);
f1174f77
EC
1359}
1360
f54c7898
DB
1361static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1362 struct bpf_reg_state *reg)
f1174f77 1363{
f54c7898 1364 __mark_reg_unknown(env, reg);
f1174f77
EC
1365 reg->type = NOT_INIT;
1366}
1367
61bd5218
JK
1368static void mark_reg_not_init(struct bpf_verifier_env *env,
1369 struct bpf_reg_state *regs, u32 regno)
f1174f77
EC
1370{
1371 if (WARN_ON(regno >= MAX_BPF_REG)) {
61bd5218 1372 verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
19ceb417
AS
1373 /* Something bad happened, let's kill all regs except FP */
1374 for (regno = 0; regno < BPF_REG_FP; regno++)
f54c7898 1375 __mark_reg_not_init(env, regs + regno);
f1174f77
EC
1376 return;
1377 }
f54c7898 1378 __mark_reg_not_init(env, regs + regno);
a9789ef9
DB
1379}
1380
41c48f3a
AI
1381static void mark_btf_ld_reg(struct bpf_verifier_env *env,
1382 struct bpf_reg_state *regs, u32 regno,
22dc4a0f
AN
1383 enum bpf_reg_type reg_type,
1384 struct btf *btf, u32 btf_id)
41c48f3a
AI
1385{
1386 if (reg_type == SCALAR_VALUE) {
1387 mark_reg_unknown(env, regs, regno);
1388 return;
1389 }
1390 mark_reg_known_zero(env, regs, regno);
1391 regs[regno].type = PTR_TO_BTF_ID;
22dc4a0f 1392 regs[regno].btf = btf;
41c48f3a
AI
1393 regs[regno].btf_id = btf_id;
1394}
1395
5327ed3d 1396#define DEF_NOT_SUBREG (0)
61bd5218 1397static void init_reg_state(struct bpf_verifier_env *env,
f4d7e40a 1398 struct bpf_func_state *state)
17a52670 1399{
f4d7e40a 1400 struct bpf_reg_state *regs = state->regs;
17a52670
AS
1401 int i;
1402
dc503a8a 1403 for (i = 0; i < MAX_BPF_REG; i++) {
61bd5218 1404 mark_reg_not_init(env, regs, i);
dc503a8a 1405 regs[i].live = REG_LIVE_NONE;
679c782d 1406 regs[i].parent = NULL;
5327ed3d 1407 regs[i].subreg_def = DEF_NOT_SUBREG;
dc503a8a 1408 }
17a52670
AS
1409
1410 /* frame pointer */
f1174f77 1411 regs[BPF_REG_FP].type = PTR_TO_STACK;
61bd5218 1412 mark_reg_known_zero(env, regs, BPF_REG_FP);
f4d7e40a 1413 regs[BPF_REG_FP].frameno = state->frameno;
6760bf2d
DB
1414}
1415
f4d7e40a
AS
1416#define BPF_MAIN_FUNC (-1)
1417static void init_func_state(struct bpf_verifier_env *env,
1418 struct bpf_func_state *state,
1419 int callsite, int frameno, int subprogno)
1420{
1421 state->callsite = callsite;
1422 state->frameno = frameno;
1423 state->subprogno = subprogno;
1424 init_reg_state(env, state);
1425}
1426
17a52670
AS
1427enum reg_arg_type {
1428 SRC_OP, /* register is used as source operand */
1429 DST_OP, /* register is used as destination operand */
1430 DST_OP_NO_MARK /* same as above, check only, don't mark */
1431};
1432
cc8b0b92
AS
1433static int cmp_subprogs(const void *a, const void *b)
1434{
9c8105bd
JW
1435 return ((struct bpf_subprog_info *)a)->start -
1436 ((struct bpf_subprog_info *)b)->start;
cc8b0b92
AS
1437}
1438
1439static int find_subprog(struct bpf_verifier_env *env, int off)
1440{
9c8105bd 1441 struct bpf_subprog_info *p;
cc8b0b92 1442
9c8105bd
JW
1443 p = bsearch(&off, env->subprog_info, env->subprog_cnt,
1444 sizeof(env->subprog_info[0]), cmp_subprogs);
cc8b0b92
AS
1445 if (!p)
1446 return -ENOENT;
9c8105bd 1447 return p - env->subprog_info;
cc8b0b92
AS
1448
1449}
1450
1451static int add_subprog(struct bpf_verifier_env *env, int off)
1452{
1453 int insn_cnt = env->prog->len;
1454 int ret;
1455
1456 if (off >= insn_cnt || off < 0) {
1457 verbose(env, "call to invalid destination\n");
1458 return -EINVAL;
1459 }
1460 ret = find_subprog(env, off);
1461 if (ret >= 0)
1462 return 0;
4cb3d99c 1463 if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
cc8b0b92
AS
1464 verbose(env, "too many subprograms\n");
1465 return -E2BIG;
1466 }
9c8105bd
JW
1467 env->subprog_info[env->subprog_cnt++].start = off;
1468 sort(env->subprog_info, env->subprog_cnt,
1469 sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
cc8b0b92
AS
1470 return 0;
1471}
1472
1473static int check_subprogs(struct bpf_verifier_env *env)
1474{
1475 int i, ret, subprog_start, subprog_end, off, cur_subprog = 0;
9c8105bd 1476 struct bpf_subprog_info *subprog = env->subprog_info;
cc8b0b92
AS
1477 struct bpf_insn *insn = env->prog->insnsi;
1478 int insn_cnt = env->prog->len;
1479
f910cefa
JW
1480 /* Add entry function. */
1481 ret = add_subprog(env, 0);
1482 if (ret < 0)
1483 return ret;
1484
cc8b0b92
AS
1485 /* determine subprog starts. The end is one before the next starts */
1486 for (i = 0; i < insn_cnt; i++) {
1487 if (insn[i].code != (BPF_JMP | BPF_CALL))
1488 continue;
1489 if (insn[i].src_reg != BPF_PSEUDO_CALL)
1490 continue;
2c78ee89
AS
1491 if (!env->bpf_capable) {
1492 verbose(env,
1493 "function calls to other bpf functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
cc8b0b92
AS
1494 return -EPERM;
1495 }
cc8b0b92
AS
1496 ret = add_subprog(env, i + insn[i].imm + 1);
1497 if (ret < 0)
1498 return ret;
1499 }
1500
4cb3d99c
JW
1501 /* Add a fake 'exit' subprog which could simplify subprog iteration
1502 * logic. 'subprog_cnt' should not be increased.
1503 */
1504 subprog[env->subprog_cnt].start = insn_cnt;
1505
06ee7115 1506 if (env->log.level & BPF_LOG_LEVEL2)
cc8b0b92 1507 for (i = 0; i < env->subprog_cnt; i++)
9c8105bd 1508 verbose(env, "func#%d @%d\n", i, subprog[i].start);
cc8b0b92
AS
1509
1510 /* now check that all jumps are within the same subprog */
4cb3d99c
JW
1511 subprog_start = subprog[cur_subprog].start;
1512 subprog_end = subprog[cur_subprog + 1].start;
cc8b0b92
AS
1513 for (i = 0; i < insn_cnt; i++) {
1514 u8 code = insn[i].code;
1515
7f6e4312
MF
1516 if (code == (BPF_JMP | BPF_CALL) &&
1517 insn[i].imm == BPF_FUNC_tail_call &&
1518 insn[i].src_reg != BPF_PSEUDO_CALL)
1519 subprog[cur_subprog].has_tail_call = true;
09b28d76
AS
1520 if (BPF_CLASS(code) == BPF_LD &&
1521 (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
1522 subprog[cur_subprog].has_ld_abs = true;
092ed096 1523 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
cc8b0b92
AS
1524 goto next;
1525 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
1526 goto next;
1527 off = i + insn[i].off + 1;
1528 if (off < subprog_start || off >= subprog_end) {
1529 verbose(env, "jump out of range from insn %d to %d\n", i, off);
1530 return -EINVAL;
1531 }
1532next:
1533 if (i == subprog_end - 1) {
1534 /* to avoid fall-through from one subprog into another
1535 * the last insn of the subprog should be either exit
1536 * or unconditional jump back
1537 */
1538 if (code != (BPF_JMP | BPF_EXIT) &&
1539 code != (BPF_JMP | BPF_JA)) {
1540 verbose(env, "last insn is not an exit or jmp\n");
1541 return -EINVAL;
1542 }
1543 subprog_start = subprog_end;
4cb3d99c
JW
1544 cur_subprog++;
1545 if (cur_subprog < env->subprog_cnt)
9c8105bd 1546 subprog_end = subprog[cur_subprog + 1].start;
cc8b0b92
AS
1547 }
1548 }
1549 return 0;
1550}
1551
679c782d
EC
1552/* Parentage chain of this register (or stack slot) should take care of all
1553 * issues like callee-saved registers, stack slot allocation time, etc.
1554 */
f4d7e40a 1555static int mark_reg_read(struct bpf_verifier_env *env,
679c782d 1556 const struct bpf_reg_state *state,
5327ed3d 1557 struct bpf_reg_state *parent, u8 flag)
f4d7e40a
AS
1558{
1559 bool writes = parent == state->parent; /* Observe write marks */
06ee7115 1560 int cnt = 0;
dc503a8a
EC
1561
1562 while (parent) {
1563 /* if read wasn't screened by an earlier write ... */
679c782d 1564 if (writes && state->live & REG_LIVE_WRITTEN)
dc503a8a 1565 break;
9242b5f5
AS
1566 if (parent->live & REG_LIVE_DONE) {
1567 verbose(env, "verifier BUG type %s var_off %lld off %d\n",
1568 reg_type_str[parent->type],
1569 parent->var_off.value, parent->off);
1570 return -EFAULT;
1571 }
5327ed3d
JW
1572 /* The first condition is more likely to be true than the
1573 * second, checked it first.
1574 */
1575 if ((parent->live & REG_LIVE_READ) == flag ||
1576 parent->live & REG_LIVE_READ64)
25af32da
AS
1577 /* The parentage chain never changes and
1578 * this parent was already marked as LIVE_READ.
1579 * There is no need to keep walking the chain again and
1580 * keep re-marking all parents as LIVE_READ.
1581 * This case happens when the same register is read
1582 * multiple times without writes into it in-between.
5327ed3d
JW
1583 * Also, if parent has the stronger REG_LIVE_READ64 set,
1584 * then no need to set the weak REG_LIVE_READ32.
25af32da
AS
1585 */
1586 break;
dc503a8a 1587 /* ... then we depend on parent's value */
5327ed3d
JW
1588 parent->live |= flag;
1589 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
1590 if (flag == REG_LIVE_READ64)
1591 parent->live &= ~REG_LIVE_READ32;
dc503a8a
EC
1592 state = parent;
1593 parent = state->parent;
f4d7e40a 1594 writes = true;
06ee7115 1595 cnt++;
dc503a8a 1596 }
06ee7115
AS
1597
1598 if (env->longest_mark_read_walk < cnt)
1599 env->longest_mark_read_walk = cnt;
f4d7e40a 1600 return 0;
dc503a8a
EC
1601}
1602
5327ed3d
JW
1603/* This function is supposed to be used by the following 32-bit optimization
1604 * code only. It returns TRUE if the source or destination register operates
1605 * on 64-bit, otherwise return FALSE.
1606 */
1607static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
1608 u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
1609{
1610 u8 code, class, op;
1611
1612 code = insn->code;
1613 class = BPF_CLASS(code);
1614 op = BPF_OP(code);
1615 if (class == BPF_JMP) {
1616 /* BPF_EXIT for "main" will reach here. Return TRUE
1617 * conservatively.
1618 */
1619 if (op == BPF_EXIT)
1620 return true;
1621 if (op == BPF_CALL) {
1622 /* BPF to BPF call will reach here because of marking
1623 * caller saved clobber with DST_OP_NO_MARK for which we
1624 * don't care the register def because they are anyway
1625 * marked as NOT_INIT already.
1626 */
1627 if (insn->src_reg == BPF_PSEUDO_CALL)
1628 return false;
1629 /* Helper call will reach here because of arg type
1630 * check, conservatively return TRUE.
1631 */
1632 if (t == SRC_OP)
1633 return true;
1634
1635 return false;
1636 }
1637 }
1638
1639 if (class == BPF_ALU64 || class == BPF_JMP ||
1640 /* BPF_END always use BPF_ALU class. */
1641 (class == BPF_ALU && op == BPF_END && insn->imm == 64))
1642 return true;
1643
1644 if (class == BPF_ALU || class == BPF_JMP32)
1645 return false;
1646
1647 if (class == BPF_LDX) {
1648 if (t != SRC_OP)
1649 return BPF_SIZE(code) == BPF_DW;
1650 /* LDX source must be ptr. */
1651 return true;
1652 }
1653
1654 if (class == BPF_STX) {
1655 if (reg->type != SCALAR_VALUE)
1656 return true;
1657 return BPF_SIZE(code) == BPF_DW;
1658 }
1659
1660 if (class == BPF_LD) {
1661 u8 mode = BPF_MODE(code);
1662
1663 /* LD_IMM64 */
1664 if (mode == BPF_IMM)
1665 return true;
1666
1667 /* Both LD_IND and LD_ABS return 32-bit data. */
1668 if (t != SRC_OP)
1669 return false;
1670
1671 /* Implicit ctx ptr. */
1672 if (regno == BPF_REG_6)
1673 return true;
1674
1675 /* Explicit source could be any width. */
1676 return true;
1677 }
1678
1679 if (class == BPF_ST)
1680 /* The only source register for BPF_ST is a ptr. */
1681 return true;
1682
1683 /* Conservatively return true at default. */
1684 return true;
1685}
1686
b325fbca
JW
1687/* Return TRUE if INSN doesn't have explicit value define. */
1688static bool insn_no_def(struct bpf_insn *insn)
1689{
1690 u8 class = BPF_CLASS(insn->code);
1691
1692 return (class == BPF_JMP || class == BPF_JMP32 ||
1693 class == BPF_STX || class == BPF_ST);
1694}
1695
1696/* Return TRUE if INSN has defined any 32-bit value explicitly. */
1697static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
1698{
1699 if (insn_no_def(insn))
1700 return false;
1701
1702 return !is_reg64(env, insn, insn->dst_reg, NULL, DST_OP);
1703}
1704
5327ed3d
JW
1705static void mark_insn_zext(struct bpf_verifier_env *env,
1706 struct bpf_reg_state *reg)
1707{
1708 s32 def_idx = reg->subreg_def;
1709
1710 if (def_idx == DEF_NOT_SUBREG)
1711 return;
1712
1713 env->insn_aux_data[def_idx - 1].zext_dst = true;
1714 /* The dst will be zero extended, so won't be sub-register anymore. */
1715 reg->subreg_def = DEF_NOT_SUBREG;
1716}
1717
dc503a8a 1718static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
17a52670
AS
1719 enum reg_arg_type t)
1720{
f4d7e40a
AS
1721 struct bpf_verifier_state *vstate = env->cur_state;
1722 struct bpf_func_state *state = vstate->frame[vstate->curframe];
5327ed3d 1723 struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
c342dc10 1724 struct bpf_reg_state *reg, *regs = state->regs;
5327ed3d 1725 bool rw64;
dc503a8a 1726
17a52670 1727 if (regno >= MAX_BPF_REG) {
61bd5218 1728 verbose(env, "R%d is invalid\n", regno);
17a52670
AS
1729 return -EINVAL;
1730 }
1731
c342dc10 1732 reg = &regs[regno];
5327ed3d 1733 rw64 = is_reg64(env, insn, regno, reg, t);
17a52670
AS
1734 if (t == SRC_OP) {
1735 /* check whether register used as source operand can be read */
c342dc10 1736 if (reg->type == NOT_INIT) {
61bd5218 1737 verbose(env, "R%d !read_ok\n", regno);
17a52670
AS
1738 return -EACCES;
1739 }
679c782d 1740 /* We don't need to worry about FP liveness because it's read-only */
c342dc10
JW
1741 if (regno == BPF_REG_FP)
1742 return 0;
1743
5327ed3d
JW
1744 if (rw64)
1745 mark_insn_zext(env, reg);
1746
1747 return mark_reg_read(env, reg, reg->parent,
1748 rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
17a52670
AS
1749 } else {
1750 /* check whether register used as dest operand can be written to */
1751 if (regno == BPF_REG_FP) {
61bd5218 1752 verbose(env, "frame pointer is read only\n");
17a52670
AS
1753 return -EACCES;
1754 }
c342dc10 1755 reg->live |= REG_LIVE_WRITTEN;
5327ed3d 1756 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
17a52670 1757 if (t == DST_OP)
61bd5218 1758 mark_reg_unknown(env, regs, regno);
17a52670
AS
1759 }
1760 return 0;
1761}
1762
b5dc0163
AS
1763/* for any branch, call, exit record the history of jmps in the given state */
1764static int push_jmp_history(struct bpf_verifier_env *env,
1765 struct bpf_verifier_state *cur)
1766{
1767 u32 cnt = cur->jmp_history_cnt;
1768 struct bpf_idx_pair *p;
1769
1770 cnt++;
1771 p = krealloc(cur->jmp_history, cnt * sizeof(*p), GFP_USER);
1772 if (!p)
1773 return -ENOMEM;
1774 p[cnt - 1].idx = env->insn_idx;
1775 p[cnt - 1].prev_idx = env->prev_insn_idx;
1776 cur->jmp_history = p;
1777 cur->jmp_history_cnt = cnt;
1778 return 0;
1779}
1780
1781/* Backtrack one insn at a time. If idx is not at the top of recorded
1782 * history then previous instruction came from straight line execution.
1783 */
1784static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
1785 u32 *history)
1786{
1787 u32 cnt = *history;
1788
1789 if (cnt && st->jmp_history[cnt - 1].idx == i) {
1790 i = st->jmp_history[cnt - 1].prev_idx;
1791 (*history)--;
1792 } else {
1793 i--;
1794 }
1795 return i;
1796}
1797
1798/* For given verifier state backtrack_insn() is called from the last insn to
1799 * the first insn. Its purpose is to compute a bitmask of registers and
1800 * stack slots that needs precision in the parent verifier state.
1801 */
1802static int backtrack_insn(struct bpf_verifier_env *env, int idx,
1803 u32 *reg_mask, u64 *stack_mask)
1804{
1805 const struct bpf_insn_cbs cbs = {
1806 .cb_print = verbose,
1807 .private_data = env,
1808 };
1809 struct bpf_insn *insn = env->prog->insnsi + idx;
1810 u8 class = BPF_CLASS(insn->code);
1811 u8 opcode = BPF_OP(insn->code);
1812 u8 mode = BPF_MODE(insn->code);
1813 u32 dreg = 1u << insn->dst_reg;
1814 u32 sreg = 1u << insn->src_reg;
1815 u32 spi;
1816
1817 if (insn->code == 0)
1818 return 0;
1819 if (env->log.level & BPF_LOG_LEVEL) {
1820 verbose(env, "regs=%x stack=%llx before ", *reg_mask, *stack_mask);
1821 verbose(env, "%d: ", idx);
1822 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
1823 }
1824
1825 if (class == BPF_ALU || class == BPF_ALU64) {
1826 if (!(*reg_mask & dreg))
1827 return 0;
1828 if (opcode == BPF_MOV) {
1829 if (BPF_SRC(insn->code) == BPF_X) {
1830 /* dreg = sreg
1831 * dreg needs precision after this insn
1832 * sreg needs precision before this insn
1833 */
1834 *reg_mask &= ~dreg;
1835 *reg_mask |= sreg;
1836 } else {
1837 /* dreg = K
1838 * dreg needs precision after this insn.
1839 * Corresponding register is already marked
1840 * as precise=true in this verifier state.
1841 * No further markings in parent are necessary
1842 */
1843 *reg_mask &= ~dreg;
1844 }
1845 } else {
1846 if (BPF_SRC(insn->code) == BPF_X) {
1847 /* dreg += sreg
1848 * both dreg and sreg need precision
1849 * before this insn
1850 */
1851 *reg_mask |= sreg;
1852 } /* else dreg += K
1853 * dreg still needs precision before this insn
1854 */
1855 }
1856 } else if (class == BPF_LDX) {
1857 if (!(*reg_mask & dreg))
1858 return 0;
1859 *reg_mask &= ~dreg;
1860
1861 /* scalars can only be spilled into stack w/o losing precision.
1862 * Load from any other memory can be zero extended.
1863 * The desire to keep that precision is already indicated
1864 * by 'precise' mark in corresponding register of this state.
1865 * No further tracking necessary.
1866 */
1867 if (insn->src_reg != BPF_REG_FP)
1868 return 0;
1869 if (BPF_SIZE(insn->code) != BPF_DW)
1870 return 0;
1871
1872 /* dreg = *(u64 *)[fp - off] was a fill from the stack.
1873 * that [fp - off] slot contains scalar that needs to be
1874 * tracked with precision
1875 */
1876 spi = (-insn->off - 1) / BPF_REG_SIZE;
1877 if (spi >= 64) {
1878 verbose(env, "BUG spi %d\n", spi);
1879 WARN_ONCE(1, "verifier backtracking bug");
1880 return -EFAULT;
1881 }
1882 *stack_mask |= 1ull << spi;
b3b50f05 1883 } else if (class == BPF_STX || class == BPF_ST) {
b5dc0163 1884 if (*reg_mask & dreg)
b3b50f05 1885 /* stx & st shouldn't be using _scalar_ dst_reg
b5dc0163
AS
1886 * to access memory. It means backtracking
1887 * encountered a case of pointer subtraction.
1888 */
1889 return -ENOTSUPP;
1890 /* scalars can only be spilled into stack */
1891 if (insn->dst_reg != BPF_REG_FP)
1892 return 0;
1893 if (BPF_SIZE(insn->code) != BPF_DW)
1894 return 0;
1895 spi = (-insn->off - 1) / BPF_REG_SIZE;
1896 if (spi >= 64) {
1897 verbose(env, "BUG spi %d\n", spi);
1898 WARN_ONCE(1, "verifier backtracking bug");
1899 return -EFAULT;
1900 }
1901 if (!(*stack_mask & (1ull << spi)))
1902 return 0;
1903 *stack_mask &= ~(1ull << spi);
b3b50f05
AN
1904 if (class == BPF_STX)
1905 *reg_mask |= sreg;
b5dc0163
AS
1906 } else if (class == BPF_JMP || class == BPF_JMP32) {
1907 if (opcode == BPF_CALL) {
1908 if (insn->src_reg == BPF_PSEUDO_CALL)
1909 return -ENOTSUPP;
1910 /* regular helper call sets R0 */
1911 *reg_mask &= ~1;
1912 if (*reg_mask & 0x3f) {
1913 /* if backtracing was looking for registers R1-R5
1914 * they should have been found already.
1915 */
1916 verbose(env, "BUG regs %x\n", *reg_mask);
1917 WARN_ONCE(1, "verifier backtracking bug");
1918 return -EFAULT;
1919 }
1920 } else if (opcode == BPF_EXIT) {
1921 return -ENOTSUPP;
1922 }
1923 } else if (class == BPF_LD) {
1924 if (!(*reg_mask & dreg))
1925 return 0;
1926 *reg_mask &= ~dreg;
1927 /* It's ld_imm64 or ld_abs or ld_ind.
1928 * For ld_imm64 no further tracking of precision
1929 * into parent is necessary
1930 */
1931 if (mode == BPF_IND || mode == BPF_ABS)
1932 /* to be analyzed */
1933 return -ENOTSUPP;
b5dc0163
AS
1934 }
1935 return 0;
1936}
1937
1938/* the scalar precision tracking algorithm:
1939 * . at the start all registers have precise=false.
1940 * . scalar ranges are tracked as normal through alu and jmp insns.
1941 * . once precise value of the scalar register is used in:
1942 * . ptr + scalar alu
1943 * . if (scalar cond K|scalar)
1944 * . helper_call(.., scalar, ...) where ARG_CONST is expected
1945 * backtrack through the verifier states and mark all registers and
1946 * stack slots with spilled constants that these scalar regisers
1947 * should be precise.
1948 * . during state pruning two registers (or spilled stack slots)
1949 * are equivalent if both are not precise.
1950 *
1951 * Note the verifier cannot simply walk register parentage chain,
1952 * since many different registers and stack slots could have been
1953 * used to compute single precise scalar.
1954 *
1955 * The approach of starting with precise=true for all registers and then
1956 * backtrack to mark a register as not precise when the verifier detects
1957 * that program doesn't care about specific value (e.g., when helper
1958 * takes register as ARG_ANYTHING parameter) is not safe.
1959 *
1960 * It's ok to walk single parentage chain of the verifier states.
1961 * It's possible that this backtracking will go all the way till 1st insn.
1962 * All other branches will be explored for needing precision later.
1963 *
1964 * The backtracking needs to deal with cases like:
1965 * R8=map_value(id=0,off=0,ks=4,vs=1952,imm=0) R9_w=map_value(id=0,off=40,ks=4,vs=1952,imm=0)
1966 * r9 -= r8
1967 * r5 = r9
1968 * if r5 > 0x79f goto pc+7
1969 * R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
1970 * r5 += 1
1971 * ...
1972 * call bpf_perf_event_output#25
1973 * where .arg5_type = ARG_CONST_SIZE_OR_ZERO
1974 *
1975 * and this case:
1976 * r6 = 1
1977 * call foo // uses callee's r6 inside to compute r0
1978 * r0 += r6
1979 * if r0 == 0 goto
1980 *
1981 * to track above reg_mask/stack_mask needs to be independent for each frame.
1982 *
1983 * Also if parent's curframe > frame where backtracking started,
1984 * the verifier need to mark registers in both frames, otherwise callees
1985 * may incorrectly prune callers. This is similar to
1986 * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
1987 *
1988 * For now backtracking falls back into conservative marking.
1989 */
1990static void mark_all_scalars_precise(struct bpf_verifier_env *env,
1991 struct bpf_verifier_state *st)
1992{
1993 struct bpf_func_state *func;
1994 struct bpf_reg_state *reg;
1995 int i, j;
1996
1997 /* big hammer: mark all scalars precise in this path.
1998 * pop_stack may still get !precise scalars.
1999 */
2000 for (; st; st = st->parent)
2001 for (i = 0; i <= st->curframe; i++) {
2002 func = st->frame[i];
2003 for (j = 0; j < BPF_REG_FP; j++) {
2004 reg = &func->regs[j];
2005 if (reg->type != SCALAR_VALUE)
2006 continue;
2007 reg->precise = true;
2008 }
2009 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
2010 if (func->stack[j].slot_type[0] != STACK_SPILL)
2011 continue;
2012 reg = &func->stack[j].spilled_ptr;
2013 if (reg->type != SCALAR_VALUE)
2014 continue;
2015 reg->precise = true;
2016 }
2017 }
2018}
2019
a3ce685d
AS
2020static int __mark_chain_precision(struct bpf_verifier_env *env, int regno,
2021 int spi)
b5dc0163
AS
2022{
2023 struct bpf_verifier_state *st = env->cur_state;
2024 int first_idx = st->first_insn_idx;
2025 int last_idx = env->insn_idx;
2026 struct bpf_func_state *func;
2027 struct bpf_reg_state *reg;
a3ce685d
AS
2028 u32 reg_mask = regno >= 0 ? 1u << regno : 0;
2029 u64 stack_mask = spi >= 0 ? 1ull << spi : 0;
b5dc0163 2030 bool skip_first = true;
a3ce685d 2031 bool new_marks = false;
b5dc0163
AS
2032 int i, err;
2033
2c78ee89 2034 if (!env->bpf_capable)
b5dc0163
AS
2035 return 0;
2036
2037 func = st->frame[st->curframe];
a3ce685d
AS
2038 if (regno >= 0) {
2039 reg = &func->regs[regno];
2040 if (reg->type != SCALAR_VALUE) {
2041 WARN_ONCE(1, "backtracing misuse");
2042 return -EFAULT;
2043 }
2044 if (!reg->precise)
2045 new_marks = true;
2046 else
2047 reg_mask = 0;
2048 reg->precise = true;
b5dc0163 2049 }
b5dc0163 2050
a3ce685d
AS
2051 while (spi >= 0) {
2052 if (func->stack[spi].slot_type[0] != STACK_SPILL) {
2053 stack_mask = 0;
2054 break;
2055 }
2056 reg = &func->stack[spi].spilled_ptr;
2057 if (reg->type != SCALAR_VALUE) {
2058 stack_mask = 0;
2059 break;
2060 }
2061 if (!reg->precise)
2062 new_marks = true;
2063 else
2064 stack_mask = 0;
2065 reg->precise = true;
2066 break;
2067 }
2068
2069 if (!new_marks)
2070 return 0;
2071 if (!reg_mask && !stack_mask)
2072 return 0;
b5dc0163
AS
2073 for (;;) {
2074 DECLARE_BITMAP(mask, 64);
b5dc0163
AS
2075 u32 history = st->jmp_history_cnt;
2076
2077 if (env->log.level & BPF_LOG_LEVEL)
2078 verbose(env, "last_idx %d first_idx %d\n", last_idx, first_idx);
2079 for (i = last_idx;;) {
2080 if (skip_first) {
2081 err = 0;
2082 skip_first = false;
2083 } else {
2084 err = backtrack_insn(env, i, &reg_mask, &stack_mask);
2085 }
2086 if (err == -ENOTSUPP) {
2087 mark_all_scalars_precise(env, st);
2088 return 0;
2089 } else if (err) {
2090 return err;
2091 }
2092 if (!reg_mask && !stack_mask)
2093 /* Found assignment(s) into tracked register in this state.
2094 * Since this state is already marked, just return.
2095 * Nothing to be tracked further in the parent state.
2096 */
2097 return 0;
2098 if (i == first_idx)
2099 break;
2100 i = get_prev_insn_idx(st, i, &history);
2101 if (i >= env->prog->len) {
2102 /* This can happen if backtracking reached insn 0
2103 * and there are still reg_mask or stack_mask
2104 * to backtrack.
2105 * It means the backtracking missed the spot where
2106 * particular register was initialized with a constant.
2107 */
2108 verbose(env, "BUG backtracking idx %d\n", i);
2109 WARN_ONCE(1, "verifier backtracking bug");
2110 return -EFAULT;
2111 }
2112 }
2113 st = st->parent;
2114 if (!st)
2115 break;
2116
a3ce685d 2117 new_marks = false;
b5dc0163
AS
2118 func = st->frame[st->curframe];
2119 bitmap_from_u64(mask, reg_mask);
2120 for_each_set_bit(i, mask, 32) {
2121 reg = &func->regs[i];
a3ce685d
AS
2122 if (reg->type != SCALAR_VALUE) {
2123 reg_mask &= ~(1u << i);
b5dc0163 2124 continue;
a3ce685d 2125 }
b5dc0163
AS
2126 if (!reg->precise)
2127 new_marks = true;
2128 reg->precise = true;
2129 }
2130
2131 bitmap_from_u64(mask, stack_mask);
2132 for_each_set_bit(i, mask, 64) {
2133 if (i >= func->allocated_stack / BPF_REG_SIZE) {
2339cd6c
AS
2134 /* the sequence of instructions:
2135 * 2: (bf) r3 = r10
2136 * 3: (7b) *(u64 *)(r3 -8) = r0
2137 * 4: (79) r4 = *(u64 *)(r10 -8)
2138 * doesn't contain jmps. It's backtracked
2139 * as a single block.
2140 * During backtracking insn 3 is not recognized as
2141 * stack access, so at the end of backtracking
2142 * stack slot fp-8 is still marked in stack_mask.
2143 * However the parent state may not have accessed
2144 * fp-8 and it's "unallocated" stack space.
2145 * In such case fallback to conservative.
b5dc0163 2146 */
2339cd6c
AS
2147 mark_all_scalars_precise(env, st);
2148 return 0;
b5dc0163
AS
2149 }
2150
a3ce685d
AS
2151 if (func->stack[i].slot_type[0] != STACK_SPILL) {
2152 stack_mask &= ~(1ull << i);
b5dc0163 2153 continue;
a3ce685d 2154 }
b5dc0163 2155 reg = &func->stack[i].spilled_ptr;
a3ce685d
AS
2156 if (reg->type != SCALAR_VALUE) {
2157 stack_mask &= ~(1ull << i);
b5dc0163 2158 continue;
a3ce685d 2159 }
b5dc0163
AS
2160 if (!reg->precise)
2161 new_marks = true;
2162 reg->precise = true;
2163 }
2164 if (env->log.level & BPF_LOG_LEVEL) {
2165 print_verifier_state(env, func);
2166 verbose(env, "parent %s regs=%x stack=%llx marks\n",
2167 new_marks ? "didn't have" : "already had",
2168 reg_mask, stack_mask);
2169 }
2170
a3ce685d
AS
2171 if (!reg_mask && !stack_mask)
2172 break;
b5dc0163
AS
2173 if (!new_marks)
2174 break;
2175
2176 last_idx = st->last_insn_idx;
2177 first_idx = st->first_insn_idx;
2178 }
2179 return 0;
2180}
2181
a3ce685d
AS
2182static int mark_chain_precision(struct bpf_verifier_env *env, int regno)
2183{
2184 return __mark_chain_precision(env, regno, -1);
2185}
2186
2187static int mark_chain_precision_stack(struct bpf_verifier_env *env, int spi)
2188{
2189 return __mark_chain_precision(env, -1, spi);
2190}
b5dc0163 2191
1be7f75d
AS
2192static bool is_spillable_regtype(enum bpf_reg_type type)
2193{
2194 switch (type) {
2195 case PTR_TO_MAP_VALUE:
2196 case PTR_TO_MAP_VALUE_OR_NULL:
2197 case PTR_TO_STACK:
2198 case PTR_TO_CTX:
969bf05e 2199 case PTR_TO_PACKET:
de8f3a83 2200 case PTR_TO_PACKET_META:
969bf05e 2201 case PTR_TO_PACKET_END:
d58e468b 2202 case PTR_TO_FLOW_KEYS:
1be7f75d 2203 case CONST_PTR_TO_MAP:
c64b7983
JS
2204 case PTR_TO_SOCKET:
2205 case PTR_TO_SOCKET_OR_NULL:
46f8bc92
MKL
2206 case PTR_TO_SOCK_COMMON:
2207 case PTR_TO_SOCK_COMMON_OR_NULL:
655a51e5
MKL
2208 case PTR_TO_TCP_SOCK:
2209 case PTR_TO_TCP_SOCK_OR_NULL:
fada7fdc 2210 case PTR_TO_XDP_SOCK:
65726b5b 2211 case PTR_TO_BTF_ID:
b121b341 2212 case PTR_TO_BTF_ID_OR_NULL:
afbf21dc
YS
2213 case PTR_TO_RDONLY_BUF:
2214 case PTR_TO_RDONLY_BUF_OR_NULL:
2215 case PTR_TO_RDWR_BUF:
2216 case PTR_TO_RDWR_BUF_OR_NULL:
eaa6bcb7 2217 case PTR_TO_PERCPU_BTF_ID:
744ea4e3
GR
2218 case PTR_TO_MEM:
2219 case PTR_TO_MEM_OR_NULL:
1be7f75d
AS
2220 return true;
2221 default:
2222 return false;
2223 }
2224}
2225
cc2b14d5
AS
2226/* Does this register contain a constant zero? */
2227static bool register_is_null(struct bpf_reg_state *reg)
2228{
2229 return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
2230}
2231
f7cf25b2
AS
2232static bool register_is_const(struct bpf_reg_state *reg)
2233{
2234 return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
2235}
2236
5689d49b
YS
2237static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
2238{
2239 return tnum_is_unknown(reg->var_off) &&
2240 reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
2241 reg->umin_value == 0 && reg->umax_value == U64_MAX &&
2242 reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
2243 reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
2244}
2245
2246static bool register_is_bounded(struct bpf_reg_state *reg)
2247{
2248 return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
2249}
2250
6e7e63cb
JH
2251static bool __is_pointer_value(bool allow_ptr_leaks,
2252 const struct bpf_reg_state *reg)
2253{
2254 if (allow_ptr_leaks)
2255 return false;
2256
2257 return reg->type != SCALAR_VALUE;
2258}
2259
f7cf25b2
AS
2260static void save_register_state(struct bpf_func_state *state,
2261 int spi, struct bpf_reg_state *reg)
2262{
2263 int i;
2264
2265 state->stack[spi].spilled_ptr = *reg;
2266 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
2267
2268 for (i = 0; i < BPF_REG_SIZE; i++)
2269 state->stack[spi].slot_type[i] = STACK_SPILL;
2270}
2271
ca5b89bf 2272/* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
17a52670
AS
2273 * stack boundary and alignment are checked in check_mem_access()
2274 */
ca5b89bf
AM
2275static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
2276 /* stack frame we're writing to */
2277 struct bpf_func_state *state,
2278 int off, int size, int value_regno,
2279 int insn_idx)
17a52670 2280{
f4d7e40a 2281 struct bpf_func_state *cur; /* state of the current function */
638f5b90 2282 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
b5dc0163 2283 u32 dst_reg = env->prog->insnsi[insn_idx].dst_reg;
f7cf25b2 2284 struct bpf_reg_state *reg = NULL;
638f5b90 2285
f4d7e40a 2286 err = realloc_func_state(state, round_up(slot + 1, BPF_REG_SIZE),
fd978bf7 2287 state->acquired_refs, true);
638f5b90
AS
2288 if (err)
2289 return err;
9c399760
AS
2290 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
2291 * so it's aligned access and [off, off + size) are within stack limits
2292 */
638f5b90
AS
2293 if (!env->allow_ptr_leaks &&
2294 state->stack[spi].slot_type[0] == STACK_SPILL &&
2295 size != BPF_REG_SIZE) {
2296 verbose(env, "attempt to corrupt spilled pointer on stack\n");
2297 return -EACCES;
2298 }
17a52670 2299
f4d7e40a 2300 cur = env->cur_state->frame[env->cur_state->curframe];
f7cf25b2
AS
2301 if (value_regno >= 0)
2302 reg = &cur->regs[value_regno];
17a52670 2303
5689d49b 2304 if (reg && size == BPF_REG_SIZE && register_is_bounded(reg) &&
2c78ee89 2305 !register_is_null(reg) && env->bpf_capable) {
b5dc0163
AS
2306 if (dst_reg != BPF_REG_FP) {
2307 /* The backtracking logic can only recognize explicit
2308 * stack slot address like [fp - 8]. Other spill of
2309 * scalar via different register has to be conervative.
2310 * Backtrack from here and mark all registers as precise
2311 * that contributed into 'reg' being a constant.
2312 */
2313 err = mark_chain_precision(env, value_regno);
2314 if (err)
2315 return err;
2316 }
f7cf25b2
AS
2317 save_register_state(state, spi, reg);
2318 } else if (reg && is_spillable_regtype(reg->type)) {
17a52670 2319 /* register containing pointer is being spilled into stack */
9c399760 2320 if (size != BPF_REG_SIZE) {
f7cf25b2 2321 verbose_linfo(env, insn_idx, "; ");
61bd5218 2322 verbose(env, "invalid size of register spill\n");
17a52670
AS
2323 return -EACCES;
2324 }
2325
f7cf25b2 2326 if (state != cur && reg->type == PTR_TO_STACK) {
f4d7e40a
AS
2327 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
2328 return -EINVAL;
2329 }
2330
2c78ee89 2331 if (!env->bypass_spec_v4) {
f7cf25b2 2332 bool sanitize = false;
17a52670 2333
f7cf25b2
AS
2334 if (state->stack[spi].slot_type[0] == STACK_SPILL &&
2335 register_is_const(&state->stack[spi].spilled_ptr))
2336 sanitize = true;
2337 for (i = 0; i < BPF_REG_SIZE; i++)
2338 if (state->stack[spi].slot_type[i] == STACK_MISC) {
2339 sanitize = true;
2340 break;
2341 }
2342 if (sanitize) {
af86ca4e
AS
2343 int *poff = &env->insn_aux_data[insn_idx].sanitize_stack_off;
2344 int soff = (-spi - 1) * BPF_REG_SIZE;
2345
2346 /* detected reuse of integer stack slot with a pointer
2347 * which means either llvm is reusing stack slot or
2348 * an attacker is trying to exploit CVE-2018-3639
2349 * (speculative store bypass)
2350 * Have to sanitize that slot with preemptive
2351 * store of zero.
2352 */
2353 if (*poff && *poff != soff) {
2354 /* disallow programs where single insn stores
2355 * into two different stack slots, since verifier
2356 * cannot sanitize them
2357 */
2358 verbose(env,
2359 "insn %d cannot access two stack slots fp%d and fp%d",
2360 insn_idx, *poff, soff);
2361 return -EINVAL;
2362 }
2363 *poff = soff;
2364 }
af86ca4e 2365 }
f7cf25b2 2366 save_register_state(state, spi, reg);
9c399760 2367 } else {
cc2b14d5
AS
2368 u8 type = STACK_MISC;
2369
679c782d
EC
2370 /* regular write of data into stack destroys any spilled ptr */
2371 state->stack[spi].spilled_ptr.type = NOT_INIT;
0bae2d4d
JW
2372 /* Mark slots as STACK_MISC if they belonged to spilled ptr. */
2373 if (state->stack[spi].slot_type[0] == STACK_SPILL)
2374 for (i = 0; i < BPF_REG_SIZE; i++)
2375 state->stack[spi].slot_type[i] = STACK_MISC;
9c399760 2376
cc2b14d5
AS
2377 /* only mark the slot as written if all 8 bytes were written
2378 * otherwise read propagation may incorrectly stop too soon
2379 * when stack slots are partially written.
2380 * This heuristic means that read propagation will be
2381 * conservative, since it will add reg_live_read marks
2382 * to stack slots all the way to first state when programs
2383 * writes+reads less than 8 bytes
2384 */
2385 if (size == BPF_REG_SIZE)
2386 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
2387
2388 /* when we zero initialize stack slots mark them as such */
b5dc0163
AS
2389 if (reg && register_is_null(reg)) {
2390 /* backtracking doesn't work for STACK_ZERO yet. */
2391 err = mark_chain_precision(env, value_regno);
2392 if (err)
2393 return err;
cc2b14d5 2394 type = STACK_ZERO;
b5dc0163 2395 }
cc2b14d5 2396
0bae2d4d 2397 /* Mark slots affected by this stack write. */
9c399760 2398 for (i = 0; i < size; i++)
638f5b90 2399 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
cc2b14d5 2400 type;
17a52670
AS
2401 }
2402 return 0;
2403}
2404
ca5b89bf
AM
2405/* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
2406 * known to contain a variable offset.
2407 * This function checks whether the write is permitted and conservatively
2408 * tracks the effects of the write, considering that each stack slot in the
2409 * dynamic range is potentially written to.
2410 *
2411 * 'off' includes 'regno->off'.
2412 * 'value_regno' can be -1, meaning that an unknown value is being written to
2413 * the stack.
2414 *
2415 * Spilled pointers in range are not marked as written because we don't know
2416 * what's going to be actually written. This means that read propagation for
2417 * future reads cannot be terminated by this write.
2418 *
2419 * For privileged programs, uninitialized stack slots are considered
2420 * initialized by this write (even though we don't know exactly what offsets
2421 * are going to be written to). The idea is that we don't want the verifier to
2422 * reject future reads that access slots written to through variable offsets.
2423 */
2424static int check_stack_write_var_off(struct bpf_verifier_env *env,
2425 /* func where register points to */
2426 struct bpf_func_state *state,
2427 int ptr_regno, int off, int size,
2428 int value_regno, int insn_idx)
2429{
2430 struct bpf_func_state *cur; /* state of the current function */
2431 int min_off, max_off;
2432 int i, err;
2433 struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
2434 bool writing_zero = false;
2435 /* set if the fact that we're writing a zero is used to let any
2436 * stack slots remain STACK_ZERO
2437 */
2438 bool zero_used = false;
2439
2440 cur = env->cur_state->frame[env->cur_state->curframe];
2441 ptr_reg = &cur->regs[ptr_regno];
2442 min_off = ptr_reg->smin_value + off;
2443 max_off = ptr_reg->smax_value + off + size;
2444 if (value_regno >= 0)
2445 value_reg = &cur->regs[value_regno];
2446 if (value_reg && register_is_null(value_reg))
2447 writing_zero = true;
2448
2449 err = realloc_func_state(state, round_up(-min_off, BPF_REG_SIZE),
2450 state->acquired_refs, true);
2451 if (err)
2452 return err;
2453
2454
2455 /* Variable offset writes destroy any spilled pointers in range. */
2456 for (i = min_off; i < max_off; i++) {
2457 u8 new_type, *stype;
2458 int slot, spi;
2459
2460 slot = -i - 1;
2461 spi = slot / BPF_REG_SIZE;
2462 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
2463
2464 if (!env->allow_ptr_leaks
2465 && *stype != NOT_INIT
2466 && *stype != SCALAR_VALUE) {
2467 /* Reject the write if there's are spilled pointers in
2468 * range. If we didn't reject here, the ptr status
2469 * would be erased below (even though not all slots are
2470 * actually overwritten), possibly opening the door to
2471 * leaks.
2472 */
2473 verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
2474 insn_idx, i);
2475 return -EINVAL;
2476 }
2477
2478 /* Erase all spilled pointers. */
2479 state->stack[spi].spilled_ptr.type = NOT_INIT;
2480
2481 /* Update the slot type. */
2482 new_type = STACK_MISC;
2483 if (writing_zero && *stype == STACK_ZERO) {
2484 new_type = STACK_ZERO;
2485 zero_used = true;
2486 }
2487 /* If the slot is STACK_INVALID, we check whether it's OK to
2488 * pretend that it will be initialized by this write. The slot
2489 * might not actually be written to, and so if we mark it as
2490 * initialized future reads might leak uninitialized memory.
2491 * For privileged programs, we will accept such reads to slots
2492 * that may or may not be written because, if we're reject
2493 * them, the error would be too confusing.
2494 */
2495 if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
2496 verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
2497 insn_idx, i);
2498 return -EINVAL;
2499 }
2500 *stype = new_type;
2501 }
2502 if (zero_used) {
2503 /* backtracking doesn't work for STACK_ZERO yet. */
2504 err = mark_chain_precision(env, value_regno);
2505 if (err)
2506 return err;
2507 }
2508 return 0;
2509}
2510
2511/* When register 'dst_regno' is assigned some values from stack[min_off,
2512 * max_off), we set the register's type according to the types of the
2513 * respective stack slots. If all the stack values are known to be zeros, then
2514 * so is the destination reg. Otherwise, the register is considered to be
2515 * SCALAR. This function does not deal with register filling; the caller must
2516 * ensure that all spilled registers in the stack range have been marked as
2517 * read.
2518 */
2519static void mark_reg_stack_read(struct bpf_verifier_env *env,
2520 /* func where src register points to */
2521 struct bpf_func_state *ptr_state,
2522 int min_off, int max_off, int dst_regno)
2523{
2524 struct bpf_verifier_state *vstate = env->cur_state;
2525 struct bpf_func_state *state = vstate->frame[vstate->curframe];
2526 int i, slot, spi;
2527 u8 *stype;
2528 int zeros = 0;
2529
2530 for (i = min_off; i < max_off; i++) {
2531 slot = -i - 1;
2532 spi = slot / BPF_REG_SIZE;
2533 stype = ptr_state->stack[spi].slot_type;
2534 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
2535 break;
2536 zeros++;
2537 }
2538 if (zeros == max_off - min_off) {
2539 /* any access_size read into register is zero extended,
2540 * so the whole register == const_zero
2541 */
2542 __mark_reg_const_zero(&state->regs[dst_regno]);
2543 /* backtracking doesn't support STACK_ZERO yet,
2544 * so mark it precise here, so that later
2545 * backtracking can stop here.
2546 * Backtracking may not need this if this register
2547 * doesn't participate in pointer adjustment.
2548 * Forward propagation of precise flag is not
2549 * necessary either. This mark is only to stop
2550 * backtracking. Any register that contributed
2551 * to const 0 was marked precise before spill.
2552 */
2553 state->regs[dst_regno].precise = true;
2554 } else {
2555 /* have read misc data from the stack */
2556 mark_reg_unknown(env, state->regs, dst_regno);
2557 }
2558 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
2559}
2560
2561/* Read the stack at 'off' and put the results into the register indicated by
2562 * 'dst_regno'. It handles reg filling if the addressed stack slot is a
2563 * spilled reg.
2564 *
2565 * 'dst_regno' can be -1, meaning that the read value is not going to a
2566 * register.
2567 *
2568 * The access is assumed to be within the current stack bounds.
2569 */
2570static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
2571 /* func where src register points to */
2572 struct bpf_func_state *reg_state,
2573 int off, int size, int dst_regno)
17a52670 2574{
f4d7e40a
AS
2575 struct bpf_verifier_state *vstate = env->cur_state;
2576 struct bpf_func_state *state = vstate->frame[vstate->curframe];
638f5b90 2577 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
f7cf25b2 2578 struct bpf_reg_state *reg;
638f5b90 2579 u8 *stype;
17a52670 2580
f4d7e40a 2581 stype = reg_state->stack[spi].slot_type;
f7cf25b2 2582 reg = &reg_state->stack[spi].spilled_ptr;
17a52670 2583
638f5b90 2584 if (stype[0] == STACK_SPILL) {
9c399760 2585 if (size != BPF_REG_SIZE) {
f7cf25b2
AS
2586 if (reg->type != SCALAR_VALUE) {
2587 verbose_linfo(env, env->insn_idx, "; ");
2588 verbose(env, "invalid size of register fill\n");
2589 return -EACCES;
2590 }
ca5b89bf
AM
2591 if (dst_regno >= 0) {
2592 mark_reg_unknown(env, state->regs, dst_regno);
2593 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
f7cf25b2
AS
2594 }
2595 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
2596 return 0;
17a52670 2597 }
9c399760 2598 for (i = 1; i < BPF_REG_SIZE; i++) {
638f5b90 2599 if (stype[(slot - i) % BPF_REG_SIZE] != STACK_SPILL) {
61bd5218 2600 verbose(env, "corrupted spill memory\n");
17a52670
AS
2601 return -EACCES;
2602 }
2603 }
2604
ca5b89bf 2605 if (dst_regno >= 0) {
17a52670 2606 /* restore register state from stack */
ca5b89bf 2607 state->regs[dst_regno] = *reg;
2f18f62e
AS
2608 /* mark reg as written since spilled pointer state likely
2609 * has its liveness marks cleared by is_state_visited()
2610 * which resets stack/reg liveness for state transitions
2611 */
ca5b89bf 2612 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
6e7e63cb 2613 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
ca5b89bf 2614 /* If dst_regno==-1, the caller is asking us whether
6e7e63cb
JH
2615 * it is acceptable to use this value as a SCALAR_VALUE
2616 * (e.g. for XADD).
2617 * We must not allow unprivileged callers to do that
2618 * with spilled pointers.
2619 */
2620 verbose(env, "leaking pointer from stack off %d\n",
2621 off);
2622 return -EACCES;
dc503a8a 2623 }
f7cf25b2 2624 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
17a52670 2625 } else {
ca5b89bf 2626 u8 type;
cc2b14d5 2627
17a52670 2628 for (i = 0; i < size; i++) {
ca5b89bf
AM
2629 type = stype[(slot - i) % BPF_REG_SIZE];
2630 if (type == STACK_MISC)
cc2b14d5 2631 continue;
ca5b89bf 2632 if (type == STACK_ZERO)
cc2b14d5 2633 continue;
cc2b14d5
AS
2634 verbose(env, "invalid read from stack off %d+%d size %d\n",
2635 off, i, size);
2636 return -EACCES;
2637 }
f7cf25b2 2638 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
ca5b89bf
AM
2639 if (dst_regno >= 0)
2640 mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
17a52670 2641 }
f7cf25b2 2642 return 0;
17a52670
AS
2643}
2644
ca5b89bf
AM
2645enum stack_access_src {
2646 ACCESS_DIRECT = 1, /* the access is performed by an instruction */
2647 ACCESS_HELPER = 2, /* the access is performed by a helper */
2648};
2649
2650static int check_stack_range_initialized(struct bpf_verifier_env *env,
2651 int regno, int off, int access_size,
2652 bool zero_size_allowed,
2653 enum stack_access_src type,
2654 struct bpf_call_arg_meta *meta);
2655
2656static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
2657{
2658 return cur_regs(env) + regno;
2659}
2660
2661/* Read the stack at 'ptr_regno + off' and put the result into the register
2662 * 'dst_regno'.
2663 * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
2664 * but not its variable offset.
2665 * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
2666 *
2667 * As opposed to check_stack_read_fixed_off, this function doesn't deal with
2668 * filling registers (i.e. reads of spilled register cannot be detected when
2669 * the offset is not fixed). We conservatively mark 'dst_regno' as containing
2670 * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
2671 * offset; for a fixed offset check_stack_read_fixed_off should be used
2672 * instead.
2673 */
2674static int check_stack_read_var_off(struct bpf_verifier_env *env,
2675 int ptr_regno, int off, int size, int dst_regno)
e4298d25 2676{
ca5b89bf
AM
2677 /* The state of the source register. */
2678 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
2679 struct bpf_func_state *ptr_state = func(env, reg);
2680 int err;
2681 int min_off, max_off;
2682
2683 /* Note that we pass a NULL meta, so raw access will not be permitted.
e4298d25 2684 */
ca5b89bf
AM
2685 err = check_stack_range_initialized(env, ptr_regno, off, size,
2686 false, ACCESS_DIRECT, NULL);
2687 if (err)
2688 return err;
2689
2690 min_off = reg->smin_value + off;
2691 max_off = reg->smax_value + off;
2692 mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
2693 return 0;
2694}
2695
2696/* check_stack_read dispatches to check_stack_read_fixed_off or
2697 * check_stack_read_var_off.
2698 *
2699 * The caller must ensure that the offset falls within the allocated stack
2700 * bounds.
2701 *
2702 * 'dst_regno' is a register which will receive the value from the stack. It
2703 * can be -1, meaning that the read value is not going to a register.
2704 */
2705static int check_stack_read(struct bpf_verifier_env *env,
2706 int ptr_regno, int off, int size,
2707 int dst_regno)
2708{
2709 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
2710 struct bpf_func_state *state = func(env, reg);
2711 int err;
2712 /* Some accesses are only permitted with a static offset. */
2713 bool var_off = !tnum_is_const(reg->var_off);
2714
2715 /* The offset is required to be static when reads don't go to a
2716 * register, in order to not leak pointers (see
2717 * check_stack_read_fixed_off).
2718 */
2719 if (dst_regno < 0 && var_off) {
e4298d25
DB
2720 char tn_buf[48];
2721
2722 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
ca5b89bf 2723 verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
e4298d25
DB
2724 tn_buf, off, size);
2725 return -EACCES;
2726 }
ca5b89bf
AM
2727 /* Variable offset is prohibited for unprivileged mode for simplicity
2728 * since it requires corresponding support in Spectre masking for stack
2729 * ALU. See also retrieve_ptr_limit().
2730 */
2731 if (!env->bypass_spec_v1 && var_off) {
2732 char tn_buf[48];
e4298d25 2733
ca5b89bf
AM
2734 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
2735 verbose(env, "R%d variable offset stack access prohibited for !root, var_off=%s\n",
2736 ptr_regno, tn_buf);
e4298d25
DB
2737 return -EACCES;
2738 }
2739
ca5b89bf
AM
2740 if (!var_off) {
2741 off += reg->var_off.value;
2742 err = check_stack_read_fixed_off(env, state, off, size,
2743 dst_regno);
2744 } else {
2745 /* Variable offset stack reads need more conservative handling
2746 * than fixed offset ones. Note that dst_regno >= 0 on this
2747 * branch.
2748 */
2749 err = check_stack_read_var_off(env, ptr_regno, off, size,
2750 dst_regno);
2751 }
2752 return err;
2753}
2754
2755
2756/* check_stack_write dispatches to check_stack_write_fixed_off or
2757 * check_stack_write_var_off.
2758 *
2759 * 'ptr_regno' is the register used as a pointer into the stack.
2760 * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
2761 * 'value_regno' is the register whose value we're writing to the stack. It can
2762 * be -1, meaning that we're not writing from a register.
2763 *
2764 * The caller must ensure that the offset falls within the maximum stack size.
2765 */
2766static int check_stack_write(struct bpf_verifier_env *env,
2767 int ptr_regno, int off, int size,
2768 int value_regno, int insn_idx)
2769{
2770 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
2771 struct bpf_func_state *state = func(env, reg);
2772 int err;
2773
2774 if (tnum_is_const(reg->var_off)) {
2775 off += reg->var_off.value;
2776 err = check_stack_write_fixed_off(env, state, off, size,
2777 value_regno, insn_idx);
2778 } else {
2779 /* Variable offset stack reads need more conservative handling
2780 * than fixed offset ones.
2781 */
2782 err = check_stack_write_var_off(env, state,
2783 ptr_regno, off, size,
2784 value_regno, insn_idx);
2785 }
2786 return err;
e4298d25
DB
2787}
2788
591fe988
DB
2789static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
2790 int off, int size, enum bpf_access_type type)
2791{
2792 struct bpf_reg_state *regs = cur_regs(env);
2793 struct bpf_map *map = regs[regno].map_ptr;
2794 u32 cap = bpf_map_flags_to_cap(map);
2795
2796 if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
2797 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
2798 map->value_size, off, size);
2799 return -EACCES;
2800 }
2801
2802 if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
2803 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
2804 map->value_size, off, size);
2805 return -EACCES;
2806 }
2807
2808 return 0;
2809}
2810
457f4436
AN
2811/* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
2812static int __check_mem_access(struct bpf_verifier_env *env, int regno,
2813 int off, int size, u32 mem_size,
2814 bool zero_size_allowed)
17a52670 2815{
457f4436
AN
2816 bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
2817 struct bpf_reg_state *reg;
2818
2819 if (off >= 0 && size_ok && (u64)off + size <= mem_size)
2820 return 0;
17a52670 2821
457f4436
AN
2822 reg = &cur_regs(env)[regno];
2823 switch (reg->type) {
2824 case PTR_TO_MAP_VALUE:
61bd5218 2825 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
457f4436
AN
2826 mem_size, off, size);
2827 break;
2828 case PTR_TO_PACKET:
2829 case PTR_TO_PACKET_META:
2830 case PTR_TO_PACKET_END:
2831 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
2832 off, size, regno, reg->id, off, mem_size);
2833 break;
2834 case PTR_TO_MEM:
2835 default:
2836 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
2837 mem_size, off, size);
17a52670 2838 }
457f4436
AN
2839
2840 return -EACCES;
17a52670
AS
2841}
2842
457f4436
AN
2843/* check read/write into a memory region with possible variable offset */
2844static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
2845 int off, int size, u32 mem_size,
2846 bool zero_size_allowed)
dbcfe5f7 2847{
f4d7e40a
AS
2848 struct bpf_verifier_state *vstate = env->cur_state;
2849 struct bpf_func_state *state = vstate->frame[vstate->curframe];
dbcfe5f7
GB
2850 struct bpf_reg_state *reg = &state->regs[regno];
2851 int err;
2852
457f4436 2853 /* We may have adjusted the register pointing to memory region, so we
f1174f77
EC
2854 * need to try adding each of min_value and max_value to off
2855 * to make sure our theoretical access will be safe.
dbcfe5f7 2856 */
06ee7115 2857 if (env->log.level & BPF_LOG_LEVEL)
61bd5218 2858 print_verifier_state(env, state);
b7137c4e 2859
dbcfe5f7
GB
2860 /* The minimum value is only important with signed
2861 * comparisons where we can't assume the floor of a
2862 * value is 0. If we are using signed variables for our
2863 * index'es we need to make sure that whatever we use
2864 * will have a set floor within our range.
2865 */
b7137c4e
DB
2866 if (reg->smin_value < 0 &&
2867 (reg->smin_value == S64_MIN ||
2868 (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
2869 reg->smin_value + off < 0)) {
61bd5218 2870 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
dbcfe5f7
GB
2871 regno);
2872 return -EACCES;
2873 }
457f4436
AN
2874 err = __check_mem_access(env, regno, reg->smin_value + off, size,
2875 mem_size, zero_size_allowed);
dbcfe5f7 2876 if (err) {
457f4436 2877 verbose(env, "R%d min value is outside of the allowed memory range\n",
61bd5218 2878 regno);
dbcfe5f7
GB
2879 return err;
2880 }
2881
b03c9f9f
EC
2882 /* If we haven't set a max value then we need to bail since we can't be
2883 * sure we won't do bad things.
2884 * If reg->umax_value + off could overflow, treat that as unbounded too.
dbcfe5f7 2885 */
b03c9f9f 2886 if (reg->umax_value >= BPF_MAX_VAR_OFF) {
457f4436 2887 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
dbcfe5f7
GB
2888 regno);
2889 return -EACCES;
2890 }
457f4436
AN
2891 err = __check_mem_access(env, regno, reg->umax_value + off, size,
2892 mem_size, zero_size_allowed);
2893 if (err) {
2894 verbose(env, "R%d max value is outside of the allowed memory range\n",
61bd5218 2895 regno);
457f4436
AN
2896 return err;
2897 }
2898
2899 return 0;
2900}
d83525ca 2901
457f4436
AN
2902/* check read/write into a map element with possible variable offset */
2903static int check_map_access(struct bpf_verifier_env *env, u32 regno,
2904 int off, int size, bool zero_size_allowed)
2905{
2906 struct bpf_verifier_state *vstate = env->cur_state;
2907 struct bpf_func_state *state = vstate->frame[vstate->curframe];
2908 struct bpf_reg_state *reg = &state->regs[regno];
2909 struct bpf_map *map = reg->map_ptr;
2910 int err;
2911
2912 err = check_mem_region_access(env, regno, off, size, map->value_size,
2913 zero_size_allowed);
2914 if (err)
2915 return err;
2916
2917 if (map_value_has_spin_lock(map)) {
2918 u32 lock = map->spin_lock_off;
d83525ca
AS
2919
2920 /* if any part of struct bpf_spin_lock can be touched by
2921 * load/store reject this program.
2922 * To check that [x1, x2) overlaps with [y1, y2)
2923 * it is sufficient to check x1 < y2 && y1 < x2.
2924 */
2925 if (reg->smin_value + off < lock + sizeof(struct bpf_spin_lock) &&
2926 lock < reg->umax_value + off + size) {
2927 verbose(env, "bpf_spin_lock cannot be accessed directly by load/store\n");
2928 return -EACCES;
2929 }
2930 }
f1174f77 2931 return err;
dbcfe5f7
GB
2932}
2933
969bf05e
AS
2934#define MAX_PACKET_OFF 0xffff
2935
7e40781c
UP
2936static enum bpf_prog_type resolve_prog_type(struct bpf_prog *prog)
2937{
3aac1ead 2938 return prog->aux->dst_prog ? prog->aux->dst_prog->type : prog->type;
7e40781c
UP
2939}
2940
58e2af8b 2941static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
3a0af8fd
TG
2942 const struct bpf_call_arg_meta *meta,
2943 enum bpf_access_type t)
4acf6c0b 2944{
7e40781c
UP
2945 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
2946
2947 switch (prog_type) {
5d66fa7d 2948 /* Program types only with direct read access go here! */
3a0af8fd
TG
2949 case BPF_PROG_TYPE_LWT_IN:
2950 case BPF_PROG_TYPE_LWT_OUT:
004d4b27 2951 case BPF_PROG_TYPE_LWT_SEG6LOCAL:
2dbb9b9e 2952 case BPF_PROG_TYPE_SK_REUSEPORT:
5d66fa7d 2953 case BPF_PROG_TYPE_FLOW_DISSECTOR:
d5563d36 2954 case BPF_PROG_TYPE_CGROUP_SKB:
3a0af8fd
TG
2955 if (t == BPF_WRITE)
2956 return false;
8731745e 2957 fallthrough;
5d66fa7d
DB
2958
2959 /* Program types with direct read + write access go here! */
36bbef52
DB
2960 case BPF_PROG_TYPE_SCHED_CLS:
2961 case BPF_PROG_TYPE_SCHED_ACT:
4acf6c0b 2962 case BPF_PROG_TYPE_XDP:
3a0af8fd 2963 case BPF_PROG_TYPE_LWT_XMIT:
8a31db56 2964 case BPF_PROG_TYPE_SK_SKB:
4f738adb 2965 case BPF_PROG_TYPE_SK_MSG:
36bbef52
DB
2966 if (meta)
2967 return meta->pkt_access;
2968
2969 env->seen_direct_write = true;
4acf6c0b 2970 return true;
0d01da6a
SF
2971
2972 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
2973 if (t == BPF_WRITE)
2974 env->seen_direct_write = true;
2975
2976 return true;
2977
4acf6c0b
BB
2978 default:
2979 return false;
2980 }
2981}
2982
f1174f77 2983static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
9fd29c08 2984 int size, bool zero_size_allowed)
f1174f77 2985{
638f5b90 2986 struct bpf_reg_state *regs = cur_regs(env);
f1174f77
EC
2987 struct bpf_reg_state *reg = &regs[regno];
2988 int err;
2989
2990 /* We may have added a variable offset to the packet pointer; but any
2991 * reg->range we have comes after that. We are only checking the fixed
2992 * offset.
2993 */
2994
2995 /* We don't allow negative numbers, because we aren't tracking enough
2996 * detail to prove they're safe.
2997 */
b03c9f9f 2998 if (reg->smin_value < 0) {
61bd5218 2999 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
f1174f77
EC
3000 regno);
3001 return -EACCES;
3002 }
6d94e741
AS
3003
3004 err = reg->range < 0 ? -EINVAL :
3005 __check_mem_access(env, regno, off, size, reg->range,
457f4436 3006 zero_size_allowed);
f1174f77 3007 if (err) {
61bd5218 3008 verbose(env, "R%d offset is outside of the packet\n", regno);
f1174f77
EC
3009 return err;
3010 }
e647815a 3011
457f4436 3012 /* __check_mem_access has made sure "off + size - 1" is within u16.
e647815a
JW
3013 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
3014 * otherwise find_good_pkt_pointers would have refused to set range info
457f4436 3015 * that __check_mem_access would have rejected this pkt access.
e647815a
JW
3016 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
3017 */
3018 env->prog->aux->max_pkt_offset =
3019 max_t(u32, env->prog->aux->max_pkt_offset,
3020 off + reg->umax_value + size - 1);
3021
f1174f77
EC
3022 return err;
3023}
3024
3025/* check access to 'struct bpf_context' fields. Supports fixed offsets only */
31fd8581 3026static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
9e15db66 3027 enum bpf_access_type t, enum bpf_reg_type *reg_type,
22dc4a0f 3028 struct btf **btf, u32 *btf_id)
17a52670 3029{
f96da094
DB
3030 struct bpf_insn_access_aux info = {
3031 .reg_type = *reg_type,
9e15db66 3032 .log = &env->log,
f96da094 3033 };
31fd8581 3034
4f9218aa 3035 if (env->ops->is_valid_access &&
5e43f899 3036 env->ops->is_valid_access(off, size, t, env->prog, &info)) {
f96da094
DB
3037 /* A non zero info.ctx_field_size indicates that this field is a
3038 * candidate for later verifier transformation to load the whole
3039 * field and then apply a mask when accessed with a narrower
3040 * access than actual ctx access size. A zero info.ctx_field_size
3041 * will only allow for whole field access and rejects any other
3042 * type of narrower access.
31fd8581 3043 */
23994631 3044 *reg_type = info.reg_type;
31fd8581 3045
22dc4a0f
AN
3046 if (*reg_type == PTR_TO_BTF_ID || *reg_type == PTR_TO_BTF_ID_OR_NULL) {
3047 *btf = info.btf;
9e15db66 3048 *btf_id = info.btf_id;
22dc4a0f 3049 } else {
9e15db66 3050 env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
22dc4a0f 3051 }
32bbe007
AS
3052 /* remember the offset of last byte accessed in ctx */
3053 if (env->prog->aux->max_ctx_offset < off + size)
3054 env->prog->aux->max_ctx_offset = off + size;
17a52670 3055 return 0;
32bbe007 3056 }
17a52670 3057
61bd5218 3058 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
17a52670
AS
3059 return -EACCES;
3060}
3061
d58e468b
PP
3062static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
3063 int size)
3064{
3065 if (size < 0 || off < 0 ||
3066 (u64)off + size > sizeof(struct bpf_flow_keys)) {
3067 verbose(env, "invalid access to flow keys off=%d size=%d\n",
3068 off, size);
3069 return -EACCES;
3070 }
3071 return 0;
3072}
3073
5f456649
MKL
3074static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
3075 u32 regno, int off, int size,
3076 enum bpf_access_type t)
c64b7983
JS
3077{
3078 struct bpf_reg_state *regs = cur_regs(env);
3079 struct bpf_reg_state *reg = &regs[regno];
5f456649 3080 struct bpf_insn_access_aux info = {};
46f8bc92 3081 bool valid;
c64b7983
JS
3082
3083 if (reg->smin_value < 0) {
3084 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3085 regno);
3086 return -EACCES;
3087 }
3088
46f8bc92
MKL
3089 switch (reg->type) {
3090 case PTR_TO_SOCK_COMMON:
3091 valid = bpf_sock_common_is_valid_access(off, size, t, &info);
3092 break;
3093 case PTR_TO_SOCKET:
3094 valid = bpf_sock_is_valid_access(off, size, t, &info);
3095 break;
655a51e5
MKL
3096 case PTR_TO_TCP_SOCK:
3097 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
3098 break;
fada7fdc
JL
3099 case PTR_TO_XDP_SOCK:
3100 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
3101 break;
46f8bc92
MKL
3102 default:
3103 valid = false;
c64b7983
JS
3104 }
3105
5f456649 3106
46f8bc92
MKL
3107 if (valid) {
3108 env->insn_aux_data[insn_idx].ctx_field_size =
3109 info.ctx_field_size;
3110 return 0;
3111 }
3112
3113 verbose(env, "R%d invalid %s access off=%d size=%d\n",
3114 regno, reg_type_str[reg->type], off, size);
3115
3116 return -EACCES;
c64b7983
JS
3117}
3118
4cabc5b1
DB
3119static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
3120{
2a159c6f 3121 return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
4cabc5b1
DB
3122}
3123
f37a8cb8
DB
3124static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
3125{
2a159c6f 3126 const struct bpf_reg_state *reg = reg_state(env, regno);
f37a8cb8 3127
46f8bc92
MKL
3128 return reg->type == PTR_TO_CTX;
3129}
3130
3131static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
3132{
3133 const struct bpf_reg_state *reg = reg_state(env, regno);
3134
3135 return type_is_sk_pointer(reg->type);
f37a8cb8
DB
3136}
3137
ca369602
DB
3138static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
3139{
2a159c6f 3140 const struct bpf_reg_state *reg = reg_state(env, regno);
ca369602
DB
3141
3142 return type_is_pkt_pointer(reg->type);
3143}
3144
4b5defde
DB
3145static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
3146{
3147 const struct bpf_reg_state *reg = reg_state(env, regno);
3148
3149 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
3150 return reg->type == PTR_TO_FLOW_KEYS;
3151}
3152
61bd5218
JK
3153static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
3154 const struct bpf_reg_state *reg,
d1174416 3155 int off, int size, bool strict)
969bf05e 3156{
f1174f77 3157 struct tnum reg_off;
e07b98d9 3158 int ip_align;
d1174416
DM
3159
3160 /* Byte size accesses are always allowed. */
3161 if (!strict || size == 1)
3162 return 0;
3163
e4eda884
DM
3164 /* For platforms that do not have a Kconfig enabling
3165 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
3166 * NET_IP_ALIGN is universally set to '2'. And on platforms
3167 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
3168 * to this code only in strict mode where we want to emulate
3169 * the NET_IP_ALIGN==2 checking. Therefore use an
3170 * unconditional IP align value of '2'.
e07b98d9 3171 */
e4eda884 3172 ip_align = 2;
f1174f77
EC
3173
3174 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
3175 if (!tnum_is_aligned(reg_off, size)) {
3176 char tn_buf[48];
3177
3178 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
61bd5218
JK
3179 verbose(env,
3180 "misaligned packet access off %d+%s+%d+%d size %d\n",
f1174f77 3181 ip_align, tn_buf, reg->off, off, size);
969bf05e
AS
3182 return -EACCES;
3183 }
79adffcd 3184
969bf05e
AS
3185 return 0;
3186}
3187
61bd5218
JK
3188static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
3189 const struct bpf_reg_state *reg,
f1174f77
EC
3190 const char *pointer_desc,
3191 int off, int size, bool strict)
79adffcd 3192{
f1174f77
EC
3193 struct tnum reg_off;
3194
3195 /* Byte size accesses are always allowed. */
3196 if (!strict || size == 1)
3197 return 0;
3198
3199 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
3200 if (!tnum_is_aligned(reg_off, size)) {
3201 char tn_buf[48];
3202
3203 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
61bd5218 3204 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
f1174f77 3205 pointer_desc, tn_buf, reg->off, off, size);
79adffcd
DB
3206 return -EACCES;
3207 }
3208
969bf05e
AS
3209 return 0;
3210}
3211
e07b98d9 3212static int check_ptr_alignment(struct bpf_verifier_env *env,
ca369602
DB
3213 const struct bpf_reg_state *reg, int off,
3214 int size, bool strict_alignment_once)
79adffcd 3215{
ca369602 3216 bool strict = env->strict_alignment || strict_alignment_once;
f1174f77 3217 const char *pointer_desc = "";
d1174416 3218
79adffcd
DB
3219 switch (reg->type) {
3220 case PTR_TO_PACKET:
de8f3a83
DB
3221 case PTR_TO_PACKET_META:
3222 /* Special case, because of NET_IP_ALIGN. Given metadata sits
3223 * right in front, treat it the very same way.
3224 */
61bd5218 3225 return check_pkt_ptr_alignment(env, reg, off, size, strict);
d58e468b
PP
3226 case PTR_TO_FLOW_KEYS:
3227 pointer_desc = "flow keys ";
3228 break;
f1174f77
EC
3229 case PTR_TO_MAP_VALUE:
3230 pointer_desc = "value ";
3231 break;
3232 case PTR_TO_CTX:
3233 pointer_desc = "context ";
3234 break;
3235 case PTR_TO_STACK:
3236 pointer_desc = "stack ";
ca5b89bf
AM
3237 /* The stack spill tracking logic in check_stack_write_fixed_off()
3238 * and check_stack_read_fixed_off() relies on stack accesses being
a5ec6ae1
JH
3239 * aligned.
3240 */
3241 strict = true;
f1174f77 3242 break;
c64b7983
JS
3243 case PTR_TO_SOCKET:
3244 pointer_desc = "sock ";
3245 break;
46f8bc92
MKL
3246 case PTR_TO_SOCK_COMMON:
3247 pointer_desc = "sock_common ";
3248 break;
655a51e5
MKL
3249 case PTR_TO_TCP_SOCK:
3250 pointer_desc = "tcp_sock ";
3251 break;
fada7fdc
JL
3252 case PTR_TO_XDP_SOCK:
3253 pointer_desc = "xdp_sock ";
3254 break;
79adffcd 3255 default:
f1174f77 3256 break;
79adffcd 3257 }
61bd5218
JK
3258 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
3259 strict);
79adffcd
DB
3260}
3261
f4d7e40a
AS
3262static int update_stack_depth(struct bpf_verifier_env *env,
3263 const struct bpf_func_state *func,
3264 int off)
3265{
9c8105bd 3266 u16 stack = env->subprog_info[func->subprogno].stack_depth;
f4d7e40a
AS
3267
3268 if (stack >= -off)
3269 return 0;
3270
3271 /* update known max for given subprogram */
9c8105bd 3272 env->subprog_info[func->subprogno].stack_depth = -off;
70a87ffe
AS
3273 return 0;
3274}
f4d7e40a 3275
70a87ffe
AS
3276/* starting from main bpf function walk all instructions of the function
3277 * and recursively walk all callees that given function can call.
3278 * Ignore jump and exit insns.
3279 * Since recursion is prevented by check_cfg() this algorithm
3280 * only needs a local stack of MAX_CALL_FRAMES to remember callsites
3281 */
3282static int check_max_stack_depth(struct bpf_verifier_env *env)
3283{
9c8105bd
JW
3284 int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
3285 struct bpf_subprog_info *subprog = env->subprog_info;
70a87ffe 3286 struct bpf_insn *insn = env->prog->insnsi;
ebf7d1f5 3287 bool tail_call_reachable = false;
70a87ffe
AS
3288 int ret_insn[MAX_CALL_FRAMES];
3289 int ret_prog[MAX_CALL_FRAMES];
ebf7d1f5 3290 int j;
f4d7e40a 3291
70a87ffe 3292process_func:
7f6e4312
MF
3293 /* protect against potential stack overflow that might happen when
3294 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
3295 * depth for such case down to 256 so that the worst case scenario
3296 * would result in 8k stack size (32 which is tailcall limit * 256 =
3297 * 8k).
3298 *
3299 * To get the idea what might happen, see an example:
3300 * func1 -> sub rsp, 128
3301 * subfunc1 -> sub rsp, 256
3302 * tailcall1 -> add rsp, 256
3303 * func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
3304 * subfunc2 -> sub rsp, 64
3305 * subfunc22 -> sub rsp, 128
3306 * tailcall2 -> add rsp, 128
3307 * func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
3308 *
3309 * tailcall will unwind the current stack frame but it will not get rid
3310 * of caller's stack as shown on the example above.
3311 */
3312 if (idx && subprog[idx].has_tail_call && depth >= 256) {
3313 verbose(env,
3314 "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
3315 depth);
3316 return -EACCES;
3317 }
70a87ffe
AS
3318 /* round up to 32-bytes, since this is granularity
3319 * of interpreter stack size
3320 */
9c8105bd 3321 depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
70a87ffe 3322 if (depth > MAX_BPF_STACK) {
f4d7e40a 3323 verbose(env, "combined stack size of %d calls is %d. Too large\n",
70a87ffe 3324 frame + 1, depth);
f4d7e40a
AS
3325 return -EACCES;
3326 }
70a87ffe 3327continue_func:
4cb3d99c 3328 subprog_end = subprog[idx + 1].start;
70a87ffe
AS
3329 for (; i < subprog_end; i++) {
3330 if (insn[i].code != (BPF_JMP | BPF_CALL))
3331 continue;
3332 if (insn[i].src_reg != BPF_PSEUDO_CALL)
3333 continue;
3334 /* remember insn and function to return to */
3335 ret_insn[frame] = i + 1;
9c8105bd 3336 ret_prog[frame] = idx;
70a87ffe
AS
3337
3338 /* find the callee */
3339 i = i + insn[i].imm + 1;
9c8105bd
JW
3340 idx = find_subprog(env, i);
3341 if (idx < 0) {
70a87ffe
AS
3342 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
3343 i);
3344 return -EFAULT;
3345 }
ebf7d1f5
MF
3346
3347 if (subprog[idx].has_tail_call)
3348 tail_call_reachable = true;
3349
70a87ffe
AS
3350 frame++;
3351 if (frame >= MAX_CALL_FRAMES) {
927cb781
PC
3352 verbose(env, "the call stack of %d frames is too deep !\n",
3353 frame);
3354 return -E2BIG;
70a87ffe
AS
3355 }
3356 goto process_func;
3357 }
ebf7d1f5
MF
3358 /* if tail call got detected across bpf2bpf calls then mark each of the
3359 * currently present subprog frames as tail call reachable subprogs;
3360 * this info will be utilized by JIT so that we will be preserving the
3361 * tail call counter throughout bpf2bpf calls combined with tailcalls
3362 */
3363 if (tail_call_reachable)
3364 for (j = 0; j < frame; j++)
3365 subprog[ret_prog[j]].tail_call_reachable = true;
3366
70a87ffe
AS
3367 /* end of for() loop means the last insn of the 'subprog'
3368 * was reached. Doesn't matter whether it was JA or EXIT
3369 */
3370 if (frame == 0)
3371 return 0;
9c8105bd 3372 depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
70a87ffe
AS
3373 frame--;
3374 i = ret_insn[frame];
9c8105bd 3375 idx = ret_prog[frame];
70a87ffe 3376 goto continue_func;
f4d7e40a
AS
3377}
3378
19d28fbd 3379#ifndef CONFIG_BPF_JIT_ALWAYS_ON
1ea47e01
AS
3380static int get_callee_stack_depth(struct bpf_verifier_env *env,
3381 const struct bpf_insn *insn, int idx)
3382{
3383 int start = idx + insn->imm + 1, subprog;
3384
3385 subprog = find_subprog(env, start);
3386 if (subprog < 0) {
3387 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
3388 start);
3389 return -EFAULT;
3390 }
9c8105bd 3391 return env->subprog_info[subprog].stack_depth;
1ea47e01 3392}
19d28fbd 3393#endif
1ea47e01 3394
51c39bb1
AS
3395int check_ctx_reg(struct bpf_verifier_env *env,
3396 const struct bpf_reg_state *reg, int regno)
58990d1f
DB
3397{
3398 /* Access to ctx or passing it to a helper is only allowed in
3399 * its original, unmodified form.
3400 */
3401
3402 if (reg->off) {
3403 verbose(env, "dereference of modified ctx ptr R%d off=%d disallowed\n",
3404 regno, reg->off);
3405 return -EACCES;
3406 }
3407
3408 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3409 char tn_buf[48];
3410
3411 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3412 verbose(env, "variable ctx access var_off=%s disallowed\n", tn_buf);
3413 return -EACCES;
3414 }
3415
3416 return 0;
3417}
3418
afbf21dc
YS
3419static int __check_buffer_access(struct bpf_verifier_env *env,
3420 const char *buf_info,
3421 const struct bpf_reg_state *reg,
3422 int regno, int off, int size)
9df1c28b
MM
3423{
3424 if (off < 0) {
3425 verbose(env,
4fc00b79 3426 "R%d invalid %s buffer access: off=%d, size=%d\n",
afbf21dc 3427 regno, buf_info, off, size);
9df1c28b
MM
3428 return -EACCES;
3429 }
3430 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3431 char tn_buf[48];
3432
3433 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3434 verbose(env,
4fc00b79 3435 "R%d invalid variable buffer offset: off=%d, var_off=%s\n",
9df1c28b
MM
3436 regno, off, tn_buf);
3437 return -EACCES;
3438 }
afbf21dc
YS
3439
3440 return 0;
3441}
3442
3443static int check_tp_buffer_access(struct bpf_verifier_env *env,
3444 const struct bpf_reg_state *reg,
3445 int regno, int off, int size)
3446{
3447 int err;
3448
3449 err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
3450 if (err)
3451 return err;
3452
9df1c28b
MM
3453 if (off + size > env->prog->aux->max_tp_access)
3454 env->prog->aux->max_tp_access = off + size;
3455
3456 return 0;
3457}
3458
afbf21dc
YS
3459static int check_buffer_access(struct bpf_verifier_env *env,
3460 const struct bpf_reg_state *reg,
3461 int regno, int off, int size,
3462 bool zero_size_allowed,
3463 const char *buf_info,
3464 u32 *max_access)
3465{
3466 int err;
3467
3468 err = __check_buffer_access(env, buf_info, reg, regno, off, size);
3469 if (err)
3470 return err;
3471
3472 if (off + size > *max_access)
3473 *max_access = off + size;
3474
3475 return 0;
3476}
3477
3f50f132
JF
3478/* BPF architecture zero extends alu32 ops into 64-bit registesr */
3479static void zext_32_to_64(struct bpf_reg_state *reg)
3480{
3481 reg->var_off = tnum_subreg(reg->var_off);
3482 __reg_assign_32_into_64(reg);
3483}
9df1c28b 3484
0c17d1d2
JH
3485/* truncate register to smaller size (in bytes)
3486 * must be called with size < BPF_REG_SIZE
3487 */
3488static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
3489{
3490 u64 mask;
3491
3492 /* clear high bits in bit representation */
3493 reg->var_off = tnum_cast(reg->var_off, size);
3494
3495 /* fix arithmetic bounds */
3496 mask = ((u64)1 << (size * 8)) - 1;
3497 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
3498 reg->umin_value &= mask;
3499 reg->umax_value &= mask;
3500 } else {
3501 reg->umin_value = 0;
3502 reg->umax_value = mask;
3503 }
3504 reg->smin_value = reg->umin_value;
3505 reg->smax_value = reg->umax_value;
3f50f132
JF
3506
3507 /* If size is smaller than 32bit register the 32bit register
3508 * values are also truncated so we push 64-bit bounds into
3509 * 32-bit bounds. Above were truncated < 32-bits already.
3510 */
3511 if (size >= 4)
3512 return;
3513 __reg_combine_64_into_32(reg);
0c17d1d2
JH
3514}
3515
a23740ec
AN
3516static bool bpf_map_is_rdonly(const struct bpf_map *map)
3517{
3518 return (map->map_flags & BPF_F_RDONLY_PROG) && map->frozen;
3519}
3520
3521static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val)
3522{
3523 void *ptr;
3524 u64 addr;
3525 int err;
3526
3527 err = map->ops->map_direct_value_addr(map, &addr, off);
3528 if (err)
3529 return err;
2dedd7d2 3530 ptr = (void *)(long)addr + off;
a23740ec
AN
3531
3532 switch (size) {
3533 case sizeof(u8):
3534 *val = (u64)*(u8 *)ptr;
3535 break;
3536 case sizeof(u16):
3537 *val = (u64)*(u16 *)ptr;
3538 break;
3539 case sizeof(u32):
3540 *val = (u64)*(u32 *)ptr;
3541 break;
3542 case sizeof(u64):
3543 *val = *(u64 *)ptr;
3544 break;
3545 default:
3546 return -EINVAL;
3547 }
3548 return 0;
3549}
3550
9e15db66
AS
3551static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
3552 struct bpf_reg_state *regs,
3553 int regno, int off, int size,
3554 enum bpf_access_type atype,
3555 int value_regno)
3556{
3557 struct bpf_reg_state *reg = regs + regno;
22dc4a0f
AN
3558 const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
3559 const char *tname = btf_name_by_offset(reg->btf, t->name_off);
9e15db66
AS
3560 u32 btf_id;
3561 int ret;
3562
9e15db66
AS
3563 if (off < 0) {
3564 verbose(env,
3565 "R%d is ptr_%s invalid negative access: off=%d\n",
3566 regno, tname, off);
3567 return -EACCES;
3568 }
3569 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3570 char tn_buf[48];
3571
3572 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3573 verbose(env,
3574 "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
3575 regno, tname, off, tn_buf);
3576 return -EACCES;
3577 }
3578
27ae7997 3579 if (env->ops->btf_struct_access) {
22dc4a0f
AN
3580 ret = env->ops->btf_struct_access(&env->log, reg->btf, t,
3581 off, size, atype, &btf_id);
27ae7997
MKL
3582 } else {
3583 if (atype != BPF_READ) {
3584 verbose(env, "only read is supported\n");
3585 return -EACCES;
3586 }
3587
22dc4a0f
AN
3588 ret = btf_struct_access(&env->log, reg->btf, t, off, size,
3589 atype, &btf_id);
27ae7997
MKL
3590 }
3591
9e15db66
AS
3592 if (ret < 0)
3593 return ret;
3594
41c48f3a 3595 if (atype == BPF_READ && value_regno >= 0)
22dc4a0f 3596 mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id);
41c48f3a
AI
3597
3598 return 0;
3599}
3600
3601static int check_ptr_to_map_access(struct bpf_verifier_env *env,
3602 struct bpf_reg_state *regs,
3603 int regno, int off, int size,
3604 enum bpf_access_type atype,
3605 int value_regno)
3606{
3607 struct bpf_reg_state *reg = regs + regno;
3608 struct bpf_map *map = reg->map_ptr;
3609 const struct btf_type *t;
3610 const char *tname;
3611 u32 btf_id;
3612 int ret;
3613
3614 if (!btf_vmlinux) {
3615 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
3616 return -ENOTSUPP;
3617 }
3618
3619 if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
3620 verbose(env, "map_ptr access not supported for map type %d\n",
3621 map->map_type);
3622 return -ENOTSUPP;
3623 }
3624
3625 t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
3626 tname = btf_name_by_offset(btf_vmlinux, t->name_off);
3627
3628 if (!env->allow_ptr_to_map_access) {
3629 verbose(env,
3630 "%s access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
3631 tname);
3632 return -EPERM;
9e15db66 3633 }
27ae7997 3634
41c48f3a
AI
3635 if (off < 0) {
3636 verbose(env, "R%d is %s invalid negative access: off=%d\n",
3637 regno, tname, off);
3638 return -EACCES;
3639 }
3640
3641 if (atype != BPF_READ) {
3642 verbose(env, "only read from %s is supported\n", tname);
3643 return -EACCES;
3644 }
3645
22dc4a0f 3646 ret = btf_struct_access(&env->log, btf_vmlinux, t, off, size, atype, &btf_id);
41c48f3a
AI
3647 if (ret < 0)
3648 return ret;
3649
3650 if (value_regno >= 0)
22dc4a0f 3651 mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id);
41c48f3a 3652
9e15db66
AS
3653 return 0;
3654}
3655
ca5b89bf
AM
3656/* Check that the stack access at the given offset is within bounds. The
3657 * maximum valid offset is -1.
3658 *
3659 * The minimum valid offset is -MAX_BPF_STACK for writes, and
3660 * -state->allocated_stack for reads.
3661 */
3662static int check_stack_slot_within_bounds(int off,
3663 struct bpf_func_state *state,
3664 enum bpf_access_type t)
3665{
3666 int min_valid_off;
3667
3668 if (t == BPF_WRITE)
3669 min_valid_off = -MAX_BPF_STACK;
3670 else
3671 min_valid_off = -state->allocated_stack;
3672
3673 if (off < min_valid_off || off > -1)
3674 return -EACCES;
3675 return 0;
3676}
3677
3678/* Check that the stack access at 'regno + off' falls within the maximum stack
3679 * bounds.
3680 *
3681 * 'off' includes `regno->offset`, but not its dynamic part (if any).
3682 */
3683static int check_stack_access_within_bounds(
3684 struct bpf_verifier_env *env,
3685 int regno, int off, int access_size,
3686 enum stack_access_src src, enum bpf_access_type type)
3687{
3688 struct bpf_reg_state *regs = cur_regs(env);
3689 struct bpf_reg_state *reg = regs + regno;
3690 struct bpf_func_state *state = func(env, reg);
3691 int min_off, max_off;
3692 int err;
3693 char *err_extra;
3694
3695 if (src == ACCESS_HELPER)
3696 /* We don't know if helpers are reading or writing (or both). */
3697 err_extra = " indirect access to";
3698 else if (type == BPF_READ)
3699 err_extra = " read from";
3700 else
3701 err_extra = " write to";
3702
3703 if (tnum_is_const(reg->var_off)) {
3704 min_off = reg->var_off.value + off;
3705 if (access_size > 0)
3706 max_off = min_off + access_size - 1;
3707 else
3708 max_off = min_off;
3709 } else {
3710 if (reg->smax_value >= BPF_MAX_VAR_OFF ||
3711 reg->smin_value <= -BPF_MAX_VAR_OFF) {
3712 verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
3713 err_extra, regno);
3714 return -EACCES;
3715 }
3716 min_off = reg->smin_value + off;
3717 if (access_size > 0)
3718 max_off = reg->smax_value + off + access_size - 1;
3719 else
3720 max_off = min_off;
3721 }
3722
3723 err = check_stack_slot_within_bounds(min_off, state, type);
3724 if (!err)
3725 err = check_stack_slot_within_bounds(max_off, state, type);
3726
3727 if (err) {
3728 if (tnum_is_const(reg->var_off)) {
3729 verbose(env, "invalid%s stack R%d off=%d size=%d\n",
3730 err_extra, regno, off, access_size);
3731 } else {
3732 char tn_buf[48];
3733
3734 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3735 verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
3736 err_extra, regno, tn_buf, access_size);
3737 }
3738 }
3739 return err;
3740}
41c48f3a 3741
17a52670
AS
3742/* check whether memory at (regno + off) is accessible for t = (read | write)
3743 * if t==write, value_regno is a register which value is stored into memory
3744 * if t==read, value_regno is a register which will receive the value from memory
3745 * if t==write && value_regno==-1, some unknown value is stored into memory
3746 * if t==read && value_regno==-1, don't care what we read from memory
3747 */
ca369602
DB
3748static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
3749 int off, int bpf_size, enum bpf_access_type t,
3750 int value_regno, bool strict_alignment_once)
17a52670 3751{
638f5b90
AS
3752 struct bpf_reg_state *regs = cur_regs(env);
3753 struct bpf_reg_state *reg = regs + regno;
f4d7e40a 3754 struct bpf_func_state *state;
17a52670
AS
3755 int size, err = 0;
3756
3757 size = bpf_size_to_bytes(bpf_size);
3758 if (size < 0)
3759 return size;
3760
f1174f77 3761 /* alignment checks will add in reg->off themselves */
ca369602 3762 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
969bf05e
AS
3763 if (err)
3764 return err;
17a52670 3765
f1174f77
EC
3766 /* for access checks, reg->off is just part of off */
3767 off += reg->off;
3768
3769 if (reg->type == PTR_TO_MAP_VALUE) {
1be7f75d
AS
3770 if (t == BPF_WRITE && value_regno >= 0 &&
3771 is_pointer_value(env, value_regno)) {
61bd5218 3772 verbose(env, "R%d leaks addr into map\n", value_regno);
1be7f75d
AS
3773 return -EACCES;
3774 }
591fe988
DB
3775 err = check_map_access_type(env, regno, off, size, t);
3776 if (err)
3777 return err;
9fd29c08 3778 err = check_map_access(env, regno, off, size, false);
a23740ec
AN
3779 if (!err && t == BPF_READ && value_regno >= 0) {
3780 struct bpf_map *map = reg->map_ptr;
3781
3782 /* if map is read-only, track its contents as scalars */
3783 if (tnum_is_const(reg->var_off) &&
3784 bpf_map_is_rdonly(map) &&
3785 map->ops->map_direct_value_addr) {
3786 int map_off = off + reg->var_off.value;
3787 u64 val = 0;
3788
3789 err = bpf_map_direct_read(map, map_off, size,
3790 &val);
3791 if (err)
3792 return err;
3793
3794 regs[value_regno].type = SCALAR_VALUE;
3795 __mark_reg_known(&regs[value_regno], val);
3796 } else {
3797 mark_reg_unknown(env, regs, value_regno);
3798 }
3799 }
457f4436
AN
3800 } else if (reg->type == PTR_TO_MEM) {
3801 if (t == BPF_WRITE && value_regno >= 0 &&
3802 is_pointer_value(env, value_regno)) {
3803 verbose(env, "R%d leaks addr into mem\n", value_regno);
3804 return -EACCES;
3805 }
3806 err = check_mem_region_access(env, regno, off, size,
3807 reg->mem_size, false);
3808 if (!err && t == BPF_READ && value_regno >= 0)
3809 mark_reg_unknown(env, regs, value_regno);
1a0dc1ac 3810 } else if (reg->type == PTR_TO_CTX) {
f1174f77 3811 enum bpf_reg_type reg_type = SCALAR_VALUE;
22dc4a0f 3812 struct btf *btf = NULL;
9e15db66 3813 u32 btf_id = 0;
19de99f7 3814
1be7f75d
AS
3815 if (t == BPF_WRITE && value_regno >= 0 &&
3816 is_pointer_value(env, value_regno)) {
61bd5218 3817 verbose(env, "R%d leaks addr into ctx\n", value_regno);
1be7f75d
AS
3818 return -EACCES;
3819 }
f1174f77 3820
58990d1f
DB
3821 err = check_ctx_reg(env, reg, regno);
3822 if (err < 0)
3823 return err;
3824
22dc4a0f 3825 err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf, &btf_id);
9e15db66
AS
3826 if (err)
3827 verbose_linfo(env, insn_idx, "; ");
969bf05e 3828 if (!err && t == BPF_READ && value_regno >= 0) {
f1174f77 3829 /* ctx access returns either a scalar, or a
de8f3a83
DB
3830 * PTR_TO_PACKET[_META,_END]. In the latter
3831 * case, we know the offset is zero.
f1174f77 3832 */
46f8bc92 3833 if (reg_type == SCALAR_VALUE) {
638f5b90 3834 mark_reg_unknown(env, regs, value_regno);
46f8bc92 3835 } else {
638f5b90 3836 mark_reg_known_zero(env, regs,
61bd5218 3837 value_regno);
46f8bc92
MKL
3838 if (reg_type_may_be_null(reg_type))
3839 regs[value_regno].id = ++env->id_gen;
5327ed3d
JW
3840 /* A load of ctx field could have different
3841 * actual load size with the one encoded in the
3842 * insn. When the dst is PTR, it is for sure not
3843 * a sub-register.
3844 */
3845 regs[value_regno].subreg_def = DEF_NOT_SUBREG;
b121b341 3846 if (reg_type == PTR_TO_BTF_ID ||
22dc4a0f
AN
3847 reg_type == PTR_TO_BTF_ID_OR_NULL) {
3848 regs[value_regno].btf = btf;
9e15db66 3849 regs[value_regno].btf_id = btf_id;
22dc4a0f 3850 }
46f8bc92 3851 }
638f5b90 3852 regs[value_regno].type = reg_type;
969bf05e 3853 }
17a52670 3854
f1174f77 3855 } else if (reg->type == PTR_TO_STACK) {
ca5b89bf
AM
3856 /* Basic bounds checks. */
3857 err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
e4298d25
DB
3858 if (err)
3859 return err;
8726679a 3860
f4d7e40a
AS
3861 state = func(env, reg);
3862 err = update_stack_depth(env, state, off);
3863 if (err)
3864 return err;
8726679a 3865
ca5b89bf
AM
3866 if (t == BPF_READ)
3867 err = check_stack_read(env, regno, off, size,
61bd5218 3868 value_regno);
ca5b89bf
AM
3869 else
3870 err = check_stack_write(env, regno, off, size,
3871 value_regno, insn_idx);
de8f3a83 3872 } else if (reg_is_pkt_pointer(reg)) {
3a0af8fd 3873 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
61bd5218 3874 verbose(env, "cannot write into packet\n");
969bf05e
AS
3875 return -EACCES;
3876 }
4acf6c0b
BB
3877 if (t == BPF_WRITE && value_regno >= 0 &&
3878 is_pointer_value(env, value_regno)) {
61bd5218
JK
3879 verbose(env, "R%d leaks addr into packet\n",
3880 value_regno);
4acf6c0b
BB
3881 return -EACCES;
3882 }
9fd29c08 3883 err = check_packet_access(env, regno, off, size, false);
969bf05e 3884 if (!err && t == BPF_READ && value_regno >= 0)
638f5b90 3885 mark_reg_unknown(env, regs, value_regno);
d58e468b
PP
3886 } else if (reg->type == PTR_TO_FLOW_KEYS) {
3887 if (t == BPF_WRITE && value_regno >= 0 &&
3888 is_pointer_value(env, value_regno)) {
3889 verbose(env, "R%d leaks addr into flow keys\n",
3890 value_regno);
3891 return -EACCES;
3892 }
3893
3894 err = check_flow_keys_access(env, off, size);
3895 if (!err && t == BPF_READ && value_regno >= 0)
3896 mark_reg_unknown(env, regs, value_regno);
46f8bc92 3897 } else if (type_is_sk_pointer(reg->type)) {
c64b7983 3898 if (t == BPF_WRITE) {
46f8bc92
MKL
3899 verbose(env, "R%d cannot write into %s\n",
3900 regno, reg_type_str[reg->type]);
c64b7983
JS
3901 return -EACCES;
3902 }
5f456649 3903 err = check_sock_access(env, insn_idx, regno, off, size, t);
c64b7983
JS
3904 if (!err && value_regno >= 0)
3905 mark_reg_unknown(env, regs, value_regno);
9df1c28b
MM
3906 } else if (reg->type == PTR_TO_TP_BUFFER) {
3907 err = check_tp_buffer_access(env, reg, regno, off, size);
3908 if (!err && t == BPF_READ && value_regno >= 0)
3909 mark_reg_unknown(env, regs, value_regno);
9e15db66
AS
3910 } else if (reg->type == PTR_TO_BTF_ID) {
3911 err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
3912 value_regno);
41c48f3a
AI
3913 } else if (reg->type == CONST_PTR_TO_MAP) {
3914 err = check_ptr_to_map_access(env, regs, regno, off, size, t,
3915 value_regno);
afbf21dc
YS
3916 } else if (reg->type == PTR_TO_RDONLY_BUF) {
3917 if (t == BPF_WRITE) {
3918 verbose(env, "R%d cannot write into %s\n",
3919 regno, reg_type_str[reg->type]);
3920 return -EACCES;
3921 }
f6dfbe31
CIK
3922 err = check_buffer_access(env, reg, regno, off, size, false,
3923 "rdonly",
afbf21dc
YS
3924 &env->prog->aux->max_rdonly_access);
3925 if (!err && value_regno >= 0)
3926 mark_reg_unknown(env, regs, value_regno);
3927 } else if (reg->type == PTR_TO_RDWR_BUF) {
f6dfbe31
CIK
3928 err = check_buffer_access(env, reg, regno, off, size, false,
3929 "rdwr",
afbf21dc
YS
3930 &env->prog->aux->max_rdwr_access);
3931 if (!err && t == BPF_READ && value_regno >= 0)
3932 mark_reg_unknown(env, regs, value_regno);
17a52670 3933 } else {
61bd5218
JK
3934 verbose(env, "R%d invalid mem access '%s'\n", regno,
3935 reg_type_str[reg->type]);
17a52670
AS
3936 return -EACCES;
3937 }
969bf05e 3938
f1174f77 3939 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
638f5b90 3940 regs[value_regno].type == SCALAR_VALUE) {
f1174f77 3941 /* b/h/w load zero-extends, mark upper bits as known 0 */
0c17d1d2 3942 coerce_reg_to_size(&regs[value_regno], size);
969bf05e 3943 }
17a52670
AS
3944 return err;
3945}
3946
31fd8581 3947static int check_xadd(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
17a52670 3948{
17a52670
AS
3949 int err;
3950
3951 if ((BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) ||
3952 insn->imm != 0) {
61bd5218 3953 verbose(env, "BPF_XADD uses reserved fields\n");
17a52670
AS
3954 return -EINVAL;
3955 }
3956
3957 /* check src1 operand */
dc503a8a 3958 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17a52670
AS
3959 if (err)
3960 return err;
3961
3962 /* check src2 operand */
dc503a8a 3963 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17a52670
AS
3964 if (err)
3965 return err;
3966
6bdf6abc 3967 if (is_pointer_value(env, insn->src_reg)) {
61bd5218 3968 verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
6bdf6abc
DB
3969 return -EACCES;
3970 }
3971
ca369602 3972 if (is_ctx_reg(env, insn->dst_reg) ||
4b5defde 3973 is_pkt_reg(env, insn->dst_reg) ||
46f8bc92
MKL
3974 is_flow_key_reg(env, insn->dst_reg) ||
3975 is_sk_reg(env, insn->dst_reg)) {
ca369602 3976 verbose(env, "BPF_XADD stores into R%d %s is not allowed\n",
2a159c6f
DB
3977 insn->dst_reg,
3978 reg_type_str[reg_state(env, insn->dst_reg)->type]);
f37a8cb8
DB
3979 return -EACCES;
3980 }
3981
17a52670 3982 /* check whether atomic_add can read the memory */
31fd8581 3983 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
ca369602 3984 BPF_SIZE(insn->code), BPF_READ, -1, true);
17a52670
AS
3985 if (err)
3986 return err;
3987
3988 /* check whether atomic_add can write into the same memory */
31fd8581 3989 return check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
ca369602 3990 BPF_SIZE(insn->code), BPF_WRITE, -1, true);
17a52670
AS
3991}
3992
ca5b89bf
AM
3993/* When register 'regno' is used to read the stack (either directly or through
3994 * a helper function) make sure that it's within stack boundary and, depending
3995 * on the access type, that all elements of the stack are initialized.
3996 *
3997 * 'off' includes 'regno->off', but not its dynamic part (if any).
3998 *
3999 * All registers that have been spilled on the stack in the slots within the
4000 * read offsets are marked as read.
4001 */
4002static int check_stack_range_initialized(
4003 struct bpf_verifier_env *env, int regno, int off,
4004 int access_size, bool zero_size_allowed,
4005 enum stack_access_src type, struct bpf_call_arg_meta *meta)
2011fccf
AI
4006{
4007 struct bpf_reg_state *reg = reg_state(env, regno);
ca5b89bf
AM
4008 struct bpf_func_state *state = func(env, reg);
4009 int err, min_off, max_off, i, j, slot, spi;
4010 char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
4011 enum bpf_access_type bounds_check_type;
4012 /* Some accesses can write anything into the stack, others are
4013 * read-only.
4014 */
4015 bool clobber = false;
2011fccf 4016
ca5b89bf
AM
4017 if (access_size == 0 && !zero_size_allowed) {
4018 verbose(env, "invalid zero-sized read\n");
2011fccf
AI
4019 return -EACCES;
4020 }
2011fccf 4021
ca5b89bf
AM
4022 if (type == ACCESS_HELPER) {
4023 /* The bounds checks for writes are more permissive than for
4024 * reads. However, if raw_mode is not set, we'll do extra
4025 * checks below.
4026 */
4027 bounds_check_type = BPF_WRITE;
4028 clobber = true;
4029 } else {
4030 bounds_check_type = BPF_READ;
4031 }
4032 err = check_stack_access_within_bounds(env, regno, off, access_size,
4033 type, bounds_check_type);
4034 if (err)
4035 return err;
4036
17a52670 4037
2011fccf 4038 if (tnum_is_const(reg->var_off)) {
ca5b89bf 4039 min_off = max_off = reg->var_off.value + off;
2011fccf 4040 } else {
088ec26d
AI
4041 /* Variable offset is prohibited for unprivileged mode for
4042 * simplicity since it requires corresponding support in
4043 * Spectre masking for stack ALU.
4044 * See also retrieve_ptr_limit().
4045 */
2c78ee89 4046 if (!env->bypass_spec_v1) {
088ec26d 4047 char tn_buf[48];
f1174f77 4048
088ec26d 4049 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
ca5b89bf
AM
4050 verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
4051 regno, err_extra, tn_buf);
088ec26d
AI
4052 return -EACCES;
4053 }
f2bcd05e
AI
4054 /* Only initialized buffer on stack is allowed to be accessed
4055 * with variable offset. With uninitialized buffer it's hard to
4056 * guarantee that whole memory is marked as initialized on
4057 * helper return since specific bounds are unknown what may
4058 * cause uninitialized stack leaking.
4059 */
4060 if (meta && meta->raw_mode)
4061 meta = NULL;
4062
ca5b89bf
AM
4063 min_off = reg->smin_value + off;
4064 max_off = reg->smax_value + off;
17a52670
AS
4065 }
4066
435faee1
DB
4067 if (meta && meta->raw_mode) {
4068 meta->access_size = access_size;
4069 meta->regno = regno;
4070 return 0;
4071 }
4072
2011fccf 4073 for (i = min_off; i < max_off + access_size; i++) {
cc2b14d5
AS
4074 u8 *stype;
4075
2011fccf 4076 slot = -i - 1;
638f5b90 4077 spi = slot / BPF_REG_SIZE;
cc2b14d5
AS
4078 if (state->allocated_stack <= slot)
4079 goto err;
4080 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
4081 if (*stype == STACK_MISC)
4082 goto mark;
4083 if (*stype == STACK_ZERO) {
ca5b89bf
AM
4084 if (clobber) {
4085 /* helper can write anything into the stack */
4086 *stype = STACK_MISC;
4087 }
cc2b14d5 4088 goto mark;
17a52670 4089 }
1d68f22b
YS
4090
4091 if (state->stack[spi].slot_type[0] == STACK_SPILL &&
4092 state->stack[spi].spilled_ptr.type == PTR_TO_BTF_ID)
4093 goto mark;
4094
f7cf25b2 4095 if (state->stack[spi].slot_type[0] == STACK_SPILL &&
cd17d38f
YS
4096 (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
4097 env->allow_ptr_leaks)) {
ca5b89bf
AM
4098 if (clobber) {
4099 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
4100 for (j = 0; j < BPF_REG_SIZE; j++)
4101 state->stack[spi].slot_type[j] = STACK_MISC;
4102 }
f7cf25b2
AS
4103 goto mark;
4104 }
4105
cc2b14d5 4106err:
2011fccf 4107 if (tnum_is_const(reg->var_off)) {
ca5b89bf
AM
4108 verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
4109 err_extra, regno, min_off, i - min_off, access_size);
2011fccf
AI
4110 } else {
4111 char tn_buf[48];
4112
4113 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
ca5b89bf
AM
4114 verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
4115 err_extra, regno, tn_buf, i - min_off, access_size);
2011fccf 4116 }
cc2b14d5
AS
4117 return -EACCES;
4118mark:
4119 /* reading any byte out of 8-byte 'spill_slot' will cause
4120 * the whole slot to be marked as 'read'
4121 */
679c782d 4122 mark_reg_read(env, &state->stack[spi].spilled_ptr,
5327ed3d
JW
4123 state->stack[spi].spilled_ptr.parent,
4124 REG_LIVE_READ64);
17a52670 4125 }
2011fccf 4126 return update_stack_depth(env, state, min_off);
17a52670
AS
4127}
4128
06c1c049
GB
4129static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
4130 int access_size, bool zero_size_allowed,
4131 struct bpf_call_arg_meta *meta)
4132{
638f5b90 4133 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
06c1c049 4134
f1174f77 4135 switch (reg->type) {
06c1c049 4136 case PTR_TO_PACKET:
de8f3a83 4137 case PTR_TO_PACKET_META:
9fd29c08
YS
4138 return check_packet_access(env, regno, reg->off, access_size,
4139 zero_size_allowed);
06c1c049 4140 case PTR_TO_MAP_VALUE:
591fe988
DB
4141 if (check_map_access_type(env, regno, reg->off, access_size,
4142 meta && meta->raw_mode ? BPF_WRITE :
4143 BPF_READ))
4144 return -EACCES;
9fd29c08
YS
4145 return check_map_access(env, regno, reg->off, access_size,
4146 zero_size_allowed);
457f4436
AN
4147 case PTR_TO_MEM:
4148 return check_mem_region_access(env, regno, reg->off,
4149 access_size, reg->mem_size,
4150 zero_size_allowed);
afbf21dc
YS
4151 case PTR_TO_RDONLY_BUF:
4152 if (meta && meta->raw_mode)
4153 return -EACCES;
4154 return check_buffer_access(env, reg, regno, reg->off,
4155 access_size, zero_size_allowed,
4156 "rdonly",
4157 &env->prog->aux->max_rdonly_access);
4158 case PTR_TO_RDWR_BUF:
4159 return check_buffer_access(env, reg, regno, reg->off,
4160 access_size, zero_size_allowed,
4161 "rdwr",
4162 &env->prog->aux->max_rdwr_access);
0d004c02 4163 case PTR_TO_STACK:
ca5b89bf
AM
4164 return check_stack_range_initialized(
4165 env,
4166 regno, reg->off, access_size,
4167 zero_size_allowed, ACCESS_HELPER, meta);
0d004c02
LB
4168 default: /* scalar_value or invalid ptr */
4169 /* Allow zero-byte read from NULL, regardless of pointer type */
4170 if (zero_size_allowed && access_size == 0 &&
4171 register_is_null(reg))
4172 return 0;
4173
4174 verbose(env, "R%d type=%s expected=%s\n", regno,
4175 reg_type_str[reg->type],
4176 reg_type_str[PTR_TO_STACK]);
4177 return -EACCES;
06c1c049
GB
4178 }
4179}
4180
d83525ca
AS
4181/* Implementation details:
4182 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL
4183 * Two bpf_map_lookups (even with the same key) will have different reg->id.
4184 * For traditional PTR_TO_MAP_VALUE the verifier clears reg->id after
4185 * value_or_null->value transition, since the verifier only cares about
4186 * the range of access to valid map value pointer and doesn't care about actual
4187 * address of the map element.
4188 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
4189 * reg->id > 0 after value_or_null->value transition. By doing so
4190 * two bpf_map_lookups will be considered two different pointers that
4191 * point to different bpf_spin_locks.
4192 * The verifier allows taking only one bpf_spin_lock at a time to avoid
4193 * dead-locks.
4194 * Since only one bpf_spin_lock is allowed the checks are simpler than
4195 * reg_is_refcounted() logic. The verifier needs to remember only
4196 * one spin_lock instead of array of acquired_refs.
4197 * cur_state->active_spin_lock remembers which map value element got locked
4198 * and clears it after bpf_spin_unlock.
4199 */
4200static int process_spin_lock(struct bpf_verifier_env *env, int regno,
4201 bool is_lock)
4202{
4203 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4204 struct bpf_verifier_state *cur = env->cur_state;
4205 bool is_const = tnum_is_const(reg->var_off);
4206 struct bpf_map *map = reg->map_ptr;
4207 u64 val = reg->var_off.value;
4208
d83525ca
AS
4209 if (!is_const) {
4210 verbose(env,
4211 "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
4212 regno);
4213 return -EINVAL;
4214 }
4215 if (!map->btf) {
4216 verbose(env,
4217 "map '%s' has to have BTF in order to use bpf_spin_lock\n",
4218 map->name);
4219 return -EINVAL;
4220 }
4221 if (!map_value_has_spin_lock(map)) {
4222 if (map->spin_lock_off == -E2BIG)
4223 verbose(env,
4224 "map '%s' has more than one 'struct bpf_spin_lock'\n",
4225 map->name);
4226 else if (map->spin_lock_off == -ENOENT)
4227 verbose(env,
4228 "map '%s' doesn't have 'struct bpf_spin_lock'\n",
4229 map->name);
4230 else
4231 verbose(env,
4232 "map '%s' is not a struct type or bpf_spin_lock is mangled\n",
4233 map->name);
4234 return -EINVAL;
4235 }
4236 if (map->spin_lock_off != val + reg->off) {
4237 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock'\n",
4238 val + reg->off);
4239 return -EINVAL;
4240 }
4241 if (is_lock) {
4242 if (cur->active_spin_lock) {
4243 verbose(env,
4244 "Locking two bpf_spin_locks are not allowed\n");
4245 return -EINVAL;
4246 }
4247 cur->active_spin_lock = reg->id;
4248 } else {
4249 if (!cur->active_spin_lock) {
4250 verbose(env, "bpf_spin_unlock without taking a lock\n");
4251 return -EINVAL;
4252 }
4253 if (cur->active_spin_lock != reg->id) {
4254 verbose(env, "bpf_spin_unlock of different lock\n");
4255 return -EINVAL;
4256 }
4257 cur->active_spin_lock = 0;
4258 }
4259 return 0;
4260}
4261
90133415
DB
4262static bool arg_type_is_mem_ptr(enum bpf_arg_type type)
4263{
4264 return type == ARG_PTR_TO_MEM ||
4265 type == ARG_PTR_TO_MEM_OR_NULL ||
4266 type == ARG_PTR_TO_UNINIT_MEM;
4267}
4268
4269static bool arg_type_is_mem_size(enum bpf_arg_type type)
4270{
4271 return type == ARG_CONST_SIZE ||
4272 type == ARG_CONST_SIZE_OR_ZERO;
4273}
4274
457f4436
AN
4275static bool arg_type_is_alloc_size(enum bpf_arg_type type)
4276{
4277 return type == ARG_CONST_ALLOC_SIZE_OR_ZERO;
4278}
4279
57c3bb72
AI
4280static bool arg_type_is_int_ptr(enum bpf_arg_type type)
4281{
4282 return type == ARG_PTR_TO_INT ||
4283 type == ARG_PTR_TO_LONG;
4284}
4285
4286static int int_ptr_type_to_size(enum bpf_arg_type type)
4287{
4288 if (type == ARG_PTR_TO_INT)
4289 return sizeof(u32);
4290 else if (type == ARG_PTR_TO_LONG)
4291 return sizeof(u64);
4292
4293 return -EINVAL;
4294}
4295
912f442c
LB
4296static int resolve_map_arg_type(struct bpf_verifier_env *env,
4297 const struct bpf_call_arg_meta *meta,
4298 enum bpf_arg_type *arg_type)
4299{
4300 if (!meta->map_ptr) {
4301 /* kernel subsystem misconfigured verifier */
4302 verbose(env, "invalid map_ptr to access map->type\n");
4303 return -EACCES;
4304 }
4305
4306 switch (meta->map_ptr->map_type) {
4307 case BPF_MAP_TYPE_SOCKMAP:
4308 case BPF_MAP_TYPE_SOCKHASH:
4309 if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
6550f2dd 4310 *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
912f442c
LB
4311 } else {
4312 verbose(env, "invalid arg_type for sockmap/sockhash\n");
4313 return -EINVAL;
4314 }
4315 break;
4316
4317 default:
4318 break;
4319 }
4320 return 0;
4321}
4322
f79e7ea5
LB
4323struct bpf_reg_types {
4324 const enum bpf_reg_type types[10];
1df8f55a 4325 u32 *btf_id;
f79e7ea5
LB
4326};
4327
4328static const struct bpf_reg_types map_key_value_types = {
4329 .types = {
4330 PTR_TO_STACK,
4331 PTR_TO_PACKET,
4332 PTR_TO_PACKET_META,
4333 PTR_TO_MAP_VALUE,
4334 },
4335};
4336
4337static const struct bpf_reg_types sock_types = {
4338 .types = {
4339 PTR_TO_SOCK_COMMON,
4340 PTR_TO_SOCKET,
4341 PTR_TO_TCP_SOCK,
4342 PTR_TO_XDP_SOCK,
4343 },
4344};
4345
49a2a4d4 4346#ifdef CONFIG_NET
1df8f55a
MKL
4347static const struct bpf_reg_types btf_id_sock_common_types = {
4348 .types = {
4349 PTR_TO_SOCK_COMMON,
4350 PTR_TO_SOCKET,
4351 PTR_TO_TCP_SOCK,
4352 PTR_TO_XDP_SOCK,
4353 PTR_TO_BTF_ID,
4354 },
4355 .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
4356};
49a2a4d4 4357#endif
1df8f55a 4358
f79e7ea5
LB
4359static const struct bpf_reg_types mem_types = {
4360 .types = {
4361 PTR_TO_STACK,
4362 PTR_TO_PACKET,
4363 PTR_TO_PACKET_META,
4364 PTR_TO_MAP_VALUE,
4365 PTR_TO_MEM,
4366 PTR_TO_RDONLY_BUF,
4367 PTR_TO_RDWR_BUF,
4368 },
4369};
4370
4371static const struct bpf_reg_types int_ptr_types = {
4372 .types = {
4373 PTR_TO_STACK,
4374 PTR_TO_PACKET,
4375 PTR_TO_PACKET_META,
4376 PTR_TO_MAP_VALUE,
4377 },
4378};
4379
4380static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
4381static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
4382static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
4383static const struct bpf_reg_types alloc_mem_types = { .types = { PTR_TO_MEM } };
4384static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
4385static const struct bpf_reg_types btf_ptr_types = { .types = { PTR_TO_BTF_ID } };
4386static const struct bpf_reg_types spin_lock_types = { .types = { PTR_TO_MAP_VALUE } };
eaa6bcb7 4387static const struct bpf_reg_types percpu_btf_ptr_types = { .types = { PTR_TO_PERCPU_BTF_ID } };
f79e7ea5 4388
0789e13b 4389static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
f79e7ea5
LB
4390 [ARG_PTR_TO_MAP_KEY] = &map_key_value_types,
4391 [ARG_PTR_TO_MAP_VALUE] = &map_key_value_types,
4392 [ARG_PTR_TO_UNINIT_MAP_VALUE] = &map_key_value_types,
4393 [ARG_PTR_TO_MAP_VALUE_OR_NULL] = &map_key_value_types,
4394 [ARG_CONST_SIZE] = &scalar_types,
4395 [ARG_CONST_SIZE_OR_ZERO] = &scalar_types,
4396 [ARG_CONST_ALLOC_SIZE_OR_ZERO] = &scalar_types,
4397 [ARG_CONST_MAP_PTR] = &const_map_ptr_types,
4398 [ARG_PTR_TO_CTX] = &context_types,
4399 [ARG_PTR_TO_CTX_OR_NULL] = &context_types,
4400 [ARG_PTR_TO_SOCK_COMMON] = &sock_types,
49a2a4d4 4401#ifdef CONFIG_NET
1df8f55a 4402 [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types,
49a2a4d4 4403#endif
f79e7ea5
LB
4404 [ARG_PTR_TO_SOCKET] = &fullsock_types,
4405 [ARG_PTR_TO_SOCKET_OR_NULL] = &fullsock_types,
4406 [ARG_PTR_TO_BTF_ID] = &btf_ptr_types,
4407 [ARG_PTR_TO_SPIN_LOCK] = &spin_lock_types,
4408 [ARG_PTR_TO_MEM] = &mem_types,
4409 [ARG_PTR_TO_MEM_OR_NULL] = &mem_types,
4410 [ARG_PTR_TO_UNINIT_MEM] = &mem_types,
4411 [ARG_PTR_TO_ALLOC_MEM] = &alloc_mem_types,
4412 [ARG_PTR_TO_ALLOC_MEM_OR_NULL] = &alloc_mem_types,
4413 [ARG_PTR_TO_INT] = &int_ptr_types,
4414 [ARG_PTR_TO_LONG] = &int_ptr_types,
eaa6bcb7 4415 [ARG_PTR_TO_PERCPU_BTF_ID] = &percpu_btf_ptr_types,
f79e7ea5
LB
4416};
4417
4418static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
a968d5e2
MKL
4419 enum bpf_arg_type arg_type,
4420 const u32 *arg_btf_id)
f79e7ea5
LB
4421{
4422 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4423 enum bpf_reg_type expected, type = reg->type;
a968d5e2 4424 const struct bpf_reg_types *compatible;
f79e7ea5
LB
4425 int i, j;
4426
a968d5e2
MKL
4427 compatible = compatible_reg_types[arg_type];
4428 if (!compatible) {
4429 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
4430 return -EFAULT;
4431 }
4432
f79e7ea5
LB
4433 for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
4434 expected = compatible->types[i];
4435 if (expected == NOT_INIT)
4436 break;
4437
4438 if (type == expected)
a968d5e2 4439 goto found;
f79e7ea5
LB
4440 }
4441
4442 verbose(env, "R%d type=%s expected=", regno, reg_type_str[type]);
4443 for (j = 0; j + 1 < i; j++)
4444 verbose(env, "%s, ", reg_type_str[compatible->types[j]]);
4445 verbose(env, "%s\n", reg_type_str[compatible->types[j]]);
4446 return -EACCES;
a968d5e2
MKL
4447
4448found:
4449 if (type == PTR_TO_BTF_ID) {
1df8f55a
MKL
4450 if (!arg_btf_id) {
4451 if (!compatible->btf_id) {
4452 verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
4453 return -EFAULT;
4454 }
4455 arg_btf_id = compatible->btf_id;
4456 }
4457
22dc4a0f
AN
4458 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
4459 btf_vmlinux, *arg_btf_id)) {
a968d5e2 4460 verbose(env, "R%d is of type %s but %s is expected\n",
22dc4a0f
AN
4461 regno, kernel_type_name(reg->btf, reg->btf_id),
4462 kernel_type_name(btf_vmlinux, *arg_btf_id));
a968d5e2
MKL
4463 return -EACCES;
4464 }
4465
4466 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4467 verbose(env, "R%d is a pointer to in-kernel struct with non-zero offset\n",
4468 regno);
4469 return -EACCES;
4470 }
4471 }
4472
4473 return 0;
f79e7ea5
LB
4474}
4475
af7ec138
YS
4476static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
4477 struct bpf_call_arg_meta *meta,
4478 const struct bpf_func_proto *fn)
17a52670 4479{
af7ec138 4480 u32 regno = BPF_REG_1 + arg;
638f5b90 4481 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
af7ec138 4482 enum bpf_arg_type arg_type = fn->arg_type[arg];
f79e7ea5 4483 enum bpf_reg_type type = reg->type;
17a52670
AS
4484 int err = 0;
4485
80f1d68c 4486 if (arg_type == ARG_DONTCARE)
17a52670
AS
4487 return 0;
4488
dc503a8a
EC
4489 err = check_reg_arg(env, regno, SRC_OP);
4490 if (err)
4491 return err;
17a52670 4492
1be7f75d
AS
4493 if (arg_type == ARG_ANYTHING) {
4494 if (is_pointer_value(env, regno)) {
61bd5218
JK
4495 verbose(env, "R%d leaks addr into helper function\n",
4496 regno);
1be7f75d
AS
4497 return -EACCES;
4498 }
80f1d68c 4499 return 0;
1be7f75d 4500 }
80f1d68c 4501
de8f3a83 4502 if (type_is_pkt_pointer(type) &&
3a0af8fd 4503 !may_access_direct_pkt_data(env, meta, BPF_READ)) {
61bd5218 4504 verbose(env, "helper access to the packet is not allowed\n");
6841de8b
AS
4505 return -EACCES;
4506 }
4507
912f442c
LB
4508 if (arg_type == ARG_PTR_TO_MAP_VALUE ||
4509 arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE ||
4510 arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL) {
4511 err = resolve_map_arg_type(env, meta, &arg_type);
4512 if (err)
4513 return err;
4514 }
4515
fd1b0d60
LB
4516 if (register_is_null(reg) && arg_type_may_be_null(arg_type))
4517 /* A NULL register has a SCALAR_VALUE type, so skip
4518 * type checking.
4519 */
4520 goto skip_type_check;
4521
a968d5e2 4522 err = check_reg_type(env, regno, arg_type, fn->arg_btf_id[arg]);
f79e7ea5
LB
4523 if (err)
4524 return err;
4525
a968d5e2 4526 if (type == PTR_TO_CTX) {
feec7040
LB
4527 err = check_ctx_reg(env, reg, regno);
4528 if (err < 0)
4529 return err;
d7b9454a
LB
4530 }
4531
fd1b0d60 4532skip_type_check:
02f7c958 4533 if (reg->ref_obj_id) {
457f4436
AN
4534 if (meta->ref_obj_id) {
4535 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
4536 regno, reg->ref_obj_id,
4537 meta->ref_obj_id);
4538 return -EFAULT;
4539 }
4540 meta->ref_obj_id = reg->ref_obj_id;
17a52670
AS
4541 }
4542
17a52670
AS
4543 if (arg_type == ARG_CONST_MAP_PTR) {
4544 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
33ff9823 4545 meta->map_ptr = reg->map_ptr;
17a52670
AS
4546 } else if (arg_type == ARG_PTR_TO_MAP_KEY) {
4547 /* bpf_map_xxx(..., map_ptr, ..., key) call:
4548 * check that [key, key + map->key_size) are within
4549 * stack limits and initialized
4550 */
33ff9823 4551 if (!meta->map_ptr) {
17a52670
AS
4552 /* in function declaration map_ptr must come before
4553 * map_key, so that it's verified and known before
4554 * we have to check map_key here. Otherwise it means
4555 * that kernel subsystem misconfigured verifier
4556 */
61bd5218 4557 verbose(env, "invalid map_ptr to access map->key\n");
17a52670
AS
4558 return -EACCES;
4559 }
d71962f3
PC
4560 err = check_helper_mem_access(env, regno,
4561 meta->map_ptr->key_size, false,
4562 NULL);
2ea864c5 4563 } else if (arg_type == ARG_PTR_TO_MAP_VALUE ||
6ac99e8f
MKL
4564 (arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL &&
4565 !register_is_null(reg)) ||
2ea864c5 4566 arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE) {
17a52670
AS
4567 /* bpf_map_xxx(..., map_ptr, ..., value) call:
4568 * check [value, value + map->value_size) validity
4569 */
33ff9823 4570 if (!meta->map_ptr) {
17a52670 4571 /* kernel subsystem misconfigured verifier */
61bd5218 4572 verbose(env, "invalid map_ptr to access map->value\n");
17a52670
AS
4573 return -EACCES;
4574 }
2ea864c5 4575 meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE);
d71962f3
PC
4576 err = check_helper_mem_access(env, regno,
4577 meta->map_ptr->value_size, false,
2ea864c5 4578 meta);
eaa6bcb7
HL
4579 } else if (arg_type == ARG_PTR_TO_PERCPU_BTF_ID) {
4580 if (!reg->btf_id) {
4581 verbose(env, "Helper has invalid btf_id in R%d\n", regno);
4582 return -EACCES;
4583 }
22dc4a0f 4584 meta->ret_btf = reg->btf;
eaa6bcb7 4585 meta->ret_btf_id = reg->btf_id;
c18f0b6a
LB
4586 } else if (arg_type == ARG_PTR_TO_SPIN_LOCK) {
4587 if (meta->func_id == BPF_FUNC_spin_lock) {
4588 if (process_spin_lock(env, regno, true))
4589 return -EACCES;
4590 } else if (meta->func_id == BPF_FUNC_spin_unlock) {
4591 if (process_spin_lock(env, regno, false))
4592 return -EACCES;
4593 } else {
4594 verbose(env, "verifier internal error\n");
4595 return -EFAULT;
4596 }
a2bbe7cc
LB
4597 } else if (arg_type_is_mem_ptr(arg_type)) {
4598 /* The access to this pointer is only checked when we hit the
4599 * next is_mem_size argument below.
4600 */
4601 meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MEM);
90133415 4602 } else if (arg_type_is_mem_size(arg_type)) {
39f19ebb 4603 bool zero_size_allowed = (arg_type == ARG_CONST_SIZE_OR_ZERO);
17a52670 4604
10060503
JF
4605 /* This is used to refine r0 return value bounds for helpers
4606 * that enforce this value as an upper bound on return values.
4607 * See do_refine_retval_range() for helpers that can refine
4608 * the return value. C type of helper is u32 so we pull register
4609 * bound from umax_value however, if negative verifier errors
4610 * out. Only upper bounds can be learned because retval is an
4611 * int type and negative retvals are allowed.
849fa506 4612 */
10060503 4613 meta->msize_max_value = reg->umax_value;
849fa506 4614
f1174f77
EC
4615 /* The register is SCALAR_VALUE; the access check
4616 * happens using its boundaries.
06c1c049 4617 */
f1174f77 4618 if (!tnum_is_const(reg->var_off))
06c1c049
GB
4619 /* For unprivileged variable accesses, disable raw
4620 * mode so that the program is required to
4621 * initialize all the memory that the helper could
4622 * just partially fill up.
4623 */
4624 meta = NULL;
4625
b03c9f9f 4626 if (reg->smin_value < 0) {
61bd5218 4627 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
f1174f77
EC
4628 regno);
4629 return -EACCES;
4630 }
06c1c049 4631
b03c9f9f 4632 if (reg->umin_value == 0) {
f1174f77
EC
4633 err = check_helper_mem_access(env, regno - 1, 0,
4634 zero_size_allowed,
4635 meta);
06c1c049
GB
4636 if (err)
4637 return err;
06c1c049 4638 }
f1174f77 4639
b03c9f9f 4640 if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
61bd5218 4641 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
f1174f77
EC
4642 regno);
4643 return -EACCES;
4644 }
4645 err = check_helper_mem_access(env, regno - 1,
b03c9f9f 4646 reg->umax_value,
f1174f77 4647 zero_size_allowed, meta);
b5dc0163
AS
4648 if (!err)
4649 err = mark_chain_precision(env, regno);
457f4436
AN
4650 } else if (arg_type_is_alloc_size(arg_type)) {
4651 if (!tnum_is_const(reg->var_off)) {
4652 verbose(env, "R%d unbounded size, use 'var &= const' or 'if (var < const)'\n",
4653 regno);
4654 return -EACCES;
4655 }
4656 meta->mem_size = reg->var_off.value;
57c3bb72
AI
4657 } else if (arg_type_is_int_ptr(arg_type)) {
4658 int size = int_ptr_type_to_size(arg_type);
4659
4660 err = check_helper_mem_access(env, regno, size, false, meta);
4661 if (err)
4662 return err;
4663 err = check_ptr_alignment(env, reg, 0, size, true);
17a52670
AS
4664 }
4665
4666 return err;
4667}
4668
0126240f
LB
4669static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
4670{
4671 enum bpf_attach_type eatype = env->prog->expected_attach_type;
7e40781c 4672 enum bpf_prog_type type = resolve_prog_type(env->prog);
0126240f
LB
4673
4674 if (func_id != BPF_FUNC_map_update_elem)
4675 return false;
4676
4677 /* It's not possible to get access to a locked struct sock in these
4678 * contexts, so updating is safe.
4679 */
4680 switch (type) {
4681 case BPF_PROG_TYPE_TRACING:
4682 if (eatype == BPF_TRACE_ITER)
4683 return true;
4684 break;
4685 case BPF_PROG_TYPE_SOCKET_FILTER:
4686 case BPF_PROG_TYPE_SCHED_CLS:
4687 case BPF_PROG_TYPE_SCHED_ACT:
4688 case BPF_PROG_TYPE_XDP:
4689 case BPF_PROG_TYPE_SK_REUSEPORT:
4690 case BPF_PROG_TYPE_FLOW_DISSECTOR:
4691 case BPF_PROG_TYPE_SK_LOOKUP:
4692 return true;
4693 default:
4694 break;
4695 }
4696
4697 verbose(env, "cannot update sockmap in this context\n");
4698 return false;
4699}
4700
e411901c
MF
4701static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
4702{
4703 return env->prog->jit_requested && IS_ENABLED(CONFIG_X86_64);
4704}
4705
61bd5218
JK
4706static int check_map_func_compatibility(struct bpf_verifier_env *env,
4707 struct bpf_map *map, int func_id)
35578d79 4708{
35578d79
KX
4709 if (!map)
4710 return 0;
4711
6aff67c8
AS
4712 /* We need a two way check, first is from map perspective ... */
4713 switch (map->map_type) {
4714 case BPF_MAP_TYPE_PROG_ARRAY:
4715 if (func_id != BPF_FUNC_tail_call)
4716 goto error;
4717 break;
4718 case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
4719 if (func_id != BPF_FUNC_perf_event_read &&
908432ca 4720 func_id != BPF_FUNC_perf_event_output &&
a7658e1a 4721 func_id != BPF_FUNC_skb_output &&
d831ee84
EC
4722 func_id != BPF_FUNC_perf_event_read_value &&
4723 func_id != BPF_FUNC_xdp_output)
6aff67c8
AS
4724 goto error;
4725 break;
457f4436
AN
4726 case BPF_MAP_TYPE_RINGBUF:
4727 if (func_id != BPF_FUNC_ringbuf_output &&
4728 func_id != BPF_FUNC_ringbuf_reserve &&
4729 func_id != BPF_FUNC_ringbuf_submit &&
4730 func_id != BPF_FUNC_ringbuf_discard &&
4731 func_id != BPF_FUNC_ringbuf_query)
4732 goto error;
4733 break;
6aff67c8
AS
4734 case BPF_MAP_TYPE_STACK_TRACE:
4735 if (func_id != BPF_FUNC_get_stackid)
4736 goto error;
4737 break;
4ed8ec52 4738 case BPF_MAP_TYPE_CGROUP_ARRAY:
60747ef4 4739 if (func_id != BPF_FUNC_skb_under_cgroup &&
60d20f91 4740 func_id != BPF_FUNC_current_task_under_cgroup)
4a482f34
MKL
4741 goto error;
4742 break;
cd339431 4743 case BPF_MAP_TYPE_CGROUP_STORAGE:
b741f163 4744 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
cd339431
RG
4745 if (func_id != BPF_FUNC_get_local_storage)
4746 goto error;
4747 break;
546ac1ff 4748 case BPF_MAP_TYPE_DEVMAP:
6f9d451a 4749 case BPF_MAP_TYPE_DEVMAP_HASH:
0cdbb4b0
THJ
4750 if (func_id != BPF_FUNC_redirect_map &&
4751 func_id != BPF_FUNC_map_lookup_elem)
546ac1ff
JF
4752 goto error;
4753 break;
fbfc504a
BT
4754 /* Restrict bpf side of cpumap and xskmap, open when use-cases
4755 * appear.
4756 */
6710e112
JDB
4757 case BPF_MAP_TYPE_CPUMAP:
4758 if (func_id != BPF_FUNC_redirect_map)
4759 goto error;
4760 break;
fada7fdc
JL
4761 case BPF_MAP_TYPE_XSKMAP:
4762 if (func_id != BPF_FUNC_redirect_map &&
4763 func_id != BPF_FUNC_map_lookup_elem)
4764 goto error;
4765 break;
56f668df 4766 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
bcc6b1b7 4767 case BPF_MAP_TYPE_HASH_OF_MAPS:
56f668df
MKL
4768 if (func_id != BPF_FUNC_map_lookup_elem)
4769 goto error;
16a43625 4770 break;
174a79ff
JF
4771 case BPF_MAP_TYPE_SOCKMAP:
4772 if (func_id != BPF_FUNC_sk_redirect_map &&
4773 func_id != BPF_FUNC_sock_map_update &&
4f738adb 4774 func_id != BPF_FUNC_map_delete_elem &&
9fed9000 4775 func_id != BPF_FUNC_msg_redirect_map &&
64d85290 4776 func_id != BPF_FUNC_sk_select_reuseport &&
0126240f
LB
4777 func_id != BPF_FUNC_map_lookup_elem &&
4778 !may_update_sockmap(env, func_id))
174a79ff
JF
4779 goto error;
4780 break;
81110384
JF
4781 case BPF_MAP_TYPE_SOCKHASH:
4782 if (func_id != BPF_FUNC_sk_redirect_hash &&
4783 func_id != BPF_FUNC_sock_hash_update &&
4784 func_id != BPF_FUNC_map_delete_elem &&
9fed9000 4785 func_id != BPF_FUNC_msg_redirect_hash &&
64d85290 4786 func_id != BPF_FUNC_sk_select_reuseport &&
0126240f
LB
4787 func_id != BPF_FUNC_map_lookup_elem &&
4788 !may_update_sockmap(env, func_id))
81110384
JF
4789 goto error;
4790 break;
2dbb9b9e
MKL
4791 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
4792 if (func_id != BPF_FUNC_sk_select_reuseport)
4793 goto error;
4794 break;
f1a2e44a
MV
4795 case BPF_MAP_TYPE_QUEUE:
4796 case BPF_MAP_TYPE_STACK:
4797 if (func_id != BPF_FUNC_map_peek_elem &&
4798 func_id != BPF_FUNC_map_pop_elem &&
4799 func_id != BPF_FUNC_map_push_elem)
4800 goto error;
4801 break;
6ac99e8f
MKL
4802 case BPF_MAP_TYPE_SK_STORAGE:
4803 if (func_id != BPF_FUNC_sk_storage_get &&
4804 func_id != BPF_FUNC_sk_storage_delete)
4805 goto error;
4806 break;
8ea63684
KS
4807 case BPF_MAP_TYPE_INODE_STORAGE:
4808 if (func_id != BPF_FUNC_inode_storage_get &&
4809 func_id != BPF_FUNC_inode_storage_delete)
4810 goto error;
4811 break;
4cf1bc1f
KS
4812 case BPF_MAP_TYPE_TASK_STORAGE:
4813 if (func_id != BPF_FUNC_task_storage_get &&
4814 func_id != BPF_FUNC_task_storage_delete)
4815 goto error;
4816 break;
6aff67c8
AS
4817 default:
4818 break;
4819 }
4820
4821 /* ... and second from the function itself. */
4822 switch (func_id) {
4823 case BPF_FUNC_tail_call:
4824 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
4825 goto error;
e411901c
MF
4826 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
4827 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
f4d7e40a
AS
4828 return -EINVAL;
4829 }
6aff67c8
AS
4830 break;
4831 case BPF_FUNC_perf_event_read:
4832 case BPF_FUNC_perf_event_output:
908432ca 4833 case BPF_FUNC_perf_event_read_value:
a7658e1a 4834 case BPF_FUNC_skb_output:
d831ee84 4835 case BPF_FUNC_xdp_output:
6aff67c8
AS
4836 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
4837 goto error;
4838 break;
4839 case BPF_FUNC_get_stackid:
4840 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
4841 goto error;
4842 break;
60d20f91 4843 case BPF_FUNC_current_task_under_cgroup:
747ea55e 4844 case BPF_FUNC_skb_under_cgroup:
4a482f34
MKL
4845 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
4846 goto error;
4847 break;
97f91a7c 4848 case BPF_FUNC_redirect_map:
9c270af3 4849 if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
6f9d451a 4850 map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
fbfc504a
BT
4851 map->map_type != BPF_MAP_TYPE_CPUMAP &&
4852 map->map_type != BPF_MAP_TYPE_XSKMAP)
97f91a7c
JF
4853 goto error;
4854 break;
174a79ff 4855 case BPF_FUNC_sk_redirect_map:
4f738adb 4856 case BPF_FUNC_msg_redirect_map:
81110384 4857 case BPF_FUNC_sock_map_update:
174a79ff
JF
4858 if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
4859 goto error;
4860 break;
81110384
JF
4861 case BPF_FUNC_sk_redirect_hash:
4862 case BPF_FUNC_msg_redirect_hash:
4863 case BPF_FUNC_sock_hash_update:
4864 if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
174a79ff
JF
4865 goto error;
4866 break;
cd339431 4867 case BPF_FUNC_get_local_storage:
b741f163
RG
4868 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
4869 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
cd339431
RG
4870 goto error;
4871 break;
2dbb9b9e 4872 case BPF_FUNC_sk_select_reuseport:
9fed9000
JS
4873 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
4874 map->map_type != BPF_MAP_TYPE_SOCKMAP &&
4875 map->map_type != BPF_MAP_TYPE_SOCKHASH)
2dbb9b9e
MKL
4876 goto error;
4877 break;
f1a2e44a
MV
4878 case BPF_FUNC_map_peek_elem:
4879 case BPF_FUNC_map_pop_elem:
4880 case BPF_FUNC_map_push_elem:
4881 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
4882 map->map_type != BPF_MAP_TYPE_STACK)
4883 goto error;
4884 break;
6ac99e8f
MKL
4885 case BPF_FUNC_sk_storage_get:
4886 case BPF_FUNC_sk_storage_delete:
4887 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
4888 goto error;
4889 break;
8ea63684
KS
4890 case BPF_FUNC_inode_storage_get:
4891 case BPF_FUNC_inode_storage_delete:
4892 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
4893 goto error;
4894 break;
4cf1bc1f
KS
4895 case BPF_FUNC_task_storage_get:
4896 case BPF_FUNC_task_storage_delete:
4897 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
4898 goto error;
4899 break;
6aff67c8
AS
4900 default:
4901 break;
35578d79
KX
4902 }
4903
4904 return 0;
6aff67c8 4905error:
61bd5218 4906 verbose(env, "cannot pass map_type %d into func %s#%d\n",
ebb676da 4907 map->map_type, func_id_name(func_id), func_id);
6aff67c8 4908 return -EINVAL;
35578d79
KX
4909}
4910
90133415 4911static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
435faee1
DB
4912{
4913 int count = 0;
4914
39f19ebb 4915 if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
435faee1 4916 count++;
39f19ebb 4917 if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
435faee1 4918 count++;
39f19ebb 4919 if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
435faee1 4920 count++;
39f19ebb 4921 if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
435faee1 4922 count++;
39f19ebb 4923 if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
435faee1
DB
4924 count++;
4925
90133415
DB
4926 /* We only support one arg being in raw mode at the moment,
4927 * which is sufficient for the helper functions we have
4928 * right now.
4929 */
4930 return count <= 1;
4931}
4932
4933static bool check_args_pair_invalid(enum bpf_arg_type arg_curr,
4934 enum bpf_arg_type arg_next)
4935{
4936 return (arg_type_is_mem_ptr(arg_curr) &&
4937 !arg_type_is_mem_size(arg_next)) ||
4938 (!arg_type_is_mem_ptr(arg_curr) &&
4939 arg_type_is_mem_size(arg_next));
4940}
4941
4942static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
4943{
4944 /* bpf_xxx(..., buf, len) call will access 'len'
4945 * bytes from memory 'buf'. Both arg types need
4946 * to be paired, so make sure there's no buggy
4947 * helper function specification.
4948 */
4949 if (arg_type_is_mem_size(fn->arg1_type) ||
4950 arg_type_is_mem_ptr(fn->arg5_type) ||
4951 check_args_pair_invalid(fn->arg1_type, fn->arg2_type) ||
4952 check_args_pair_invalid(fn->arg2_type, fn->arg3_type) ||
4953 check_args_pair_invalid(fn->arg3_type, fn->arg4_type) ||
4954 check_args_pair_invalid(fn->arg4_type, fn->arg5_type))
4955 return false;
4956
4957 return true;
4958}
4959
1b986589 4960static bool check_refcount_ok(const struct bpf_func_proto *fn, int func_id)
fd978bf7
JS
4961{
4962 int count = 0;
4963
1b986589 4964 if (arg_type_may_be_refcounted(fn->arg1_type))
fd978bf7 4965 count++;
1b986589 4966 if (arg_type_may_be_refcounted(fn->arg2_type))
fd978bf7 4967 count++;
1b986589 4968 if (arg_type_may_be_refcounted(fn->arg3_type))
fd978bf7 4969 count++;
1b986589 4970 if (arg_type_may_be_refcounted(fn->arg4_type))
fd978bf7 4971 count++;
1b986589 4972 if (arg_type_may_be_refcounted(fn->arg5_type))
fd978bf7
JS
4973 count++;
4974
1b986589
MKL
4975 /* A reference acquiring function cannot acquire
4976 * another refcounted ptr.
4977 */
64d85290 4978 if (may_be_acquire_function(func_id) && count)
1b986589
MKL
4979 return false;
4980
fd978bf7
JS
4981 /* We only support one arg being unreferenced at the moment,
4982 * which is sufficient for the helper functions we have right now.
4983 */
4984 return count <= 1;
4985}
4986
9436ef6e
LB
4987static bool check_btf_id_ok(const struct bpf_func_proto *fn)
4988{
4989 int i;
4990
1df8f55a 4991 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
9436ef6e
LB
4992 if (fn->arg_type[i] == ARG_PTR_TO_BTF_ID && !fn->arg_btf_id[i])
4993 return false;
4994
1df8f55a
MKL
4995 if (fn->arg_type[i] != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i])
4996 return false;
4997 }
4998
9436ef6e
LB
4999 return true;
5000}
5001
1b986589 5002static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
90133415
DB
5003{
5004 return check_raw_mode_ok(fn) &&
fd978bf7 5005 check_arg_pair_ok(fn) &&
9436ef6e 5006 check_btf_id_ok(fn) &&
1b986589 5007 check_refcount_ok(fn, func_id) ? 0 : -EINVAL;
435faee1
DB
5008}
5009
de8f3a83
DB
5010/* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
5011 * are now invalid, so turn them into unknown SCALAR_VALUE.
f1174f77 5012 */
f4d7e40a
AS
5013static void __clear_all_pkt_pointers(struct bpf_verifier_env *env,
5014 struct bpf_func_state *state)
969bf05e 5015{
58e2af8b 5016 struct bpf_reg_state *regs = state->regs, *reg;
969bf05e
AS
5017 int i;
5018
5019 for (i = 0; i < MAX_BPF_REG; i++)
de8f3a83 5020 if (reg_is_pkt_pointer_any(&regs[i]))
61bd5218 5021 mark_reg_unknown(env, regs, i);
969bf05e 5022
f3709f69
JS
5023 bpf_for_each_spilled_reg(i, state, reg) {
5024 if (!reg)
969bf05e 5025 continue;
de8f3a83 5026 if (reg_is_pkt_pointer_any(reg))
f54c7898 5027 __mark_reg_unknown(env, reg);
969bf05e
AS
5028 }
5029}
5030
f4d7e40a
AS
5031static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
5032{
5033 struct bpf_verifier_state *vstate = env->cur_state;
5034 int i;
5035
5036 for (i = 0; i <= vstate->curframe; i++)
5037 __clear_all_pkt_pointers(env, vstate->frame[i]);
5038}
5039
6d94e741
AS
5040enum {
5041 AT_PKT_END = -1,
5042 BEYOND_PKT_END = -2,
5043};
5044
5045static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
5046{
5047 struct bpf_func_state *state = vstate->frame[vstate->curframe];
5048 struct bpf_reg_state *reg = &state->regs[regn];
5049
5050 if (reg->type != PTR_TO_PACKET)
5051 /* PTR_TO_PACKET_META is not supported yet */
5052 return;
5053
5054 /* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
5055 * How far beyond pkt_end it goes is unknown.
5056 * if (!range_open) it's the case of pkt >= pkt_end
5057 * if (range_open) it's the case of pkt > pkt_end
5058 * hence this pointer is at least 1 byte bigger than pkt_end
5059 */
5060 if (range_open)
5061 reg->range = BEYOND_PKT_END;
5062 else
5063 reg->range = AT_PKT_END;
5064}
5065
fd978bf7 5066static void release_reg_references(struct bpf_verifier_env *env,
1b986589
MKL
5067 struct bpf_func_state *state,
5068 int ref_obj_id)
fd978bf7
JS
5069{
5070 struct bpf_reg_state *regs = state->regs, *reg;
5071 int i;
5072
5073 for (i = 0; i < MAX_BPF_REG; i++)
1b986589 5074 if (regs[i].ref_obj_id == ref_obj_id)
fd978bf7
JS
5075 mark_reg_unknown(env, regs, i);
5076
5077 bpf_for_each_spilled_reg(i, state, reg) {
5078 if (!reg)
5079 continue;
1b986589 5080 if (reg->ref_obj_id == ref_obj_id)
f54c7898 5081 __mark_reg_unknown(env, reg);
fd978bf7
JS
5082 }
5083}
5084
5085/* The pointer with the specified id has released its reference to kernel
5086 * resources. Identify all copies of the same pointer and clear the reference.
5087 */
5088static int release_reference(struct bpf_verifier_env *env,
1b986589 5089 int ref_obj_id)
fd978bf7
JS
5090{
5091 struct bpf_verifier_state *vstate = env->cur_state;
1b986589 5092 int err;
fd978bf7
JS
5093 int i;
5094
1b986589
MKL
5095 err = release_reference_state(cur_func(env), ref_obj_id);
5096 if (err)
5097 return err;
5098
fd978bf7 5099 for (i = 0; i <= vstate->curframe; i++)
1b986589 5100 release_reg_references(env, vstate->frame[i], ref_obj_id);
fd978bf7 5101
1b986589 5102 return 0;
fd978bf7
JS
5103}
5104
51c39bb1
AS
5105static void clear_caller_saved_regs(struct bpf_verifier_env *env,
5106 struct bpf_reg_state *regs)
5107{
5108 int i;
5109
5110 /* after the call registers r0 - r5 were scratched */
5111 for (i = 0; i < CALLER_SAVED_REGS; i++) {
5112 mark_reg_not_init(env, regs, caller_saved[i]);
5113 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
5114 }
5115}
5116
f4d7e40a
AS
5117static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
5118 int *insn_idx)
5119{
5120 struct bpf_verifier_state *state = env->cur_state;
51c39bb1 5121 struct bpf_func_info_aux *func_info_aux;
f4d7e40a 5122 struct bpf_func_state *caller, *callee;
fd978bf7 5123 int i, err, subprog, target_insn;
51c39bb1 5124 bool is_global = false;
f4d7e40a 5125
aada9ce6 5126 if (state->curframe + 1 >= MAX_CALL_FRAMES) {
f4d7e40a 5127 verbose(env, "the call stack of %d frames is too deep\n",
aada9ce6 5128 state->curframe + 2);
f4d7e40a
AS
5129 return -E2BIG;
5130 }
5131
5132 target_insn = *insn_idx + insn->imm;
5133 subprog = find_subprog(env, target_insn + 1);
5134 if (subprog < 0) {
5135 verbose(env, "verifier bug. No program starts at insn %d\n",
5136 target_insn + 1);
5137 return -EFAULT;
5138 }
5139
5140 caller = state->frame[state->curframe];
5141 if (state->frame[state->curframe + 1]) {
5142 verbose(env, "verifier bug. Frame %d already allocated\n",
5143 state->curframe + 1);
5144 return -EFAULT;
5145 }
5146
51c39bb1
AS
5147 func_info_aux = env->prog->aux->func_info_aux;
5148 if (func_info_aux)
5149 is_global = func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
5150 err = btf_check_func_arg_match(env, subprog, caller->regs);
5151 if (err == -EFAULT)
5152 return err;
5153 if (is_global) {
5154 if (err) {
5155 verbose(env, "Caller passes invalid args into func#%d\n",
5156 subprog);
5157 return err;
5158 } else {
5159 if (env->log.level & BPF_LOG_LEVEL)
5160 verbose(env,
5161 "Func#%d is global and valid. Skipping.\n",
5162 subprog);
5163 clear_caller_saved_regs(env, caller->regs);
5164
1f0a2930 5165 /* All global functions return a 64-bit SCALAR_VALUE */
51c39bb1 5166 mark_reg_unknown(env, caller->regs, BPF_REG_0);
1f0a2930 5167 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
51c39bb1
AS
5168
5169 /* continue with next insn after call */
5170 return 0;
5171 }
5172 }
5173
f4d7e40a
AS
5174 callee = kzalloc(sizeof(*callee), GFP_KERNEL);
5175 if (!callee)
5176 return -ENOMEM;
5177 state->frame[state->curframe + 1] = callee;
5178
5179 /* callee cannot access r0, r6 - r9 for reading and has to write
5180 * into its own stack before reading from it.
5181 * callee can read/write into caller's stack
5182 */
5183 init_func_state(env, callee,
5184 /* remember the callsite, it will be used by bpf_exit */
5185 *insn_idx /* callsite */,
5186 state->curframe + 1 /* frameno within this callchain */,
f910cefa 5187 subprog /* subprog number within this prog */);
f4d7e40a 5188
fd978bf7
JS
5189 /* Transfer references to the callee */
5190 err = transfer_reference_state(callee, caller);
5191 if (err)
5192 return err;
5193
679c782d
EC
5194 /* copy r1 - r5 args that callee can access. The copy includes parent
5195 * pointers, which connects us up to the liveness chain
5196 */
f4d7e40a
AS
5197 for (i = BPF_REG_1; i <= BPF_REG_5; i++)
5198 callee->regs[i] = caller->regs[i];
5199
51c39bb1 5200 clear_caller_saved_regs(env, caller->regs);
f4d7e40a
AS
5201
5202 /* only increment it after check_reg_arg() finished */
5203 state->curframe++;
5204
5205 /* and go analyze first insn of the callee */
5206 *insn_idx = target_insn;
5207
06ee7115 5208 if (env->log.level & BPF_LOG_LEVEL) {
f4d7e40a
AS
5209 verbose(env, "caller:\n");
5210 print_verifier_state(env, caller);
5211 verbose(env, "callee:\n");
5212 print_verifier_state(env, callee);
5213 }
5214 return 0;
5215}
5216
5217static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
5218{
5219 struct bpf_verifier_state *state = env->cur_state;
5220 struct bpf_func_state *caller, *callee;
5221 struct bpf_reg_state *r0;
fd978bf7 5222 int err;
f4d7e40a
AS
5223
5224 callee = state->frame[state->curframe];
5225 r0 = &callee->regs[BPF_REG_0];
5226 if (r0->type == PTR_TO_STACK) {
5227 /* technically it's ok to return caller's stack pointer
5228 * (or caller's caller's pointer) back to the caller,
5229 * since these pointers are valid. Only current stack
5230 * pointer will be invalid as soon as function exits,
5231 * but let's be conservative
5232 */
5233 verbose(env, "cannot return stack pointer to the caller\n");
5234 return -EINVAL;
5235 }
5236
5237 state->curframe--;
5238 caller = state->frame[state->curframe];
5239 /* return to the caller whatever r0 had in the callee */
5240 caller->regs[BPF_REG_0] = *r0;
5241
fd978bf7
JS
5242 /* Transfer references to the caller */
5243 err = transfer_reference_state(caller, callee);
5244 if (err)
5245 return err;
5246
f4d7e40a 5247 *insn_idx = callee->callsite + 1;
06ee7115 5248 if (env->log.level & BPF_LOG_LEVEL) {
f4d7e40a
AS
5249 verbose(env, "returning from callee:\n");
5250 print_verifier_state(env, callee);
5251 verbose(env, "to caller at %d:\n", *insn_idx);
5252 print_verifier_state(env, caller);
5253 }
5254 /* clear everything in the callee */
5255 free_func_state(callee);
5256 state->frame[state->curframe + 1] = NULL;
5257 return 0;
5258}
5259
849fa506
YS
5260static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
5261 int func_id,
5262 struct bpf_call_arg_meta *meta)
5263{
5264 struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
5265
5266 if (ret_type != RET_INTEGER ||
5267 (func_id != BPF_FUNC_get_stack &&
47cc0ed5
DB
5268 func_id != BPF_FUNC_probe_read_str &&
5269 func_id != BPF_FUNC_probe_read_kernel_str &&
5270 func_id != BPF_FUNC_probe_read_user_str))
849fa506
YS
5271 return;
5272
10060503 5273 ret_reg->smax_value = meta->msize_max_value;
fa123ac0 5274 ret_reg->s32_max_value = meta->msize_max_value;
b0270958
AS
5275 ret_reg->smin_value = -MAX_ERRNO;
5276 ret_reg->s32_min_value = -MAX_ERRNO;
849fa506
YS
5277 __reg_deduce_bounds(ret_reg);
5278 __reg_bound_offset(ret_reg);
10060503 5279 __update_reg_bounds(ret_reg);
849fa506
YS
5280}
5281
c93552c4
DB
5282static int
5283record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
5284 int func_id, int insn_idx)
5285{
5286 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
591fe988 5287 struct bpf_map *map = meta->map_ptr;
c93552c4
DB
5288
5289 if (func_id != BPF_FUNC_tail_call &&
09772d92
DB
5290 func_id != BPF_FUNC_map_lookup_elem &&
5291 func_id != BPF_FUNC_map_update_elem &&
f1a2e44a
MV
5292 func_id != BPF_FUNC_map_delete_elem &&
5293 func_id != BPF_FUNC_map_push_elem &&
5294 func_id != BPF_FUNC_map_pop_elem &&
5295 func_id != BPF_FUNC_map_peek_elem)
c93552c4 5296 return 0;
09772d92 5297
591fe988 5298 if (map == NULL) {
c93552c4
DB
5299 verbose(env, "kernel subsystem misconfigured verifier\n");
5300 return -EINVAL;
5301 }
5302
591fe988
DB
5303 /* In case of read-only, some additional restrictions
5304 * need to be applied in order to prevent altering the
5305 * state of the map from program side.
5306 */
5307 if ((map->map_flags & BPF_F_RDONLY_PROG) &&
5308 (func_id == BPF_FUNC_map_delete_elem ||
5309 func_id == BPF_FUNC_map_update_elem ||
5310 func_id == BPF_FUNC_map_push_elem ||
5311 func_id == BPF_FUNC_map_pop_elem)) {
5312 verbose(env, "write into map forbidden\n");
5313 return -EACCES;
5314 }
5315
d2e4c1e6 5316 if (!BPF_MAP_PTR(aux->map_ptr_state))
c93552c4 5317 bpf_map_ptr_store(aux, meta->map_ptr,
2c78ee89 5318 !meta->map_ptr->bypass_spec_v1);
d2e4c1e6 5319 else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
c93552c4 5320 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
2c78ee89 5321 !meta->map_ptr->bypass_spec_v1);
c93552c4
DB
5322 return 0;
5323}
5324
d2e4c1e6
DB
5325static int
5326record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
5327 int func_id, int insn_idx)
5328{
5329 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
5330 struct bpf_reg_state *regs = cur_regs(env), *reg;
5331 struct bpf_map *map = meta->map_ptr;
5332 struct tnum range;
5333 u64 val;
cc52d914 5334 int err;
d2e4c1e6
DB
5335
5336 if (func_id != BPF_FUNC_tail_call)
5337 return 0;
5338 if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
5339 verbose(env, "kernel subsystem misconfigured verifier\n");
5340 return -EINVAL;
5341 }
5342
5343 range = tnum_range(0, map->max_entries - 1);
5344 reg = &regs[BPF_REG_3];
5345
5346 if (!register_is_const(reg) || !tnum_in(range, reg->var_off)) {
5347 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
5348 return 0;
5349 }
5350
cc52d914
DB
5351 err = mark_chain_precision(env, BPF_REG_3);
5352 if (err)
5353 return err;
5354
d2e4c1e6
DB
5355 val = reg->var_off.value;
5356 if (bpf_map_key_unseen(aux))
5357 bpf_map_key_store(aux, val);
5358 else if (!bpf_map_key_poisoned(aux) &&
5359 bpf_map_key_immediate(aux) != val)
5360 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
5361 return 0;
5362}
5363
fd978bf7
JS
5364static int check_reference_leak(struct bpf_verifier_env *env)
5365{
5366 struct bpf_func_state *state = cur_func(env);
5367 int i;
5368
5369 for (i = 0; i < state->acquired_refs; i++) {
5370 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
5371 state->refs[i].id, state->refs[i].insn_idx);
5372 }
5373 return state->acquired_refs ? -EINVAL : 0;
5374}
5375
f4d7e40a 5376static int check_helper_call(struct bpf_verifier_env *env, int func_id, int insn_idx)
17a52670 5377{
17a52670 5378 const struct bpf_func_proto *fn = NULL;
638f5b90 5379 struct bpf_reg_state *regs;
33ff9823 5380 struct bpf_call_arg_meta meta;
969bf05e 5381 bool changes_data;
17a52670
AS
5382 int i, err;
5383
5384 /* find function prototype */
5385 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
61bd5218
JK
5386 verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
5387 func_id);
17a52670
AS
5388 return -EINVAL;
5389 }
5390
00176a34 5391 if (env->ops->get_func_proto)
5e43f899 5392 fn = env->ops->get_func_proto(func_id, env->prog);
17a52670 5393 if (!fn) {
61bd5218
JK
5394 verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
5395 func_id);
17a52670
AS
5396 return -EINVAL;
5397 }
5398
5399 /* eBPF programs must be GPL compatible to use GPL-ed functions */
24701ece 5400 if (!env->prog->gpl_compatible && fn->gpl_only) {
3fe2867c 5401 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
17a52670
AS
5402 return -EINVAL;
5403 }
5404
eae2e83e
JO
5405 if (fn->allowed && !fn->allowed(env->prog)) {
5406 verbose(env, "helper call is not allowed in probe\n");
5407 return -EINVAL;
5408 }
5409
04514d13 5410 /* With LD_ABS/IND some JITs save/restore skb from r1. */
17bedab2 5411 changes_data = bpf_helper_changes_pkt_data(fn->func);
04514d13
DB
5412 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
5413 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
5414 func_id_name(func_id), func_id);
5415 return -EINVAL;
5416 }
969bf05e 5417
33ff9823 5418 memset(&meta, 0, sizeof(meta));
36bbef52 5419 meta.pkt_access = fn->pkt_access;
33ff9823 5420
1b986589 5421 err = check_func_proto(fn, func_id);
435faee1 5422 if (err) {
61bd5218 5423 verbose(env, "kernel subsystem misconfigured func %s#%d\n",
ebb676da 5424 func_id_name(func_id), func_id);
435faee1
DB
5425 return err;
5426 }
5427
d83525ca 5428 meta.func_id = func_id;
17a52670 5429 /* check args */
a7658e1a 5430 for (i = 0; i < 5; i++) {
af7ec138 5431 err = check_func_arg(env, i, &meta, fn);
a7658e1a
AS
5432 if (err)
5433 return err;
5434 }
17a52670 5435
c93552c4
DB
5436 err = record_func_map(env, &meta, func_id, insn_idx);
5437 if (err)
5438 return err;
5439
d2e4c1e6
DB
5440 err = record_func_key(env, &meta, func_id, insn_idx);
5441 if (err)
5442 return err;
5443
435faee1
DB
5444 /* Mark slots with STACK_MISC in case of raw mode, stack offset
5445 * is inferred from register state.
5446 */
5447 for (i = 0; i < meta.access_size; i++) {
ca369602
DB
5448 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
5449 BPF_WRITE, -1, false);
435faee1
DB
5450 if (err)
5451 return err;
5452 }
5453
fd978bf7
JS
5454 if (func_id == BPF_FUNC_tail_call) {
5455 err = check_reference_leak(env);
5456 if (err) {
5457 verbose(env, "tail_call would lead to reference leak\n");
5458 return err;
5459 }
5460 } else if (is_release_function(func_id)) {
1b986589 5461 err = release_reference(env, meta.ref_obj_id);
46f8bc92
MKL
5462 if (err) {
5463 verbose(env, "func %s#%d reference has not been acquired before\n",
5464 func_id_name(func_id), func_id);
fd978bf7 5465 return err;
46f8bc92 5466 }
fd978bf7
JS
5467 }
5468
638f5b90 5469 regs = cur_regs(env);
cd339431
RG
5470
5471 /* check that flags argument in get_local_storage(map, flags) is 0,
5472 * this is required because get_local_storage() can't return an error.
5473 */
5474 if (func_id == BPF_FUNC_get_local_storage &&
5475 !register_is_null(&regs[BPF_REG_2])) {
5476 verbose(env, "get_local_storage() doesn't support non-zero flags\n");
5477 return -EINVAL;
5478 }
5479
17a52670 5480 /* reset caller saved regs */
dc503a8a 5481 for (i = 0; i < CALLER_SAVED_REGS; i++) {
61bd5218 5482 mark_reg_not_init(env, regs, caller_saved[i]);
dc503a8a
EC
5483 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
5484 }
17a52670 5485
5327ed3d
JW
5486 /* helper call returns 64-bit value. */
5487 regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
5488
dc503a8a 5489 /* update return register (already marked as written above) */
17a52670 5490 if (fn->ret_type == RET_INTEGER) {
f1174f77 5491 /* sets type to SCALAR_VALUE */
61bd5218 5492 mark_reg_unknown(env, regs, BPF_REG_0);
17a52670
AS
5493 } else if (fn->ret_type == RET_VOID) {
5494 regs[BPF_REG_0].type = NOT_INIT;
3e6a4b3e
RG
5495 } else if (fn->ret_type == RET_PTR_TO_MAP_VALUE_OR_NULL ||
5496 fn->ret_type == RET_PTR_TO_MAP_VALUE) {
f1174f77 5497 /* There is no offset yet applied, variable or fixed */
61bd5218 5498 mark_reg_known_zero(env, regs, BPF_REG_0);
17a52670
AS
5499 /* remember map_ptr, so that check_map_access()
5500 * can check 'value_size' boundary of memory access
5501 * to map element returned from bpf_map_lookup_elem()
5502 */
33ff9823 5503 if (meta.map_ptr == NULL) {
61bd5218
JK
5504 verbose(env,
5505 "kernel subsystem misconfigured verifier\n");
17a52670
AS
5506 return -EINVAL;
5507 }
33ff9823 5508 regs[BPF_REG_0].map_ptr = meta.map_ptr;
4d31f301
DB
5509 if (fn->ret_type == RET_PTR_TO_MAP_VALUE) {
5510 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE;
e16d2f1a
AS
5511 if (map_value_has_spin_lock(meta.map_ptr))
5512 regs[BPF_REG_0].id = ++env->id_gen;
4d31f301
DB
5513 } else {
5514 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE_OR_NULL;
4d31f301 5515 }
c64b7983
JS
5516 } else if (fn->ret_type == RET_PTR_TO_SOCKET_OR_NULL) {
5517 mark_reg_known_zero(env, regs, BPF_REG_0);
5518 regs[BPF_REG_0].type = PTR_TO_SOCKET_OR_NULL;
85a51f8c
LB
5519 } else if (fn->ret_type == RET_PTR_TO_SOCK_COMMON_OR_NULL) {
5520 mark_reg_known_zero(env, regs, BPF_REG_0);
5521 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON_OR_NULL;
655a51e5
MKL
5522 } else if (fn->ret_type == RET_PTR_TO_TCP_SOCK_OR_NULL) {
5523 mark_reg_known_zero(env, regs, BPF_REG_0);
5524 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK_OR_NULL;
457f4436
AN
5525 } else if (fn->ret_type == RET_PTR_TO_ALLOC_MEM_OR_NULL) {
5526 mark_reg_known_zero(env, regs, BPF_REG_0);
5527 regs[BPF_REG_0].type = PTR_TO_MEM_OR_NULL;
457f4436 5528 regs[BPF_REG_0].mem_size = meta.mem_size;
63d9b80d
HL
5529 } else if (fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID_OR_NULL ||
5530 fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID) {
eaa6bcb7
HL
5531 const struct btf_type *t;
5532
5533 mark_reg_known_zero(env, regs, BPF_REG_0);
22dc4a0f 5534 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
eaa6bcb7
HL
5535 if (!btf_type_is_struct(t)) {
5536 u32 tsize;
5537 const struct btf_type *ret;
5538 const char *tname;
5539
5540 /* resolve the type size of ksym. */
22dc4a0f 5541 ret = btf_resolve_size(meta.ret_btf, t, &tsize);
eaa6bcb7 5542 if (IS_ERR(ret)) {
22dc4a0f 5543 tname = btf_name_by_offset(meta.ret_btf, t->name_off);
eaa6bcb7
HL
5544 verbose(env, "unable to resolve the size of type '%s': %ld\n",
5545 tname, PTR_ERR(ret));
5546 return -EINVAL;
5547 }
63d9b80d
HL
5548 regs[BPF_REG_0].type =
5549 fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID ?
5550 PTR_TO_MEM : PTR_TO_MEM_OR_NULL;
eaa6bcb7
HL
5551 regs[BPF_REG_0].mem_size = tsize;
5552 } else {
63d9b80d
HL
5553 regs[BPF_REG_0].type =
5554 fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID ?
5555 PTR_TO_BTF_ID : PTR_TO_BTF_ID_OR_NULL;
22dc4a0f 5556 regs[BPF_REG_0].btf = meta.ret_btf;
eaa6bcb7
HL
5557 regs[BPF_REG_0].btf_id = meta.ret_btf_id;
5558 }
3ca1032a
KS
5559 } else if (fn->ret_type == RET_PTR_TO_BTF_ID_OR_NULL ||
5560 fn->ret_type == RET_PTR_TO_BTF_ID) {
af7ec138
YS
5561 int ret_btf_id;
5562
5563 mark_reg_known_zero(env, regs, BPF_REG_0);
3ca1032a
KS
5564 regs[BPF_REG_0].type = fn->ret_type == RET_PTR_TO_BTF_ID ?
5565 PTR_TO_BTF_ID :
5566 PTR_TO_BTF_ID_OR_NULL;
af7ec138
YS
5567 ret_btf_id = *fn->ret_btf_id;
5568 if (ret_btf_id == 0) {
5569 verbose(env, "invalid return type %d of func %s#%d\n",
5570 fn->ret_type, func_id_name(func_id), func_id);
5571 return -EINVAL;
5572 }
22dc4a0f
AN
5573 /* current BPF helper definitions are only coming from
5574 * built-in code with type IDs from vmlinux BTF
5575 */
5576 regs[BPF_REG_0].btf = btf_vmlinux;
af7ec138 5577 regs[BPF_REG_0].btf_id = ret_btf_id;
17a52670 5578 } else {
61bd5218 5579 verbose(env, "unknown return type %d of func %s#%d\n",
ebb676da 5580 fn->ret_type, func_id_name(func_id), func_id);
17a52670
AS
5581 return -EINVAL;
5582 }
04fd61ab 5583
93c230e3
MKL
5584 if (reg_type_may_be_null(regs[BPF_REG_0].type))
5585 regs[BPF_REG_0].id = ++env->id_gen;
5586
0f3adc28 5587 if (is_ptr_cast_function(func_id)) {
1b986589
MKL
5588 /* For release_reference() */
5589 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
64d85290 5590 } else if (is_acquire_function(func_id, meta.map_ptr)) {
0f3adc28
LB
5591 int id = acquire_reference_state(env, insn_idx);
5592
5593 if (id < 0)
5594 return id;
5595 /* For mark_ptr_or_null_reg() */
5596 regs[BPF_REG_0].id = id;
5597 /* For release_reference() */
5598 regs[BPF_REG_0].ref_obj_id = id;
5599 }
1b986589 5600
849fa506
YS
5601 do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
5602
61bd5218 5603 err = check_map_func_compatibility(env, meta.map_ptr, func_id);
35578d79
KX
5604 if (err)
5605 return err;
04fd61ab 5606
fa28dcb8
SL
5607 if ((func_id == BPF_FUNC_get_stack ||
5608 func_id == BPF_FUNC_get_task_stack) &&
5609 !env->prog->has_callchain_buf) {
c195651e
YS
5610 const char *err_str;
5611
5612#ifdef CONFIG_PERF_EVENTS
5613 err = get_callchain_buffers(sysctl_perf_event_max_stack);
5614 err_str = "cannot get callchain buffer for func %s#%d\n";
5615#else
5616 err = -ENOTSUPP;
5617 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
5618#endif
5619 if (err) {
5620 verbose(env, err_str, func_id_name(func_id), func_id);
5621 return err;
5622 }
5623
5624 env->prog->has_callchain_buf = true;
5625 }
5626
5d99cb2c
SL
5627 if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
5628 env->prog->call_get_stack = true;
5629
969bf05e
AS
5630 if (changes_data)
5631 clear_all_pkt_pointers(env);
5632 return 0;
5633}
5634
b03c9f9f
EC
5635static bool signed_add_overflows(s64 a, s64 b)
5636{
5637 /* Do the add in u64, where overflow is well-defined */
5638 s64 res = (s64)((u64)a + (u64)b);
5639
5640 if (b < 0)
5641 return res > a;
5642 return res < a;
5643}
5644
bc895e8b 5645static bool signed_add32_overflows(s32 a, s32 b)
3f50f132
JF
5646{
5647 /* Do the add in u32, where overflow is well-defined */
5648 s32 res = (s32)((u32)a + (u32)b);
5649
5650 if (b < 0)
5651 return res > a;
5652 return res < a;
5653}
5654
bc895e8b 5655static bool signed_sub_overflows(s64 a, s64 b)
b03c9f9f
EC
5656{
5657 /* Do the sub in u64, where overflow is well-defined */
5658 s64 res = (s64)((u64)a - (u64)b);
5659
5660 if (b < 0)
5661 return res < a;
5662 return res > a;
969bf05e
AS
5663}
5664
3f50f132
JF
5665static bool signed_sub32_overflows(s32 a, s32 b)
5666{
bc895e8b 5667 /* Do the sub in u32, where overflow is well-defined */
3f50f132
JF
5668 s32 res = (s32)((u32)a - (u32)b);
5669
5670 if (b < 0)
5671 return res < a;
5672 return res > a;
5673}
5674
bb7f0f98
AS
5675static bool check_reg_sane_offset(struct bpf_verifier_env *env,
5676 const struct bpf_reg_state *reg,
5677 enum bpf_reg_type type)
5678{
5679 bool known = tnum_is_const(reg->var_off);
5680 s64 val = reg->var_off.value;
5681 s64 smin = reg->smin_value;
5682
5683 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
5684 verbose(env, "math between %s pointer and %lld is not allowed\n",
5685 reg_type_str[type], val);
5686 return false;
5687 }
5688
5689 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
5690 verbose(env, "%s pointer offset %d is not allowed\n",
5691 reg_type_str[type], reg->off);
5692 return false;
5693 }
5694
5695 if (smin == S64_MIN) {
5696 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
5697 reg_type_str[type]);
5698 return false;
5699 }
5700
5701 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
5702 verbose(env, "value %lld makes %s pointer be out of bounds\n",
5703 smin, reg_type_str[type]);
5704 return false;
5705 }
5706
5707 return true;
5708}
5709
979d63d5
DB
5710static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
5711{
5712 return &env->insn_aux_data[env->insn_idx];
5713}
5714
1e1331d6
DB
5715enum {
5716 REASON_BOUNDS = -1,
5717 REASON_TYPE = -2,
5718 REASON_PATHS = -3,
5719 REASON_LIMIT = -4,
5720 REASON_STACK = -5,
5721};
5722
979d63d5 5723static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
75c82d37 5724 const struct bpf_reg_state *off_reg,
81526ed4 5725 u32 *alu_limit, u8 opcode)
979d63d5 5726{
75c82d37 5727 bool off_is_neg = off_reg->smin_value < 0;
979d63d5
DB
5728 bool mask_to_left = (opcode == BPF_ADD && off_is_neg) ||
5729 (opcode == BPF_SUB && !off_is_neg);
70bd6fa1 5730 u32 max = 0, ptr_limit = 0;
979d63d5 5731
75c82d37
DB
5732 if (!tnum_is_const(off_reg->var_off) &&
5733 (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
1e1331d6 5734 return REASON_BOUNDS;
75c82d37 5735
979d63d5
DB
5736 switch (ptr_reg->type) {
5737 case PTR_TO_STACK:
24d7115d 5738 /* Offset 0 is out-of-bounds, but acceptable start for the
70bd6fa1
DB
5739 * left direction, see BPF_REG_FP. Also, unknown scalar
5740 * offset where we would need to deal with min/max bounds is
5741 * currently prohibited for unprivileged.
24d7115d
PK
5742 */
5743 max = MAX_BPF_STACK + mask_to_left;
70bd6fa1 5744 ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
81526ed4 5745 break;
979d63d5 5746 case PTR_TO_MAP_VALUE:
24d7115d 5747 max = ptr_reg->map_ptr->value_size;
70bd6fa1
DB
5748 ptr_limit = (mask_to_left ?
5749 ptr_reg->smin_value :
5750 ptr_reg->umax_value) + ptr_reg->off;
81526ed4 5751 break;
979d63d5 5752 default:
1e1331d6 5753 return REASON_TYPE;
979d63d5 5754 }
81526ed4
DB
5755
5756 if (ptr_limit >= max)
1e1331d6 5757 return REASON_LIMIT;
81526ed4
DB
5758 *alu_limit = ptr_limit;
5759 return 0;
979d63d5
DB
5760}
5761
d3bd7413
DB
5762static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
5763 const struct bpf_insn *insn)
5764{
2c78ee89 5765 return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
d3bd7413
DB
5766}
5767
5768static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
5769 u32 alu_state, u32 alu_limit)
5770{
5771 /* If we arrived here from different branches with different
5772 * state or limits to sanitize, then this won't work.
5773 */
5774 if (aux->alu_state &&
5775 (aux->alu_state != alu_state ||
5776 aux->alu_limit != alu_limit))
1e1331d6 5777 return REASON_PATHS;
d3bd7413
DB
5778
5779 /* Corresponding fixup done in fixup_bpf_calls(). */
5780 aux->alu_state = alu_state;
5781 aux->alu_limit = alu_limit;
5782 return 0;
5783}
5784
5785static int sanitize_val_alu(struct bpf_verifier_env *env,
5786 struct bpf_insn *insn)
5787{
5788 struct bpf_insn_aux_data *aux = cur_aux(env);
5789
5790 if (can_skip_alu_sanitation(env, insn))
5791 return 0;
5792
5793 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
5794}
5795
46023efe
DB
5796static bool sanitize_needed(u8 opcode)
5797{
5798 return opcode == BPF_ADD || opcode == BPF_SUB;
5799}
5800
979d63d5
DB
5801static int sanitize_ptr_alu(struct bpf_verifier_env *env,
5802 struct bpf_insn *insn,
5803 const struct bpf_reg_state *ptr_reg,
bf97c5ca 5804 const struct bpf_reg_state *off_reg,
70bd6fa1
DB
5805 struct bpf_reg_state *dst_reg,
5806 struct bpf_insn_aux_data *tmp_aux,
5807 const bool commit_window)
979d63d5 5808{
70bd6fa1 5809 struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : tmp_aux;
979d63d5 5810 struct bpf_verifier_state *vstate = env->cur_state;
d4bad720 5811 bool off_is_imm = tnum_is_const(off_reg->var_off);
bf97c5ca 5812 bool off_is_neg = off_reg->smin_value < 0;
979d63d5
DB
5813 bool ptr_is_dst_reg = ptr_reg == dst_reg;
5814 u8 opcode = BPF_OP(insn->code);
5815 u32 alu_state, alu_limit;
5816 struct bpf_reg_state tmp;
5817 bool ret;
cd078f5b 5818 int err;
979d63d5 5819
d3bd7413 5820 if (can_skip_alu_sanitation(env, insn))
979d63d5
DB
5821 return 0;
5822
5823 /* We already marked aux for masking from non-speculative
5824 * paths, thus we got here in the first place. We only care
5825 * to explore bad access from here.
5826 */
5827 if (vstate->speculative)
5828 goto do_sim;
5829
75c82d37 5830 err = retrieve_ptr_limit(ptr_reg, off_reg, &alu_limit, opcode);
cd078f5b
PK
5831 if (err < 0)
5832 return err;
5833
70bd6fa1
DB
5834 if (commit_window) {
5835 /* In commit phase we narrow the masking window based on
5836 * the observed pointer move after the simulated operation.
5837 */
5838 alu_state = tmp_aux->alu_state;
5839 alu_limit = abs(tmp_aux->alu_limit - alu_limit);
5840 } else {
5841 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
d4bad720 5842 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
70bd6fa1
DB
5843 alu_state |= ptr_is_dst_reg ?
5844 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
5845 }
5846
cd078f5b
PK
5847 err = update_alu_sanitation_state(aux, alu_state, alu_limit);
5848 if (err < 0)
5849 return err;
979d63d5 5850do_sim:
70bd6fa1
DB
5851 /* If we're in commit phase, we're done here given we already
5852 * pushed the truncated dst_reg into the speculative verification
5853 * stack.
5854 */
5855 if (commit_window)
5856 return 0;
5857
979d63d5
DB
5858 /* Simulate and find potential out-of-bounds access under
5859 * speculative execution from truncation as a result of
5860 * masking when off was not within expected range. If off
5861 * sits in dst, then we temporarily need to move ptr there
5862 * to simulate dst (== 0) +/-= ptr. Needed, for example,
5863 * for cases where we use K-based arithmetic in one direction
5864 * and truncated reg-based in the other in order to explore
5865 * bad access.
5866 */
5867 if (!ptr_is_dst_reg) {
5868 tmp = *dst_reg;
5869 *dst_reg = *ptr_reg;
5870 }
5871 ret = push_stack(env, env->insn_idx + 1, env->insn_idx, true);
0803278b 5872 if (!ptr_is_dst_reg && ret)
979d63d5 5873 *dst_reg = tmp;
1e1331d6
DB
5874 return !ret ? REASON_STACK : 0;
5875}
5876
5877static int sanitize_err(struct bpf_verifier_env *env,
5878 const struct bpf_insn *insn, int reason,
5879 const struct bpf_reg_state *off_reg,
5880 const struct bpf_reg_state *dst_reg)
5881{
5882 static const char *err = "pointer arithmetic with it prohibited for !root";
5883 const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
5884 u32 dst = insn->dst_reg, src = insn->src_reg;
5885
5886 switch (reason) {
5887 case REASON_BOUNDS:
5888 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
5889 off_reg == dst_reg ? dst : src, err);
5890 break;
5891 case REASON_TYPE:
5892 verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
5893 off_reg == dst_reg ? src : dst, err);
5894 break;
5895 case REASON_PATHS:
5896 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
5897 dst, op, err);
5898 break;
5899 case REASON_LIMIT:
5900 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
5901 dst, op, err);
5902 break;
5903 case REASON_STACK:
5904 verbose(env, "R%d could not be pushed for speculative verification, %s\n",
5905 dst, err);
5906 break;
5907 default:
5908 verbose(env, "verifier internal error: unknown reason (%d)\n",
5909 reason);
5910 break;
5911 }
5912
5913 return -EACCES;
979d63d5
DB
5914}
5915
ca5b89bf
AM
5916/* check that stack access falls within stack limits and that 'reg' doesn't
5917 * have a variable offset.
5918 *
5919 * Variable offset is prohibited for unprivileged mode for simplicity since it
5920 * requires corresponding support in Spectre masking for stack ALU. See also
5921 * retrieve_ptr_limit().
5922 *
5923 *
5924 * 'off' includes 'reg->off'.
5925 */
5926static int check_stack_access_for_ptr_arithmetic(
5927 struct bpf_verifier_env *env,
5928 int regno,
5929 const struct bpf_reg_state *reg,
5930 int off)
5931{
5932 if (!tnum_is_const(reg->var_off)) {
5933 char tn_buf[48];
5934
5935 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5936 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
5937 regno, tn_buf, off);
5938 return -EACCES;
5939 }
5940
5941 if (off >= 0 || off < -MAX_BPF_STACK) {
5942 verbose(env, "R%d stack pointer arithmetic goes out of range, "
5943 "prohibited for !root; off=%d\n", regno, off);
5944 return -EACCES;
5945 }
5946
5947 return 0;
5948}
5949
3d6ab350
DB
5950static int sanitize_check_bounds(struct bpf_verifier_env *env,
5951 const struct bpf_insn *insn,
5952 const struct bpf_reg_state *dst_reg)
5953{
5954 u32 dst = insn->dst_reg;
5955
5956 /* For unprivileged we require that resulting offset must be in bounds
5957 * in order to be able to sanitize access later on.
5958 */
5959 if (env->bypass_spec_v1)
5960 return 0;
5961
5962 switch (dst_reg->type) {
5963 case PTR_TO_STACK:
5964 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
5965 dst_reg->off + dst_reg->var_off.value))
5966 return -EACCES;
5967 break;
5968 case PTR_TO_MAP_VALUE:
5969 if (check_map_access(env, dst, dst_reg->off, 1, false)) {
5970 verbose(env, "R%d pointer arithmetic of map value goes out of range, "
5971 "prohibited for !root\n", dst);
5972 return -EACCES;
5973 }
5974 break;
5975 default:
5976 break;
5977 }
5978
5979 return 0;
5980}
ca5b89bf 5981
f1174f77 5982/* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
f1174f77
EC
5983 * Caller should also handle BPF_MOV case separately.
5984 * If we return -EACCES, caller may want to try again treating pointer as a
5985 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks.
5986 */
5987static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
5988 struct bpf_insn *insn,
5989 const struct bpf_reg_state *ptr_reg,
5990 const struct bpf_reg_state *off_reg)
969bf05e 5991{
f4d7e40a
AS
5992 struct bpf_verifier_state *vstate = env->cur_state;
5993 struct bpf_func_state *state = vstate->frame[vstate->curframe];
5994 struct bpf_reg_state *regs = state->regs, *dst_reg;
f1174f77 5995 bool known = tnum_is_const(off_reg->var_off);
b03c9f9f
EC
5996 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
5997 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
5998 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
5999 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
70bd6fa1 6000 struct bpf_insn_aux_data tmp_aux = {};
969bf05e 6001 u8 opcode = BPF_OP(insn->code);
75c82d37 6002 u32 dst = insn->dst_reg;
979d63d5 6003 int ret;
969bf05e 6004
f1174f77 6005 dst_reg = &regs[dst];
969bf05e 6006
6f16101e
DB
6007 if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
6008 smin_val > smax_val || umin_val > umax_val) {
6009 /* Taint dst register if offset had invalid bounds derived from
6010 * e.g. dead branches.
6011 */
f54c7898 6012 __mark_reg_unknown(env, dst_reg);
6f16101e 6013 return 0;
f1174f77
EC
6014 }
6015
6016 if (BPF_CLASS(insn->code) != BPF_ALU64) {
6017 /* 32-bit ALU ops on pointers produce (meaningless) scalars */
6c693541
YS
6018 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
6019 __mark_reg_unknown(env, dst_reg);
6020 return 0;
6021 }
6022
82abbf8d
AS
6023 verbose(env,
6024 "R%d 32-bit pointer arithmetic prohibited\n",
6025 dst);
f1174f77 6026 return -EACCES;
969bf05e
AS
6027 }
6028
aad2eeaf
JS
6029 switch (ptr_reg->type) {
6030 case PTR_TO_MAP_VALUE_OR_NULL:
6031 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
6032 dst, reg_type_str[ptr_reg->type]);
f1174f77 6033 return -EACCES;
aad2eeaf 6034 case CONST_PTR_TO_MAP:
7c696732
YS
6035 /* smin_val represents the known value */
6036 if (known && smin_val == 0 && opcode == BPF_ADD)
6037 break;
8731745e 6038 fallthrough;
aad2eeaf 6039 case PTR_TO_PACKET_END:
c64b7983
JS
6040 case PTR_TO_SOCKET:
6041 case PTR_TO_SOCKET_OR_NULL:
46f8bc92
MKL
6042 case PTR_TO_SOCK_COMMON:
6043 case PTR_TO_SOCK_COMMON_OR_NULL:
655a51e5
MKL
6044 case PTR_TO_TCP_SOCK:
6045 case PTR_TO_TCP_SOCK_OR_NULL:
fada7fdc 6046 case PTR_TO_XDP_SOCK:
aad2eeaf
JS
6047 verbose(env, "R%d pointer arithmetic on %s prohibited\n",
6048 dst, reg_type_str[ptr_reg->type]);
f1174f77 6049 return -EACCES;
aad2eeaf
JS
6050 default:
6051 break;
f1174f77
EC
6052 }
6053
6054 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
6055 * The id may be overwritten later if we create a new variable offset.
969bf05e 6056 */
f1174f77
EC
6057 dst_reg->type = ptr_reg->type;
6058 dst_reg->id = ptr_reg->id;
969bf05e 6059
bb7f0f98
AS
6060 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
6061 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
6062 return -EINVAL;
6063
3f50f132
JF
6064 /* pointer types do not carry 32-bit bounds at the moment. */
6065 __mark_reg32_unbounded(dst_reg);
6066
70bd6fa1
DB
6067 if (sanitize_needed(opcode)) {
6068 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
6069 &tmp_aux, false);
1e1331d6
DB
6070 if (ret < 0)
6071 return sanitize_err(env, insn, ret, off_reg, dst_reg);
70bd6fa1 6072 }
1e1331d6 6073
70bd6fa1
DB
6074 switch (opcode) {
6075 case BPF_ADD:
f1174f77
EC
6076 /* We can take a fixed offset as long as it doesn't overflow
6077 * the s32 'off' field
969bf05e 6078 */
b03c9f9f
EC
6079 if (known && (ptr_reg->off + smin_val ==
6080 (s64)(s32)(ptr_reg->off + smin_val))) {
f1174f77 6081 /* pointer += K. Accumulate it into fixed offset */
b03c9f9f
EC
6082 dst_reg->smin_value = smin_ptr;
6083 dst_reg->smax_value = smax_ptr;
6084 dst_reg->umin_value = umin_ptr;
6085 dst_reg->umax_value = umax_ptr;
f1174f77 6086 dst_reg->var_off = ptr_reg->var_off;
b03c9f9f 6087 dst_reg->off = ptr_reg->off + smin_val;
0962590e 6088 dst_reg->raw = ptr_reg->raw;
f1174f77
EC
6089 break;
6090 }
f1174f77
EC
6091 /* A new variable offset is created. Note that off_reg->off
6092 * == 0, since it's a scalar.
6093 * dst_reg gets the pointer type and since some positive
6094 * integer value was added to the pointer, give it a new 'id'
6095 * if it's a PTR_TO_PACKET.
6096 * this creates a new 'base' pointer, off_reg (variable) gets
6097 * added into the variable offset, and we copy the fixed offset
6098 * from ptr_reg.
969bf05e 6099 */
b03c9f9f
EC
6100 if (signed_add_overflows(smin_ptr, smin_val) ||
6101 signed_add_overflows(smax_ptr, smax_val)) {
6102 dst_reg->smin_value = S64_MIN;
6103 dst_reg->smax_value = S64_MAX;
6104 } else {
6105 dst_reg->smin_value = smin_ptr + smin_val;
6106 dst_reg->smax_value = smax_ptr + smax_val;
6107 }
6108 if (umin_ptr + umin_val < umin_ptr ||
6109 umax_ptr + umax_val < umax_ptr) {
6110 dst_reg->umin_value = 0;
6111 dst_reg->umax_value = U64_MAX;
6112 } else {
6113 dst_reg->umin_value = umin_ptr + umin_val;
6114 dst_reg->umax_value = umax_ptr + umax_val;
6115 }
f1174f77
EC
6116 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
6117 dst_reg->off = ptr_reg->off;
0962590e 6118 dst_reg->raw = ptr_reg->raw;
de8f3a83 6119 if (reg_is_pkt_pointer(ptr_reg)) {
f1174f77
EC
6120 dst_reg->id = ++env->id_gen;
6121 /* something was added to pkt_ptr, set range to zero */
22dc4a0f 6122 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
f1174f77
EC
6123 }
6124 break;
6125 case BPF_SUB:
6126 if (dst_reg == off_reg) {
6127 /* scalar -= pointer. Creates an unknown scalar */
82abbf8d
AS
6128 verbose(env, "R%d tried to subtract pointer from scalar\n",
6129 dst);
f1174f77
EC
6130 return -EACCES;
6131 }
6132 /* We don't allow subtraction from FP, because (according to
6133 * test_verifier.c test "invalid fp arithmetic", JITs might not
6134 * be able to deal with it.
969bf05e 6135 */
f1174f77 6136 if (ptr_reg->type == PTR_TO_STACK) {
82abbf8d
AS
6137 verbose(env, "R%d subtraction from stack pointer prohibited\n",
6138 dst);
f1174f77
EC
6139 return -EACCES;
6140 }
b03c9f9f
EC
6141 if (known && (ptr_reg->off - smin_val ==
6142 (s64)(s32)(ptr_reg->off - smin_val))) {
f1174f77 6143 /* pointer -= K. Subtract it from fixed offset */
b03c9f9f
EC
6144 dst_reg->smin_value = smin_ptr;
6145 dst_reg->smax_value = smax_ptr;
6146 dst_reg->umin_value = umin_ptr;
6147 dst_reg->umax_value = umax_ptr;
f1174f77
EC
6148 dst_reg->var_off = ptr_reg->var_off;
6149 dst_reg->id = ptr_reg->id;
b03c9f9f 6150 dst_reg->off = ptr_reg->off - smin_val;
0962590e 6151 dst_reg->raw = ptr_reg->raw;
f1174f77
EC
6152 break;
6153 }
f1174f77
EC
6154 /* A new variable offset is created. If the subtrahend is known
6155 * nonnegative, then any reg->range we had before is still good.
969bf05e 6156 */
b03c9f9f
EC
6157 if (signed_sub_overflows(smin_ptr, smax_val) ||
6158 signed_sub_overflows(smax_ptr, smin_val)) {
6159 /* Overflow possible, we know nothing */
6160 dst_reg->smin_value = S64_MIN;
6161 dst_reg->smax_value = S64_MAX;
6162 } else {
6163 dst_reg->smin_value = smin_ptr - smax_val;
6164 dst_reg->smax_value = smax_ptr - smin_val;
6165 }
6166 if (umin_ptr < umax_val) {
6167 /* Overflow possible, we know nothing */
6168 dst_reg->umin_value = 0;
6169 dst_reg->umax_value = U64_MAX;
6170 } else {
6171 /* Cannot overflow (as long as bounds are consistent) */
6172 dst_reg->umin_value = umin_ptr - umax_val;
6173 dst_reg->umax_value = umax_ptr - umin_val;
6174 }
f1174f77
EC
6175 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
6176 dst_reg->off = ptr_reg->off;
0962590e 6177 dst_reg->raw = ptr_reg->raw;
de8f3a83 6178 if (reg_is_pkt_pointer(ptr_reg)) {
f1174f77
EC
6179 dst_reg->id = ++env->id_gen;
6180 /* something was added to pkt_ptr, set range to zero */
b03c9f9f 6181 if (smin_val < 0)
22dc4a0f 6182 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
43188702 6183 }
f1174f77
EC
6184 break;
6185 case BPF_AND:
6186 case BPF_OR:
6187 case BPF_XOR:
82abbf8d
AS
6188 /* bitwise ops on pointers are troublesome, prohibit. */
6189 verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
6190 dst, bpf_alu_string[opcode >> 4]);
f1174f77
EC
6191 return -EACCES;
6192 default:
6193 /* other operators (e.g. MUL,LSH) produce non-pointer results */
82abbf8d
AS
6194 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
6195 dst, bpf_alu_string[opcode >> 4]);
f1174f77 6196 return -EACCES;
43188702
JF
6197 }
6198
bb7f0f98
AS
6199 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
6200 return -EINVAL;
6201
b03c9f9f
EC
6202 __update_reg_bounds(dst_reg);
6203 __reg_deduce_bounds(dst_reg);
6204 __reg_bound_offset(dst_reg);
0d6303db 6205
3d6ab350
DB
6206 if (sanitize_check_bounds(env, insn, dst_reg) < 0)
6207 return -EACCES;
70bd6fa1
DB
6208 if (sanitize_needed(opcode)) {
6209 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
6210 &tmp_aux, true);
6211 if (ret < 0)
6212 return sanitize_err(env, insn, ret, off_reg, dst_reg);
6213 }
0d6303db 6214
43188702
JF
6215 return 0;
6216}
6217
3f50f132
JF
6218static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
6219 struct bpf_reg_state *src_reg)
6220{
6221 s32 smin_val = src_reg->s32_min_value;
6222 s32 smax_val = src_reg->s32_max_value;
6223 u32 umin_val = src_reg->u32_min_value;
6224 u32 umax_val = src_reg->u32_max_value;
6225
6226 if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
6227 signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
6228 dst_reg->s32_min_value = S32_MIN;
6229 dst_reg->s32_max_value = S32_MAX;
6230 } else {
6231 dst_reg->s32_min_value += smin_val;
6232 dst_reg->s32_max_value += smax_val;
6233 }
6234 if (dst_reg->u32_min_value + umin_val < umin_val ||
6235 dst_reg->u32_max_value + umax_val < umax_val) {
6236 dst_reg->u32_min_value = 0;
6237 dst_reg->u32_max_value = U32_MAX;
6238 } else {
6239 dst_reg->u32_min_value += umin_val;
6240 dst_reg->u32_max_value += umax_val;
6241 }
6242}
6243
07cd2631
JF
6244static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
6245 struct bpf_reg_state *src_reg)
6246{
6247 s64 smin_val = src_reg->smin_value;
6248 s64 smax_val = src_reg->smax_value;
6249 u64 umin_val = src_reg->umin_value;
6250 u64 umax_val = src_reg->umax_value;
6251
6252 if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
6253 signed_add_overflows(dst_reg->smax_value, smax_val)) {
6254 dst_reg->smin_value = S64_MIN;
6255 dst_reg->smax_value = S64_MAX;
6256 } else {
6257 dst_reg->smin_value += smin_val;
6258 dst_reg->smax_value += smax_val;
6259 }
6260 if (dst_reg->umin_value + umin_val < umin_val ||
6261 dst_reg->umax_value + umax_val < umax_val) {
6262 dst_reg->umin_value = 0;
6263 dst_reg->umax_value = U64_MAX;
6264 } else {
6265 dst_reg->umin_value += umin_val;
6266 dst_reg->umax_value += umax_val;
6267 }
3f50f132
JF
6268}
6269
6270static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
6271 struct bpf_reg_state *src_reg)
6272{
6273 s32 smin_val = src_reg->s32_min_value;
6274 s32 smax_val = src_reg->s32_max_value;
6275 u32 umin_val = src_reg->u32_min_value;
6276 u32 umax_val = src_reg->u32_max_value;
6277
6278 if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
6279 signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
6280 /* Overflow possible, we know nothing */
6281 dst_reg->s32_min_value = S32_MIN;
6282 dst_reg->s32_max_value = S32_MAX;
6283 } else {
6284 dst_reg->s32_min_value -= smax_val;
6285 dst_reg->s32_max_value -= smin_val;
6286 }
6287 if (dst_reg->u32_min_value < umax_val) {
6288 /* Overflow possible, we know nothing */
6289 dst_reg->u32_min_value = 0;
6290 dst_reg->u32_max_value = U32_MAX;
6291 } else {
6292 /* Cannot overflow (as long as bounds are consistent) */
6293 dst_reg->u32_min_value -= umax_val;
6294 dst_reg->u32_max_value -= umin_val;
6295 }
07cd2631
JF
6296}
6297
6298static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
6299 struct bpf_reg_state *src_reg)
6300{
6301 s64 smin_val = src_reg->smin_value;
6302 s64 smax_val = src_reg->smax_value;
6303 u64 umin_val = src_reg->umin_value;
6304 u64 umax_val = src_reg->umax_value;
6305
6306 if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
6307 signed_sub_overflows(dst_reg->smax_value, smin_val)) {
6308 /* Overflow possible, we know nothing */
6309 dst_reg->smin_value = S64_MIN;
6310 dst_reg->smax_value = S64_MAX;
6311 } else {
6312 dst_reg->smin_value -= smax_val;
6313 dst_reg->smax_value -= smin_val;
6314 }
6315 if (dst_reg->umin_value < umax_val) {
6316 /* Overflow possible, we know nothing */
6317 dst_reg->umin_value = 0;
6318 dst_reg->umax_value = U64_MAX;
6319 } else {
6320 /* Cannot overflow (as long as bounds are consistent) */
6321 dst_reg->umin_value -= umax_val;
6322 dst_reg->umax_value -= umin_val;
6323 }
3f50f132
JF
6324}
6325
6326static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
6327 struct bpf_reg_state *src_reg)
6328{
6329 s32 smin_val = src_reg->s32_min_value;
6330 u32 umin_val = src_reg->u32_min_value;
6331 u32 umax_val = src_reg->u32_max_value;
6332
6333 if (smin_val < 0 || dst_reg->s32_min_value < 0) {
6334 /* Ain't nobody got time to multiply that sign */
6335 __mark_reg32_unbounded(dst_reg);
6336 return;
6337 }
6338 /* Both values are positive, so we can work with unsigned and
6339 * copy the result to signed (unless it exceeds S32_MAX).
6340 */
6341 if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
6342 /* Potential overflow, we know nothing */
6343 __mark_reg32_unbounded(dst_reg);
6344 return;
6345 }
6346 dst_reg->u32_min_value *= umin_val;
6347 dst_reg->u32_max_value *= umax_val;
6348 if (dst_reg->u32_max_value > S32_MAX) {
6349 /* Overflow possible, we know nothing */
6350 dst_reg->s32_min_value = S32_MIN;
6351 dst_reg->s32_max_value = S32_MAX;
6352 } else {
6353 dst_reg->s32_min_value = dst_reg->u32_min_value;
6354 dst_reg->s32_max_value = dst_reg->u32_max_value;
6355 }
07cd2631
JF
6356}
6357
6358static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
6359 struct bpf_reg_state *src_reg)
6360{
6361 s64 smin_val = src_reg->smin_value;
6362 u64 umin_val = src_reg->umin_value;
6363 u64 umax_val = src_reg->umax_value;
6364
07cd2631
JF
6365 if (smin_val < 0 || dst_reg->smin_value < 0) {
6366 /* Ain't nobody got time to multiply that sign */
3f50f132 6367 __mark_reg64_unbounded(dst_reg);
07cd2631
JF
6368 return;
6369 }
6370 /* Both values are positive, so we can work with unsigned and
6371 * copy the result to signed (unless it exceeds S64_MAX).
6372 */
6373 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
6374 /* Potential overflow, we know nothing */
3f50f132 6375 __mark_reg64_unbounded(dst_reg);
07cd2631
JF
6376 return;
6377 }
6378 dst_reg->umin_value *= umin_val;
6379 dst_reg->umax_value *= umax_val;
6380 if (dst_reg->umax_value > S64_MAX) {
6381 /* Overflow possible, we know nothing */
6382 dst_reg->smin_value = S64_MIN;
6383 dst_reg->smax_value = S64_MAX;
6384 } else {
6385 dst_reg->smin_value = dst_reg->umin_value;
6386 dst_reg->smax_value = dst_reg->umax_value;
6387 }
6388}
6389
3f50f132
JF
6390static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
6391 struct bpf_reg_state *src_reg)
6392{
3bce7404
TLSC
6393 bool src_known = tnum_subreg_is_const(src_reg->var_off);
6394 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
3f50f132
JF
6395 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
6396 s32 smin_val = src_reg->s32_min_value;
6397 u32 umax_val = src_reg->u32_max_value;
6398
3bce7404
TLSC
6399 /* Assuming scalar64_min_max_and will be called so its safe
6400 * to skip updating register for known 32-bit case.
6401 */
6402 if (src_known && dst_known)
6403 return;
6404
3f50f132
JF
6405 /* We get our minimum from the var_off, since that's inherently
6406 * bitwise. Our maximum is the minimum of the operands' maxima.
6407 */
6408 dst_reg->u32_min_value = var32_off.value;
6409 dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
6410 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
6411 /* Lose signed bounds when ANDing negative numbers,
6412 * ain't nobody got time for that.
6413 */
6414 dst_reg->s32_min_value = S32_MIN;
6415 dst_reg->s32_max_value = S32_MAX;
6416 } else {
6417 /* ANDing two positives gives a positive, so safe to
6418 * cast result into s64.
6419 */
6420 dst_reg->s32_min_value = dst_reg->u32_min_value;
6421 dst_reg->s32_max_value = dst_reg->u32_max_value;
6422 }
6423
6424}
6425
07cd2631
JF
6426static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
6427 struct bpf_reg_state *src_reg)
6428{
3f50f132
JF
6429 bool src_known = tnum_is_const(src_reg->var_off);
6430 bool dst_known = tnum_is_const(dst_reg->var_off);
07cd2631
JF
6431 s64 smin_val = src_reg->smin_value;
6432 u64 umax_val = src_reg->umax_value;
6433
3f50f132 6434 if (src_known && dst_known) {
4fbb38a3 6435 __mark_reg_known(dst_reg, dst_reg->var_off.value);
3f50f132
JF
6436 return;
6437 }
6438
07cd2631
JF
6439 /* We get our minimum from the var_off, since that's inherently
6440 * bitwise. Our maximum is the minimum of the operands' maxima.
6441 */
07cd2631
JF
6442 dst_reg->umin_value = dst_reg->var_off.value;
6443 dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
6444 if (dst_reg->smin_value < 0 || smin_val < 0) {
6445 /* Lose signed bounds when ANDing negative numbers,
6446 * ain't nobody got time for that.
6447 */
6448 dst_reg->smin_value = S64_MIN;
6449 dst_reg->smax_value = S64_MAX;
6450 } else {
6451 /* ANDing two positives gives a positive, so safe to
6452 * cast result into s64.
6453 */
6454 dst_reg->smin_value = dst_reg->umin_value;
6455 dst_reg->smax_value = dst_reg->umax_value;
6456 }
6457 /* We may learn something more from the var_off */
6458 __update_reg_bounds(dst_reg);
6459}
6460
3f50f132
JF
6461static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
6462 struct bpf_reg_state *src_reg)
6463{
3bce7404
TLSC
6464 bool src_known = tnum_subreg_is_const(src_reg->var_off);
6465 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
3f50f132 6466 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
5b9fbeb7
DB
6467 s32 smin_val = src_reg->s32_min_value;
6468 u32 umin_val = src_reg->u32_min_value;
3f50f132 6469
3bce7404
TLSC
6470 /* Assuming scalar64_min_max_or will be called so it is safe
6471 * to skip updating register for known case.
6472 */
6473 if (src_known && dst_known)
6474 return;
6475
3f50f132
JF
6476 /* We get our maximum from the var_off, and our minimum is the
6477 * maximum of the operands' minima
6478 */
6479 dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
6480 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
6481 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
6482 /* Lose signed bounds when ORing negative numbers,
6483 * ain't nobody got time for that.
6484 */
6485 dst_reg->s32_min_value = S32_MIN;
6486 dst_reg->s32_max_value = S32_MAX;
6487 } else {
6488 /* ORing two positives gives a positive, so safe to
6489 * cast result into s64.
6490 */
5b9fbeb7
DB
6491 dst_reg->s32_min_value = dst_reg->u32_min_value;
6492 dst_reg->s32_max_value = dst_reg->u32_max_value;
3f50f132
JF
6493 }
6494}
6495
07cd2631
JF
6496static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
6497 struct bpf_reg_state *src_reg)
6498{
3f50f132
JF
6499 bool src_known = tnum_is_const(src_reg->var_off);
6500 bool dst_known = tnum_is_const(dst_reg->var_off);
07cd2631
JF
6501 s64 smin_val = src_reg->smin_value;
6502 u64 umin_val = src_reg->umin_value;
6503
3f50f132 6504 if (src_known && dst_known) {
4fbb38a3 6505 __mark_reg_known(dst_reg, dst_reg->var_off.value);
3f50f132
JF
6506 return;
6507 }
6508
07cd2631
JF
6509 /* We get our maximum from the var_off, and our minimum is the
6510 * maximum of the operands' minima
6511 */
07cd2631
JF
6512 dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
6513 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
6514 if (dst_reg->smin_value < 0 || smin_val < 0) {
6515 /* Lose signed bounds when ORing negative numbers,
6516 * ain't nobody got time for that.
6517 */
6518 dst_reg->smin_value = S64_MIN;
6519 dst_reg->smax_value = S64_MAX;
6520 } else {
6521 /* ORing two positives gives a positive, so safe to
6522 * cast result into s64.
6523 */
6524 dst_reg->smin_value = dst_reg->umin_value;
6525 dst_reg->smax_value = dst_reg->umax_value;
6526 }
6527 /* We may learn something more from the var_off */
6528 __update_reg_bounds(dst_reg);
6529}
6530
2921c90d
YS
6531static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
6532 struct bpf_reg_state *src_reg)
6533{
3bce7404
TLSC
6534 bool src_known = tnum_subreg_is_const(src_reg->var_off);
6535 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
2921c90d
YS
6536 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
6537 s32 smin_val = src_reg->s32_min_value;
6538
3bce7404
TLSC
6539 /* Assuming scalar64_min_max_xor will be called so it is safe
6540 * to skip updating register for known case.
6541 */
6542 if (src_known && dst_known)
6543 return;
6544
2921c90d
YS
6545 /* We get both minimum and maximum from the var32_off. */
6546 dst_reg->u32_min_value = var32_off.value;
6547 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
6548
6549 if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
6550 /* XORing two positive sign numbers gives a positive,
6551 * so safe to cast u32 result into s32.
6552 */
6553 dst_reg->s32_min_value = dst_reg->u32_min_value;
6554 dst_reg->s32_max_value = dst_reg->u32_max_value;
6555 } else {
6556 dst_reg->s32_min_value = S32_MIN;
6557 dst_reg->s32_max_value = S32_MAX;
6558 }
6559}
6560
6561static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
6562 struct bpf_reg_state *src_reg)
6563{
6564 bool src_known = tnum_is_const(src_reg->var_off);
6565 bool dst_known = tnum_is_const(dst_reg->var_off);
6566 s64 smin_val = src_reg->smin_value;
6567
6568 if (src_known && dst_known) {
6569 /* dst_reg->var_off.value has been updated earlier */
6570 __mark_reg_known(dst_reg, dst_reg->var_off.value);
6571 return;
6572 }
6573
6574 /* We get both minimum and maximum from the var_off. */
6575 dst_reg->umin_value = dst_reg->var_off.value;
6576 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
6577
6578 if (dst_reg->smin_value >= 0 && smin_val >= 0) {
6579 /* XORing two positive sign numbers gives a positive,
6580 * so safe to cast u64 result into s64.
6581 */
6582 dst_reg->smin_value = dst_reg->umin_value;
6583 dst_reg->smax_value = dst_reg->umax_value;
6584 } else {
6585 dst_reg->smin_value = S64_MIN;
6586 dst_reg->smax_value = S64_MAX;
6587 }
6588
6589 __update_reg_bounds(dst_reg);
6590}
6591
3f50f132
JF
6592static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
6593 u64 umin_val, u64 umax_val)
07cd2631 6594{
07cd2631
JF
6595 /* We lose all sign bit information (except what we can pick
6596 * up from var_off)
6597 */
3f50f132
JF
6598 dst_reg->s32_min_value = S32_MIN;
6599 dst_reg->s32_max_value = S32_MAX;
6600 /* If we might shift our top bit out, then we know nothing */
6601 if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
6602 dst_reg->u32_min_value = 0;
6603 dst_reg->u32_max_value = U32_MAX;
6604 } else {
6605 dst_reg->u32_min_value <<= umin_val;
6606 dst_reg->u32_max_value <<= umax_val;
6607 }
6608}
6609
6610static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
6611 struct bpf_reg_state *src_reg)
6612{
6613 u32 umax_val = src_reg->u32_max_value;
6614 u32 umin_val = src_reg->u32_min_value;
6615 /* u32 alu operation will zext upper bits */
6616 struct tnum subreg = tnum_subreg(dst_reg->var_off);
6617
6618 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
6619 dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
6620 /* Not required but being careful mark reg64 bounds as unknown so
6621 * that we are forced to pick them up from tnum and zext later and
6622 * if some path skips this step we are still safe.
6623 */
6624 __mark_reg64_unbounded(dst_reg);
6625 __update_reg32_bounds(dst_reg);
6626}
6627
6628static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
6629 u64 umin_val, u64 umax_val)
6630{
6631 /* Special case <<32 because it is a common compiler pattern to sign
6632 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
6633 * positive we know this shift will also be positive so we can track
6634 * bounds correctly. Otherwise we lose all sign bit information except
6635 * what we can pick up from var_off. Perhaps we can generalize this
6636 * later to shifts of any length.
6637 */
6638 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
6639 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
6640 else
6641 dst_reg->smax_value = S64_MAX;
6642
6643 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
6644 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
6645 else
6646 dst_reg->smin_value = S64_MIN;
6647
07cd2631
JF
6648 /* If we might shift our top bit out, then we know nothing */
6649 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
6650 dst_reg->umin_value = 0;
6651 dst_reg->umax_value = U64_MAX;
6652 } else {
6653 dst_reg->umin_value <<= umin_val;
6654 dst_reg->umax_value <<= umax_val;
6655 }
3f50f132
JF
6656}
6657
6658static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
6659 struct bpf_reg_state *src_reg)
6660{
6661 u64 umax_val = src_reg->umax_value;
6662 u64 umin_val = src_reg->umin_value;
6663
6664 /* scalar64 calc uses 32bit unshifted bounds so must be called first */
6665 __scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
6666 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
6667
07cd2631
JF
6668 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
6669 /* We may learn something more from the var_off */
6670 __update_reg_bounds(dst_reg);
6671}
6672
3f50f132
JF
6673static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
6674 struct bpf_reg_state *src_reg)
6675{
6676 struct tnum subreg = tnum_subreg(dst_reg->var_off);
6677 u32 umax_val = src_reg->u32_max_value;
6678 u32 umin_val = src_reg->u32_min_value;
6679
6680 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
6681 * be negative, then either:
6682 * 1) src_reg might be zero, so the sign bit of the result is
6683 * unknown, so we lose our signed bounds
6684 * 2) it's known negative, thus the unsigned bounds capture the
6685 * signed bounds
6686 * 3) the signed bounds cross zero, so they tell us nothing
6687 * about the result
6688 * If the value in dst_reg is known nonnegative, then again the
6689 * unsigned bounts capture the signed bounds.
6690 * Thus, in all cases it suffices to blow away our signed bounds
6691 * and rely on inferring new ones from the unsigned bounds and
6692 * var_off of the result.
6693 */
6694 dst_reg->s32_min_value = S32_MIN;
6695 dst_reg->s32_max_value = S32_MAX;
6696
6697 dst_reg->var_off = tnum_rshift(subreg, umin_val);
6698 dst_reg->u32_min_value >>= umax_val;
6699 dst_reg->u32_max_value >>= umin_val;
6700
6701 __mark_reg64_unbounded(dst_reg);
6702 __update_reg32_bounds(dst_reg);
6703}
6704
07cd2631
JF
6705static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
6706 struct bpf_reg_state *src_reg)
6707{
6708 u64 umax_val = src_reg->umax_value;
6709 u64 umin_val = src_reg->umin_value;
6710
6711 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
6712 * be negative, then either:
6713 * 1) src_reg might be zero, so the sign bit of the result is
6714 * unknown, so we lose our signed bounds
6715 * 2) it's known negative, thus the unsigned bounds capture the
6716 * signed bounds
6717 * 3) the signed bounds cross zero, so they tell us nothing
6718 * about the result
6719 * If the value in dst_reg is known nonnegative, then again the
6720 * unsigned bounts capture the signed bounds.
6721 * Thus, in all cases it suffices to blow away our signed bounds
6722 * and rely on inferring new ones from the unsigned bounds and
6723 * var_off of the result.
6724 */
6725 dst_reg->smin_value = S64_MIN;
6726 dst_reg->smax_value = S64_MAX;
6727 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
6728 dst_reg->umin_value >>= umax_val;
6729 dst_reg->umax_value >>= umin_val;
3f50f132
JF
6730
6731 /* Its not easy to operate on alu32 bounds here because it depends
6732 * on bits being shifted in. Take easy way out and mark unbounded
6733 * so we can recalculate later from tnum.
6734 */
6735 __mark_reg32_unbounded(dst_reg);
07cd2631
JF
6736 __update_reg_bounds(dst_reg);
6737}
6738
3f50f132
JF
6739static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
6740 struct bpf_reg_state *src_reg)
07cd2631 6741{
3f50f132 6742 u64 umin_val = src_reg->u32_min_value;
07cd2631
JF
6743
6744 /* Upon reaching here, src_known is true and
6745 * umax_val is equal to umin_val.
6746 */
3f50f132
JF
6747 dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
6748 dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
07cd2631 6749
3f50f132
JF
6750 dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
6751
6752 /* blow away the dst_reg umin_value/umax_value and rely on
6753 * dst_reg var_off to refine the result.
6754 */
6755 dst_reg->u32_min_value = 0;
6756 dst_reg->u32_max_value = U32_MAX;
6757
6758 __mark_reg64_unbounded(dst_reg);
6759 __update_reg32_bounds(dst_reg);
6760}
6761
6762static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
6763 struct bpf_reg_state *src_reg)
6764{
6765 u64 umin_val = src_reg->umin_value;
6766
6767 /* Upon reaching here, src_known is true and umax_val is equal
6768 * to umin_val.
6769 */
6770 dst_reg->smin_value >>= umin_val;
6771 dst_reg->smax_value >>= umin_val;
6772
6773 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
07cd2631
JF
6774
6775 /* blow away the dst_reg umin_value/umax_value and rely on
6776 * dst_reg var_off to refine the result.
6777 */
6778 dst_reg->umin_value = 0;
6779 dst_reg->umax_value = U64_MAX;
3f50f132
JF
6780
6781 /* Its not easy to operate on alu32 bounds here because it depends
6782 * on bits being shifted in from upper 32-bits. Take easy way out
6783 * and mark unbounded so we can recalculate later from tnum.
6784 */
6785 __mark_reg32_unbounded(dst_reg);
07cd2631
JF
6786 __update_reg_bounds(dst_reg);
6787}
6788
468f6eaf
JH
6789/* WARNING: This function does calculations on 64-bit values, but the actual
6790 * execution may occur on 32-bit values. Therefore, things like bitshifts
6791 * need extra checks in the 32-bit case.
6792 */
f1174f77
EC
6793static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
6794 struct bpf_insn *insn,
6795 struct bpf_reg_state *dst_reg,
6796 struct bpf_reg_state src_reg)
969bf05e 6797{
638f5b90 6798 struct bpf_reg_state *regs = cur_regs(env);
48461135 6799 u8 opcode = BPF_OP(insn->code);
b0b3fb67 6800 bool src_known;
b03c9f9f
EC
6801 s64 smin_val, smax_val;
6802 u64 umin_val, umax_val;
3f50f132
JF
6803 s32 s32_min_val, s32_max_val;
6804 u32 u32_min_val, u32_max_val;
468f6eaf 6805 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
3f50f132 6806 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
1e1331d6 6807 int ret;
b799207e 6808
b03c9f9f
EC
6809 smin_val = src_reg.smin_value;
6810 smax_val = src_reg.smax_value;
6811 umin_val = src_reg.umin_value;
6812 umax_val = src_reg.umax_value;
f23cc643 6813
3f50f132
JF
6814 s32_min_val = src_reg.s32_min_value;
6815 s32_max_val = src_reg.s32_max_value;
6816 u32_min_val = src_reg.u32_min_value;
6817 u32_max_val = src_reg.u32_max_value;
6818
6819 if (alu32) {
6820 src_known = tnum_subreg_is_const(src_reg.var_off);
3f50f132
JF
6821 if ((src_known &&
6822 (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
6823 s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
6824 /* Taint dst register if offset had invalid bounds
6825 * derived from e.g. dead branches.
6826 */
6827 __mark_reg_unknown(env, dst_reg);
6828 return 0;
6829 }
6830 } else {
6831 src_known = tnum_is_const(src_reg.var_off);
3f50f132
JF
6832 if ((src_known &&
6833 (smin_val != smax_val || umin_val != umax_val)) ||
6834 smin_val > smax_val || umin_val > umax_val) {
6835 /* Taint dst register if offset had invalid bounds
6836 * derived from e.g. dead branches.
6837 */
6838 __mark_reg_unknown(env, dst_reg);
6839 return 0;
6840 }
6f16101e
DB
6841 }
6842
bb7f0f98
AS
6843 if (!src_known &&
6844 opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
f54c7898 6845 __mark_reg_unknown(env, dst_reg);
bb7f0f98
AS
6846 return 0;
6847 }
6848
46023efe
DB
6849 if (sanitize_needed(opcode)) {
6850 ret = sanitize_val_alu(env, insn);
6851 if (ret < 0)
6852 return sanitize_err(env, insn, ret, NULL, NULL);
6853 }
6854
3f50f132
JF
6855 /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
6856 * There are two classes of instructions: The first class we track both
6857 * alu32 and alu64 sign/unsigned bounds independently this provides the
6858 * greatest amount of precision when alu operations are mixed with jmp32
6859 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
6860 * and BPF_OR. This is possible because these ops have fairly easy to
6861 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
6862 * See alu32 verifier tests for examples. The second class of
6863 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
6864 * with regards to tracking sign/unsigned bounds because the bits may
6865 * cross subreg boundaries in the alu64 case. When this happens we mark
6866 * the reg unbounded in the subreg bound space and use the resulting
6867 * tnum to calculate an approximation of the sign/unsigned bounds.
6868 */
48461135
JB
6869 switch (opcode) {
6870 case BPF_ADD:
3f50f132 6871 scalar32_min_max_add(dst_reg, &src_reg);
07cd2631 6872 scalar_min_max_add(dst_reg, &src_reg);
3f50f132 6873 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
48461135
JB
6874 break;
6875 case BPF_SUB:
3f50f132 6876 scalar32_min_max_sub(dst_reg, &src_reg);
07cd2631 6877 scalar_min_max_sub(dst_reg, &src_reg);
3f50f132 6878 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
48461135
JB
6879 break;
6880 case BPF_MUL:
3f50f132
JF
6881 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
6882 scalar32_min_max_mul(dst_reg, &src_reg);
07cd2631 6883 scalar_min_max_mul(dst_reg, &src_reg);
48461135
JB
6884 break;
6885 case BPF_AND:
3f50f132
JF
6886 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
6887 scalar32_min_max_and(dst_reg, &src_reg);
07cd2631 6888 scalar_min_max_and(dst_reg, &src_reg);
f1174f77
EC
6889 break;
6890 case BPF_OR:
3f50f132
JF
6891 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
6892 scalar32_min_max_or(dst_reg, &src_reg);
07cd2631 6893 scalar_min_max_or(dst_reg, &src_reg);
48461135 6894 break;
2921c90d
YS
6895 case BPF_XOR:
6896 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
6897 scalar32_min_max_xor(dst_reg, &src_reg);
6898 scalar_min_max_xor(dst_reg, &src_reg);
6899 break;
48461135 6900 case BPF_LSH:
468f6eaf
JH
6901 if (umax_val >= insn_bitness) {
6902 /* Shifts greater than 31 or 63 are undefined.
6903 * This includes shifts by a negative number.
b03c9f9f 6904 */
61bd5218 6905 mark_reg_unknown(env, regs, insn->dst_reg);
f1174f77
EC
6906 break;
6907 }
3f50f132
JF
6908 if (alu32)
6909 scalar32_min_max_lsh(dst_reg, &src_reg);
6910 else
6911 scalar_min_max_lsh(dst_reg, &src_reg);
48461135
JB
6912 break;
6913 case BPF_RSH:
468f6eaf
JH
6914 if (umax_val >= insn_bitness) {
6915 /* Shifts greater than 31 or 63 are undefined.
6916 * This includes shifts by a negative number.
b03c9f9f 6917 */
61bd5218 6918 mark_reg_unknown(env, regs, insn->dst_reg);
f1174f77
EC
6919 break;
6920 }
3f50f132
JF
6921 if (alu32)
6922 scalar32_min_max_rsh(dst_reg, &src_reg);
6923 else
6924 scalar_min_max_rsh(dst_reg, &src_reg);
48461135 6925 break;
9cbe1f5a
YS
6926 case BPF_ARSH:
6927 if (umax_val >= insn_bitness) {
6928 /* Shifts greater than 31 or 63 are undefined.
6929 * This includes shifts by a negative number.
6930 */
6931 mark_reg_unknown(env, regs, insn->dst_reg);
6932 break;
6933 }
3f50f132
JF
6934 if (alu32)
6935 scalar32_min_max_arsh(dst_reg, &src_reg);
6936 else
6937 scalar_min_max_arsh(dst_reg, &src_reg);
9cbe1f5a 6938 break;
48461135 6939 default:
61bd5218 6940 mark_reg_unknown(env, regs, insn->dst_reg);
48461135
JB
6941 break;
6942 }
6943
3f50f132
JF
6944 /* ALU32 ops are zero extended into 64bit register */
6945 if (alu32)
6946 zext_32_to_64(dst_reg);
468f6eaf 6947
294f2fc6 6948 __update_reg_bounds(dst_reg);
b03c9f9f
EC
6949 __reg_deduce_bounds(dst_reg);
6950 __reg_bound_offset(dst_reg);
f1174f77
EC
6951 return 0;
6952}
6953
6954/* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
6955 * and var_off.
6956 */
6957static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
6958 struct bpf_insn *insn)
6959{
f4d7e40a
AS
6960 struct bpf_verifier_state *vstate = env->cur_state;
6961 struct bpf_func_state *state = vstate->frame[vstate->curframe];
6962 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
f1174f77
EC
6963 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
6964 u8 opcode = BPF_OP(insn->code);
b5dc0163 6965 int err;
f1174f77
EC
6966
6967 dst_reg = &regs[insn->dst_reg];
f1174f77
EC
6968 src_reg = NULL;
6969 if (dst_reg->type != SCALAR_VALUE)
6970 ptr_reg = dst_reg;
75748837
AS
6971 else
6972 /* Make sure ID is cleared otherwise dst_reg min/max could be
6973 * incorrectly propagated into other registers by find_equal_scalars()
6974 */
6975 dst_reg->id = 0;
f1174f77
EC
6976 if (BPF_SRC(insn->code) == BPF_X) {
6977 src_reg = &regs[insn->src_reg];
f1174f77
EC
6978 if (src_reg->type != SCALAR_VALUE) {
6979 if (dst_reg->type != SCALAR_VALUE) {
6980 /* Combining two pointers by any ALU op yields
82abbf8d
AS
6981 * an arbitrary scalar. Disallow all math except
6982 * pointer subtraction
f1174f77 6983 */
dd066823 6984 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
82abbf8d
AS
6985 mark_reg_unknown(env, regs, insn->dst_reg);
6986 return 0;
f1174f77 6987 }
82abbf8d
AS
6988 verbose(env, "R%d pointer %s pointer prohibited\n",
6989 insn->dst_reg,
6990 bpf_alu_string[opcode >> 4]);
6991 return -EACCES;
f1174f77
EC
6992 } else {
6993 /* scalar += pointer
6994 * This is legal, but we have to reverse our
6995 * src/dest handling in computing the range
6996 */
b5dc0163
AS
6997 err = mark_chain_precision(env, insn->dst_reg);
6998 if (err)
6999 return err;
82abbf8d
AS
7000 return adjust_ptr_min_max_vals(env, insn,
7001 src_reg, dst_reg);
f1174f77
EC
7002 }
7003 } else if (ptr_reg) {
7004 /* pointer += scalar */
b5dc0163
AS
7005 err = mark_chain_precision(env, insn->src_reg);
7006 if (err)
7007 return err;
82abbf8d
AS
7008 return adjust_ptr_min_max_vals(env, insn,
7009 dst_reg, src_reg);
f1174f77
EC
7010 }
7011 } else {
7012 /* Pretend the src is a reg with a known value, since we only
7013 * need to be able to read from this state.
7014 */
7015 off_reg.type = SCALAR_VALUE;
b03c9f9f 7016 __mark_reg_known(&off_reg, insn->imm);
f1174f77 7017 src_reg = &off_reg;
82abbf8d
AS
7018 if (ptr_reg) /* pointer += K */
7019 return adjust_ptr_min_max_vals(env, insn,
7020 ptr_reg, src_reg);
f1174f77
EC
7021 }
7022
7023 /* Got here implies adding two SCALAR_VALUEs */
7024 if (WARN_ON_ONCE(ptr_reg)) {
f4d7e40a 7025 print_verifier_state(env, state);
61bd5218 7026 verbose(env, "verifier internal error: unexpected ptr_reg\n");
f1174f77
EC
7027 return -EINVAL;
7028 }
7029 if (WARN_ON(!src_reg)) {
f4d7e40a 7030 print_verifier_state(env, state);
61bd5218 7031 verbose(env, "verifier internal error: no src_reg\n");
f1174f77
EC
7032 return -EINVAL;
7033 }
7034 return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
48461135
JB
7035}
7036
17a52670 7037/* check validity of 32-bit and 64-bit arithmetic operations */
58e2af8b 7038static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
17a52670 7039{
638f5b90 7040 struct bpf_reg_state *regs = cur_regs(env);
17a52670
AS
7041 u8 opcode = BPF_OP(insn->code);
7042 int err;
7043
7044 if (opcode == BPF_END || opcode == BPF_NEG) {
7045 if (opcode == BPF_NEG) {
7046 if (BPF_SRC(insn->code) != 0 ||
7047 insn->src_reg != BPF_REG_0 ||
7048 insn->off != 0 || insn->imm != 0) {
61bd5218 7049 verbose(env, "BPF_NEG uses reserved fields\n");
17a52670
AS
7050 return -EINVAL;
7051 }
7052 } else {
7053 if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
e67b8a68
EC
7054 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
7055 BPF_CLASS(insn->code) == BPF_ALU64) {
61bd5218 7056 verbose(env, "BPF_END uses reserved fields\n");
17a52670
AS
7057 return -EINVAL;
7058 }
7059 }
7060
7061 /* check src operand */
dc503a8a 7062 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17a52670
AS
7063 if (err)
7064 return err;
7065
1be7f75d 7066 if (is_pointer_value(env, insn->dst_reg)) {
61bd5218 7067 verbose(env, "R%d pointer arithmetic prohibited\n",
1be7f75d
AS
7068 insn->dst_reg);
7069 return -EACCES;
7070 }
7071
17a52670 7072 /* check dest operand */
dc503a8a 7073 err = check_reg_arg(env, insn->dst_reg, DST_OP);
17a52670
AS
7074 if (err)
7075 return err;
7076
7077 } else if (opcode == BPF_MOV) {
7078
7079 if (BPF_SRC(insn->code) == BPF_X) {
7080 if (insn->imm != 0 || insn->off != 0) {
61bd5218 7081 verbose(env, "BPF_MOV uses reserved fields\n");
17a52670
AS
7082 return -EINVAL;
7083 }
7084
7085 /* check src operand */
dc503a8a 7086 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17a52670
AS
7087 if (err)
7088 return err;
7089 } else {
7090 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
61bd5218 7091 verbose(env, "BPF_MOV uses reserved fields\n");
17a52670
AS
7092 return -EINVAL;
7093 }
7094 }
7095
fbeb1603
AF
7096 /* check dest operand, mark as required later */
7097 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
17a52670
AS
7098 if (err)
7099 return err;
7100
7101 if (BPF_SRC(insn->code) == BPF_X) {
e434b8cd
JW
7102 struct bpf_reg_state *src_reg = regs + insn->src_reg;
7103 struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
7104
17a52670
AS
7105 if (BPF_CLASS(insn->code) == BPF_ALU64) {
7106 /* case: R1 = R2
7107 * copy register state to dest reg
7108 */
75748837
AS
7109 if (src_reg->type == SCALAR_VALUE && !src_reg->id)
7110 /* Assign src and dst registers the same ID
7111 * that will be used by find_equal_scalars()
7112 * to propagate min/max range.
7113 */
7114 src_reg->id = ++env->id_gen;
e434b8cd
JW
7115 *dst_reg = *src_reg;
7116 dst_reg->live |= REG_LIVE_WRITTEN;
5327ed3d 7117 dst_reg->subreg_def = DEF_NOT_SUBREG;
17a52670 7118 } else {
f1174f77 7119 /* R1 = (u32) R2 */
1be7f75d 7120 if (is_pointer_value(env, insn->src_reg)) {
61bd5218
JK
7121 verbose(env,
7122 "R%d partial copy of pointer\n",
1be7f75d
AS
7123 insn->src_reg);
7124 return -EACCES;
e434b8cd
JW
7125 } else if (src_reg->type == SCALAR_VALUE) {
7126 *dst_reg = *src_reg;
75748837
AS
7127 /* Make sure ID is cleared otherwise
7128 * dst_reg min/max could be incorrectly
7129 * propagated into src_reg by find_equal_scalars()
7130 */
7131 dst_reg->id = 0;
e434b8cd 7132 dst_reg->live |= REG_LIVE_WRITTEN;
5327ed3d 7133 dst_reg->subreg_def = env->insn_idx + 1;
e434b8cd
JW
7134 } else {
7135 mark_reg_unknown(env, regs,
7136 insn->dst_reg);
1be7f75d 7137 }
3f50f132 7138 zext_32_to_64(dst_reg);
17a52670
AS
7139 }
7140 } else {
7141 /* case: R = imm
7142 * remember the value we stored into this reg
7143 */
fbeb1603
AF
7144 /* clear any state __mark_reg_known doesn't set */
7145 mark_reg_unknown(env, regs, insn->dst_reg);
f1174f77 7146 regs[insn->dst_reg].type = SCALAR_VALUE;
95a762e2
JH
7147 if (BPF_CLASS(insn->code) == BPF_ALU64) {
7148 __mark_reg_known(regs + insn->dst_reg,
7149 insn->imm);
7150 } else {
7151 __mark_reg_known(regs + insn->dst_reg,
7152 (u32)insn->imm);
7153 }
17a52670
AS
7154 }
7155
7156 } else if (opcode > BPF_END) {
61bd5218 7157 verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
17a52670
AS
7158 return -EINVAL;
7159
7160 } else { /* all other ALU ops: and, sub, xor, add, ... */
7161
17a52670
AS
7162 if (BPF_SRC(insn->code) == BPF_X) {
7163 if (insn->imm != 0 || insn->off != 0) {
61bd5218 7164 verbose(env, "BPF_ALU uses reserved fields\n");
17a52670
AS
7165 return -EINVAL;
7166 }
7167 /* check src1 operand */
dc503a8a 7168 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17a52670
AS
7169 if (err)
7170 return err;
7171 } else {
7172 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
61bd5218 7173 verbose(env, "BPF_ALU uses reserved fields\n");
17a52670
AS
7174 return -EINVAL;
7175 }
7176 }
7177
7178 /* check src2 operand */
dc503a8a 7179 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17a52670
AS
7180 if (err)
7181 return err;
7182
7183 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
7184 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
61bd5218 7185 verbose(env, "div by zero\n");
17a52670
AS
7186 return -EINVAL;
7187 }
7188
229394e8
RV
7189 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
7190 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
7191 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
7192
7193 if (insn->imm < 0 || insn->imm >= size) {
61bd5218 7194 verbose(env, "invalid shift %d\n", insn->imm);
229394e8
RV
7195 return -EINVAL;
7196 }
7197 }
7198
1a0dc1ac 7199 /* check dest operand */
dc503a8a 7200 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
1a0dc1ac
AS
7201 if (err)
7202 return err;
7203
f1174f77 7204 return adjust_reg_min_max_vals(env, insn);
17a52670
AS
7205 }
7206
7207 return 0;
7208}
7209
c6a9efa1
PC
7210static void __find_good_pkt_pointers(struct bpf_func_state *state,
7211 struct bpf_reg_state *dst_reg,
6d94e741 7212 enum bpf_reg_type type, int new_range)
c6a9efa1
PC
7213{
7214 struct bpf_reg_state *reg;
7215 int i;
7216
7217 for (i = 0; i < MAX_BPF_REG; i++) {
7218 reg = &state->regs[i];
7219 if (reg->type == type && reg->id == dst_reg->id)
7220 /* keep the maximum range already checked */
7221 reg->range = max(reg->range, new_range);
7222 }
7223
7224 bpf_for_each_spilled_reg(i, state, reg) {
7225 if (!reg)
7226 continue;
7227 if (reg->type == type && reg->id == dst_reg->id)
7228 reg->range = max(reg->range, new_range);
7229 }
7230}
7231
f4d7e40a 7232static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
de8f3a83 7233 struct bpf_reg_state *dst_reg,
f8ddadc4 7234 enum bpf_reg_type type,
fb2a311a 7235 bool range_right_open)
969bf05e 7236{
6d94e741 7237 int new_range, i;
2d2be8ca 7238
fb2a311a
DB
7239 if (dst_reg->off < 0 ||
7240 (dst_reg->off == 0 && range_right_open))
f1174f77
EC
7241 /* This doesn't give us any range */
7242 return;
7243
b03c9f9f
EC
7244 if (dst_reg->umax_value > MAX_PACKET_OFF ||
7245 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
f1174f77
EC
7246 /* Risk of overflow. For instance, ptr + (1<<63) may be less
7247 * than pkt_end, but that's because it's also less than pkt.
7248 */
7249 return;
7250
fb2a311a
DB
7251 new_range = dst_reg->off;
7252 if (range_right_open)
7253 new_range--;
7254
7255 /* Examples for register markings:
2d2be8ca 7256 *
fb2a311a 7257 * pkt_data in dst register:
2d2be8ca
DB
7258 *
7259 * r2 = r3;
7260 * r2 += 8;
7261 * if (r2 > pkt_end) goto <handle exception>
7262 * <access okay>
7263 *
b4e432f1
DB
7264 * r2 = r3;
7265 * r2 += 8;
7266 * if (r2 < pkt_end) goto <access okay>
7267 * <handle exception>
7268 *
2d2be8ca
DB
7269 * Where:
7270 * r2 == dst_reg, pkt_end == src_reg
7271 * r2=pkt(id=n,off=8,r=0)
7272 * r3=pkt(id=n,off=0,r=0)
7273 *
fb2a311a 7274 * pkt_data in src register:
2d2be8ca
DB
7275 *
7276 * r2 = r3;
7277 * r2 += 8;
7278 * if (pkt_end >= r2) goto <access okay>
7279 * <handle exception>
7280 *
b4e432f1
DB
7281 * r2 = r3;
7282 * r2 += 8;
7283 * if (pkt_end <= r2) goto <handle exception>
7284 * <access okay>
7285 *
2d2be8ca
DB
7286 * Where:
7287 * pkt_end == dst_reg, r2 == src_reg
7288 * r2=pkt(id=n,off=8,r=0)
7289 * r3=pkt(id=n,off=0,r=0)
7290 *
7291 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
fb2a311a
DB
7292 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
7293 * and [r3, r3 + 8-1) respectively is safe to access depending on
7294 * the check.
969bf05e 7295 */
2d2be8ca 7296
f1174f77
EC
7297 /* If our ids match, then we must have the same max_value. And we
7298 * don't care about the other reg's fixed offset, since if it's too big
7299 * the range won't allow anything.
7300 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
7301 */
c6a9efa1
PC
7302 for (i = 0; i <= vstate->curframe; i++)
7303 __find_good_pkt_pointers(vstate->frame[i], dst_reg, type,
7304 new_range);
969bf05e
AS
7305}
7306
3f50f132 7307static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
4f7b3e82 7308{
3f50f132
JF
7309 struct tnum subreg = tnum_subreg(reg->var_off);
7310 s32 sval = (s32)val;
a72dafaf 7311
3f50f132
JF
7312 switch (opcode) {
7313 case BPF_JEQ:
7314 if (tnum_is_const(subreg))
7315 return !!tnum_equals_const(subreg, val);
7316 break;
7317 case BPF_JNE:
7318 if (tnum_is_const(subreg))
7319 return !tnum_equals_const(subreg, val);
7320 break;
7321 case BPF_JSET:
7322 if ((~subreg.mask & subreg.value) & val)
7323 return 1;
7324 if (!((subreg.mask | subreg.value) & val))
7325 return 0;
7326 break;
7327 case BPF_JGT:
7328 if (reg->u32_min_value > val)
7329 return 1;
7330 else if (reg->u32_max_value <= val)
7331 return 0;
7332 break;
7333 case BPF_JSGT:
7334 if (reg->s32_min_value > sval)
7335 return 1;
ee114dd6 7336 else if (reg->s32_max_value <= sval)
3f50f132
JF
7337 return 0;
7338 break;
7339 case BPF_JLT:
7340 if (reg->u32_max_value < val)
7341 return 1;
7342 else if (reg->u32_min_value >= val)
7343 return 0;
7344 break;
7345 case BPF_JSLT:
7346 if (reg->s32_max_value < sval)
7347 return 1;
7348 else if (reg->s32_min_value >= sval)
7349 return 0;
7350 break;
7351 case BPF_JGE:
7352 if (reg->u32_min_value >= val)
7353 return 1;
7354 else if (reg->u32_max_value < val)
7355 return 0;
7356 break;
7357 case BPF_JSGE:
7358 if (reg->s32_min_value >= sval)
7359 return 1;
7360 else if (reg->s32_max_value < sval)
7361 return 0;
7362 break;
7363 case BPF_JLE:
7364 if (reg->u32_max_value <= val)
7365 return 1;
7366 else if (reg->u32_min_value > val)
7367 return 0;
7368 break;
7369 case BPF_JSLE:
7370 if (reg->s32_max_value <= sval)
7371 return 1;
7372 else if (reg->s32_min_value > sval)
7373 return 0;
7374 break;
7375 }
4f7b3e82 7376
3f50f132
JF
7377 return -1;
7378}
092ed096 7379
3f50f132
JF
7380
7381static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
7382{
7383 s64 sval = (s64)val;
a72dafaf 7384
4f7b3e82
AS
7385 switch (opcode) {
7386 case BPF_JEQ:
7387 if (tnum_is_const(reg->var_off))
7388 return !!tnum_equals_const(reg->var_off, val);
7389 break;
7390 case BPF_JNE:
7391 if (tnum_is_const(reg->var_off))
7392 return !tnum_equals_const(reg->var_off, val);
7393 break;
960ea056
JK
7394 case BPF_JSET:
7395 if ((~reg->var_off.mask & reg->var_off.value) & val)
7396 return 1;
7397 if (!((reg->var_off.mask | reg->var_off.value) & val))
7398 return 0;
7399 break;
4f7b3e82
AS
7400 case BPF_JGT:
7401 if (reg->umin_value > val)
7402 return 1;
7403 else if (reg->umax_value <= val)
7404 return 0;
7405 break;
7406 case BPF_JSGT:
a72dafaf 7407 if (reg->smin_value > sval)
4f7b3e82 7408 return 1;
ee114dd6 7409 else if (reg->smax_value <= sval)
4f7b3e82
AS
7410 return 0;
7411 break;
7412 case BPF_JLT:
7413 if (reg->umax_value < val)
7414 return 1;
7415 else if (reg->umin_value >= val)
7416 return 0;
7417 break;
7418 case BPF_JSLT:
a72dafaf 7419 if (reg->smax_value < sval)
4f7b3e82 7420 return 1;
a72dafaf 7421 else if (reg->smin_value >= sval)
4f7b3e82
AS
7422 return 0;
7423 break;
7424 case BPF_JGE:
7425 if (reg->umin_value >= val)
7426 return 1;
7427 else if (reg->umax_value < val)
7428 return 0;
7429 break;
7430 case BPF_JSGE:
a72dafaf 7431 if (reg->smin_value >= sval)
4f7b3e82 7432 return 1;
a72dafaf 7433 else if (reg->smax_value < sval)
4f7b3e82
AS
7434 return 0;
7435 break;
7436 case BPF_JLE:
7437 if (reg->umax_value <= val)
7438 return 1;
7439 else if (reg->umin_value > val)
7440 return 0;
7441 break;
7442 case BPF_JSLE:
a72dafaf 7443 if (reg->smax_value <= sval)
4f7b3e82 7444 return 1;
a72dafaf 7445 else if (reg->smin_value > sval)
4f7b3e82
AS
7446 return 0;
7447 break;
7448 }
7449
7450 return -1;
7451}
7452
3f50f132
JF
7453/* compute branch direction of the expression "if (reg opcode val) goto target;"
7454 * and return:
7455 * 1 - branch will be taken and "goto target" will be executed
7456 * 0 - branch will not be taken and fall-through to next insn
7457 * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
7458 * range [0,10]
604dca5e 7459 */
3f50f132
JF
7460static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
7461 bool is_jmp32)
604dca5e 7462{
cac616db
JF
7463 if (__is_pointer_value(false, reg)) {
7464 if (!reg_type_not_null(reg->type))
7465 return -1;
7466
7467 /* If pointer is valid tests against zero will fail so we can
7468 * use this to direct branch taken.
7469 */
7470 if (val != 0)
7471 return -1;
7472
7473 switch (opcode) {
7474 case BPF_JEQ:
7475 return 0;
7476 case BPF_JNE:
7477 return 1;
7478 default:
7479 return -1;
7480 }
7481 }
604dca5e 7482
3f50f132
JF
7483 if (is_jmp32)
7484 return is_branch32_taken(reg, val, opcode);
7485 return is_branch64_taken(reg, val, opcode);
604dca5e
JH
7486}
7487
6d94e741
AS
7488static int flip_opcode(u32 opcode)
7489{
7490 /* How can we transform "a <op> b" into "b <op> a"? */
7491 static const u8 opcode_flip[16] = {
7492 /* these stay the same */
7493 [BPF_JEQ >> 4] = BPF_JEQ,
7494 [BPF_JNE >> 4] = BPF_JNE,
7495 [BPF_JSET >> 4] = BPF_JSET,
7496 /* these swap "lesser" and "greater" (L and G in the opcodes) */
7497 [BPF_JGE >> 4] = BPF_JLE,
7498 [BPF_JGT >> 4] = BPF_JLT,
7499 [BPF_JLE >> 4] = BPF_JGE,
7500 [BPF_JLT >> 4] = BPF_JGT,
7501 [BPF_JSGE >> 4] = BPF_JSLE,
7502 [BPF_JSGT >> 4] = BPF_JSLT,
7503 [BPF_JSLE >> 4] = BPF_JSGE,
7504 [BPF_JSLT >> 4] = BPF_JSGT
7505 };
7506 return opcode_flip[opcode >> 4];
7507}
7508
7509static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
7510 struct bpf_reg_state *src_reg,
7511 u8 opcode)
7512{
7513 struct bpf_reg_state *pkt;
7514
7515 if (src_reg->type == PTR_TO_PACKET_END) {
7516 pkt = dst_reg;
7517 } else if (dst_reg->type == PTR_TO_PACKET_END) {
7518 pkt = src_reg;
7519 opcode = flip_opcode(opcode);
7520 } else {
7521 return -1;
7522 }
7523
7524 if (pkt->range >= 0)
7525 return -1;
7526
7527 switch (opcode) {
7528 case BPF_JLE:
7529 /* pkt <= pkt_end */
7530 fallthrough;
7531 case BPF_JGT:
7532 /* pkt > pkt_end */
7533 if (pkt->range == BEYOND_PKT_END)
7534 /* pkt has at last one extra byte beyond pkt_end */
7535 return opcode == BPF_JGT;
7536 break;
7537 case BPF_JLT:
7538 /* pkt < pkt_end */
7539 fallthrough;
7540 case BPF_JGE:
7541 /* pkt >= pkt_end */
7542 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
7543 return opcode == BPF_JGE;
7544 break;
7545 }
7546 return -1;
7547}
7548
48461135
JB
7549/* Adjusts the register min/max values in the case that the dst_reg is the
7550 * variable register that we are working on, and src_reg is a constant or we're
7551 * simply doing a BPF_K check.
f1174f77 7552 * In JEQ/JNE cases we also adjust the var_off values.
48461135
JB
7553 */
7554static void reg_set_min_max(struct bpf_reg_state *true_reg,
3f50f132
JF
7555 struct bpf_reg_state *false_reg,
7556 u64 val, u32 val32,
092ed096 7557 u8 opcode, bool is_jmp32)
48461135 7558{
3f50f132
JF
7559 struct tnum false_32off = tnum_subreg(false_reg->var_off);
7560 struct tnum false_64off = false_reg->var_off;
7561 struct tnum true_32off = tnum_subreg(true_reg->var_off);
7562 struct tnum true_64off = true_reg->var_off;
7563 s64 sval = (s64)val;
7564 s32 sval32 = (s32)val32;
a72dafaf 7565
f1174f77
EC
7566 /* If the dst_reg is a pointer, we can't learn anything about its
7567 * variable offset from the compare (unless src_reg were a pointer into
7568 * the same object, but we don't bother with that.
7569 * Since false_reg and true_reg have the same type by construction, we
7570 * only need to check one of them for pointerness.
7571 */
7572 if (__is_pointer_value(false, false_reg))
7573 return;
4cabc5b1 7574
48461135
JB
7575 switch (opcode) {
7576 case BPF_JEQ:
48461135 7577 case BPF_JNE:
a72dafaf
JW
7578 {
7579 struct bpf_reg_state *reg =
7580 opcode == BPF_JEQ ? true_reg : false_reg;
7581
e688c3db
AS
7582 /* JEQ/JNE comparison doesn't change the register equivalence.
7583 * r1 = r2;
7584 * if (r1 == 42) goto label;
7585 * ...
7586 * label: // here both r1 and r2 are known to be 42.
7587 *
7588 * Hence when marking register as known preserve it's ID.
48461135 7589 */
3f50f132
JF
7590 if (is_jmp32)
7591 __mark_reg32_known(reg, val32);
7592 else
e688c3db 7593 ___mark_reg_known(reg, val);
48461135 7594 break;
a72dafaf 7595 }
960ea056 7596 case BPF_JSET:
3f50f132
JF
7597 if (is_jmp32) {
7598 false_32off = tnum_and(false_32off, tnum_const(~val32));
7599 if (is_power_of_2(val32))
7600 true_32off = tnum_or(true_32off,
7601 tnum_const(val32));
7602 } else {
7603 false_64off = tnum_and(false_64off, tnum_const(~val));
7604 if (is_power_of_2(val))
7605 true_64off = tnum_or(true_64off,
7606 tnum_const(val));
7607 }
960ea056 7608 break;
48461135 7609 case BPF_JGE:
a72dafaf
JW
7610 case BPF_JGT:
7611 {
3f50f132
JF
7612 if (is_jmp32) {
7613 u32 false_umax = opcode == BPF_JGT ? val32 : val32 - 1;
7614 u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
7615
7616 false_reg->u32_max_value = min(false_reg->u32_max_value,
7617 false_umax);
7618 true_reg->u32_min_value = max(true_reg->u32_min_value,
7619 true_umin);
7620 } else {
7621 u64 false_umax = opcode == BPF_JGT ? val : val - 1;
7622 u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
7623
7624 false_reg->umax_value = min(false_reg->umax_value, false_umax);
7625 true_reg->umin_value = max(true_reg->umin_value, true_umin);
7626 }
b03c9f9f 7627 break;
a72dafaf 7628 }
48461135 7629 case BPF_JSGE:
a72dafaf
JW
7630 case BPF_JSGT:
7631 {
3f50f132
JF
7632 if (is_jmp32) {
7633 s32 false_smax = opcode == BPF_JSGT ? sval32 : sval32 - 1;
7634 s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
a72dafaf 7635
3f50f132
JF
7636 false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
7637 true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
7638 } else {
7639 s64 false_smax = opcode == BPF_JSGT ? sval : sval - 1;
7640 s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
7641
7642 false_reg->smax_value = min(false_reg->smax_value, false_smax);
7643 true_reg->smin_value = max(true_reg->smin_value, true_smin);
7644 }
48461135 7645 break;
a72dafaf 7646 }
b4e432f1 7647 case BPF_JLE:
a72dafaf
JW
7648 case BPF_JLT:
7649 {
3f50f132
JF
7650 if (is_jmp32) {
7651 u32 false_umin = opcode == BPF_JLT ? val32 : val32 + 1;
7652 u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
7653
7654 false_reg->u32_min_value = max(false_reg->u32_min_value,
7655 false_umin);
7656 true_reg->u32_max_value = min(true_reg->u32_max_value,
7657 true_umax);
7658 } else {
7659 u64 false_umin = opcode == BPF_JLT ? val : val + 1;
7660 u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
7661
7662 false_reg->umin_value = max(false_reg->umin_value, false_umin);
7663 true_reg->umax_value = min(true_reg->umax_value, true_umax);
7664 }
b4e432f1 7665 break;
a72dafaf 7666 }
b4e432f1 7667 case BPF_JSLE:
a72dafaf
JW
7668 case BPF_JSLT:
7669 {
3f50f132
JF
7670 if (is_jmp32) {
7671 s32 false_smin = opcode == BPF_JSLT ? sval32 : sval32 + 1;
7672 s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
a72dafaf 7673
3f50f132
JF
7674 false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
7675 true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
7676 } else {
7677 s64 false_smin = opcode == BPF_JSLT ? sval : sval + 1;
7678 s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
7679
7680 false_reg->smin_value = max(false_reg->smin_value, false_smin);
7681 true_reg->smax_value = min(true_reg->smax_value, true_smax);
7682 }
b4e432f1 7683 break;
a72dafaf 7684 }
48461135 7685 default:
0fc31b10 7686 return;
48461135
JB
7687 }
7688
3f50f132
JF
7689 if (is_jmp32) {
7690 false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
7691 tnum_subreg(false_32off));
7692 true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
7693 tnum_subreg(true_32off));
7694 __reg_combine_32_into_64(false_reg);
7695 __reg_combine_32_into_64(true_reg);
7696 } else {
7697 false_reg->var_off = false_64off;
7698 true_reg->var_off = true_64off;
7699 __reg_combine_64_into_32(false_reg);
7700 __reg_combine_64_into_32(true_reg);
7701 }
48461135
JB
7702}
7703
f1174f77
EC
7704/* Same as above, but for the case that dst_reg holds a constant and src_reg is
7705 * the variable reg.
48461135
JB
7706 */
7707static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
3f50f132
JF
7708 struct bpf_reg_state *false_reg,
7709 u64 val, u32 val32,
092ed096 7710 u8 opcode, bool is_jmp32)
48461135 7711{
6d94e741 7712 opcode = flip_opcode(opcode);
0fc31b10
JH
7713 /* This uses zero as "not present in table"; luckily the zero opcode,
7714 * BPF_JA, can't get here.
b03c9f9f 7715 */
0fc31b10 7716 if (opcode)
3f50f132 7717 reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
f1174f77
EC
7718}
7719
7720/* Regs are known to be equal, so intersect their min/max/var_off */
7721static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
7722 struct bpf_reg_state *dst_reg)
7723{
b03c9f9f
EC
7724 src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
7725 dst_reg->umin_value);
7726 src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
7727 dst_reg->umax_value);
7728 src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
7729 dst_reg->smin_value);
7730 src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
7731 dst_reg->smax_value);
f1174f77
EC
7732 src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
7733 dst_reg->var_off);
b03c9f9f
EC
7734 /* We might have learned new bounds from the var_off. */
7735 __update_reg_bounds(src_reg);
7736 __update_reg_bounds(dst_reg);
7737 /* We might have learned something about the sign bit. */
7738 __reg_deduce_bounds(src_reg);
7739 __reg_deduce_bounds(dst_reg);
7740 /* We might have learned some bits from the bounds. */
7741 __reg_bound_offset(src_reg);
7742 __reg_bound_offset(dst_reg);
7743 /* Intersecting with the old var_off might have improved our bounds
7744 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
7745 * then new var_off is (0; 0x7f...fc) which improves our umax.
7746 */
7747 __update_reg_bounds(src_reg);
7748 __update_reg_bounds(dst_reg);
f1174f77
EC
7749}
7750
7751static void reg_combine_min_max(struct bpf_reg_state *true_src,
7752 struct bpf_reg_state *true_dst,
7753 struct bpf_reg_state *false_src,
7754 struct bpf_reg_state *false_dst,
7755 u8 opcode)
7756{
7757 switch (opcode) {
7758 case BPF_JEQ:
7759 __reg_combine_min_max(true_src, true_dst);
7760 break;
7761 case BPF_JNE:
7762 __reg_combine_min_max(false_src, false_dst);
b03c9f9f 7763 break;
4cabc5b1 7764 }
48461135
JB
7765}
7766
fd978bf7
JS
7767static void mark_ptr_or_null_reg(struct bpf_func_state *state,
7768 struct bpf_reg_state *reg, u32 id,
840b9615 7769 bool is_null)
57a09bf0 7770{
93c230e3
MKL
7771 if (reg_type_may_be_null(reg->type) && reg->id == id &&
7772 !WARN_ON_ONCE(!reg->id)) {
f1174f77
EC
7773 /* Old offset (both fixed and variable parts) should
7774 * have been known-zero, because we don't allow pointer
7775 * arithmetic on pointers that might be NULL.
7776 */
b03c9f9f
EC
7777 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value ||
7778 !tnum_equals_const(reg->var_off, 0) ||
f1174f77 7779 reg->off)) {
b03c9f9f
EC
7780 __mark_reg_known_zero(reg);
7781 reg->off = 0;
f1174f77
EC
7782 }
7783 if (is_null) {
7784 reg->type = SCALAR_VALUE;
840b9615 7785 } else if (reg->type == PTR_TO_MAP_VALUE_OR_NULL) {
64d85290
JS
7786 const struct bpf_map *map = reg->map_ptr;
7787
7788 if (map->inner_map_meta) {
840b9615 7789 reg->type = CONST_PTR_TO_MAP;
64d85290
JS
7790 reg->map_ptr = map->inner_map_meta;
7791 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
fada7fdc 7792 reg->type = PTR_TO_XDP_SOCK;
64d85290
JS
7793 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
7794 map->map_type == BPF_MAP_TYPE_SOCKHASH) {
7795 reg->type = PTR_TO_SOCKET;
840b9615
JS
7796 } else {
7797 reg->type = PTR_TO_MAP_VALUE;
7798 }
c64b7983
JS
7799 } else if (reg->type == PTR_TO_SOCKET_OR_NULL) {
7800 reg->type = PTR_TO_SOCKET;
46f8bc92
MKL
7801 } else if (reg->type == PTR_TO_SOCK_COMMON_OR_NULL) {
7802 reg->type = PTR_TO_SOCK_COMMON;
655a51e5
MKL
7803 } else if (reg->type == PTR_TO_TCP_SOCK_OR_NULL) {
7804 reg->type = PTR_TO_TCP_SOCK;
b121b341
YS
7805 } else if (reg->type == PTR_TO_BTF_ID_OR_NULL) {
7806 reg->type = PTR_TO_BTF_ID;
457f4436
AN
7807 } else if (reg->type == PTR_TO_MEM_OR_NULL) {
7808 reg->type = PTR_TO_MEM;
afbf21dc
YS
7809 } else if (reg->type == PTR_TO_RDONLY_BUF_OR_NULL) {
7810 reg->type = PTR_TO_RDONLY_BUF;
7811 } else if (reg->type == PTR_TO_RDWR_BUF_OR_NULL) {
7812 reg->type = PTR_TO_RDWR_BUF;
56f668df 7813 }
1b986589
MKL
7814 if (is_null) {
7815 /* We don't need id and ref_obj_id from this point
7816 * onwards anymore, thus we should better reset it,
7817 * so that state pruning has chances to take effect.
7818 */
7819 reg->id = 0;
7820 reg->ref_obj_id = 0;
7821 } else if (!reg_may_point_to_spin_lock(reg)) {
7822 /* For not-NULL ptr, reg->ref_obj_id will be reset
7823 * in release_reg_references().
7824 *
7825 * reg->id is still used by spin_lock ptr. Other
7826 * than spin_lock ptr type, reg->id can be reset.
fd978bf7
JS
7827 */
7828 reg->id = 0;
56f668df 7829 }
57a09bf0
TG
7830 }
7831}
7832
c6a9efa1
PC
7833static void __mark_ptr_or_null_regs(struct bpf_func_state *state, u32 id,
7834 bool is_null)
7835{
7836 struct bpf_reg_state *reg;
7837 int i;
7838
7839 for (i = 0; i < MAX_BPF_REG; i++)
7840 mark_ptr_or_null_reg(state, &state->regs[i], id, is_null);
7841
7842 bpf_for_each_spilled_reg(i, state, reg) {
7843 if (!reg)
7844 continue;
7845 mark_ptr_or_null_reg(state, reg, id, is_null);
7846 }
7847}
7848
57a09bf0
TG
7849/* The logic is similar to find_good_pkt_pointers(), both could eventually
7850 * be folded together at some point.
7851 */
840b9615
JS
7852static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
7853 bool is_null)
57a09bf0 7854{
f4d7e40a 7855 struct bpf_func_state *state = vstate->frame[vstate->curframe];
c6a9efa1 7856 struct bpf_reg_state *regs = state->regs;
1b986589 7857 u32 ref_obj_id = regs[regno].ref_obj_id;
a08dd0da 7858 u32 id = regs[regno].id;
c6a9efa1 7859 int i;
57a09bf0 7860
1b986589
MKL
7861 if (ref_obj_id && ref_obj_id == id && is_null)
7862 /* regs[regno] is in the " == NULL" branch.
7863 * No one could have freed the reference state before
7864 * doing the NULL check.
7865 */
7866 WARN_ON_ONCE(release_reference_state(state, id));
fd978bf7 7867
c6a9efa1
PC
7868 for (i = 0; i <= vstate->curframe; i++)
7869 __mark_ptr_or_null_regs(vstate->frame[i], id, is_null);
57a09bf0
TG
7870}
7871
5beca081
DB
7872static bool try_match_pkt_pointers(const struct bpf_insn *insn,
7873 struct bpf_reg_state *dst_reg,
7874 struct bpf_reg_state *src_reg,
7875 struct bpf_verifier_state *this_branch,
7876 struct bpf_verifier_state *other_branch)
7877{
7878 if (BPF_SRC(insn->code) != BPF_X)
7879 return false;
7880
092ed096
JW
7881 /* Pointers are always 64-bit. */
7882 if (BPF_CLASS(insn->code) == BPF_JMP32)
7883 return false;
7884
5beca081
DB
7885 switch (BPF_OP(insn->code)) {
7886 case BPF_JGT:
7887 if ((dst_reg->type == PTR_TO_PACKET &&
7888 src_reg->type == PTR_TO_PACKET_END) ||
7889 (dst_reg->type == PTR_TO_PACKET_META &&
7890 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
7891 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
7892 find_good_pkt_pointers(this_branch, dst_reg,
7893 dst_reg->type, false);
6d94e741 7894 mark_pkt_end(other_branch, insn->dst_reg, true);
5beca081
DB
7895 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
7896 src_reg->type == PTR_TO_PACKET) ||
7897 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
7898 src_reg->type == PTR_TO_PACKET_META)) {
7899 /* pkt_end > pkt_data', pkt_data > pkt_meta' */
7900 find_good_pkt_pointers(other_branch, src_reg,
7901 src_reg->type, true);
6d94e741 7902 mark_pkt_end(this_branch, insn->src_reg, false);
5beca081
DB
7903 } else {
7904 return false;
7905 }
7906 break;
7907 case BPF_JLT:
7908 if ((dst_reg->type == PTR_TO_PACKET &&
7909 src_reg->type == PTR_TO_PACKET_END) ||
7910 (dst_reg->type == PTR_TO_PACKET_META &&
7911 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
7912 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
7913 find_good_pkt_pointers(other_branch, dst_reg,
7914 dst_reg->type, true);
6d94e741 7915 mark_pkt_end(this_branch, insn->dst_reg, false);
5beca081
DB
7916 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
7917 src_reg->type == PTR_TO_PACKET) ||
7918 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
7919 src_reg->type == PTR_TO_PACKET_META)) {
7920 /* pkt_end < pkt_data', pkt_data > pkt_meta' */
7921 find_good_pkt_pointers(this_branch, src_reg,
7922 src_reg->type, false);
6d94e741 7923 mark_pkt_end(other_branch, insn->src_reg, true);
5beca081
DB
7924 } else {
7925 return false;
7926 }
7927 break;
7928 case BPF_JGE:
7929 if ((dst_reg->type == PTR_TO_PACKET &&
7930 src_reg->type == PTR_TO_PACKET_END) ||
7931 (dst_reg->type == PTR_TO_PACKET_META &&
7932 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
7933 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
7934 find_good_pkt_pointers(this_branch, dst_reg,
7935 dst_reg->type, true);
6d94e741 7936 mark_pkt_end(other_branch, insn->dst_reg, false);
5beca081
DB
7937 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
7938 src_reg->type == PTR_TO_PACKET) ||
7939 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
7940 src_reg->type == PTR_TO_PACKET_META)) {
7941 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
7942 find_good_pkt_pointers(other_branch, src_reg,
7943 src_reg->type, false);
6d94e741 7944 mark_pkt_end(this_branch, insn->src_reg, true);
5beca081
DB
7945 } else {
7946 return false;
7947 }
7948 break;
7949 case BPF_JLE:
7950 if ((dst_reg->type == PTR_TO_PACKET &&
7951 src_reg->type == PTR_TO_PACKET_END) ||
7952 (dst_reg->type == PTR_TO_PACKET_META &&
7953 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
7954 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
7955 find_good_pkt_pointers(other_branch, dst_reg,
7956 dst_reg->type, false);
6d94e741 7957 mark_pkt_end(this_branch, insn->dst_reg, true);
5beca081
DB
7958 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
7959 src_reg->type == PTR_TO_PACKET) ||
7960 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
7961 src_reg->type == PTR_TO_PACKET_META)) {
7962 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
7963 find_good_pkt_pointers(this_branch, src_reg,
7964 src_reg->type, true);
6d94e741 7965 mark_pkt_end(other_branch, insn->src_reg, false);
5beca081
DB
7966 } else {
7967 return false;
7968 }
7969 break;
7970 default:
7971 return false;
7972 }
7973
7974 return true;
7975}
7976
75748837
AS
7977static void find_equal_scalars(struct bpf_verifier_state *vstate,
7978 struct bpf_reg_state *known_reg)
7979{
7980 struct bpf_func_state *state;
7981 struct bpf_reg_state *reg;
7982 int i, j;
7983
7984 for (i = 0; i <= vstate->curframe; i++) {
7985 state = vstate->frame[i];
7986 for (j = 0; j < MAX_BPF_REG; j++) {
7987 reg = &state->regs[j];
7988 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
7989 *reg = *known_reg;
7990 }
7991
7992 bpf_for_each_spilled_reg(j, state, reg) {
7993 if (!reg)
7994 continue;
7995 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
7996 *reg = *known_reg;
7997 }
7998 }
7999}
8000
58e2af8b 8001static int check_cond_jmp_op(struct bpf_verifier_env *env,
17a52670
AS
8002 struct bpf_insn *insn, int *insn_idx)
8003{
f4d7e40a
AS
8004 struct bpf_verifier_state *this_branch = env->cur_state;
8005 struct bpf_verifier_state *other_branch;
8006 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
fb8d251e 8007 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
17a52670 8008 u8 opcode = BPF_OP(insn->code);
092ed096 8009 bool is_jmp32;
fb8d251e 8010 int pred = -1;
17a52670
AS
8011 int err;
8012
092ed096
JW
8013 /* Only conditional jumps are expected to reach here. */
8014 if (opcode == BPF_JA || opcode > BPF_JSLE) {
8015 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
17a52670
AS
8016 return -EINVAL;
8017 }
8018
8019 if (BPF_SRC(insn->code) == BPF_X) {
8020 if (insn->imm != 0) {
092ed096 8021 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
17a52670
AS
8022 return -EINVAL;
8023 }
8024
8025 /* check src1 operand */
dc503a8a 8026 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17a52670
AS
8027 if (err)
8028 return err;
1be7f75d
AS
8029
8030 if (is_pointer_value(env, insn->src_reg)) {
61bd5218 8031 verbose(env, "R%d pointer comparison prohibited\n",
1be7f75d
AS
8032 insn->src_reg);
8033 return -EACCES;
8034 }
fb8d251e 8035 src_reg = &regs[insn->src_reg];
17a52670
AS
8036 } else {
8037 if (insn->src_reg != BPF_REG_0) {
092ed096 8038 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
17a52670
AS
8039 return -EINVAL;
8040 }
8041 }
8042
8043 /* check src2 operand */
dc503a8a 8044 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17a52670
AS
8045 if (err)
8046 return err;
8047
1a0dc1ac 8048 dst_reg = &regs[insn->dst_reg];
092ed096 8049 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
1a0dc1ac 8050
3f50f132
JF
8051 if (BPF_SRC(insn->code) == BPF_K) {
8052 pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
8053 } else if (src_reg->type == SCALAR_VALUE &&
8054 is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
8055 pred = is_branch_taken(dst_reg,
8056 tnum_subreg(src_reg->var_off).value,
8057 opcode,
8058 is_jmp32);
8059 } else if (src_reg->type == SCALAR_VALUE &&
8060 !is_jmp32 && tnum_is_const(src_reg->var_off)) {
8061 pred = is_branch_taken(dst_reg,
8062 src_reg->var_off.value,
8063 opcode,
8064 is_jmp32);
6d94e741
AS
8065 } else if (reg_is_pkt_pointer_any(dst_reg) &&
8066 reg_is_pkt_pointer_any(src_reg) &&
8067 !is_jmp32) {
8068 pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
3f50f132
JF
8069 }
8070
b5dc0163 8071 if (pred >= 0) {
cac616db
JF
8072 /* If we get here with a dst_reg pointer type it is because
8073 * above is_branch_taken() special cased the 0 comparison.
8074 */
8075 if (!__is_pointer_value(false, dst_reg))
8076 err = mark_chain_precision(env, insn->dst_reg);
6d94e741
AS
8077 if (BPF_SRC(insn->code) == BPF_X && !err &&
8078 !__is_pointer_value(false, src_reg))
b5dc0163
AS
8079 err = mark_chain_precision(env, insn->src_reg);
8080 if (err)
8081 return err;
8082 }
fb8d251e
AS
8083 if (pred == 1) {
8084 /* only follow the goto, ignore fall-through */
8085 *insn_idx += insn->off;
8086 return 0;
8087 } else if (pred == 0) {
8088 /* only follow fall-through branch, since
8089 * that's where the program will go
8090 */
8091 return 0;
17a52670
AS
8092 }
8093
979d63d5
DB
8094 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
8095 false);
17a52670
AS
8096 if (!other_branch)
8097 return -EFAULT;
f4d7e40a 8098 other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
17a52670 8099
48461135
JB
8100 /* detect if we are comparing against a constant value so we can adjust
8101 * our min/max values for our dst register.
f1174f77
EC
8102 * this is only legit if both are scalars (or pointers to the same
8103 * object, I suppose, but we don't support that right now), because
8104 * otherwise the different base pointers mean the offsets aren't
8105 * comparable.
48461135
JB
8106 */
8107 if (BPF_SRC(insn->code) == BPF_X) {
092ed096 8108 struct bpf_reg_state *src_reg = &regs[insn->src_reg];
092ed096 8109
f1174f77 8110 if (dst_reg->type == SCALAR_VALUE &&
092ed096
JW
8111 src_reg->type == SCALAR_VALUE) {
8112 if (tnum_is_const(src_reg->var_off) ||
3f50f132
JF
8113 (is_jmp32 &&
8114 tnum_is_const(tnum_subreg(src_reg->var_off))))
f4d7e40a 8115 reg_set_min_max(&other_branch_regs[insn->dst_reg],
092ed096 8116 dst_reg,
3f50f132
JF
8117 src_reg->var_off.value,
8118 tnum_subreg(src_reg->var_off).value,
092ed096
JW
8119 opcode, is_jmp32);
8120 else if (tnum_is_const(dst_reg->var_off) ||
3f50f132
JF
8121 (is_jmp32 &&
8122 tnum_is_const(tnum_subreg(dst_reg->var_off))))
f4d7e40a 8123 reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
092ed096 8124 src_reg,
3f50f132
JF
8125 dst_reg->var_off.value,
8126 tnum_subreg(dst_reg->var_off).value,
092ed096
JW
8127 opcode, is_jmp32);
8128 else if (!is_jmp32 &&
8129 (opcode == BPF_JEQ || opcode == BPF_JNE))
f1174f77 8130 /* Comparing for equality, we can combine knowledge */
f4d7e40a
AS
8131 reg_combine_min_max(&other_branch_regs[insn->src_reg],
8132 &other_branch_regs[insn->dst_reg],
092ed096 8133 src_reg, dst_reg, opcode);
e688c3db
AS
8134 if (src_reg->id &&
8135 !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
75748837
AS
8136 find_equal_scalars(this_branch, src_reg);
8137 find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
8138 }
8139
f1174f77
EC
8140 }
8141 } else if (dst_reg->type == SCALAR_VALUE) {
f4d7e40a 8142 reg_set_min_max(&other_branch_regs[insn->dst_reg],
3f50f132
JF
8143 dst_reg, insn->imm, (u32)insn->imm,
8144 opcode, is_jmp32);
48461135
JB
8145 }
8146
e688c3db
AS
8147 if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
8148 !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
75748837
AS
8149 find_equal_scalars(this_branch, dst_reg);
8150 find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
8151 }
8152
092ed096
JW
8153 /* detect if R == 0 where R is returned from bpf_map_lookup_elem().
8154 * NOTE: these optimizations below are related with pointer comparison
8155 * which will never be JMP32.
8156 */
8157 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
1a0dc1ac 8158 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
840b9615
JS
8159 reg_type_may_be_null(dst_reg->type)) {
8160 /* Mark all identical registers in each branch as either
57a09bf0
TG
8161 * safe or unknown depending R == 0 or R != 0 conditional.
8162 */
840b9615
JS
8163 mark_ptr_or_null_regs(this_branch, insn->dst_reg,
8164 opcode == BPF_JNE);
8165 mark_ptr_or_null_regs(other_branch, insn->dst_reg,
8166 opcode == BPF_JEQ);
5beca081
DB
8167 } else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
8168 this_branch, other_branch) &&
8169 is_pointer_value(env, insn->dst_reg)) {
61bd5218
JK
8170 verbose(env, "R%d pointer comparison prohibited\n",
8171 insn->dst_reg);
1be7f75d 8172 return -EACCES;
17a52670 8173 }
06ee7115 8174 if (env->log.level & BPF_LOG_LEVEL)
f4d7e40a 8175 print_verifier_state(env, this_branch->frame[this_branch->curframe]);
17a52670
AS
8176 return 0;
8177}
8178
17a52670 8179/* verify BPF_LD_IMM64 instruction */
58e2af8b 8180static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
17a52670 8181{
d8eca5bb 8182 struct bpf_insn_aux_data *aux = cur_aux(env);
638f5b90 8183 struct bpf_reg_state *regs = cur_regs(env);
4976b718 8184 struct bpf_reg_state *dst_reg;
d8eca5bb 8185 struct bpf_map *map;
17a52670
AS
8186 int err;
8187
8188 if (BPF_SIZE(insn->code) != BPF_DW) {
61bd5218 8189 verbose(env, "invalid BPF_LD_IMM insn\n");
17a52670
AS
8190 return -EINVAL;
8191 }
8192 if (insn->off != 0) {
61bd5218 8193 verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
17a52670
AS
8194 return -EINVAL;
8195 }
8196
dc503a8a 8197 err = check_reg_arg(env, insn->dst_reg, DST_OP);
17a52670
AS
8198 if (err)
8199 return err;
8200
4976b718 8201 dst_reg = &regs[insn->dst_reg];
6b173873 8202 if (insn->src_reg == 0) {
6b173873
JK
8203 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
8204
4976b718 8205 dst_reg->type = SCALAR_VALUE;
b03c9f9f 8206 __mark_reg_known(&regs[insn->dst_reg], imm);
17a52670 8207 return 0;
6b173873 8208 }
17a52670 8209
4976b718
HL
8210 if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
8211 mark_reg_known_zero(env, regs, insn->dst_reg);
8212
8213 dst_reg->type = aux->btf_var.reg_type;
8214 switch (dst_reg->type) {
8215 case PTR_TO_MEM:
8216 dst_reg->mem_size = aux->btf_var.mem_size;
8217 break;
8218 case PTR_TO_BTF_ID:
eaa6bcb7 8219 case PTR_TO_PERCPU_BTF_ID:
22dc4a0f 8220 dst_reg->btf = aux->btf_var.btf;
4976b718
HL
8221 dst_reg->btf_id = aux->btf_var.btf_id;
8222 break;
8223 default:
8224 verbose(env, "bpf verifier is misconfigured\n");
8225 return -EFAULT;
8226 }
8227 return 0;
8228 }
8229
d8eca5bb
DB
8230 map = env->used_maps[aux->map_index];
8231 mark_reg_known_zero(env, regs, insn->dst_reg);
4976b718 8232 dst_reg->map_ptr = map;
d8eca5bb
DB
8233
8234 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE) {
4976b718
HL
8235 dst_reg->type = PTR_TO_MAP_VALUE;
8236 dst_reg->off = aux->map_off;
d8eca5bb 8237 if (map_value_has_spin_lock(map))
4976b718 8238 dst_reg->id = ++env->id_gen;
d8eca5bb 8239 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD) {
4976b718 8240 dst_reg->type = CONST_PTR_TO_MAP;
d8eca5bb
DB
8241 } else {
8242 verbose(env, "bpf verifier is misconfigured\n");
8243 return -EINVAL;
8244 }
17a52670 8245
17a52670
AS
8246 return 0;
8247}
8248
96be4325
DB
8249static bool may_access_skb(enum bpf_prog_type type)
8250{
8251 switch (type) {
8252 case BPF_PROG_TYPE_SOCKET_FILTER:
8253 case BPF_PROG_TYPE_SCHED_CLS:
94caee8c 8254 case BPF_PROG_TYPE_SCHED_ACT:
96be4325
DB
8255 return true;
8256 default:
8257 return false;
8258 }
8259}
8260
ddd872bc
AS
8261/* verify safety of LD_ABS|LD_IND instructions:
8262 * - they can only appear in the programs where ctx == skb
8263 * - since they are wrappers of function calls, they scratch R1-R5 registers,
8264 * preserve R6-R9, and store return value into R0
8265 *
8266 * Implicit input:
8267 * ctx == skb == R6 == CTX
8268 *
8269 * Explicit input:
8270 * SRC == any register
8271 * IMM == 32-bit immediate
8272 *
8273 * Output:
8274 * R0 - 8/16/32-bit skb data converted to cpu endianness
8275 */
58e2af8b 8276static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
ddd872bc 8277{
638f5b90 8278 struct bpf_reg_state *regs = cur_regs(env);
6d4f151a 8279 static const int ctx_reg = BPF_REG_6;
ddd872bc 8280 u8 mode = BPF_MODE(insn->code);
ddd872bc
AS
8281 int i, err;
8282
7e40781c 8283 if (!may_access_skb(resolve_prog_type(env->prog))) {
61bd5218 8284 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
ddd872bc
AS
8285 return -EINVAL;
8286 }
8287
e0cea7ce
DB
8288 if (!env->ops->gen_ld_abs) {
8289 verbose(env, "bpf verifier is misconfigured\n");
8290 return -EINVAL;
8291 }
8292
ddd872bc 8293 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
d82bccc6 8294 BPF_SIZE(insn->code) == BPF_DW ||
ddd872bc 8295 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
61bd5218 8296 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
ddd872bc
AS
8297 return -EINVAL;
8298 }
8299
8300 /* check whether implicit source operand (register R6) is readable */
6d4f151a 8301 err = check_reg_arg(env, ctx_reg, SRC_OP);
ddd872bc
AS
8302 if (err)
8303 return err;
8304
fd978bf7
JS
8305 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
8306 * gen_ld_abs() may terminate the program at runtime, leading to
8307 * reference leak.
8308 */
8309 err = check_reference_leak(env);
8310 if (err) {
8311 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
8312 return err;
8313 }
8314
d83525ca
AS
8315 if (env->cur_state->active_spin_lock) {
8316 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
8317 return -EINVAL;
8318 }
8319
6d4f151a 8320 if (regs[ctx_reg].type != PTR_TO_CTX) {
61bd5218
JK
8321 verbose(env,
8322 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
ddd872bc
AS
8323 return -EINVAL;
8324 }
8325
8326 if (mode == BPF_IND) {
8327 /* check explicit source operand */
dc503a8a 8328 err = check_reg_arg(env, insn->src_reg, SRC_OP);
ddd872bc
AS
8329 if (err)
8330 return err;
8331 }
8332
6d4f151a
DB
8333 err = check_ctx_reg(env, &regs[ctx_reg], ctx_reg);
8334 if (err < 0)
8335 return err;
8336
ddd872bc 8337 /* reset caller saved regs to unreadable */
dc503a8a 8338 for (i = 0; i < CALLER_SAVED_REGS; i++) {
61bd5218 8339 mark_reg_not_init(env, regs, caller_saved[i]);
dc503a8a
EC
8340 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
8341 }
ddd872bc
AS
8342
8343 /* mark destination R0 register as readable, since it contains
dc503a8a
EC
8344 * the value fetched from the packet.
8345 * Already marked as written above.
ddd872bc 8346 */
61bd5218 8347 mark_reg_unknown(env, regs, BPF_REG_0);
5327ed3d
JW
8348 /* ld_abs load up to 32-bit skb data. */
8349 regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
ddd872bc
AS
8350 return 0;
8351}
8352
390ee7e2
AS
8353static int check_return_code(struct bpf_verifier_env *env)
8354{
5cf1e914 8355 struct tnum enforce_attach_type_range = tnum_unknown;
27ae7997 8356 const struct bpf_prog *prog = env->prog;
390ee7e2
AS
8357 struct bpf_reg_state *reg;
8358 struct tnum range = tnum_range(0, 1);
7e40781c 8359 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
27ae7997 8360 int err;
f782e2c3 8361 const bool is_subprog = env->cur_state->frame[0]->subprogno;
27ae7997 8362
9e4e01df 8363 /* LSM and struct_ops func-ptr's return type could be "void" */
f782e2c3
DB
8364 if (!is_subprog &&
8365 (prog_type == BPF_PROG_TYPE_STRUCT_OPS ||
7e40781c 8366 prog_type == BPF_PROG_TYPE_LSM) &&
27ae7997
MKL
8367 !prog->aux->attach_func_proto->type)
8368 return 0;
8369
8370 /* eBPF calling convetion is such that R0 is used
8371 * to return the value from eBPF program.
8372 * Make sure that it's readable at this time
8373 * of bpf_exit, which means that program wrote
8374 * something into it earlier
8375 */
8376 err = check_reg_arg(env, BPF_REG_0, SRC_OP);
8377 if (err)
8378 return err;
8379
8380 if (is_pointer_value(env, BPF_REG_0)) {
8381 verbose(env, "R0 leaks addr as return value\n");
8382 return -EACCES;
8383 }
390ee7e2 8384
f782e2c3
DB
8385 reg = cur_regs(env) + BPF_REG_0;
8386 if (is_subprog) {
8387 if (reg->type != SCALAR_VALUE) {
8388 verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
8389 reg_type_str[reg->type]);
8390 return -EINVAL;
8391 }
8392 return 0;
8393 }
8394
7e40781c 8395 switch (prog_type) {
983695fa
DB
8396 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
8397 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
1b66d253
DB
8398 env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
8399 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
8400 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
8401 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
8402 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
983695fa 8403 range = tnum_range(1, 1);
ed4ed404 8404 break;
390ee7e2 8405 case BPF_PROG_TYPE_CGROUP_SKB:
5cf1e914 8406 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
8407 range = tnum_range(0, 3);
8408 enforce_attach_type_range = tnum_range(2, 3);
8409 }
ed4ed404 8410 break;
390ee7e2
AS
8411 case BPF_PROG_TYPE_CGROUP_SOCK:
8412 case BPF_PROG_TYPE_SOCK_OPS:
ebc614f6 8413 case BPF_PROG_TYPE_CGROUP_DEVICE:
7b146ceb 8414 case BPF_PROG_TYPE_CGROUP_SYSCTL:
0d01da6a 8415 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
390ee7e2 8416 break;
15ab09bd
AS
8417 case BPF_PROG_TYPE_RAW_TRACEPOINT:
8418 if (!env->prog->aux->attach_btf_id)
8419 return 0;
8420 range = tnum_const(0);
8421 break;
15d83c4d 8422 case BPF_PROG_TYPE_TRACING:
e92888c7
YS
8423 switch (env->prog->expected_attach_type) {
8424 case BPF_TRACE_FENTRY:
8425 case BPF_TRACE_FEXIT:
8426 range = tnum_const(0);
8427 break;
8428 case BPF_TRACE_RAW_TP:
8429 case BPF_MODIFY_RETURN:
15d83c4d 8430 return 0;
2ec0616e
DB
8431 case BPF_TRACE_ITER:
8432 break;
e92888c7
YS
8433 default:
8434 return -ENOTSUPP;
8435 }
15d83c4d 8436 break;
e9ddbb77
JS
8437 case BPF_PROG_TYPE_SK_LOOKUP:
8438 range = tnum_range(SK_DROP, SK_PASS);
8439 break;
e92888c7
YS
8440 case BPF_PROG_TYPE_EXT:
8441 /* freplace program can return anything as its return value
8442 * depends on the to-be-replaced kernel func or bpf program.
8443 */
390ee7e2
AS
8444 default:
8445 return 0;
8446 }
8447
390ee7e2 8448 if (reg->type != SCALAR_VALUE) {
61bd5218 8449 verbose(env, "At program exit the register R0 is not a known value (%s)\n",
390ee7e2
AS
8450 reg_type_str[reg->type]);
8451 return -EINVAL;
8452 }
8453
8454 if (!tnum_in(range, reg->var_off)) {
5cf1e914 8455 char tn_buf[48];
8456
61bd5218 8457 verbose(env, "At program exit the register R0 ");
390ee7e2 8458 if (!tnum_is_unknown(reg->var_off)) {
390ee7e2 8459 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
61bd5218 8460 verbose(env, "has value %s", tn_buf);
390ee7e2 8461 } else {
61bd5218 8462 verbose(env, "has unknown scalar value");
390ee7e2 8463 }
5cf1e914 8464 tnum_strn(tn_buf, sizeof(tn_buf), range);
983695fa 8465 verbose(env, " should have been in %s\n", tn_buf);
390ee7e2
AS
8466 return -EINVAL;
8467 }
5cf1e914 8468
8469 if (!tnum_is_unknown(enforce_attach_type_range) &&
8470 tnum_in(enforce_attach_type_range, reg->var_off))
8471 env->prog->enforce_expected_attach_type = 1;
390ee7e2
AS
8472 return 0;
8473}
8474
475fb78f
AS
8475/* non-recursive DFS pseudo code
8476 * 1 procedure DFS-iterative(G,v):
8477 * 2 label v as discovered
8478 * 3 let S be a stack
8479 * 4 S.push(v)
8480 * 5 while S is not empty
8481 * 6 t <- S.pop()
8482 * 7 if t is what we're looking for:
8483 * 8 return t
8484 * 9 for all edges e in G.adjacentEdges(t) do
8485 * 10 if edge e is already labelled
8486 * 11 continue with the next edge
8487 * 12 w <- G.adjacentVertex(t,e)
8488 * 13 if vertex w is not discovered and not explored
8489 * 14 label e as tree-edge
8490 * 15 label w as discovered
8491 * 16 S.push(w)
8492 * 17 continue at 5
8493 * 18 else if vertex w is discovered
8494 * 19 label e as back-edge
8495 * 20 else
8496 * 21 // vertex w is explored
8497 * 22 label e as forward- or cross-edge
8498 * 23 label t as explored
8499 * 24 S.pop()
8500 *
8501 * convention:
8502 * 0x10 - discovered
8503 * 0x11 - discovered and fall-through edge labelled
8504 * 0x12 - discovered and fall-through and branch edges labelled
8505 * 0x20 - explored
8506 */
8507
8508enum {
8509 DISCOVERED = 0x10,
8510 EXPLORED = 0x20,
8511 FALLTHROUGH = 1,
8512 BRANCH = 2,
8513};
8514
dc2a4ebc
AS
8515static u32 state_htab_size(struct bpf_verifier_env *env)
8516{
8517 return env->prog->len;
8518}
8519
5d839021
AS
8520static struct bpf_verifier_state_list **explored_state(
8521 struct bpf_verifier_env *env,
8522 int idx)
8523{
dc2a4ebc
AS
8524 struct bpf_verifier_state *cur = env->cur_state;
8525 struct bpf_func_state *state = cur->frame[cur->curframe];
8526
8527 return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
5d839021
AS
8528}
8529
8530static void init_explored_state(struct bpf_verifier_env *env, int idx)
8531{
a8f500af 8532 env->insn_aux_data[idx].prune_point = true;
5d839021 8533}
f1bca824 8534
59e2e27d
WAF
8535enum {
8536 DONE_EXPLORING = 0,
8537 KEEP_EXPLORING = 1,
8538};
8539
475fb78f
AS
8540/* t, w, e - match pseudo-code above:
8541 * t - index of current instruction
8542 * w - next instruction
8543 * e - edge
8544 */
2589726d
AS
8545static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
8546 bool loop_ok)
475fb78f 8547{
7df737e9
AS
8548 int *insn_stack = env->cfg.insn_stack;
8549 int *insn_state = env->cfg.insn_state;
8550
475fb78f 8551 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
59e2e27d 8552 return DONE_EXPLORING;
475fb78f
AS
8553
8554 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
59e2e27d 8555 return DONE_EXPLORING;
475fb78f
AS
8556
8557 if (w < 0 || w >= env->prog->len) {
d9762e84 8558 verbose_linfo(env, t, "%d: ", t);
61bd5218 8559 verbose(env, "jump out of range from insn %d to %d\n", t, w);
475fb78f
AS
8560 return -EINVAL;
8561 }
8562
f1bca824
AS
8563 if (e == BRANCH)
8564 /* mark branch target for state pruning */
5d839021 8565 init_explored_state(env, w);
f1bca824 8566
475fb78f
AS
8567 if (insn_state[w] == 0) {
8568 /* tree-edge */
8569 insn_state[t] = DISCOVERED | e;
8570 insn_state[w] = DISCOVERED;
7df737e9 8571 if (env->cfg.cur_stack >= env->prog->len)
475fb78f 8572 return -E2BIG;
7df737e9 8573 insn_stack[env->cfg.cur_stack++] = w;
59e2e27d 8574 return KEEP_EXPLORING;
475fb78f 8575 } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
2c78ee89 8576 if (loop_ok && env->bpf_capable)
59e2e27d 8577 return DONE_EXPLORING;
d9762e84
MKL
8578 verbose_linfo(env, t, "%d: ", t);
8579 verbose_linfo(env, w, "%d: ", w);
61bd5218 8580 verbose(env, "back-edge from insn %d to %d\n", t, w);
475fb78f
AS
8581 return -EINVAL;
8582 } else if (insn_state[w] == EXPLORED) {
8583 /* forward- or cross-edge */
8584 insn_state[t] = DISCOVERED | e;
8585 } else {
61bd5218 8586 verbose(env, "insn state internal bug\n");
475fb78f
AS
8587 return -EFAULT;
8588 }
59e2e27d
WAF
8589 return DONE_EXPLORING;
8590}
8591
8592/* Visits the instruction at index t and returns one of the following:
8593 * < 0 - an error occurred
8594 * DONE_EXPLORING - the instruction was fully explored
8595 * KEEP_EXPLORING - there is still work to be done before it is fully explored
8596 */
8597static int visit_insn(int t, int insn_cnt, struct bpf_verifier_env *env)
8598{
8599 struct bpf_insn *insns = env->prog->insnsi;
8600 int ret;
8601
8602 /* All non-branch instructions have a single fall-through edge. */
8603 if (BPF_CLASS(insns[t].code) != BPF_JMP &&
8604 BPF_CLASS(insns[t].code) != BPF_JMP32)
8605 return push_insn(t, t + 1, FALLTHROUGH, env, false);
8606
8607 switch (BPF_OP(insns[t].code)) {
8608 case BPF_EXIT:
8609 return DONE_EXPLORING;
8610
8611 case BPF_CALL:
8612 ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
8613 if (ret)
8614 return ret;
8615
8616 if (t + 1 < insn_cnt)
8617 init_explored_state(env, t + 1);
8618 if (insns[t].src_reg == BPF_PSEUDO_CALL) {
8619 init_explored_state(env, t);
8620 ret = push_insn(t, t + insns[t].imm + 1, BRANCH,
8621 env, false);
8622 }
8623 return ret;
8624
8625 case BPF_JA:
8626 if (BPF_SRC(insns[t].code) != BPF_K)
8627 return -EINVAL;
8628
8629 /* unconditional jump with single edge */
8630 ret = push_insn(t, t + insns[t].off + 1, FALLTHROUGH, env,
8631 true);
8632 if (ret)
8633 return ret;
8634
8635 /* unconditional jmp is not a good pruning point,
8636 * but it's marked, since backtracking needs
8637 * to record jmp history in is_state_visited().
8638 */
8639 init_explored_state(env, t + insns[t].off + 1);
8640 /* tell verifier to check for equivalent states
8641 * after every call and jump
8642 */
8643 if (t + 1 < insn_cnt)
8644 init_explored_state(env, t + 1);
8645
8646 return ret;
8647
8648 default:
8649 /* conditional jump with two edges */
8650 init_explored_state(env, t);
8651 ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
8652 if (ret)
8653 return ret;
8654
8655 return push_insn(t, t + insns[t].off + 1, BRANCH, env, true);
8656 }
475fb78f
AS
8657}
8658
8659/* non-recursive depth-first-search to detect loops in BPF program
8660 * loop == back-edge in directed graph
8661 */
58e2af8b 8662static int check_cfg(struct bpf_verifier_env *env)
475fb78f 8663{
475fb78f 8664 int insn_cnt = env->prog->len;
7df737e9 8665 int *insn_stack, *insn_state;
475fb78f 8666 int ret = 0;
59e2e27d 8667 int i;
475fb78f 8668
7df737e9 8669 insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
475fb78f
AS
8670 if (!insn_state)
8671 return -ENOMEM;
8672
7df737e9 8673 insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
475fb78f 8674 if (!insn_stack) {
71dde681 8675 kvfree(insn_state);
475fb78f
AS
8676 return -ENOMEM;
8677 }
8678
8679 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
8680 insn_stack[0] = 0; /* 0 is the first instruction */
7df737e9 8681 env->cfg.cur_stack = 1;
475fb78f 8682
59e2e27d
WAF
8683 while (env->cfg.cur_stack > 0) {
8684 int t = insn_stack[env->cfg.cur_stack - 1];
475fb78f 8685
59e2e27d
WAF
8686 ret = visit_insn(t, insn_cnt, env);
8687 switch (ret) {
8688 case DONE_EXPLORING:
8689 insn_state[t] = EXPLORED;
8690 env->cfg.cur_stack--;
8691 break;
8692 case KEEP_EXPLORING:
8693 break;
8694 default:
8695 if (ret > 0) {
8696 verbose(env, "visit_insn internal bug\n");
8697 ret = -EFAULT;
475fb78f 8698 }
475fb78f 8699 goto err_free;
59e2e27d 8700 }
475fb78f
AS
8701 }
8702
59e2e27d 8703 if (env->cfg.cur_stack < 0) {
61bd5218 8704 verbose(env, "pop stack internal bug\n");
475fb78f
AS
8705 ret = -EFAULT;
8706 goto err_free;
8707 }
475fb78f 8708
475fb78f
AS
8709 for (i = 0; i < insn_cnt; i++) {
8710 if (insn_state[i] != EXPLORED) {
61bd5218 8711 verbose(env, "unreachable insn %d\n", i);
475fb78f
AS
8712 ret = -EINVAL;
8713 goto err_free;
8714 }
8715 }
8716 ret = 0; /* cfg looks good */
8717
8718err_free:
71dde681
AS
8719 kvfree(insn_state);
8720 kvfree(insn_stack);
7df737e9 8721 env->cfg.insn_state = env->cfg.insn_stack = NULL;
475fb78f
AS
8722 return ret;
8723}
8724
09b28d76
AS
8725static int check_abnormal_return(struct bpf_verifier_env *env)
8726{
8727 int i;
8728
8729 for (i = 1; i < env->subprog_cnt; i++) {
8730 if (env->subprog_info[i].has_ld_abs) {
8731 verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
8732 return -EINVAL;
8733 }
8734 if (env->subprog_info[i].has_tail_call) {
8735 verbose(env, "tail_call is not allowed in subprogs without BTF\n");
8736 return -EINVAL;
8737 }
8738 }
8739 return 0;
8740}
8741
838e9690
YS
8742/* The minimum supported BTF func info size */
8743#define MIN_BPF_FUNCINFO_SIZE 8
8744#define MAX_FUNCINFO_REC_SIZE 252
8745
c454a46b
MKL
8746static int check_btf_func(struct bpf_verifier_env *env,
8747 const union bpf_attr *attr,
8748 union bpf_attr __user *uattr)
838e9690 8749{
09b28d76 8750 const struct btf_type *type, *func_proto, *ret_type;
d0b2818e 8751 u32 i, nfuncs, urec_size, min_size;
838e9690 8752 u32 krec_size = sizeof(struct bpf_func_info);
c454a46b 8753 struct bpf_func_info *krecord;
8c1b6e69 8754 struct bpf_func_info_aux *info_aux = NULL;
c454a46b
MKL
8755 struct bpf_prog *prog;
8756 const struct btf *btf;
838e9690 8757 void __user *urecord;
d0b2818e 8758 u32 prev_offset = 0;
09b28d76 8759 bool scalar_return;
e7ed83d6 8760 int ret = -ENOMEM;
838e9690
YS
8761
8762 nfuncs = attr->func_info_cnt;
09b28d76
AS
8763 if (!nfuncs) {
8764 if (check_abnormal_return(env))
8765 return -EINVAL;
838e9690 8766 return 0;
09b28d76 8767 }
838e9690
YS
8768
8769 if (nfuncs != env->subprog_cnt) {
8770 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
8771 return -EINVAL;
8772 }
8773
8774 urec_size = attr->func_info_rec_size;
8775 if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
8776 urec_size > MAX_FUNCINFO_REC_SIZE ||
8777 urec_size % sizeof(u32)) {
8778 verbose(env, "invalid func info rec size %u\n", urec_size);
8779 return -EINVAL;
8780 }
8781
c454a46b
MKL
8782 prog = env->prog;
8783 btf = prog->aux->btf;
838e9690
YS
8784
8785 urecord = u64_to_user_ptr(attr->func_info);
8786 min_size = min_t(u32, krec_size, urec_size);
8787
ba64e7d8 8788 krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
c454a46b
MKL
8789 if (!krecord)
8790 return -ENOMEM;
8c1b6e69
AS
8791 info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
8792 if (!info_aux)
8793 goto err_free;
ba64e7d8 8794
838e9690
YS
8795 for (i = 0; i < nfuncs; i++) {
8796 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
8797 if (ret) {
8798 if (ret == -E2BIG) {
8799 verbose(env, "nonzero tailing record in func info");
8800 /* set the size kernel expects so loader can zero
8801 * out the rest of the record.
8802 */
8803 if (put_user(min_size, &uattr->func_info_rec_size))
8804 ret = -EFAULT;
8805 }
c454a46b 8806 goto err_free;
838e9690
YS
8807 }
8808
ba64e7d8 8809 if (copy_from_user(&krecord[i], urecord, min_size)) {
838e9690 8810 ret = -EFAULT;
c454a46b 8811 goto err_free;
838e9690
YS
8812 }
8813
d30d42e0 8814 /* check insn_off */
09b28d76 8815 ret = -EINVAL;
838e9690 8816 if (i == 0) {
d30d42e0 8817 if (krecord[i].insn_off) {
838e9690 8818 verbose(env,
d30d42e0
MKL
8819 "nonzero insn_off %u for the first func info record",
8820 krecord[i].insn_off);
c454a46b 8821 goto err_free;
838e9690 8822 }
d30d42e0 8823 } else if (krecord[i].insn_off <= prev_offset) {
838e9690
YS
8824 verbose(env,
8825 "same or smaller insn offset (%u) than previous func info record (%u)",
d30d42e0 8826 krecord[i].insn_off, prev_offset);
c454a46b 8827 goto err_free;
838e9690
YS
8828 }
8829
d30d42e0 8830 if (env->subprog_info[i].start != krecord[i].insn_off) {
838e9690 8831 verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
c454a46b 8832 goto err_free;
838e9690
YS
8833 }
8834
8835 /* check type_id */
ba64e7d8 8836 type = btf_type_by_id(btf, krecord[i].type_id);
51c39bb1 8837 if (!type || !btf_type_is_func(type)) {
838e9690 8838 verbose(env, "invalid type id %d in func info",
ba64e7d8 8839 krecord[i].type_id);
c454a46b 8840 goto err_free;
838e9690 8841 }
51c39bb1 8842 info_aux[i].linkage = BTF_INFO_VLEN(type->info);
09b28d76
AS
8843
8844 func_proto = btf_type_by_id(btf, type->type);
8845 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
8846 /* btf_func_check() already verified it during BTF load */
8847 goto err_free;
8848 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
8849 scalar_return =
8850 btf_type_is_small_int(ret_type) || btf_type_is_enum(ret_type);
8851 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
8852 verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
8853 goto err_free;
8854 }
8855 if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
8856 verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
8857 goto err_free;
8858 }
8859
d30d42e0 8860 prev_offset = krecord[i].insn_off;
838e9690
YS
8861 urecord += urec_size;
8862 }
8863
ba64e7d8
YS
8864 prog->aux->func_info = krecord;
8865 prog->aux->func_info_cnt = nfuncs;
8c1b6e69 8866 prog->aux->func_info_aux = info_aux;
838e9690
YS
8867 return 0;
8868
c454a46b 8869err_free:
ba64e7d8 8870 kvfree(krecord);
8c1b6e69 8871 kfree(info_aux);
838e9690
YS
8872 return ret;
8873}
8874
ba64e7d8
YS
8875static void adjust_btf_func(struct bpf_verifier_env *env)
8876{
8c1b6e69 8877 struct bpf_prog_aux *aux = env->prog->aux;
ba64e7d8
YS
8878 int i;
8879
8c1b6e69 8880 if (!aux->func_info)
ba64e7d8
YS
8881 return;
8882
8883 for (i = 0; i < env->subprog_cnt; i++)
8c1b6e69 8884 aux->func_info[i].insn_off = env->subprog_info[i].start;
ba64e7d8
YS
8885}
8886
c454a46b
MKL
8887#define MIN_BPF_LINEINFO_SIZE (offsetof(struct bpf_line_info, line_col) + \
8888 sizeof(((struct bpf_line_info *)(0))->line_col))
8889#define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE
8890
8891static int check_btf_line(struct bpf_verifier_env *env,
8892 const union bpf_attr *attr,
8893 union bpf_attr __user *uattr)
8894{
8895 u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
8896 struct bpf_subprog_info *sub;
8897 struct bpf_line_info *linfo;
8898 struct bpf_prog *prog;
8899 const struct btf *btf;
8900 void __user *ulinfo;
8901 int err;
8902
8903 nr_linfo = attr->line_info_cnt;
8904 if (!nr_linfo)
8905 return 0;
8906
8907 rec_size = attr->line_info_rec_size;
8908 if (rec_size < MIN_BPF_LINEINFO_SIZE ||
8909 rec_size > MAX_LINEINFO_REC_SIZE ||
8910 rec_size & (sizeof(u32) - 1))
8911 return -EINVAL;
8912
8913 /* Need to zero it in case the userspace may
8914 * pass in a smaller bpf_line_info object.
8915 */
8916 linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
8917 GFP_KERNEL | __GFP_NOWARN);
8918 if (!linfo)
8919 return -ENOMEM;
8920
8921 prog = env->prog;
8922 btf = prog->aux->btf;
8923
8924 s = 0;
8925 sub = env->subprog_info;
8926 ulinfo = u64_to_user_ptr(attr->line_info);
8927 expected_size = sizeof(struct bpf_line_info);
8928 ncopy = min_t(u32, expected_size, rec_size);
8929 for (i = 0; i < nr_linfo; i++) {
8930 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
8931 if (err) {
8932 if (err == -E2BIG) {
8933 verbose(env, "nonzero tailing record in line_info");
8934 if (put_user(expected_size,
8935 &uattr->line_info_rec_size))
8936 err = -EFAULT;
8937 }
8938 goto err_free;
8939 }
8940
8941 if (copy_from_user(&linfo[i], ulinfo, ncopy)) {
8942 err = -EFAULT;
8943 goto err_free;
8944 }
8945
8946 /*
8947 * Check insn_off to ensure
8948 * 1) strictly increasing AND
8949 * 2) bounded by prog->len
8950 *
8951 * The linfo[0].insn_off == 0 check logically falls into
8952 * the later "missing bpf_line_info for func..." case
8953 * because the first linfo[0].insn_off must be the
8954 * first sub also and the first sub must have
8955 * subprog_info[0].start == 0.
8956 */
8957 if ((i && linfo[i].insn_off <= prev_offset) ||
8958 linfo[i].insn_off >= prog->len) {
8959 verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
8960 i, linfo[i].insn_off, prev_offset,
8961 prog->len);
8962 err = -EINVAL;
8963 goto err_free;
8964 }
8965
fdbaa0be
MKL
8966 if (!prog->insnsi[linfo[i].insn_off].code) {
8967 verbose(env,
8968 "Invalid insn code at line_info[%u].insn_off\n",
8969 i);
8970 err = -EINVAL;
8971 goto err_free;
8972 }
8973
23127b33
MKL
8974 if (!btf_name_by_offset(btf, linfo[i].line_off) ||
8975 !btf_name_by_offset(btf, linfo[i].file_name_off)) {
c454a46b
MKL
8976 verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
8977 err = -EINVAL;
8978 goto err_free;
8979 }
8980
8981 if (s != env->subprog_cnt) {
8982 if (linfo[i].insn_off == sub[s].start) {
8983 sub[s].linfo_idx = i;
8984 s++;
8985 } else if (sub[s].start < linfo[i].insn_off) {
8986 verbose(env, "missing bpf_line_info for func#%u\n", s);
8987 err = -EINVAL;
8988 goto err_free;
8989 }
8990 }
8991
8992 prev_offset = linfo[i].insn_off;
8993 ulinfo += rec_size;
8994 }
8995
8996 if (s != env->subprog_cnt) {
8997 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
8998 env->subprog_cnt - s, s);
8999 err = -EINVAL;
9000 goto err_free;
9001 }
9002
9003 prog->aux->linfo = linfo;
9004 prog->aux->nr_linfo = nr_linfo;
9005
9006 return 0;
9007
9008err_free:
9009 kvfree(linfo);
9010 return err;
9011}
9012
9013static int check_btf_info(struct bpf_verifier_env *env,
9014 const union bpf_attr *attr,
9015 union bpf_attr __user *uattr)
9016{
9017 struct btf *btf;
9018 int err;
9019
09b28d76
AS
9020 if (!attr->func_info_cnt && !attr->line_info_cnt) {
9021 if (check_abnormal_return(env))
9022 return -EINVAL;
c454a46b 9023 return 0;
09b28d76 9024 }
c454a46b
MKL
9025
9026 btf = btf_get_by_fd(attr->prog_btf_fd);
9027 if (IS_ERR(btf))
9028 return PTR_ERR(btf);
717d9476
AS
9029 if (btf_is_kernel(btf)) {
9030 btf_put(btf);
9031 return -EACCES;
9032 }
c454a46b
MKL
9033 env->prog->aux->btf = btf;
9034
9035 err = check_btf_func(env, attr, uattr);
9036 if (err)
9037 return err;
9038
9039 err = check_btf_line(env, attr, uattr);
9040 if (err)
9041 return err;
9042
9043 return 0;
ba64e7d8
YS
9044}
9045
f1174f77
EC
9046/* check %cur's range satisfies %old's */
9047static bool range_within(struct bpf_reg_state *old,
9048 struct bpf_reg_state *cur)
9049{
b03c9f9f
EC
9050 return old->umin_value <= cur->umin_value &&
9051 old->umax_value >= cur->umax_value &&
9052 old->smin_value <= cur->smin_value &&
fd675184
DB
9053 old->smax_value >= cur->smax_value &&
9054 old->u32_min_value <= cur->u32_min_value &&
9055 old->u32_max_value >= cur->u32_max_value &&
9056 old->s32_min_value <= cur->s32_min_value &&
9057 old->s32_max_value >= cur->s32_max_value;
f1174f77
EC
9058}
9059
9060/* Maximum number of register states that can exist at once */
9061#define ID_MAP_SIZE (MAX_BPF_REG + MAX_BPF_STACK / BPF_REG_SIZE)
9062struct idpair {
9063 u32 old;
9064 u32 cur;
9065};
9066
9067/* If in the old state two registers had the same id, then they need to have
9068 * the same id in the new state as well. But that id could be different from
9069 * the old state, so we need to track the mapping from old to new ids.
9070 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
9071 * regs with old id 5 must also have new id 9 for the new state to be safe. But
9072 * regs with a different old id could still have new id 9, we don't care about
9073 * that.
9074 * So we look through our idmap to see if this old id has been seen before. If
9075 * so, we require the new id to match; otherwise, we add the id pair to the map.
969bf05e 9076 */
f1174f77 9077static bool check_ids(u32 old_id, u32 cur_id, struct idpair *idmap)
969bf05e 9078{
f1174f77 9079 unsigned int i;
969bf05e 9080
f1174f77
EC
9081 for (i = 0; i < ID_MAP_SIZE; i++) {
9082 if (!idmap[i].old) {
9083 /* Reached an empty slot; haven't seen this id before */
9084 idmap[i].old = old_id;
9085 idmap[i].cur = cur_id;
9086 return true;
9087 }
9088 if (idmap[i].old == old_id)
9089 return idmap[i].cur == cur_id;
9090 }
9091 /* We ran out of idmap slots, which should be impossible */
9092 WARN_ON_ONCE(1);
9093 return false;
9094}
9095
9242b5f5
AS
9096static void clean_func_state(struct bpf_verifier_env *env,
9097 struct bpf_func_state *st)
9098{
9099 enum bpf_reg_liveness live;
9100 int i, j;
9101
9102 for (i = 0; i < BPF_REG_FP; i++) {
9103 live = st->regs[i].live;
9104 /* liveness must not touch this register anymore */
9105 st->regs[i].live |= REG_LIVE_DONE;
9106 if (!(live & REG_LIVE_READ))
9107 /* since the register is unused, clear its state
9108 * to make further comparison simpler
9109 */
f54c7898 9110 __mark_reg_not_init(env, &st->regs[i]);
9242b5f5
AS
9111 }
9112
9113 for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
9114 live = st->stack[i].spilled_ptr.live;
9115 /* liveness must not touch this stack slot anymore */
9116 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
9117 if (!(live & REG_LIVE_READ)) {
f54c7898 9118 __mark_reg_not_init(env, &st->stack[i].spilled_ptr);
9242b5f5
AS
9119 for (j = 0; j < BPF_REG_SIZE; j++)
9120 st->stack[i].slot_type[j] = STACK_INVALID;
9121 }
9122 }
9123}
9124
9125static void clean_verifier_state(struct bpf_verifier_env *env,
9126 struct bpf_verifier_state *st)
9127{
9128 int i;
9129
9130 if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
9131 /* all regs in this state in all frames were already marked */
9132 return;
9133
9134 for (i = 0; i <= st->curframe; i++)
9135 clean_func_state(env, st->frame[i]);
9136}
9137
9138/* the parentage chains form a tree.
9139 * the verifier states are added to state lists at given insn and
9140 * pushed into state stack for future exploration.
9141 * when the verifier reaches bpf_exit insn some of the verifer states
9142 * stored in the state lists have their final liveness state already,
9143 * but a lot of states will get revised from liveness point of view when
9144 * the verifier explores other branches.
9145 * Example:
9146 * 1: r0 = 1
9147 * 2: if r1 == 100 goto pc+1
9148 * 3: r0 = 2
9149 * 4: exit
9150 * when the verifier reaches exit insn the register r0 in the state list of
9151 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
9152 * of insn 2 and goes exploring further. At the insn 4 it will walk the
9153 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
9154 *
9155 * Since the verifier pushes the branch states as it sees them while exploring
9156 * the program the condition of walking the branch instruction for the second
9157 * time means that all states below this branch were already explored and
9158 * their final liveness markes are already propagated.
9159 * Hence when the verifier completes the search of state list in is_state_visited()
9160 * we can call this clean_live_states() function to mark all liveness states
9161 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
9162 * will not be used.
9163 * This function also clears the registers and stack for states that !READ
9164 * to simplify state merging.
9165 *
9166 * Important note here that walking the same branch instruction in the callee
9167 * doesn't meant that the states are DONE. The verifier has to compare
9168 * the callsites
9169 */
9170static void clean_live_states(struct bpf_verifier_env *env, int insn,
9171 struct bpf_verifier_state *cur)
9172{
9173 struct bpf_verifier_state_list *sl;
9174 int i;
9175
5d839021 9176 sl = *explored_state(env, insn);
a8f500af 9177 while (sl) {
2589726d
AS
9178 if (sl->state.branches)
9179 goto next;
dc2a4ebc
AS
9180 if (sl->state.insn_idx != insn ||
9181 sl->state.curframe != cur->curframe)
9242b5f5
AS
9182 goto next;
9183 for (i = 0; i <= cur->curframe; i++)
9184 if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
9185 goto next;
9186 clean_verifier_state(env, &sl->state);
9187next:
9188 sl = sl->next;
9189 }
9190}
9191
f1174f77 9192/* Returns true if (rold safe implies rcur safe) */
1b688a19
EC
9193static bool regsafe(struct bpf_reg_state *rold, struct bpf_reg_state *rcur,
9194 struct idpair *idmap)
f1174f77 9195{
f4d7e40a
AS
9196 bool equal;
9197
dc503a8a
EC
9198 if (!(rold->live & REG_LIVE_READ))
9199 /* explored state didn't use this */
9200 return true;
9201
679c782d 9202 equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, parent)) == 0;
f4d7e40a
AS
9203
9204 if (rold->type == PTR_TO_STACK)
9205 /* two stack pointers are equal only if they're pointing to
9206 * the same stack frame, since fp-8 in foo != fp-8 in bar
9207 */
9208 return equal && rold->frameno == rcur->frameno;
9209
9210 if (equal)
969bf05e
AS
9211 return true;
9212
f1174f77
EC
9213 if (rold->type == NOT_INIT)
9214 /* explored state can't have used this */
969bf05e 9215 return true;
f1174f77
EC
9216 if (rcur->type == NOT_INIT)
9217 return false;
9218 switch (rold->type) {
9219 case SCALAR_VALUE:
9220 if (rcur->type == SCALAR_VALUE) {
b5dc0163
AS
9221 if (!rold->precise && !rcur->precise)
9222 return true;
f1174f77
EC
9223 /* new val must satisfy old val knowledge */
9224 return range_within(rold, rcur) &&
9225 tnum_in(rold->var_off, rcur->var_off);
9226 } else {
179d1c56
JH
9227 /* We're trying to use a pointer in place of a scalar.
9228 * Even if the scalar was unbounded, this could lead to
9229 * pointer leaks because scalars are allowed to leak
9230 * while pointers are not. We could make this safe in
9231 * special cases if root is calling us, but it's
9232 * probably not worth the hassle.
f1174f77 9233 */
179d1c56 9234 return false;
f1174f77
EC
9235 }
9236 case PTR_TO_MAP_VALUE:
1b688a19
EC
9237 /* If the new min/max/var_off satisfy the old ones and
9238 * everything else matches, we are OK.
d83525ca
AS
9239 * 'id' is not compared, since it's only used for maps with
9240 * bpf_spin_lock inside map element and in such cases if
9241 * the rest of the prog is valid for one map element then
9242 * it's valid for all map elements regardless of the key
9243 * used in bpf_map_lookup()
1b688a19
EC
9244 */
9245 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
9246 range_within(rold, rcur) &&
9247 tnum_in(rold->var_off, rcur->var_off);
f1174f77
EC
9248 case PTR_TO_MAP_VALUE_OR_NULL:
9249 /* a PTR_TO_MAP_VALUE could be safe to use as a
9250 * PTR_TO_MAP_VALUE_OR_NULL into the same map.
9251 * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
9252 * checked, doing so could have affected others with the same
9253 * id, and we can't check for that because we lost the id when
9254 * we converted to a PTR_TO_MAP_VALUE.
9255 */
9256 if (rcur->type != PTR_TO_MAP_VALUE_OR_NULL)
9257 return false;
9258 if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
9259 return false;
9260 /* Check our ids match any regs they're supposed to */
9261 return check_ids(rold->id, rcur->id, idmap);
de8f3a83 9262 case PTR_TO_PACKET_META:
f1174f77 9263 case PTR_TO_PACKET:
de8f3a83 9264 if (rcur->type != rold->type)
f1174f77
EC
9265 return false;
9266 /* We must have at least as much range as the old ptr
9267 * did, so that any accesses which were safe before are
9268 * still safe. This is true even if old range < old off,
9269 * since someone could have accessed through (ptr - k), or
9270 * even done ptr -= k in a register, to get a safe access.
9271 */
9272 if (rold->range > rcur->range)
9273 return false;
9274 /* If the offsets don't match, we can't trust our alignment;
9275 * nor can we be sure that we won't fall out of range.
9276 */
9277 if (rold->off != rcur->off)
9278 return false;
9279 /* id relations must be preserved */
9280 if (rold->id && !check_ids(rold->id, rcur->id, idmap))
9281 return false;
9282 /* new val must satisfy old val knowledge */
9283 return range_within(rold, rcur) &&
9284 tnum_in(rold->var_off, rcur->var_off);
9285 case PTR_TO_CTX:
9286 case CONST_PTR_TO_MAP:
f1174f77 9287 case PTR_TO_PACKET_END:
d58e468b 9288 case PTR_TO_FLOW_KEYS:
c64b7983
JS
9289 case PTR_TO_SOCKET:
9290 case PTR_TO_SOCKET_OR_NULL:
46f8bc92
MKL
9291 case PTR_TO_SOCK_COMMON:
9292 case PTR_TO_SOCK_COMMON_OR_NULL:
655a51e5
MKL
9293 case PTR_TO_TCP_SOCK:
9294 case PTR_TO_TCP_SOCK_OR_NULL:
fada7fdc 9295 case PTR_TO_XDP_SOCK:
f1174f77
EC
9296 /* Only valid matches are exact, which memcmp() above
9297 * would have accepted
9298 */
9299 default:
9300 /* Don't know what's going on, just say it's not safe */
9301 return false;
9302 }
969bf05e 9303
f1174f77
EC
9304 /* Shouldn't get here; if we do, say it's not safe */
9305 WARN_ON_ONCE(1);
969bf05e
AS
9306 return false;
9307}
9308
f4d7e40a
AS
9309static bool stacksafe(struct bpf_func_state *old,
9310 struct bpf_func_state *cur,
638f5b90
AS
9311 struct idpair *idmap)
9312{
9313 int i, spi;
9314
638f5b90
AS
9315 /* walk slots of the explored stack and ignore any additional
9316 * slots in the current stack, since explored(safe) state
9317 * didn't use them
9318 */
9319 for (i = 0; i < old->allocated_stack; i++) {
9320 spi = i / BPF_REG_SIZE;
9321
b233920c
AS
9322 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
9323 i += BPF_REG_SIZE - 1;
cc2b14d5 9324 /* explored state didn't use this */
fd05e57b 9325 continue;
b233920c 9326 }
cc2b14d5 9327
638f5b90
AS
9328 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
9329 continue;
19e2dbb7
AS
9330
9331 /* explored stack has more populated slots than current stack
9332 * and these slots were used
9333 */
9334 if (i >= cur->allocated_stack)
9335 return false;
9336
cc2b14d5
AS
9337 /* if old state was safe with misc data in the stack
9338 * it will be safe with zero-initialized stack.
9339 * The opposite is not true
9340 */
9341 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
9342 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
9343 continue;
638f5b90
AS
9344 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
9345 cur->stack[spi].slot_type[i % BPF_REG_SIZE])
9346 /* Ex: old explored (safe) state has STACK_SPILL in
b8c1a309 9347 * this stack slot, but current has STACK_MISC ->
638f5b90
AS
9348 * this verifier states are not equivalent,
9349 * return false to continue verification of this path
9350 */
9351 return false;
9352 if (i % BPF_REG_SIZE)
9353 continue;
9354 if (old->stack[spi].slot_type[0] != STACK_SPILL)
9355 continue;
9356 if (!regsafe(&old->stack[spi].spilled_ptr,
9357 &cur->stack[spi].spilled_ptr,
9358 idmap))
9359 /* when explored and current stack slot are both storing
9360 * spilled registers, check that stored pointers types
9361 * are the same as well.
9362 * Ex: explored safe path could have stored
9363 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
9364 * but current path has stored:
9365 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
9366 * such verifier states are not equivalent.
9367 * return false to continue verification of this path
9368 */
9369 return false;
9370 }
9371 return true;
9372}
9373
fd978bf7
JS
9374static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur)
9375{
9376 if (old->acquired_refs != cur->acquired_refs)
9377 return false;
9378 return !memcmp(old->refs, cur->refs,
9379 sizeof(*old->refs) * old->acquired_refs);
9380}
9381
f1bca824
AS
9382/* compare two verifier states
9383 *
9384 * all states stored in state_list are known to be valid, since
9385 * verifier reached 'bpf_exit' instruction through them
9386 *
9387 * this function is called when verifier exploring different branches of
9388 * execution popped from the state stack. If it sees an old state that has
9389 * more strict register state and more strict stack state then this execution
9390 * branch doesn't need to be explored further, since verifier already
9391 * concluded that more strict state leads to valid finish.
9392 *
9393 * Therefore two states are equivalent if register state is more conservative
9394 * and explored stack state is more conservative than the current one.
9395 * Example:
9396 * explored current
9397 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
9398 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
9399 *
9400 * In other words if current stack state (one being explored) has more
9401 * valid slots than old one that already passed validation, it means
9402 * the verifier can stop exploring and conclude that current state is valid too
9403 *
9404 * Similarly with registers. If explored state has register type as invalid
9405 * whereas register type in current state is meaningful, it means that
9406 * the current state will reach 'bpf_exit' instruction safely
9407 */
f4d7e40a
AS
9408static bool func_states_equal(struct bpf_func_state *old,
9409 struct bpf_func_state *cur)
f1bca824 9410{
f1174f77
EC
9411 struct idpair *idmap;
9412 bool ret = false;
f1bca824
AS
9413 int i;
9414
f1174f77
EC
9415 idmap = kcalloc(ID_MAP_SIZE, sizeof(struct idpair), GFP_KERNEL);
9416 /* If we failed to allocate the idmap, just say it's not safe */
9417 if (!idmap)
1a0dc1ac 9418 return false;
f1174f77
EC
9419
9420 for (i = 0; i < MAX_BPF_REG; i++) {
1b688a19 9421 if (!regsafe(&old->regs[i], &cur->regs[i], idmap))
f1174f77 9422 goto out_free;
f1bca824
AS
9423 }
9424
638f5b90
AS
9425 if (!stacksafe(old, cur, idmap))
9426 goto out_free;
fd978bf7
JS
9427
9428 if (!refsafe(old, cur))
9429 goto out_free;
f1174f77
EC
9430 ret = true;
9431out_free:
9432 kfree(idmap);
9433 return ret;
f1bca824
AS
9434}
9435
f4d7e40a
AS
9436static bool states_equal(struct bpf_verifier_env *env,
9437 struct bpf_verifier_state *old,
9438 struct bpf_verifier_state *cur)
9439{
9440 int i;
9441
9442 if (old->curframe != cur->curframe)
9443 return false;
9444
979d63d5
DB
9445 /* Verification state from speculative execution simulation
9446 * must never prune a non-speculative execution one.
9447 */
9448 if (old->speculative && !cur->speculative)
9449 return false;
9450
d83525ca
AS
9451 if (old->active_spin_lock != cur->active_spin_lock)
9452 return false;
9453
f4d7e40a
AS
9454 /* for states to be equal callsites have to be the same
9455 * and all frame states need to be equivalent
9456 */
9457 for (i = 0; i <= old->curframe; i++) {
9458 if (old->frame[i]->callsite != cur->frame[i]->callsite)
9459 return false;
9460 if (!func_states_equal(old->frame[i], cur->frame[i]))
9461 return false;
9462 }
9463 return true;
9464}
9465
5327ed3d
JW
9466/* Return 0 if no propagation happened. Return negative error code if error
9467 * happened. Otherwise, return the propagated bit.
9468 */
55e7f3b5
JW
9469static int propagate_liveness_reg(struct bpf_verifier_env *env,
9470 struct bpf_reg_state *reg,
9471 struct bpf_reg_state *parent_reg)
9472{
5327ed3d
JW
9473 u8 parent_flag = parent_reg->live & REG_LIVE_READ;
9474 u8 flag = reg->live & REG_LIVE_READ;
55e7f3b5
JW
9475 int err;
9476
5327ed3d
JW
9477 /* When comes here, read flags of PARENT_REG or REG could be any of
9478 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
9479 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
9480 */
9481 if (parent_flag == REG_LIVE_READ64 ||
9482 /* Or if there is no read flag from REG. */
9483 !flag ||
9484 /* Or if the read flag from REG is the same as PARENT_REG. */
9485 parent_flag == flag)
55e7f3b5
JW
9486 return 0;
9487
5327ed3d 9488 err = mark_reg_read(env, reg, parent_reg, flag);
55e7f3b5
JW
9489 if (err)
9490 return err;
9491
5327ed3d 9492 return flag;
55e7f3b5
JW
9493}
9494
8e9cd9ce 9495/* A write screens off any subsequent reads; but write marks come from the
f4d7e40a
AS
9496 * straight-line code between a state and its parent. When we arrive at an
9497 * equivalent state (jump target or such) we didn't arrive by the straight-line
9498 * code, so read marks in the state must propagate to the parent regardless
9499 * of the state's write marks. That's what 'parent == state->parent' comparison
679c782d 9500 * in mark_reg_read() is for.
8e9cd9ce 9501 */
f4d7e40a
AS
9502static int propagate_liveness(struct bpf_verifier_env *env,
9503 const struct bpf_verifier_state *vstate,
9504 struct bpf_verifier_state *vparent)
dc503a8a 9505{
3f8cafa4 9506 struct bpf_reg_state *state_reg, *parent_reg;
f4d7e40a 9507 struct bpf_func_state *state, *parent;
3f8cafa4 9508 int i, frame, err = 0;
dc503a8a 9509
f4d7e40a
AS
9510 if (vparent->curframe != vstate->curframe) {
9511 WARN(1, "propagate_live: parent frame %d current frame %d\n",
9512 vparent->curframe, vstate->curframe);
9513 return -EFAULT;
9514 }
dc503a8a
EC
9515 /* Propagate read liveness of registers... */
9516 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
83d16312 9517 for (frame = 0; frame <= vstate->curframe; frame++) {
3f8cafa4
JW
9518 parent = vparent->frame[frame];
9519 state = vstate->frame[frame];
9520 parent_reg = parent->regs;
9521 state_reg = state->regs;
83d16312
JK
9522 /* We don't need to worry about FP liveness, it's read-only */
9523 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
55e7f3b5
JW
9524 err = propagate_liveness_reg(env, &state_reg[i],
9525 &parent_reg[i]);
5327ed3d 9526 if (err < 0)
3f8cafa4 9527 return err;
5327ed3d
JW
9528 if (err == REG_LIVE_READ64)
9529 mark_insn_zext(env, &parent_reg[i]);
dc503a8a 9530 }
f4d7e40a 9531
1b04aee7 9532 /* Propagate stack slots. */
f4d7e40a
AS
9533 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
9534 i < parent->allocated_stack / BPF_REG_SIZE; i++) {
3f8cafa4
JW
9535 parent_reg = &parent->stack[i].spilled_ptr;
9536 state_reg = &state->stack[i].spilled_ptr;
55e7f3b5
JW
9537 err = propagate_liveness_reg(env, state_reg,
9538 parent_reg);
5327ed3d 9539 if (err < 0)
3f8cafa4 9540 return err;
dc503a8a
EC
9541 }
9542 }
5327ed3d 9543 return 0;
dc503a8a
EC
9544}
9545
a3ce685d
AS
9546/* find precise scalars in the previous equivalent state and
9547 * propagate them into the current state
9548 */
9549static int propagate_precision(struct bpf_verifier_env *env,
9550 const struct bpf_verifier_state *old)
9551{
9552 struct bpf_reg_state *state_reg;
9553 struct bpf_func_state *state;
9554 int i, err = 0;
9555
9556 state = old->frame[old->curframe];
9557 state_reg = state->regs;
9558 for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
9559 if (state_reg->type != SCALAR_VALUE ||
9560 !state_reg->precise)
9561 continue;
9562 if (env->log.level & BPF_LOG_LEVEL2)
9563 verbose(env, "propagating r%d\n", i);
9564 err = mark_chain_precision(env, i);
9565 if (err < 0)
9566 return err;
9567 }
9568
9569 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
9570 if (state->stack[i].slot_type[0] != STACK_SPILL)
9571 continue;
9572 state_reg = &state->stack[i].spilled_ptr;
9573 if (state_reg->type != SCALAR_VALUE ||
9574 !state_reg->precise)
9575 continue;
9576 if (env->log.level & BPF_LOG_LEVEL2)
9577 verbose(env, "propagating fp%d\n",
9578 (-i - 1) * BPF_REG_SIZE);
9579 err = mark_chain_precision_stack(env, i);
9580 if (err < 0)
9581 return err;
9582 }
9583 return 0;
9584}
9585
2589726d
AS
9586static bool states_maybe_looping(struct bpf_verifier_state *old,
9587 struct bpf_verifier_state *cur)
9588{
9589 struct bpf_func_state *fold, *fcur;
9590 int i, fr = cur->curframe;
9591
9592 if (old->curframe != fr)
9593 return false;
9594
9595 fold = old->frame[fr];
9596 fcur = cur->frame[fr];
9597 for (i = 0; i < MAX_BPF_REG; i++)
9598 if (memcmp(&fold->regs[i], &fcur->regs[i],
9599 offsetof(struct bpf_reg_state, parent)))
9600 return false;
9601 return true;
9602}
9603
9604
58e2af8b 9605static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
f1bca824 9606{
58e2af8b 9607 struct bpf_verifier_state_list *new_sl;
9f4686c4 9608 struct bpf_verifier_state_list *sl, **pprev;
679c782d 9609 struct bpf_verifier_state *cur = env->cur_state, *new;
ceefbc96 9610 int i, j, err, states_cnt = 0;
10d274e8 9611 bool add_new_state = env->test_state_freq ? true : false;
f1bca824 9612
b5dc0163 9613 cur->last_insn_idx = env->prev_insn_idx;
a8f500af 9614 if (!env->insn_aux_data[insn_idx].prune_point)
f1bca824
AS
9615 /* this 'insn_idx' instruction wasn't marked, so we will not
9616 * be doing state search here
9617 */
9618 return 0;
9619
2589726d
AS
9620 /* bpf progs typically have pruning point every 4 instructions
9621 * http://vger.kernel.org/bpfconf2019.html#session-1
9622 * Do not add new state for future pruning if the verifier hasn't seen
9623 * at least 2 jumps and at least 8 instructions.
9624 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
9625 * In tests that amounts to up to 50% reduction into total verifier
9626 * memory consumption and 20% verifier time speedup.
9627 */
9628 if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
9629 env->insn_processed - env->prev_insn_processed >= 8)
9630 add_new_state = true;
9631
a8f500af
AS
9632 pprev = explored_state(env, insn_idx);
9633 sl = *pprev;
9634
9242b5f5
AS
9635 clean_live_states(env, insn_idx, cur);
9636
a8f500af 9637 while (sl) {
dc2a4ebc
AS
9638 states_cnt++;
9639 if (sl->state.insn_idx != insn_idx)
9640 goto next;
2589726d
AS
9641 if (sl->state.branches) {
9642 if (states_maybe_looping(&sl->state, cur) &&
9643 states_equal(env, &sl->state, cur)) {
9644 verbose_linfo(env, insn_idx, "; ");
9645 verbose(env, "infinite loop detected at insn %d\n", insn_idx);
9646 return -EINVAL;
9647 }
9648 /* if the verifier is processing a loop, avoid adding new state
9649 * too often, since different loop iterations have distinct
9650 * states and may not help future pruning.
9651 * This threshold shouldn't be too low to make sure that
9652 * a loop with large bound will be rejected quickly.
9653 * The most abusive loop will be:
9654 * r1 += 1
9655 * if r1 < 1000000 goto pc-2
9656 * 1M insn_procssed limit / 100 == 10k peak states.
9657 * This threshold shouldn't be too high either, since states
9658 * at the end of the loop are likely to be useful in pruning.
9659 */
9660 if (env->jmps_processed - env->prev_jmps_processed < 20 &&
9661 env->insn_processed - env->prev_insn_processed < 100)
9662 add_new_state = false;
9663 goto miss;
9664 }
638f5b90 9665 if (states_equal(env, &sl->state, cur)) {
9f4686c4 9666 sl->hit_cnt++;
f1bca824 9667 /* reached equivalent register/stack state,
dc503a8a
EC
9668 * prune the search.
9669 * Registers read by the continuation are read by us.
8e9cd9ce
EC
9670 * If we have any write marks in env->cur_state, they
9671 * will prevent corresponding reads in the continuation
9672 * from reaching our parent (an explored_state). Our
9673 * own state will get the read marks recorded, but
9674 * they'll be immediately forgotten as we're pruning
9675 * this state and will pop a new one.
f1bca824 9676 */
f4d7e40a 9677 err = propagate_liveness(env, &sl->state, cur);
a3ce685d
AS
9678
9679 /* if previous state reached the exit with precision and
9680 * current state is equivalent to it (except precsion marks)
9681 * the precision needs to be propagated back in
9682 * the current state.
9683 */
9684 err = err ? : push_jmp_history(env, cur);
9685 err = err ? : propagate_precision(env, &sl->state);
f4d7e40a
AS
9686 if (err)
9687 return err;
f1bca824 9688 return 1;
dc503a8a 9689 }
2589726d
AS
9690miss:
9691 /* when new state is not going to be added do not increase miss count.
9692 * Otherwise several loop iterations will remove the state
9693 * recorded earlier. The goal of these heuristics is to have
9694 * states from some iterations of the loop (some in the beginning
9695 * and some at the end) to help pruning.
9696 */
9697 if (add_new_state)
9698 sl->miss_cnt++;
9f4686c4
AS
9699 /* heuristic to determine whether this state is beneficial
9700 * to keep checking from state equivalence point of view.
9701 * Higher numbers increase max_states_per_insn and verification time,
9702 * but do not meaningfully decrease insn_processed.
9703 */
9704 if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
9705 /* the state is unlikely to be useful. Remove it to
9706 * speed up verification
9707 */
9708 *pprev = sl->next;
9709 if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
2589726d
AS
9710 u32 br = sl->state.branches;
9711
9712 WARN_ONCE(br,
9713 "BUG live_done but branches_to_explore %d\n",
9714 br);
9f4686c4
AS
9715 free_verifier_state(&sl->state, false);
9716 kfree(sl);
9717 env->peak_states--;
9718 } else {
9719 /* cannot free this state, since parentage chain may
9720 * walk it later. Add it for free_list instead to
9721 * be freed at the end of verification
9722 */
9723 sl->next = env->free_list;
9724 env->free_list = sl;
9725 }
9726 sl = *pprev;
9727 continue;
9728 }
dc2a4ebc 9729next:
9f4686c4
AS
9730 pprev = &sl->next;
9731 sl = *pprev;
f1bca824
AS
9732 }
9733
06ee7115
AS
9734 if (env->max_states_per_insn < states_cnt)
9735 env->max_states_per_insn = states_cnt;
9736
2c78ee89 9737 if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
b5dc0163 9738 return push_jmp_history(env, cur);
ceefbc96 9739
2589726d 9740 if (!add_new_state)
b5dc0163 9741 return push_jmp_history(env, cur);
ceefbc96 9742
2589726d
AS
9743 /* There were no equivalent states, remember the current one.
9744 * Technically the current state is not proven to be safe yet,
f4d7e40a 9745 * but it will either reach outer most bpf_exit (which means it's safe)
2589726d 9746 * or it will be rejected. When there are no loops the verifier won't be
f4d7e40a 9747 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
2589726d
AS
9748 * again on the way to bpf_exit.
9749 * When looping the sl->state.branches will be > 0 and this state
9750 * will not be considered for equivalence until branches == 0.
f1bca824 9751 */
638f5b90 9752 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
f1bca824
AS
9753 if (!new_sl)
9754 return -ENOMEM;
06ee7115
AS
9755 env->total_states++;
9756 env->peak_states++;
2589726d
AS
9757 env->prev_jmps_processed = env->jmps_processed;
9758 env->prev_insn_processed = env->insn_processed;
f1bca824
AS
9759
9760 /* add new state to the head of linked list */
679c782d
EC
9761 new = &new_sl->state;
9762 err = copy_verifier_state(new, cur);
1969db47 9763 if (err) {
679c782d 9764 free_verifier_state(new, false);
1969db47
AS
9765 kfree(new_sl);
9766 return err;
9767 }
dc2a4ebc 9768 new->insn_idx = insn_idx;
2589726d
AS
9769 WARN_ONCE(new->branches != 1,
9770 "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
b5dc0163 9771
2589726d 9772 cur->parent = new;
b5dc0163
AS
9773 cur->first_insn_idx = insn_idx;
9774 clear_jmp_history(cur);
5d839021
AS
9775 new_sl->next = *explored_state(env, insn_idx);
9776 *explored_state(env, insn_idx) = new_sl;
7640ead9
JK
9777 /* connect new state to parentage chain. Current frame needs all
9778 * registers connected. Only r6 - r9 of the callers are alive (pushed
9779 * to the stack implicitly by JITs) so in callers' frames connect just
9780 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
9781 * the state of the call instruction (with WRITTEN set), and r0 comes
9782 * from callee with its full parentage chain, anyway.
9783 */
8e9cd9ce
EC
9784 /* clear write marks in current state: the writes we did are not writes
9785 * our child did, so they don't screen off its reads from us.
9786 * (There are no read marks in current state, because reads always mark
9787 * their parent and current state never has children yet. Only
9788 * explored_states can get read marks.)
9789 */
eea1c227
AS
9790 for (j = 0; j <= cur->curframe; j++) {
9791 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
9792 cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
9793 for (i = 0; i < BPF_REG_FP; i++)
9794 cur->frame[j]->regs[i].live = REG_LIVE_NONE;
9795 }
f4d7e40a
AS
9796
9797 /* all stack frames are accessible from callee, clear them all */
9798 for (j = 0; j <= cur->curframe; j++) {
9799 struct bpf_func_state *frame = cur->frame[j];
679c782d 9800 struct bpf_func_state *newframe = new->frame[j];
f4d7e40a 9801
679c782d 9802 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
cc2b14d5 9803 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
679c782d
EC
9804 frame->stack[i].spilled_ptr.parent =
9805 &newframe->stack[i].spilled_ptr;
9806 }
f4d7e40a 9807 }
f1bca824
AS
9808 return 0;
9809}
9810
c64b7983
JS
9811/* Return true if it's OK to have the same insn return a different type. */
9812static bool reg_type_mismatch_ok(enum bpf_reg_type type)
9813{
9814 switch (type) {
9815 case PTR_TO_CTX:
9816 case PTR_TO_SOCKET:
9817 case PTR_TO_SOCKET_OR_NULL:
46f8bc92
MKL
9818 case PTR_TO_SOCK_COMMON:
9819 case PTR_TO_SOCK_COMMON_OR_NULL:
655a51e5
MKL
9820 case PTR_TO_TCP_SOCK:
9821 case PTR_TO_TCP_SOCK_OR_NULL:
fada7fdc 9822 case PTR_TO_XDP_SOCK:
2a02759e 9823 case PTR_TO_BTF_ID:
b121b341 9824 case PTR_TO_BTF_ID_OR_NULL:
c64b7983
JS
9825 return false;
9826 default:
9827 return true;
9828 }
9829}
9830
9831/* If an instruction was previously used with particular pointer types, then we
9832 * need to be careful to avoid cases such as the below, where it may be ok
9833 * for one branch accessing the pointer, but not ok for the other branch:
9834 *
9835 * R1 = sock_ptr
9836 * goto X;
9837 * ...
9838 * R1 = some_other_valid_ptr;
9839 * goto X;
9840 * ...
9841 * R2 = *(u32 *)(R1 + 0);
9842 */
9843static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
9844{
9845 return src != prev && (!reg_type_mismatch_ok(src) ||
9846 !reg_type_mismatch_ok(prev));
9847}
9848
58e2af8b 9849static int do_check(struct bpf_verifier_env *env)
17a52670 9850{
6f8a57cc 9851 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
51c39bb1 9852 struct bpf_verifier_state *state = env->cur_state;
17a52670 9853 struct bpf_insn *insns = env->prog->insnsi;
638f5b90 9854 struct bpf_reg_state *regs;
06ee7115 9855 int insn_cnt = env->prog->len;
17a52670 9856 bool do_print_state = false;
b5dc0163 9857 int prev_insn_idx = -1;
17a52670 9858
17a52670
AS
9859 for (;;) {
9860 struct bpf_insn *insn;
9861 u8 class;
9862 int err;
9863
b5dc0163 9864 env->prev_insn_idx = prev_insn_idx;
c08435ec 9865 if (env->insn_idx >= insn_cnt) {
61bd5218 9866 verbose(env, "invalid insn idx %d insn_cnt %d\n",
c08435ec 9867 env->insn_idx, insn_cnt);
17a52670
AS
9868 return -EFAULT;
9869 }
9870
c08435ec 9871 insn = &insns[env->insn_idx];
17a52670
AS
9872 class = BPF_CLASS(insn->code);
9873
06ee7115 9874 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
61bd5218
JK
9875 verbose(env,
9876 "BPF program is too large. Processed %d insn\n",
06ee7115 9877 env->insn_processed);
17a52670
AS
9878 return -E2BIG;
9879 }
9880
c08435ec 9881 err = is_state_visited(env, env->insn_idx);
f1bca824
AS
9882 if (err < 0)
9883 return err;
9884 if (err == 1) {
9885 /* found equivalent state, can prune the search */
06ee7115 9886 if (env->log.level & BPF_LOG_LEVEL) {
f1bca824 9887 if (do_print_state)
979d63d5
DB
9888 verbose(env, "\nfrom %d to %d%s: safe\n",
9889 env->prev_insn_idx, env->insn_idx,
9890 env->cur_state->speculative ?
9891 " (speculative execution)" : "");
f1bca824 9892 else
c08435ec 9893 verbose(env, "%d: safe\n", env->insn_idx);
f1bca824
AS
9894 }
9895 goto process_bpf_exit;
9896 }
9897
c3494801
AS
9898 if (signal_pending(current))
9899 return -EAGAIN;
9900
3c2ce60b
DB
9901 if (need_resched())
9902 cond_resched();
9903
06ee7115
AS
9904 if (env->log.level & BPF_LOG_LEVEL2 ||
9905 (env->log.level & BPF_LOG_LEVEL && do_print_state)) {
9906 if (env->log.level & BPF_LOG_LEVEL2)
c08435ec 9907 verbose(env, "%d:", env->insn_idx);
c5fc9692 9908 else
979d63d5
DB
9909 verbose(env, "\nfrom %d to %d%s:",
9910 env->prev_insn_idx, env->insn_idx,
9911 env->cur_state->speculative ?
9912 " (speculative execution)" : "");
f4d7e40a 9913 print_verifier_state(env, state->frame[state->curframe]);
17a52670
AS
9914 do_print_state = false;
9915 }
9916
06ee7115 9917 if (env->log.level & BPF_LOG_LEVEL) {
7105e828
DB
9918 const struct bpf_insn_cbs cbs = {
9919 .cb_print = verbose,
abe08840 9920 .private_data = env,
7105e828
DB
9921 };
9922
c08435ec
DB
9923 verbose_linfo(env, env->insn_idx, "; ");
9924 verbose(env, "%d: ", env->insn_idx);
abe08840 9925 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
17a52670
AS
9926 }
9927
cae1927c 9928 if (bpf_prog_is_dev_bound(env->prog->aux)) {
c08435ec
DB
9929 err = bpf_prog_offload_verify_insn(env, env->insn_idx,
9930 env->prev_insn_idx);
cae1927c
JK
9931 if (err)
9932 return err;
9933 }
13a27dfc 9934
638f5b90 9935 regs = cur_regs(env);
51c39bb1 9936 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
b5dc0163 9937 prev_insn_idx = env->insn_idx;
fd978bf7 9938
17a52670 9939 if (class == BPF_ALU || class == BPF_ALU64) {
1be7f75d 9940 err = check_alu_op(env, insn);
17a52670
AS
9941 if (err)
9942 return err;
9943
9944 } else if (class == BPF_LDX) {
3df126f3 9945 enum bpf_reg_type *prev_src_type, src_reg_type;
9bac3d6d
AS
9946
9947 /* check for reserved fields is already done */
9948
17a52670 9949 /* check src operand */
dc503a8a 9950 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17a52670
AS
9951 if (err)
9952 return err;
9953
dc503a8a 9954 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
17a52670
AS
9955 if (err)
9956 return err;
9957
725f9dcd
AS
9958 src_reg_type = regs[insn->src_reg].type;
9959
17a52670
AS
9960 /* check that memory (src_reg + off) is readable,
9961 * the state of dst_reg will be updated by this func
9962 */
c08435ec
DB
9963 err = check_mem_access(env, env->insn_idx, insn->src_reg,
9964 insn->off, BPF_SIZE(insn->code),
9965 BPF_READ, insn->dst_reg, false);
17a52670
AS
9966 if (err)
9967 return err;
9968
c08435ec 9969 prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type;
3df126f3
JK
9970
9971 if (*prev_src_type == NOT_INIT) {
9bac3d6d
AS
9972 /* saw a valid insn
9973 * dst_reg = *(u32 *)(src_reg + off)
3df126f3 9974 * save type to validate intersecting paths
9bac3d6d 9975 */
3df126f3 9976 *prev_src_type = src_reg_type;
9bac3d6d 9977
c64b7983 9978 } else if (reg_type_mismatch(src_reg_type, *prev_src_type)) {
9bac3d6d
AS
9979 /* ABuser program is trying to use the same insn
9980 * dst_reg = *(u32*) (src_reg + off)
9981 * with different pointer types:
9982 * src_reg == ctx in one branch and
9983 * src_reg == stack|map in some other branch.
9984 * Reject it.
9985 */
61bd5218 9986 verbose(env, "same insn cannot be used with different pointers\n");
9bac3d6d
AS
9987 return -EINVAL;
9988 }
9989
17a52670 9990 } else if (class == BPF_STX) {
3df126f3 9991 enum bpf_reg_type *prev_dst_type, dst_reg_type;
d691f9e8 9992
17a52670 9993 if (BPF_MODE(insn->code) == BPF_XADD) {
c08435ec 9994 err = check_xadd(env, env->insn_idx, insn);
17a52670
AS
9995 if (err)
9996 return err;
c08435ec 9997 env->insn_idx++;
17a52670
AS
9998 continue;
9999 }
10000
17a52670 10001 /* check src1 operand */
dc503a8a 10002 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17a52670
AS
10003 if (err)
10004 return err;
10005 /* check src2 operand */
dc503a8a 10006 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17a52670
AS
10007 if (err)
10008 return err;
10009
d691f9e8
AS
10010 dst_reg_type = regs[insn->dst_reg].type;
10011
17a52670 10012 /* check that memory (dst_reg + off) is writeable */
c08435ec
DB
10013 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
10014 insn->off, BPF_SIZE(insn->code),
10015 BPF_WRITE, insn->src_reg, false);
17a52670
AS
10016 if (err)
10017 return err;
10018
c08435ec 10019 prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type;
3df126f3
JK
10020
10021 if (*prev_dst_type == NOT_INIT) {
10022 *prev_dst_type = dst_reg_type;
c64b7983 10023 } else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) {
61bd5218 10024 verbose(env, "same insn cannot be used with different pointers\n");
d691f9e8
AS
10025 return -EINVAL;
10026 }
10027
17a52670
AS
10028 } else if (class == BPF_ST) {
10029 if (BPF_MODE(insn->code) != BPF_MEM ||
10030 insn->src_reg != BPF_REG_0) {
61bd5218 10031 verbose(env, "BPF_ST uses reserved fields\n");
17a52670
AS
10032 return -EINVAL;
10033 }
10034 /* check src operand */
dc503a8a 10035 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17a52670
AS
10036 if (err)
10037 return err;
10038
f37a8cb8 10039 if (is_ctx_reg(env, insn->dst_reg)) {
9d2be44a 10040 verbose(env, "BPF_ST stores into R%d %s is not allowed\n",
2a159c6f
DB
10041 insn->dst_reg,
10042 reg_type_str[reg_state(env, insn->dst_reg)->type]);
f37a8cb8
DB
10043 return -EACCES;
10044 }
10045
17a52670 10046 /* check that memory (dst_reg + off) is writeable */
c08435ec
DB
10047 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
10048 insn->off, BPF_SIZE(insn->code),
10049 BPF_WRITE, -1, false);
17a52670
AS
10050 if (err)
10051 return err;
10052
092ed096 10053 } else if (class == BPF_JMP || class == BPF_JMP32) {
17a52670
AS
10054 u8 opcode = BPF_OP(insn->code);
10055
2589726d 10056 env->jmps_processed++;
17a52670
AS
10057 if (opcode == BPF_CALL) {
10058 if (BPF_SRC(insn->code) != BPF_K ||
10059 insn->off != 0 ||
f4d7e40a
AS
10060 (insn->src_reg != BPF_REG_0 &&
10061 insn->src_reg != BPF_PSEUDO_CALL) ||
092ed096
JW
10062 insn->dst_reg != BPF_REG_0 ||
10063 class == BPF_JMP32) {
61bd5218 10064 verbose(env, "BPF_CALL uses reserved fields\n");
17a52670
AS
10065 return -EINVAL;
10066 }
10067
d83525ca
AS
10068 if (env->cur_state->active_spin_lock &&
10069 (insn->src_reg == BPF_PSEUDO_CALL ||
10070 insn->imm != BPF_FUNC_spin_unlock)) {
10071 verbose(env, "function calls are not allowed while holding a lock\n");
10072 return -EINVAL;
10073 }
f4d7e40a 10074 if (insn->src_reg == BPF_PSEUDO_CALL)
c08435ec 10075 err = check_func_call(env, insn, &env->insn_idx);
f4d7e40a 10076 else
c08435ec 10077 err = check_helper_call(env, insn->imm, env->insn_idx);
17a52670
AS
10078 if (err)
10079 return err;
10080
10081 } else if (opcode == BPF_JA) {
10082 if (BPF_SRC(insn->code) != BPF_K ||
10083 insn->imm != 0 ||
10084 insn->src_reg != BPF_REG_0 ||
092ed096
JW
10085 insn->dst_reg != BPF_REG_0 ||
10086 class == BPF_JMP32) {
61bd5218 10087 verbose(env, "BPF_JA uses reserved fields\n");
17a52670
AS
10088 return -EINVAL;
10089 }
10090
c08435ec 10091 env->insn_idx += insn->off + 1;
17a52670
AS
10092 continue;
10093
10094 } else if (opcode == BPF_EXIT) {
10095 if (BPF_SRC(insn->code) != BPF_K ||
10096 insn->imm != 0 ||
10097 insn->src_reg != BPF_REG_0 ||
092ed096
JW
10098 insn->dst_reg != BPF_REG_0 ||
10099 class == BPF_JMP32) {
61bd5218 10100 verbose(env, "BPF_EXIT uses reserved fields\n");
17a52670
AS
10101 return -EINVAL;
10102 }
10103
d83525ca
AS
10104 if (env->cur_state->active_spin_lock) {
10105 verbose(env, "bpf_spin_unlock is missing\n");
10106 return -EINVAL;
10107 }
10108
f4d7e40a
AS
10109 if (state->curframe) {
10110 /* exit from nested function */
c08435ec 10111 err = prepare_func_exit(env, &env->insn_idx);
f4d7e40a
AS
10112 if (err)
10113 return err;
10114 do_print_state = true;
10115 continue;
10116 }
10117
fd978bf7
JS
10118 err = check_reference_leak(env);
10119 if (err)
10120 return err;
10121
390ee7e2
AS
10122 err = check_return_code(env);
10123 if (err)
10124 return err;
f1bca824 10125process_bpf_exit:
2589726d 10126 update_branch_counts(env, env->cur_state);
b5dc0163 10127 err = pop_stack(env, &prev_insn_idx,
6f8a57cc 10128 &env->insn_idx, pop_log);
638f5b90
AS
10129 if (err < 0) {
10130 if (err != -ENOENT)
10131 return err;
17a52670
AS
10132 break;
10133 } else {
10134 do_print_state = true;
10135 continue;
10136 }
10137 } else {
c08435ec 10138 err = check_cond_jmp_op(env, insn, &env->insn_idx);
17a52670
AS
10139 if (err)
10140 return err;
10141 }
10142 } else if (class == BPF_LD) {
10143 u8 mode = BPF_MODE(insn->code);
10144
10145 if (mode == BPF_ABS || mode == BPF_IND) {
ddd872bc
AS
10146 err = check_ld_abs(env, insn);
10147 if (err)
10148 return err;
10149
17a52670
AS
10150 } else if (mode == BPF_IMM) {
10151 err = check_ld_imm(env, insn);
10152 if (err)
10153 return err;
10154
c08435ec 10155 env->insn_idx++;
51c39bb1 10156 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
17a52670 10157 } else {
61bd5218 10158 verbose(env, "invalid BPF_LD mode\n");
17a52670
AS
10159 return -EINVAL;
10160 }
10161 } else {
61bd5218 10162 verbose(env, "unknown insn class %d\n", class);
17a52670
AS
10163 return -EINVAL;
10164 }
10165
c08435ec 10166 env->insn_idx++;
17a52670
AS
10167 }
10168
10169 return 0;
10170}
10171
4976b718
HL
10172/* replace pseudo btf_id with kernel symbol address */
10173static int check_pseudo_btf_id(struct bpf_verifier_env *env,
10174 struct bpf_insn *insn,
10175 struct bpf_insn_aux_data *aux)
10176{
eaa6bcb7
HL
10177 const struct btf_var_secinfo *vsi;
10178 const struct btf_type *datasec;
4976b718
HL
10179 const struct btf_type *t;
10180 const char *sym_name;
eaa6bcb7 10181 bool percpu = false;
f16e6313
KX
10182 u32 type, id = insn->imm;
10183 s32 datasec_id;
4976b718 10184 u64 addr;
eaa6bcb7 10185 int i;
4976b718
HL
10186
10187 if (!btf_vmlinux) {
10188 verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
10189 return -EINVAL;
10190 }
10191
10192 if (insn[1].imm != 0) {
10193 verbose(env, "reserved field (insn[1].imm) is used in pseudo_btf_id ldimm64 insn.\n");
10194 return -EINVAL;
10195 }
10196
10197 t = btf_type_by_id(btf_vmlinux, id);
10198 if (!t) {
10199 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
10200 return -ENOENT;
10201 }
10202
10203 if (!btf_type_is_var(t)) {
10204 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR.\n",
10205 id);
10206 return -EINVAL;
10207 }
10208
10209 sym_name = btf_name_by_offset(btf_vmlinux, t->name_off);
10210 addr = kallsyms_lookup_name(sym_name);
10211 if (!addr) {
10212 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
10213 sym_name);
10214 return -ENOENT;
10215 }
10216
eaa6bcb7
HL
10217 datasec_id = btf_find_by_name_kind(btf_vmlinux, ".data..percpu",
10218 BTF_KIND_DATASEC);
10219 if (datasec_id > 0) {
10220 datasec = btf_type_by_id(btf_vmlinux, datasec_id);
10221 for_each_vsi(i, datasec, vsi) {
10222 if (vsi->type == id) {
10223 percpu = true;
10224 break;
10225 }
10226 }
10227 }
10228
4976b718
HL
10229 insn[0].imm = (u32)addr;
10230 insn[1].imm = addr >> 32;
10231
10232 type = t->type;
10233 t = btf_type_skip_modifiers(btf_vmlinux, type, NULL);
eaa6bcb7
HL
10234 if (percpu) {
10235 aux->btf_var.reg_type = PTR_TO_PERCPU_BTF_ID;
22dc4a0f 10236 aux->btf_var.btf = btf_vmlinux;
eaa6bcb7
HL
10237 aux->btf_var.btf_id = type;
10238 } else if (!btf_type_is_struct(t)) {
4976b718
HL
10239 const struct btf_type *ret;
10240 const char *tname;
10241 u32 tsize;
10242
10243 /* resolve the type size of ksym. */
10244 ret = btf_resolve_size(btf_vmlinux, t, &tsize);
10245 if (IS_ERR(ret)) {
10246 tname = btf_name_by_offset(btf_vmlinux, t->name_off);
10247 verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
10248 tname, PTR_ERR(ret));
10249 return -EINVAL;
10250 }
10251 aux->btf_var.reg_type = PTR_TO_MEM;
10252 aux->btf_var.mem_size = tsize;
10253 } else {
10254 aux->btf_var.reg_type = PTR_TO_BTF_ID;
22dc4a0f 10255 aux->btf_var.btf = btf_vmlinux;
4976b718
HL
10256 aux->btf_var.btf_id = type;
10257 }
10258 return 0;
10259}
10260
56f668df
MKL
10261static int check_map_prealloc(struct bpf_map *map)
10262{
10263 return (map->map_type != BPF_MAP_TYPE_HASH &&
bcc6b1b7
MKL
10264 map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
10265 map->map_type != BPF_MAP_TYPE_HASH_OF_MAPS) ||
56f668df
MKL
10266 !(map->map_flags & BPF_F_NO_PREALLOC);
10267}
10268
d83525ca
AS
10269static bool is_tracing_prog_type(enum bpf_prog_type type)
10270{
10271 switch (type) {
10272 case BPF_PROG_TYPE_KPROBE:
10273 case BPF_PROG_TYPE_TRACEPOINT:
10274 case BPF_PROG_TYPE_PERF_EVENT:
10275 case BPF_PROG_TYPE_RAW_TRACEPOINT:
10276 return true;
10277 default:
10278 return false;
10279 }
10280}
10281
94dacdbd
TG
10282static bool is_preallocated_map(struct bpf_map *map)
10283{
10284 if (!check_map_prealloc(map))
10285 return false;
10286 if (map->inner_map_meta && !check_map_prealloc(map->inner_map_meta))
10287 return false;
10288 return true;
10289}
10290
61bd5218
JK
10291static int check_map_prog_compatibility(struct bpf_verifier_env *env,
10292 struct bpf_map *map,
fdc15d38
AS
10293 struct bpf_prog *prog)
10294
10295{
7e40781c 10296 enum bpf_prog_type prog_type = resolve_prog_type(prog);
94dacdbd
TG
10297 /*
10298 * Validate that trace type programs use preallocated hash maps.
10299 *
10300 * For programs attached to PERF events this is mandatory as the
10301 * perf NMI can hit any arbitrary code sequence.
10302 *
10303 * All other trace types using preallocated hash maps are unsafe as
10304 * well because tracepoint or kprobes can be inside locked regions
10305 * of the memory allocator or at a place where a recursion into the
10306 * memory allocator would see inconsistent state.
10307 *
2ed905c5
TG
10308 * On RT enabled kernels run-time allocation of all trace type
10309 * programs is strictly prohibited due to lock type constraints. On
10310 * !RT kernels it is allowed for backwards compatibility reasons for
10311 * now, but warnings are emitted so developers are made aware of
10312 * the unsafety and can fix their programs before this is enforced.
56f668df 10313 */
7e40781c
UP
10314 if (is_tracing_prog_type(prog_type) && !is_preallocated_map(map)) {
10315 if (prog_type == BPF_PROG_TYPE_PERF_EVENT) {
61bd5218 10316 verbose(env, "perf_event programs can only use preallocated hash map\n");
56f668df
MKL
10317 return -EINVAL;
10318 }
2ed905c5
TG
10319 if (IS_ENABLED(CONFIG_PREEMPT_RT)) {
10320 verbose(env, "trace type programs can only use preallocated hash map\n");
10321 return -EINVAL;
10322 }
94dacdbd
TG
10323 WARN_ONCE(1, "trace type BPF program uses run-time allocation\n");
10324 verbose(env, "trace type programs with run-time allocated hash maps are unsafe. Switch to preallocated hash maps.\n");
fdc15d38 10325 }
a3884572 10326
9e7a4d98
KS
10327 if (map_value_has_spin_lock(map)) {
10328 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
10329 verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
10330 return -EINVAL;
10331 }
10332
10333 if (is_tracing_prog_type(prog_type)) {
10334 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
10335 return -EINVAL;
10336 }
10337
10338 if (prog->aux->sleepable) {
10339 verbose(env, "sleepable progs cannot use bpf_spin_lock yet\n");
10340 return -EINVAL;
10341 }
d83525ca
AS
10342 }
10343
a3884572 10344 if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) &&
09728266 10345 !bpf_offload_prog_map_match(prog, map)) {
a3884572
JK
10346 verbose(env, "offload device mismatch between prog and map\n");
10347 return -EINVAL;
10348 }
10349
85d33df3
MKL
10350 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
10351 verbose(env, "bpf_struct_ops map cannot be used in prog\n");
10352 return -EINVAL;
10353 }
10354
1e6c62a8
AS
10355 if (prog->aux->sleepable)
10356 switch (map->map_type) {
10357 case BPF_MAP_TYPE_HASH:
10358 case BPF_MAP_TYPE_LRU_HASH:
10359 case BPF_MAP_TYPE_ARRAY:
10360 if (!is_preallocated_map(map)) {
10361 verbose(env,
10362 "Sleepable programs can only use preallocated hash maps\n");
10363 return -EINVAL;
10364 }
10365 break;
10366 default:
10367 verbose(env,
10368 "Sleepable programs can only use array and hash maps\n");
10369 return -EINVAL;
10370 }
10371
fdc15d38
AS
10372 return 0;
10373}
10374
b741f163
RG
10375static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
10376{
10377 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
10378 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
10379}
10380
4976b718
HL
10381/* find and rewrite pseudo imm in ld_imm64 instructions:
10382 *
10383 * 1. if it accesses map FD, replace it with actual map pointer.
10384 * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
10385 *
10386 * NOTE: btf_vmlinux is required for converting pseudo btf_id.
0246e64d 10387 */
4976b718 10388static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
0246e64d
AS
10389{
10390 struct bpf_insn *insn = env->prog->insnsi;
10391 int insn_cnt = env->prog->len;
fdc15d38 10392 int i, j, err;
0246e64d 10393
f1f7714e 10394 err = bpf_prog_calc_tag(env->prog);
aafe6ae9
DB
10395 if (err)
10396 return err;
10397
0246e64d 10398 for (i = 0; i < insn_cnt; i++, insn++) {
9bac3d6d 10399 if (BPF_CLASS(insn->code) == BPF_LDX &&
d691f9e8 10400 (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
61bd5218 10401 verbose(env, "BPF_LDX uses reserved fields\n");
9bac3d6d
AS
10402 return -EINVAL;
10403 }
10404
d691f9e8
AS
10405 if (BPF_CLASS(insn->code) == BPF_STX &&
10406 ((BPF_MODE(insn->code) != BPF_MEM &&
10407 BPF_MODE(insn->code) != BPF_XADD) || insn->imm != 0)) {
61bd5218 10408 verbose(env, "BPF_STX uses reserved fields\n");
d691f9e8
AS
10409 return -EINVAL;
10410 }
10411
0246e64d 10412 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
d8eca5bb 10413 struct bpf_insn_aux_data *aux;
0246e64d
AS
10414 struct bpf_map *map;
10415 struct fd f;
d8eca5bb 10416 u64 addr;
0246e64d
AS
10417
10418 if (i == insn_cnt - 1 || insn[1].code != 0 ||
10419 insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
10420 insn[1].off != 0) {
61bd5218 10421 verbose(env, "invalid bpf_ld_imm64 insn\n");
0246e64d
AS
10422 return -EINVAL;
10423 }
10424
d8eca5bb 10425 if (insn[0].src_reg == 0)
0246e64d
AS
10426 /* valid generic load 64-bit imm */
10427 goto next_insn;
10428
4976b718
HL
10429 if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
10430 aux = &env->insn_aux_data[i];
10431 err = check_pseudo_btf_id(env, insn, aux);
10432 if (err)
10433 return err;
10434 goto next_insn;
10435 }
10436
d8eca5bb
DB
10437 /* In final convert_pseudo_ld_imm64() step, this is
10438 * converted into regular 64-bit imm load insn.
10439 */
10440 if ((insn[0].src_reg != BPF_PSEUDO_MAP_FD &&
10441 insn[0].src_reg != BPF_PSEUDO_MAP_VALUE) ||
10442 (insn[0].src_reg == BPF_PSEUDO_MAP_FD &&
10443 insn[1].imm != 0)) {
10444 verbose(env,
10445 "unrecognized bpf_ld_imm64 insn\n");
0246e64d
AS
10446 return -EINVAL;
10447 }
10448
20182390 10449 f = fdget(insn[0].imm);
c2101297 10450 map = __bpf_map_get(f);
0246e64d 10451 if (IS_ERR(map)) {
61bd5218 10452 verbose(env, "fd %d is not pointing to valid bpf_map\n",
20182390 10453 insn[0].imm);
0246e64d
AS
10454 return PTR_ERR(map);
10455 }
10456
61bd5218 10457 err = check_map_prog_compatibility(env, map, env->prog);
fdc15d38
AS
10458 if (err) {
10459 fdput(f);
10460 return err;
10461 }
10462
d8eca5bb
DB
10463 aux = &env->insn_aux_data[i];
10464 if (insn->src_reg == BPF_PSEUDO_MAP_FD) {
10465 addr = (unsigned long)map;
10466 } else {
10467 u32 off = insn[1].imm;
10468
10469 if (off >= BPF_MAX_VAR_OFF) {
10470 verbose(env, "direct value offset of %u is not allowed\n", off);
10471 fdput(f);
10472 return -EINVAL;
10473 }
10474
10475 if (!map->ops->map_direct_value_addr) {
10476 verbose(env, "no direct value access support for this map type\n");
10477 fdput(f);
10478 return -EINVAL;
10479 }
10480
10481 err = map->ops->map_direct_value_addr(map, &addr, off);
10482 if (err) {
10483 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
10484 map->value_size, off);
10485 fdput(f);
10486 return err;
10487 }
10488
10489 aux->map_off = off;
10490 addr += off;
10491 }
10492
10493 insn[0].imm = (u32)addr;
10494 insn[1].imm = addr >> 32;
0246e64d
AS
10495
10496 /* check whether we recorded this map already */
d8eca5bb 10497 for (j = 0; j < env->used_map_cnt; j++) {
0246e64d 10498 if (env->used_maps[j] == map) {
d8eca5bb 10499 aux->map_index = j;
0246e64d
AS
10500 fdput(f);
10501 goto next_insn;
10502 }
d8eca5bb 10503 }
0246e64d
AS
10504
10505 if (env->used_map_cnt >= MAX_USED_MAPS) {
10506 fdput(f);
10507 return -E2BIG;
10508 }
10509
0246e64d
AS
10510 /* hold the map. If the program is rejected by verifier,
10511 * the map will be released by release_maps() or it
10512 * will be used by the valid program until it's unloaded
ab7f5bf0 10513 * and all maps are released in free_used_maps()
0246e64d 10514 */
1e0bd5a0 10515 bpf_map_inc(map);
d8eca5bb
DB
10516
10517 aux->map_index = env->used_map_cnt;
92117d84
AS
10518 env->used_maps[env->used_map_cnt++] = map;
10519
b741f163 10520 if (bpf_map_is_cgroup_storage(map) &&
e4730423 10521 bpf_cgroup_storage_assign(env->prog->aux, map)) {
b741f163 10522 verbose(env, "only one cgroup storage of each type is allowed\n");
de9cbbaa
RG
10523 fdput(f);
10524 return -EBUSY;
10525 }
10526
0246e64d
AS
10527 fdput(f);
10528next_insn:
10529 insn++;
10530 i++;
5e581dad
DB
10531 continue;
10532 }
10533
10534 /* Basic sanity check before we invest more work here. */
10535 if (!bpf_opcode_in_insntable(insn->code)) {
10536 verbose(env, "unknown opcode %02x\n", insn->code);
10537 return -EINVAL;
0246e64d
AS
10538 }
10539 }
10540
10541 /* now all pseudo BPF_LD_IMM64 instructions load valid
10542 * 'struct bpf_map *' into a register instead of user map_fd.
10543 * These pointers will be used later by verifier to validate map access.
10544 */
10545 return 0;
10546}
10547
10548/* drop refcnt of maps used by the rejected program */
58e2af8b 10549static void release_maps(struct bpf_verifier_env *env)
0246e64d 10550{
a2ea0746
DB
10551 __bpf_free_used_maps(env->prog->aux, env->used_maps,
10552 env->used_map_cnt);
0246e64d
AS
10553}
10554
10555/* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
58e2af8b 10556static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
0246e64d
AS
10557{
10558 struct bpf_insn *insn = env->prog->insnsi;
10559 int insn_cnt = env->prog->len;
10560 int i;
10561
10562 for (i = 0; i < insn_cnt; i++, insn++)
10563 if (insn->code == (BPF_LD | BPF_IMM | BPF_DW))
10564 insn->src_reg = 0;
10565}
10566
8041902d
AS
10567/* single env->prog->insni[off] instruction was replaced with the range
10568 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying
10569 * [0, off) and [off, end) to new locations, so the patched range stays zero
10570 */
b325fbca
JW
10571static int adjust_insn_aux_data(struct bpf_verifier_env *env,
10572 struct bpf_prog *new_prog, u32 off, u32 cnt)
8041902d
AS
10573{
10574 struct bpf_insn_aux_data *new_data, *old_data = env->insn_aux_data;
b325fbca
JW
10575 struct bpf_insn *insn = new_prog->insnsi;
10576 u32 prog_len;
c131187d 10577 int i;
8041902d 10578
b325fbca
JW
10579 /* aux info at OFF always needs adjustment, no matter fast path
10580 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
10581 * original insn at old prog.
10582 */
10583 old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
10584
8041902d
AS
10585 if (cnt == 1)
10586 return 0;
b325fbca 10587 prog_len = new_prog->len;
fad953ce
KC
10588 new_data = vzalloc(array_size(prog_len,
10589 sizeof(struct bpf_insn_aux_data)));
8041902d
AS
10590 if (!new_data)
10591 return -ENOMEM;
10592 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
10593 memcpy(new_data + off + cnt - 1, old_data + off,
10594 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
b325fbca 10595 for (i = off; i < off + cnt - 1; i++) {
51c39bb1 10596 new_data[i].seen = env->pass_cnt;
b325fbca
JW
10597 new_data[i].zext_dst = insn_has_def32(env, insn + i);
10598 }
8041902d
AS
10599 env->insn_aux_data = new_data;
10600 vfree(old_data);
10601 return 0;
10602}
10603
cc8b0b92
AS
10604static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
10605{
10606 int i;
10607
10608 if (len == 1)
10609 return;
4cb3d99c
JW
10610 /* NOTE: fake 'exit' subprog should be updated as well. */
10611 for (i = 0; i <= env->subprog_cnt; i++) {
afd59424 10612 if (env->subprog_info[i].start <= off)
cc8b0b92 10613 continue;
9c8105bd 10614 env->subprog_info[i].start += len - 1;
cc8b0b92
AS
10615 }
10616}
10617
a748c697
MF
10618static void adjust_poke_descs(struct bpf_prog *prog, u32 len)
10619{
10620 struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
10621 int i, sz = prog->aux->size_poke_tab;
10622 struct bpf_jit_poke_descriptor *desc;
10623
10624 for (i = 0; i < sz; i++) {
10625 desc = &tab[i];
10626 desc->insn_idx += len - 1;
10627 }
10628}
10629
8041902d
AS
10630static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
10631 const struct bpf_insn *patch, u32 len)
10632{
10633 struct bpf_prog *new_prog;
10634
10635 new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
4f73379e
AS
10636 if (IS_ERR(new_prog)) {
10637 if (PTR_ERR(new_prog) == -ERANGE)
10638 verbose(env,
10639 "insn %d cannot be patched due to 16-bit range\n",
10640 env->insn_aux_data[off].orig_idx);
8041902d 10641 return NULL;
4f73379e 10642 }
b325fbca 10643 if (adjust_insn_aux_data(env, new_prog, off, len))
8041902d 10644 return NULL;
cc8b0b92 10645 adjust_subprog_starts(env, off, len);
a748c697 10646 adjust_poke_descs(new_prog, len);
8041902d
AS
10647 return new_prog;
10648}
10649
52875a04
JK
10650static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
10651 u32 off, u32 cnt)
10652{
10653 int i, j;
10654
10655 /* find first prog starting at or after off (first to remove) */
10656 for (i = 0; i < env->subprog_cnt; i++)
10657 if (env->subprog_info[i].start >= off)
10658 break;
10659 /* find first prog starting at or after off + cnt (first to stay) */
10660 for (j = i; j < env->subprog_cnt; j++)
10661 if (env->subprog_info[j].start >= off + cnt)
10662 break;
10663 /* if j doesn't start exactly at off + cnt, we are just removing
10664 * the front of previous prog
10665 */
10666 if (env->subprog_info[j].start != off + cnt)
10667 j--;
10668
10669 if (j > i) {
10670 struct bpf_prog_aux *aux = env->prog->aux;
10671 int move;
10672
10673 /* move fake 'exit' subprog as well */
10674 move = env->subprog_cnt + 1 - j;
10675
10676 memmove(env->subprog_info + i,
10677 env->subprog_info + j,
10678 sizeof(*env->subprog_info) * move);
10679 env->subprog_cnt -= j - i;
10680
10681 /* remove func_info */
10682 if (aux->func_info) {
10683 move = aux->func_info_cnt - j;
10684
10685 memmove(aux->func_info + i,
10686 aux->func_info + j,
10687 sizeof(*aux->func_info) * move);
10688 aux->func_info_cnt -= j - i;
10689 /* func_info->insn_off is set after all code rewrites,
10690 * in adjust_btf_func() - no need to adjust
10691 */
10692 }
10693 } else {
10694 /* convert i from "first prog to remove" to "first to adjust" */
10695 if (env->subprog_info[i].start == off)
10696 i++;
10697 }
10698
10699 /* update fake 'exit' subprog as well */
10700 for (; i <= env->subprog_cnt; i++)
10701 env->subprog_info[i].start -= cnt;
10702
10703 return 0;
10704}
10705
10706static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
10707 u32 cnt)
10708{
10709 struct bpf_prog *prog = env->prog;
10710 u32 i, l_off, l_cnt, nr_linfo;
10711 struct bpf_line_info *linfo;
10712
10713 nr_linfo = prog->aux->nr_linfo;
10714 if (!nr_linfo)
10715 return 0;
10716
10717 linfo = prog->aux->linfo;
10718
10719 /* find first line info to remove, count lines to be removed */
10720 for (i = 0; i < nr_linfo; i++)
10721 if (linfo[i].insn_off >= off)
10722 break;
10723
10724 l_off = i;
10725 l_cnt = 0;
10726 for (; i < nr_linfo; i++)
10727 if (linfo[i].insn_off < off + cnt)
10728 l_cnt++;
10729 else
10730 break;
10731
10732 /* First live insn doesn't match first live linfo, it needs to "inherit"
10733 * last removed linfo. prog is already modified, so prog->len == off
10734 * means no live instructions after (tail of the program was removed).
10735 */
10736 if (prog->len != off && l_cnt &&
10737 (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
10738 l_cnt--;
10739 linfo[--i].insn_off = off + cnt;
10740 }
10741
10742 /* remove the line info which refer to the removed instructions */
10743 if (l_cnt) {
10744 memmove(linfo + l_off, linfo + i,
10745 sizeof(*linfo) * (nr_linfo - i));
10746
10747 prog->aux->nr_linfo -= l_cnt;
10748 nr_linfo = prog->aux->nr_linfo;
10749 }
10750
10751 /* pull all linfo[i].insn_off >= off + cnt in by cnt */
10752 for (i = l_off; i < nr_linfo; i++)
10753 linfo[i].insn_off -= cnt;
10754
10755 /* fix up all subprogs (incl. 'exit') which start >= off */
10756 for (i = 0; i <= env->subprog_cnt; i++)
10757 if (env->subprog_info[i].linfo_idx > l_off) {
10758 /* program may have started in the removed region but
10759 * may not be fully removed
10760 */
10761 if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
10762 env->subprog_info[i].linfo_idx -= l_cnt;
10763 else
10764 env->subprog_info[i].linfo_idx = l_off;
10765 }
10766
10767 return 0;
10768}
10769
10770static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
10771{
10772 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
10773 unsigned int orig_prog_len = env->prog->len;
10774 int err;
10775
08ca90af
JK
10776 if (bpf_prog_is_dev_bound(env->prog->aux))
10777 bpf_prog_offload_remove_insns(env, off, cnt);
10778
52875a04
JK
10779 err = bpf_remove_insns(env->prog, off, cnt);
10780 if (err)
10781 return err;
10782
10783 err = adjust_subprog_starts_after_remove(env, off, cnt);
10784 if (err)
10785 return err;
10786
10787 err = bpf_adj_linfo_after_remove(env, off, cnt);
10788 if (err)
10789 return err;
10790
10791 memmove(aux_data + off, aux_data + off + cnt,
10792 sizeof(*aux_data) * (orig_prog_len - off - cnt));
10793
10794 return 0;
10795}
10796
2a5418a1
DB
10797/* The verifier does more data flow analysis than llvm and will not
10798 * explore branches that are dead at run time. Malicious programs can
10799 * have dead code too. Therefore replace all dead at-run-time code
10800 * with 'ja -1'.
10801 *
10802 * Just nops are not optimal, e.g. if they would sit at the end of the
10803 * program and through another bug we would manage to jump there, then
10804 * we'd execute beyond program memory otherwise. Returning exception
10805 * code also wouldn't work since we can have subprogs where the dead
10806 * code could be located.
c131187d
AS
10807 */
10808static void sanitize_dead_code(struct bpf_verifier_env *env)
10809{
10810 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
2a5418a1 10811 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
c131187d
AS
10812 struct bpf_insn *insn = env->prog->insnsi;
10813 const int insn_cnt = env->prog->len;
10814 int i;
10815
10816 for (i = 0; i < insn_cnt; i++) {
10817 if (aux_data[i].seen)
10818 continue;
2a5418a1 10819 memcpy(insn + i, &trap, sizeof(trap));
c131187d
AS
10820 }
10821}
10822
e2ae4ca2
JK
10823static bool insn_is_cond_jump(u8 code)
10824{
10825 u8 op;
10826
092ed096
JW
10827 if (BPF_CLASS(code) == BPF_JMP32)
10828 return true;
10829
e2ae4ca2
JK
10830 if (BPF_CLASS(code) != BPF_JMP)
10831 return false;
10832
10833 op = BPF_OP(code);
10834 return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
10835}
10836
10837static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
10838{
10839 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
10840 struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
10841 struct bpf_insn *insn = env->prog->insnsi;
10842 const int insn_cnt = env->prog->len;
10843 int i;
10844
10845 for (i = 0; i < insn_cnt; i++, insn++) {
10846 if (!insn_is_cond_jump(insn->code))
10847 continue;
10848
10849 if (!aux_data[i + 1].seen)
10850 ja.off = insn->off;
10851 else if (!aux_data[i + 1 + insn->off].seen)
10852 ja.off = 0;
10853 else
10854 continue;
10855
08ca90af
JK
10856 if (bpf_prog_is_dev_bound(env->prog->aux))
10857 bpf_prog_offload_replace_insn(env, i, &ja);
10858
e2ae4ca2
JK
10859 memcpy(insn, &ja, sizeof(ja));
10860 }
10861}
10862
52875a04
JK
10863static int opt_remove_dead_code(struct bpf_verifier_env *env)
10864{
10865 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
10866 int insn_cnt = env->prog->len;
10867 int i, err;
10868
10869 for (i = 0; i < insn_cnt; i++) {
10870 int j;
10871
10872 j = 0;
10873 while (i + j < insn_cnt && !aux_data[i + j].seen)
10874 j++;
10875 if (!j)
10876 continue;
10877
10878 err = verifier_remove_insns(env, i, j);
10879 if (err)
10880 return err;
10881 insn_cnt = env->prog->len;
10882 }
10883
10884 return 0;
10885}
10886
a1b14abc
JK
10887static int opt_remove_nops(struct bpf_verifier_env *env)
10888{
10889 const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
10890 struct bpf_insn *insn = env->prog->insnsi;
10891 int insn_cnt = env->prog->len;
10892 int i, err;
10893
10894 for (i = 0; i < insn_cnt; i++) {
10895 if (memcmp(&insn[i], &ja, sizeof(ja)))
10896 continue;
10897
10898 err = verifier_remove_insns(env, i, 1);
10899 if (err)
10900 return err;
10901 insn_cnt--;
10902 i--;
10903 }
10904
10905 return 0;
10906}
10907
d6c2308c
JW
10908static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
10909 const union bpf_attr *attr)
a4b1d3c1 10910{
d6c2308c 10911 struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
a4b1d3c1 10912 struct bpf_insn_aux_data *aux = env->insn_aux_data;
d6c2308c 10913 int i, patch_len, delta = 0, len = env->prog->len;
a4b1d3c1 10914 struct bpf_insn *insns = env->prog->insnsi;
a4b1d3c1 10915 struct bpf_prog *new_prog;
d6c2308c 10916 bool rnd_hi32;
a4b1d3c1 10917
d6c2308c 10918 rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
a4b1d3c1 10919 zext_patch[1] = BPF_ZEXT_REG(0);
d6c2308c
JW
10920 rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
10921 rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
10922 rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
a4b1d3c1
JW
10923 for (i = 0; i < len; i++) {
10924 int adj_idx = i + delta;
10925 struct bpf_insn insn;
10926
d6c2308c
JW
10927 insn = insns[adj_idx];
10928 if (!aux[adj_idx].zext_dst) {
10929 u8 code, class;
10930 u32 imm_rnd;
10931
10932 if (!rnd_hi32)
10933 continue;
10934
10935 code = insn.code;
10936 class = BPF_CLASS(code);
10937 if (insn_no_def(&insn))
10938 continue;
10939
10940 /* NOTE: arg "reg" (the fourth one) is only used for
10941 * BPF_STX which has been ruled out in above
10942 * check, it is safe to pass NULL here.
10943 */
10944 if (is_reg64(env, &insn, insn.dst_reg, NULL, DST_OP)) {
10945 if (class == BPF_LD &&
10946 BPF_MODE(code) == BPF_IMM)
10947 i++;
10948 continue;
10949 }
10950
10951 /* ctx load could be transformed into wider load. */
10952 if (class == BPF_LDX &&
10953 aux[adj_idx].ptr_type == PTR_TO_CTX)
10954 continue;
10955
10956 imm_rnd = get_random_int();
10957 rnd_hi32_patch[0] = insn;
10958 rnd_hi32_patch[1].imm = imm_rnd;
10959 rnd_hi32_patch[3].dst_reg = insn.dst_reg;
10960 patch = rnd_hi32_patch;
10961 patch_len = 4;
10962 goto apply_patch_buffer;
10963 }
10964
10965 if (!bpf_jit_needs_zext())
a4b1d3c1
JW
10966 continue;
10967
a4b1d3c1
JW
10968 zext_patch[0] = insn;
10969 zext_patch[1].dst_reg = insn.dst_reg;
10970 zext_patch[1].src_reg = insn.dst_reg;
d6c2308c
JW
10971 patch = zext_patch;
10972 patch_len = 2;
10973apply_patch_buffer:
10974 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
a4b1d3c1
JW
10975 if (!new_prog)
10976 return -ENOMEM;
10977 env->prog = new_prog;
10978 insns = new_prog->insnsi;
10979 aux = env->insn_aux_data;
d6c2308c 10980 delta += patch_len - 1;
a4b1d3c1
JW
10981 }
10982
10983 return 0;
10984}
10985
c64b7983
JS
10986/* convert load instructions that access fields of a context type into a
10987 * sequence of instructions that access fields of the underlying structure:
10988 * struct __sk_buff -> struct sk_buff
10989 * struct bpf_sock_ops -> struct sock
9bac3d6d 10990 */
58e2af8b 10991static int convert_ctx_accesses(struct bpf_verifier_env *env)
9bac3d6d 10992{
00176a34 10993 const struct bpf_verifier_ops *ops = env->ops;
f96da094 10994 int i, cnt, size, ctx_field_size, delta = 0;
3df126f3 10995 const int insn_cnt = env->prog->len;
36bbef52 10996 struct bpf_insn insn_buf[16], *insn;
46f53a65 10997 u32 target_size, size_default, off;
9bac3d6d 10998 struct bpf_prog *new_prog;
d691f9e8 10999 enum bpf_access_type type;
f96da094 11000 bool is_narrower_load;
9bac3d6d 11001
b09928b9
DB
11002 if (ops->gen_prologue || env->seen_direct_write) {
11003 if (!ops->gen_prologue) {
11004 verbose(env, "bpf verifier is misconfigured\n");
11005 return -EINVAL;
11006 }
36bbef52
DB
11007 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
11008 env->prog);
11009 if (cnt >= ARRAY_SIZE(insn_buf)) {
61bd5218 11010 verbose(env, "bpf verifier is misconfigured\n");
36bbef52
DB
11011 return -EINVAL;
11012 } else if (cnt) {
8041902d 11013 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
36bbef52
DB
11014 if (!new_prog)
11015 return -ENOMEM;
8041902d 11016
36bbef52 11017 env->prog = new_prog;
3df126f3 11018 delta += cnt - 1;
36bbef52
DB
11019 }
11020 }
11021
c64b7983 11022 if (bpf_prog_is_dev_bound(env->prog->aux))
9bac3d6d
AS
11023 return 0;
11024
3df126f3 11025 insn = env->prog->insnsi + delta;
36bbef52 11026
9bac3d6d 11027 for (i = 0; i < insn_cnt; i++, insn++) {
c64b7983
JS
11028 bpf_convert_ctx_access_t convert_ctx_access;
11029
62c7989b
DB
11030 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
11031 insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
11032 insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
ea2e7ce5 11033 insn->code == (BPF_LDX | BPF_MEM | BPF_DW))
d691f9e8 11034 type = BPF_READ;
62c7989b
DB
11035 else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
11036 insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
11037 insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
ea2e7ce5 11038 insn->code == (BPF_STX | BPF_MEM | BPF_DW))
d691f9e8
AS
11039 type = BPF_WRITE;
11040 else
9bac3d6d
AS
11041 continue;
11042
af86ca4e
AS
11043 if (type == BPF_WRITE &&
11044 env->insn_aux_data[i + delta].sanitize_stack_off) {
11045 struct bpf_insn patch[] = {
11046 /* Sanitize suspicious stack slot with zero.
11047 * There are no memory dependencies for this store,
11048 * since it's only using frame pointer and immediate
11049 * constant of zero
11050 */
11051 BPF_ST_MEM(BPF_DW, BPF_REG_FP,
11052 env->insn_aux_data[i + delta].sanitize_stack_off,
11053 0),
11054 /* the original STX instruction will immediately
11055 * overwrite the same stack slot with appropriate value
11056 */
11057 *insn,
11058 };
11059
11060 cnt = ARRAY_SIZE(patch);
11061 new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
11062 if (!new_prog)
11063 return -ENOMEM;
11064
11065 delta += cnt - 1;
11066 env->prog = new_prog;
11067 insn = new_prog->insnsi + i + delta;
11068 continue;
11069 }
11070
c64b7983
JS
11071 switch (env->insn_aux_data[i + delta].ptr_type) {
11072 case PTR_TO_CTX:
11073 if (!ops->convert_ctx_access)
11074 continue;
11075 convert_ctx_access = ops->convert_ctx_access;
11076 break;
11077 case PTR_TO_SOCKET:
46f8bc92 11078 case PTR_TO_SOCK_COMMON:
c64b7983
JS
11079 convert_ctx_access = bpf_sock_convert_ctx_access;
11080 break;
655a51e5
MKL
11081 case PTR_TO_TCP_SOCK:
11082 convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
11083 break;
fada7fdc
JL
11084 case PTR_TO_XDP_SOCK:
11085 convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
11086 break;
2a02759e 11087 case PTR_TO_BTF_ID:
27ae7997
MKL
11088 if (type == BPF_READ) {
11089 insn->code = BPF_LDX | BPF_PROBE_MEM |
11090 BPF_SIZE((insn)->code);
11091 env->prog->aux->num_exentries++;
7e40781c 11092 } else if (resolve_prog_type(env->prog) != BPF_PROG_TYPE_STRUCT_OPS) {
2a02759e
AS
11093 verbose(env, "Writes through BTF pointers are not allowed\n");
11094 return -EINVAL;
11095 }
2a02759e 11096 continue;
c64b7983 11097 default:
9bac3d6d 11098 continue;
c64b7983 11099 }
9bac3d6d 11100
31fd8581 11101 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
f96da094 11102 size = BPF_LDST_BYTES(insn);
31fd8581
YS
11103
11104 /* If the read access is a narrower load of the field,
11105 * convert to a 4/8-byte load, to minimum program type specific
11106 * convert_ctx_access changes. If conversion is successful,
11107 * we will apply proper mask to the result.
11108 */
f96da094 11109 is_narrower_load = size < ctx_field_size;
46f53a65
AI
11110 size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
11111 off = insn->off;
31fd8581 11112 if (is_narrower_load) {
f96da094
DB
11113 u8 size_code;
11114
11115 if (type == BPF_WRITE) {
61bd5218 11116 verbose(env, "bpf verifier narrow ctx access misconfigured\n");
f96da094
DB
11117 return -EINVAL;
11118 }
31fd8581 11119
f96da094 11120 size_code = BPF_H;
31fd8581
YS
11121 if (ctx_field_size == 4)
11122 size_code = BPF_W;
11123 else if (ctx_field_size == 8)
11124 size_code = BPF_DW;
f96da094 11125
bc23105c 11126 insn->off = off & ~(size_default - 1);
31fd8581
YS
11127 insn->code = BPF_LDX | BPF_MEM | size_code;
11128 }
f96da094
DB
11129
11130 target_size = 0;
c64b7983
JS
11131 cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
11132 &target_size);
f96da094
DB
11133 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
11134 (ctx_field_size && !target_size)) {
61bd5218 11135 verbose(env, "bpf verifier is misconfigured\n");
9bac3d6d
AS
11136 return -EINVAL;
11137 }
f96da094
DB
11138
11139 if (is_narrower_load && size < target_size) {
d895a0f1
IL
11140 u8 shift = bpf_ctx_narrow_access_offset(
11141 off, size, size_default) * 8;
46f53a65
AI
11142 if (ctx_field_size <= 4) {
11143 if (shift)
11144 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
11145 insn->dst_reg,
11146 shift);
31fd8581 11147 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
f96da094 11148 (1 << size * 8) - 1);
46f53a65
AI
11149 } else {
11150 if (shift)
11151 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
11152 insn->dst_reg,
11153 shift);
31fd8581 11154 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
e2f7fc0a 11155 (1ULL << size * 8) - 1);
46f53a65 11156 }
31fd8581 11157 }
9bac3d6d 11158
8041902d 11159 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
9bac3d6d
AS
11160 if (!new_prog)
11161 return -ENOMEM;
11162
3df126f3 11163 delta += cnt - 1;
9bac3d6d
AS
11164
11165 /* keep walking new program and skip insns we just inserted */
11166 env->prog = new_prog;
3df126f3 11167 insn = new_prog->insnsi + i + delta;
9bac3d6d
AS
11168 }
11169
11170 return 0;
11171}
11172
1c2a088a
AS
11173static int jit_subprogs(struct bpf_verifier_env *env)
11174{
11175 struct bpf_prog *prog = env->prog, **func, *tmp;
11176 int i, j, subprog_start, subprog_end = 0, len, subprog;
a748c697 11177 struct bpf_map *map_ptr;
7105e828 11178 struct bpf_insn *insn;
1c2a088a 11179 void *old_bpf_func;
c4c0bdc0 11180 int err, num_exentries;
1c2a088a 11181
f910cefa 11182 if (env->subprog_cnt <= 1)
1c2a088a
AS
11183 return 0;
11184
7105e828 11185 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
1c2a088a
AS
11186 if (insn->code != (BPF_JMP | BPF_CALL) ||
11187 insn->src_reg != BPF_PSEUDO_CALL)
11188 continue;
c7a89784
DB
11189 /* Upon error here we cannot fall back to interpreter but
11190 * need a hard reject of the program. Thus -EFAULT is
11191 * propagated in any case.
11192 */
1c2a088a
AS
11193 subprog = find_subprog(env, i + insn->imm + 1);
11194 if (subprog < 0) {
11195 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
11196 i + insn->imm + 1);
11197 return -EFAULT;
11198 }
11199 /* temporarily remember subprog id inside insn instead of
11200 * aux_data, since next loop will split up all insns into funcs
11201 */
f910cefa 11202 insn->off = subprog;
1c2a088a
AS
11203 /* remember original imm in case JIT fails and fallback
11204 * to interpreter will be needed
11205 */
11206 env->insn_aux_data[i].call_imm = insn->imm;
11207 /* point imm to __bpf_call_base+1 from JITs point of view */
11208 insn->imm = 1;
11209 }
11210
c454a46b
MKL
11211 err = bpf_prog_alloc_jited_linfo(prog);
11212 if (err)
11213 goto out_undo_insn;
11214
11215 err = -ENOMEM;
6396bb22 11216 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
1c2a088a 11217 if (!func)
c7a89784 11218 goto out_undo_insn;
1c2a088a 11219
f910cefa 11220 for (i = 0; i < env->subprog_cnt; i++) {
1c2a088a 11221 subprog_start = subprog_end;
4cb3d99c 11222 subprog_end = env->subprog_info[i + 1].start;
1c2a088a
AS
11223
11224 len = subprog_end - subprog_start;
492ecee8
AS
11225 /* BPF_PROG_RUN doesn't call subprogs directly,
11226 * hence main prog stats include the runtime of subprogs.
11227 * subprogs don't have IDs and not reachable via prog_get_next_id
11228 * func[i]->aux->stats will never be accessed and stays NULL
11229 */
11230 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
1c2a088a
AS
11231 if (!func[i])
11232 goto out_free;
11233 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
11234 len * sizeof(struct bpf_insn));
4f74d809 11235 func[i]->type = prog->type;
1c2a088a 11236 func[i]->len = len;
4f74d809
DB
11237 if (bpf_prog_calc_tag(func[i]))
11238 goto out_free;
1c2a088a 11239 func[i]->is_func = 1;
ba64e7d8
YS
11240 func[i]->aux->func_idx = i;
11241 /* the btf and func_info will be freed only at prog->aux */
11242 func[i]->aux->btf = prog->aux->btf;
11243 func[i]->aux->func_info = prog->aux->func_info;
11244
a748c697
MF
11245 for (j = 0; j < prog->aux->size_poke_tab; j++) {
11246 u32 insn_idx = prog->aux->poke_tab[j].insn_idx;
11247 int ret;
11248
11249 if (!(insn_idx >= subprog_start &&
11250 insn_idx <= subprog_end))
11251 continue;
11252
11253 ret = bpf_jit_add_poke_descriptor(func[i],
11254 &prog->aux->poke_tab[j]);
11255 if (ret < 0) {
11256 verbose(env, "adding tail call poke descriptor failed\n");
11257 goto out_free;
11258 }
11259
11260 func[i]->insnsi[insn_idx - subprog_start].imm = ret + 1;
11261
11262 map_ptr = func[i]->aux->poke_tab[ret].tail_call.map;
11263 ret = map_ptr->ops->map_poke_track(map_ptr, func[i]->aux);
11264 if (ret < 0) {
11265 verbose(env, "tracking tail call prog failed\n");
11266 goto out_free;
11267 }
11268 }
11269
1c2a088a
AS
11270 /* Use bpf_prog_F_tag to indicate functions in stack traces.
11271 * Long term would need debug info to populate names
11272 */
11273 func[i]->aux->name[0] = 'F';
9c8105bd 11274 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
1c2a088a 11275 func[i]->jit_requested = 1;
c454a46b
MKL
11276 func[i]->aux->linfo = prog->aux->linfo;
11277 func[i]->aux->nr_linfo = prog->aux->nr_linfo;
11278 func[i]->aux->jited_linfo = prog->aux->jited_linfo;
11279 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
c4c0bdc0
YS
11280 num_exentries = 0;
11281 insn = func[i]->insnsi;
11282 for (j = 0; j < func[i]->len; j++, insn++) {
11283 if (BPF_CLASS(insn->code) == BPF_LDX &&
11284 BPF_MODE(insn->code) == BPF_PROBE_MEM)
11285 num_exentries++;
11286 }
11287 func[i]->aux->num_exentries = num_exentries;
ebf7d1f5 11288 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
1c2a088a
AS
11289 func[i] = bpf_int_jit_compile(func[i]);
11290 if (!func[i]->jited) {
11291 err = -ENOTSUPP;
11292 goto out_free;
11293 }
11294 cond_resched();
11295 }
a748c697
MF
11296
11297 /* Untrack main program's aux structs so that during map_poke_run()
11298 * we will not stumble upon the unfilled poke descriptors; each
11299 * of the main program's poke descs got distributed across subprogs
11300 * and got tracked onto map, so we are sure that none of them will
11301 * be missed after the operation below
11302 */
11303 for (i = 0; i < prog->aux->size_poke_tab; i++) {
11304 map_ptr = prog->aux->poke_tab[i].tail_call.map;
11305
11306 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
11307 }
11308
1c2a088a
AS
11309 /* at this point all bpf functions were successfully JITed
11310 * now populate all bpf_calls with correct addresses and
11311 * run last pass of JIT
11312 */
f910cefa 11313 for (i = 0; i < env->subprog_cnt; i++) {
1c2a088a
AS
11314 insn = func[i]->insnsi;
11315 for (j = 0; j < func[i]->len; j++, insn++) {
11316 if (insn->code != (BPF_JMP | BPF_CALL) ||
11317 insn->src_reg != BPF_PSEUDO_CALL)
11318 continue;
11319 subprog = insn->off;
0d306c31
PB
11320 insn->imm = BPF_CAST_CALL(func[subprog]->bpf_func) -
11321 __bpf_call_base;
1c2a088a 11322 }
2162fed4
SD
11323
11324 /* we use the aux data to keep a list of the start addresses
11325 * of the JITed images for each function in the program
11326 *
11327 * for some architectures, such as powerpc64, the imm field
11328 * might not be large enough to hold the offset of the start
11329 * address of the callee's JITed image from __bpf_call_base
11330 *
11331 * in such cases, we can lookup the start address of a callee
11332 * by using its subprog id, available from the off field of
11333 * the call instruction, as an index for this list
11334 */
11335 func[i]->aux->func = func;
11336 func[i]->aux->func_cnt = env->subprog_cnt;
1c2a088a 11337 }
f910cefa 11338 for (i = 0; i < env->subprog_cnt; i++) {
1c2a088a
AS
11339 old_bpf_func = func[i]->bpf_func;
11340 tmp = bpf_int_jit_compile(func[i]);
11341 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
11342 verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
c7a89784 11343 err = -ENOTSUPP;
1c2a088a
AS
11344 goto out_free;
11345 }
11346 cond_resched();
11347 }
11348
11349 /* finally lock prog and jit images for all functions and
11350 * populate kallsysm
11351 */
f910cefa 11352 for (i = 0; i < env->subprog_cnt; i++) {
1c2a088a
AS
11353 bpf_prog_lock_ro(func[i]);
11354 bpf_prog_kallsyms_add(func[i]);
11355 }
7105e828
DB
11356
11357 /* Last step: make now unused interpreter insns from main
11358 * prog consistent for later dump requests, so they can
11359 * later look the same as if they were interpreted only.
11360 */
11361 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
7105e828
DB
11362 if (insn->code != (BPF_JMP | BPF_CALL) ||
11363 insn->src_reg != BPF_PSEUDO_CALL)
11364 continue;
11365 insn->off = env->insn_aux_data[i].call_imm;
11366 subprog = find_subprog(env, i + insn->off + 1);
dbecd738 11367 insn->imm = subprog;
7105e828
DB
11368 }
11369
1c2a088a
AS
11370 prog->jited = 1;
11371 prog->bpf_func = func[0]->bpf_func;
11372 prog->aux->func = func;
f910cefa 11373 prog->aux->func_cnt = env->subprog_cnt;
c454a46b 11374 bpf_prog_free_unused_jited_linfo(prog);
1c2a088a
AS
11375 return 0;
11376out_free:
a748c697
MF
11377 for (i = 0; i < env->subprog_cnt; i++) {
11378 if (!func[i])
11379 continue;
11380
11381 for (j = 0; j < func[i]->aux->size_poke_tab; j++) {
11382 map_ptr = func[i]->aux->poke_tab[j].tail_call.map;
11383 map_ptr->ops->map_poke_untrack(map_ptr, func[i]->aux);
11384 }
11385 bpf_jit_free(func[i]);
11386 }
1c2a088a 11387 kfree(func);
c7a89784 11388out_undo_insn:
1c2a088a
AS
11389 /* cleanup main prog to be interpreted */
11390 prog->jit_requested = 0;
11391 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
11392 if (insn->code != (BPF_JMP | BPF_CALL) ||
11393 insn->src_reg != BPF_PSEUDO_CALL)
11394 continue;
11395 insn->off = 0;
11396 insn->imm = env->insn_aux_data[i].call_imm;
11397 }
c454a46b 11398 bpf_prog_free_jited_linfo(prog);
1c2a088a
AS
11399 return err;
11400}
11401
1ea47e01
AS
11402static int fixup_call_args(struct bpf_verifier_env *env)
11403{
19d28fbd 11404#ifndef CONFIG_BPF_JIT_ALWAYS_ON
1ea47e01
AS
11405 struct bpf_prog *prog = env->prog;
11406 struct bpf_insn *insn = prog->insnsi;
11407 int i, depth;
19d28fbd 11408#endif
e4052d06 11409 int err = 0;
1ea47e01 11410
e4052d06
QM
11411 if (env->prog->jit_requested &&
11412 !bpf_prog_is_dev_bound(env->prog->aux)) {
19d28fbd
DM
11413 err = jit_subprogs(env);
11414 if (err == 0)
1c2a088a 11415 return 0;
c7a89784
DB
11416 if (err == -EFAULT)
11417 return err;
19d28fbd
DM
11418 }
11419#ifndef CONFIG_BPF_JIT_ALWAYS_ON
e411901c
MF
11420 if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
11421 /* When JIT fails the progs with bpf2bpf calls and tail_calls
11422 * have to be rejected, since interpreter doesn't support them yet.
11423 */
11424 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
11425 return -EINVAL;
11426 }
1ea47e01
AS
11427 for (i = 0; i < prog->len; i++, insn++) {
11428 if (insn->code != (BPF_JMP | BPF_CALL) ||
11429 insn->src_reg != BPF_PSEUDO_CALL)
11430 continue;
11431 depth = get_callee_stack_depth(env, insn, i);
11432 if (depth < 0)
11433 return depth;
11434 bpf_patch_call_args(insn, depth);
11435 }
19d28fbd
DM
11436 err = 0;
11437#endif
11438 return err;
1ea47e01
AS
11439}
11440
79741b3b 11441/* fixup insn->imm field of bpf_call instructions
81ed18ab 11442 * and inline eligible helpers as explicit sequence of BPF instructions
e245c5c6
AS
11443 *
11444 * this function is called after eBPF program passed verification
11445 */
79741b3b 11446static int fixup_bpf_calls(struct bpf_verifier_env *env)
e245c5c6 11447{
79741b3b 11448 struct bpf_prog *prog = env->prog;
d2e4c1e6 11449 bool expect_blinding = bpf_jit_blinding_enabled(prog);
79741b3b 11450 struct bpf_insn *insn = prog->insnsi;
e245c5c6 11451 const struct bpf_func_proto *fn;
79741b3b 11452 const int insn_cnt = prog->len;
09772d92 11453 const struct bpf_map_ops *ops;
c93552c4 11454 struct bpf_insn_aux_data *aux;
81ed18ab
AS
11455 struct bpf_insn insn_buf[16];
11456 struct bpf_prog *new_prog;
11457 struct bpf_map *map_ptr;
d2e4c1e6 11458 int i, ret, cnt, delta = 0;
e245c5c6 11459
79741b3b 11460 for (i = 0; i < insn_cnt; i++, insn++) {
f6b1b3bf
DB
11461 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
11462 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
11463 insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
68fda450 11464 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
f6b1b3bf 11465 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
e88b2c6e
DB
11466 bool isdiv = BPF_OP(insn->code) == BPF_DIV;
11467 struct bpf_insn *patchlet;
11468 struct bpf_insn chk_and_div[] = {
f62c9df2 11469 /* [R,W]x div 0 -> 0 */
e88b2c6e
DB
11470 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
11471 BPF_JNE | BPF_K, insn->src_reg,
11472 0, 2, 0),
f6b1b3bf
DB
11473 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
11474 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
11475 *insn,
11476 };
e88b2c6e 11477 struct bpf_insn chk_and_mod[] = {
f62c9df2 11478 /* [R,W]x mod 0 -> [R,W]x */
e88b2c6e
DB
11479 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
11480 BPF_JEQ | BPF_K, insn->src_reg,
f62c9df2 11481 0, 1 + (is64 ? 0 : 1), 0),
f6b1b3bf 11482 *insn,
f62c9df2
DB
11483 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
11484 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
f6b1b3bf 11485 };
f6b1b3bf 11486
e88b2c6e
DB
11487 patchlet = isdiv ? chk_and_div : chk_and_mod;
11488 cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
f62c9df2 11489 ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
f6b1b3bf
DB
11490
11491 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
68fda450
AS
11492 if (!new_prog)
11493 return -ENOMEM;
11494
11495 delta += cnt - 1;
11496 env->prog = prog = new_prog;
11497 insn = new_prog->insnsi + i + delta;
11498 continue;
11499 }
11500
e0cea7ce
DB
11501 if (BPF_CLASS(insn->code) == BPF_LD &&
11502 (BPF_MODE(insn->code) == BPF_ABS ||
11503 BPF_MODE(insn->code) == BPF_IND)) {
11504 cnt = env->ops->gen_ld_abs(insn, insn_buf);
11505 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
11506 verbose(env, "bpf verifier is misconfigured\n");
11507 return -EINVAL;
11508 }
11509
11510 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
11511 if (!new_prog)
11512 return -ENOMEM;
11513
11514 delta += cnt - 1;
11515 env->prog = prog = new_prog;
11516 insn = new_prog->insnsi + i + delta;
11517 continue;
11518 }
11519
979d63d5
DB
11520 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
11521 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
11522 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
11523 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
11524 struct bpf_insn insn_buf[16];
11525 struct bpf_insn *patch = &insn_buf[0];
d4bad720 11526 bool issrc, isneg, isimm;
979d63d5
DB
11527 u32 off_reg;
11528
11529 aux = &env->insn_aux_data[i + delta];
3612af78
DB
11530 if (!aux->alu_state ||
11531 aux->alu_state == BPF_ALU_NON_POINTER)
979d63d5
DB
11532 continue;
11533
11534 isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
11535 issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
11536 BPF_ALU_SANITIZE_SRC;
d4bad720 11537 isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
979d63d5
DB
11538
11539 off_reg = issrc ? insn->src_reg : insn->dst_reg;
d4bad720
DB
11540 if (isimm) {
11541 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
11542 } else {
11543 if (isneg)
11544 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
11545 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
11546 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
11547 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
11548 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
11549 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
11550 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
11551 }
714bbfae
DB
11552 if (!issrc)
11553 *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
11554 insn->src_reg = BPF_REG_AX;
979d63d5
DB
11555 if (isneg)
11556 insn->code = insn->code == code_add ?
11557 code_sub : code_add;
11558 *patch++ = *insn;
d4bad720 11559 if (issrc && isneg && !isimm)
979d63d5
DB
11560 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
11561 cnt = patch - insn_buf;
11562
11563 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
11564 if (!new_prog)
11565 return -ENOMEM;
11566
11567 delta += cnt - 1;
11568 env->prog = prog = new_prog;
11569 insn = new_prog->insnsi + i + delta;
11570 continue;
11571 }
11572
79741b3b
AS
11573 if (insn->code != (BPF_JMP | BPF_CALL))
11574 continue;
cc8b0b92
AS
11575 if (insn->src_reg == BPF_PSEUDO_CALL)
11576 continue;
e245c5c6 11577
79741b3b
AS
11578 if (insn->imm == BPF_FUNC_get_route_realm)
11579 prog->dst_needed = 1;
11580 if (insn->imm == BPF_FUNC_get_prandom_u32)
11581 bpf_user_rnd_init_once();
9802d865
JB
11582 if (insn->imm == BPF_FUNC_override_return)
11583 prog->kprobe_override = 1;
79741b3b 11584 if (insn->imm == BPF_FUNC_tail_call) {
7b9f6da1
DM
11585 /* If we tail call into other programs, we
11586 * cannot make any assumptions since they can
11587 * be replaced dynamically during runtime in
11588 * the program array.
11589 */
11590 prog->cb_access = 1;
e411901c
MF
11591 if (!allow_tail_call_in_subprogs(env))
11592 prog->aux->stack_depth = MAX_BPF_STACK;
11593 prog->aux->max_pkt_offset = MAX_PACKET_OFF;
7b9f6da1 11594
79741b3b
AS
11595 /* mark bpf_tail_call as different opcode to avoid
11596 * conditional branch in the interpeter for every normal
11597 * call and to prevent accidental JITing by JIT compiler
11598 * that doesn't support bpf_tail_call yet
e245c5c6 11599 */
79741b3b 11600 insn->imm = 0;
71189fa9 11601 insn->code = BPF_JMP | BPF_TAIL_CALL;
b2157399 11602
c93552c4 11603 aux = &env->insn_aux_data[i + delta];
2c78ee89 11604 if (env->bpf_capable && !expect_blinding &&
cc52d914 11605 prog->jit_requested &&
d2e4c1e6
DB
11606 !bpf_map_key_poisoned(aux) &&
11607 !bpf_map_ptr_poisoned(aux) &&
11608 !bpf_map_ptr_unpriv(aux)) {
11609 struct bpf_jit_poke_descriptor desc = {
11610 .reason = BPF_POKE_REASON_TAIL_CALL,
11611 .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
11612 .tail_call.key = bpf_map_key_immediate(aux),
a748c697 11613 .insn_idx = i + delta,
d2e4c1e6
DB
11614 };
11615
11616 ret = bpf_jit_add_poke_descriptor(prog, &desc);
11617 if (ret < 0) {
11618 verbose(env, "adding tail call poke descriptor failed\n");
11619 return ret;
11620 }
11621
11622 insn->imm = ret + 1;
11623 continue;
11624 }
11625
c93552c4
DB
11626 if (!bpf_map_ptr_unpriv(aux))
11627 continue;
11628
b2157399
AS
11629 /* instead of changing every JIT dealing with tail_call
11630 * emit two extra insns:
11631 * if (index >= max_entries) goto out;
11632 * index &= array->index_mask;
11633 * to avoid out-of-bounds cpu speculation
11634 */
c93552c4 11635 if (bpf_map_ptr_poisoned(aux)) {
40950343 11636 verbose(env, "tail_call abusing map_ptr\n");
b2157399
AS
11637 return -EINVAL;
11638 }
c93552c4 11639
d2e4c1e6 11640 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
b2157399
AS
11641 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
11642 map_ptr->max_entries, 2);
11643 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
11644 container_of(map_ptr,
11645 struct bpf_array,
11646 map)->index_mask);
11647 insn_buf[2] = *insn;
11648 cnt = 3;
11649 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
11650 if (!new_prog)
11651 return -ENOMEM;
11652
11653 delta += cnt - 1;
11654 env->prog = prog = new_prog;
11655 insn = new_prog->insnsi + i + delta;
79741b3b
AS
11656 continue;
11657 }
e245c5c6 11658
89c63074 11659 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
09772d92
DB
11660 * and other inlining handlers are currently limited to 64 bit
11661 * only.
89c63074 11662 */
60b58afc 11663 if (prog->jit_requested && BITS_PER_LONG == 64 &&
09772d92
DB
11664 (insn->imm == BPF_FUNC_map_lookup_elem ||
11665 insn->imm == BPF_FUNC_map_update_elem ||
84430d42
DB
11666 insn->imm == BPF_FUNC_map_delete_elem ||
11667 insn->imm == BPF_FUNC_map_push_elem ||
11668 insn->imm == BPF_FUNC_map_pop_elem ||
11669 insn->imm == BPF_FUNC_map_peek_elem)) {
c93552c4
DB
11670 aux = &env->insn_aux_data[i + delta];
11671 if (bpf_map_ptr_poisoned(aux))
11672 goto patch_call_imm;
11673
d2e4c1e6 11674 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
09772d92
DB
11675 ops = map_ptr->ops;
11676 if (insn->imm == BPF_FUNC_map_lookup_elem &&
11677 ops->map_gen_lookup) {
11678 cnt = ops->map_gen_lookup(map_ptr, insn_buf);
4a8f87e6
DB
11679 if (cnt == -EOPNOTSUPP)
11680 goto patch_map_ops_generic;
11681 if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
09772d92
DB
11682 verbose(env, "bpf verifier is misconfigured\n");
11683 return -EINVAL;
11684 }
81ed18ab 11685
09772d92
DB
11686 new_prog = bpf_patch_insn_data(env, i + delta,
11687 insn_buf, cnt);
11688 if (!new_prog)
11689 return -ENOMEM;
81ed18ab 11690
09772d92
DB
11691 delta += cnt - 1;
11692 env->prog = prog = new_prog;
11693 insn = new_prog->insnsi + i + delta;
11694 continue;
11695 }
81ed18ab 11696
09772d92
DB
11697 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
11698 (void *(*)(struct bpf_map *map, void *key))NULL));
11699 BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
11700 (int (*)(struct bpf_map *map, void *key))NULL));
11701 BUILD_BUG_ON(!__same_type(ops->map_update_elem,
11702 (int (*)(struct bpf_map *map, void *key, void *value,
11703 u64 flags))NULL));
84430d42
DB
11704 BUILD_BUG_ON(!__same_type(ops->map_push_elem,
11705 (int (*)(struct bpf_map *map, void *value,
11706 u64 flags))NULL));
11707 BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
11708 (int (*)(struct bpf_map *map, void *value))NULL));
11709 BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
11710 (int (*)(struct bpf_map *map, void *value))NULL));
4a8f87e6 11711patch_map_ops_generic:
09772d92
DB
11712 switch (insn->imm) {
11713 case BPF_FUNC_map_lookup_elem:
11714 insn->imm = BPF_CAST_CALL(ops->map_lookup_elem) -
11715 __bpf_call_base;
11716 continue;
11717 case BPF_FUNC_map_update_elem:
11718 insn->imm = BPF_CAST_CALL(ops->map_update_elem) -
11719 __bpf_call_base;
11720 continue;
11721 case BPF_FUNC_map_delete_elem:
11722 insn->imm = BPF_CAST_CALL(ops->map_delete_elem) -
11723 __bpf_call_base;
11724 continue;
84430d42
DB
11725 case BPF_FUNC_map_push_elem:
11726 insn->imm = BPF_CAST_CALL(ops->map_push_elem) -
11727 __bpf_call_base;
11728 continue;
11729 case BPF_FUNC_map_pop_elem:
11730 insn->imm = BPF_CAST_CALL(ops->map_pop_elem) -
11731 __bpf_call_base;
11732 continue;
11733 case BPF_FUNC_map_peek_elem:
11734 insn->imm = BPF_CAST_CALL(ops->map_peek_elem) -
11735 __bpf_call_base;
11736 continue;
09772d92 11737 }
81ed18ab 11738
09772d92 11739 goto patch_call_imm;
81ed18ab
AS
11740 }
11741
5576b991
MKL
11742 if (prog->jit_requested && BITS_PER_LONG == 64 &&
11743 insn->imm == BPF_FUNC_jiffies64) {
11744 struct bpf_insn ld_jiffies_addr[2] = {
11745 BPF_LD_IMM64(BPF_REG_0,
11746 (unsigned long)&jiffies),
11747 };
11748
11749 insn_buf[0] = ld_jiffies_addr[0];
11750 insn_buf[1] = ld_jiffies_addr[1];
11751 insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
11752 BPF_REG_0, 0);
11753 cnt = 3;
11754
11755 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
11756 cnt);
11757 if (!new_prog)
11758 return -ENOMEM;
11759
11760 delta += cnt - 1;
11761 env->prog = prog = new_prog;
11762 insn = new_prog->insnsi + i + delta;
11763 continue;
11764 }
11765
81ed18ab 11766patch_call_imm:
5e43f899 11767 fn = env->ops->get_func_proto(insn->imm, env->prog);
79741b3b
AS
11768 /* all functions that have prototype and verifier allowed
11769 * programs to call them, must be real in-kernel functions
11770 */
11771 if (!fn->func) {
61bd5218
JK
11772 verbose(env,
11773 "kernel subsystem misconfigured func %s#%d\n",
79741b3b
AS
11774 func_id_name(insn->imm), insn->imm);
11775 return -EFAULT;
e245c5c6 11776 }
79741b3b 11777 insn->imm = fn->func - __bpf_call_base;
e245c5c6 11778 }
e245c5c6 11779
d2e4c1e6
DB
11780 /* Since poke tab is now finalized, publish aux to tracker. */
11781 for (i = 0; i < prog->aux->size_poke_tab; i++) {
11782 map_ptr = prog->aux->poke_tab[i].tail_call.map;
11783 if (!map_ptr->ops->map_poke_track ||
11784 !map_ptr->ops->map_poke_untrack ||
11785 !map_ptr->ops->map_poke_run) {
11786 verbose(env, "bpf verifier is misconfigured\n");
11787 return -EINVAL;
11788 }
11789
11790 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
11791 if (ret < 0) {
11792 verbose(env, "tracking tail call prog failed\n");
11793 return ret;
11794 }
11795 }
11796
79741b3b
AS
11797 return 0;
11798}
e245c5c6 11799
58e2af8b 11800static void free_states(struct bpf_verifier_env *env)
f1bca824 11801{
58e2af8b 11802 struct bpf_verifier_state_list *sl, *sln;
f1bca824
AS
11803 int i;
11804
9f4686c4
AS
11805 sl = env->free_list;
11806 while (sl) {
11807 sln = sl->next;
11808 free_verifier_state(&sl->state, false);
11809 kfree(sl);
11810 sl = sln;
11811 }
51c39bb1 11812 env->free_list = NULL;
9f4686c4 11813
f1bca824
AS
11814 if (!env->explored_states)
11815 return;
11816
dc2a4ebc 11817 for (i = 0; i < state_htab_size(env); i++) {
f1bca824
AS
11818 sl = env->explored_states[i];
11819
a8f500af
AS
11820 while (sl) {
11821 sln = sl->next;
11822 free_verifier_state(&sl->state, false);
11823 kfree(sl);
11824 sl = sln;
11825 }
51c39bb1 11826 env->explored_states[i] = NULL;
f1bca824 11827 }
51c39bb1 11828}
f1bca824 11829
51c39bb1
AS
11830/* The verifier is using insn_aux_data[] to store temporary data during
11831 * verification and to store information for passes that run after the
11832 * verification like dead code sanitization. do_check_common() for subprogram N
11833 * may analyze many other subprograms. sanitize_insn_aux_data() clears all
11834 * temporary data after do_check_common() finds that subprogram N cannot be
11835 * verified independently. pass_cnt counts the number of times
11836 * do_check_common() was run and insn->aux->seen tells the pass number
11837 * insn_aux_data was touched. These variables are compared to clear temporary
11838 * data from failed pass. For testing and experiments do_check_common() can be
11839 * run multiple times even when prior attempt to verify is unsuccessful.
11840 */
11841static void sanitize_insn_aux_data(struct bpf_verifier_env *env)
11842{
11843 struct bpf_insn *insn = env->prog->insnsi;
11844 struct bpf_insn_aux_data *aux;
11845 int i, class;
11846
11847 for (i = 0; i < env->prog->len; i++) {
11848 class = BPF_CLASS(insn[i].code);
11849 if (class != BPF_LDX && class != BPF_STX)
11850 continue;
11851 aux = &env->insn_aux_data[i];
11852 if (aux->seen != env->pass_cnt)
11853 continue;
11854 memset(aux, 0, offsetof(typeof(*aux), orig_idx));
11855 }
f1bca824
AS
11856}
11857
51c39bb1
AS
11858static int do_check_common(struct bpf_verifier_env *env, int subprog)
11859{
6f8a57cc 11860 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
51c39bb1
AS
11861 struct bpf_verifier_state *state;
11862 struct bpf_reg_state *regs;
11863 int ret, i;
11864
11865 env->prev_linfo = NULL;
11866 env->pass_cnt++;
11867
11868 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
11869 if (!state)
11870 return -ENOMEM;
11871 state->curframe = 0;
11872 state->speculative = false;
11873 state->branches = 1;
11874 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
11875 if (!state->frame[0]) {
11876 kfree(state);
11877 return -ENOMEM;
11878 }
11879 env->cur_state = state;
11880 init_func_state(env, state->frame[0],
11881 BPF_MAIN_FUNC /* callsite */,
11882 0 /* frameno */,
11883 subprog);
11884
11885 regs = state->frame[state->curframe]->regs;
be8704ff 11886 if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
51c39bb1
AS
11887 ret = btf_prepare_func_args(env, subprog, regs);
11888 if (ret)
11889 goto out;
11890 for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
11891 if (regs[i].type == PTR_TO_CTX)
11892 mark_reg_known_zero(env, regs, i);
11893 else if (regs[i].type == SCALAR_VALUE)
11894 mark_reg_unknown(env, regs, i);
11895 }
11896 } else {
11897 /* 1st arg to a function */
11898 regs[BPF_REG_1].type = PTR_TO_CTX;
11899 mark_reg_known_zero(env, regs, BPF_REG_1);
11900 ret = btf_check_func_arg_match(env, subprog, regs);
11901 if (ret == -EFAULT)
11902 /* unlikely verifier bug. abort.
11903 * ret == 0 and ret < 0 are sadly acceptable for
11904 * main() function due to backward compatibility.
11905 * Like socket filter program may be written as:
11906 * int bpf_prog(struct pt_regs *ctx)
11907 * and never dereference that ctx in the program.
11908 * 'struct pt_regs' is a type mismatch for socket
11909 * filter that should be using 'struct __sk_buff'.
11910 */
11911 goto out;
11912 }
11913
11914 ret = do_check(env);
11915out:
f59bbfc2
AS
11916 /* check for NULL is necessary, since cur_state can be freed inside
11917 * do_check() under memory pressure.
11918 */
11919 if (env->cur_state) {
11920 free_verifier_state(env->cur_state, true);
11921 env->cur_state = NULL;
11922 }
6f8a57cc
AN
11923 while (!pop_stack(env, NULL, NULL, false));
11924 if (!ret && pop_log)
11925 bpf_vlog_reset(&env->log, 0);
51c39bb1
AS
11926 free_states(env);
11927 if (ret)
11928 /* clean aux data in case subprog was rejected */
11929 sanitize_insn_aux_data(env);
11930 return ret;
11931}
11932
11933/* Verify all global functions in a BPF program one by one based on their BTF.
11934 * All global functions must pass verification. Otherwise the whole program is rejected.
11935 * Consider:
11936 * int bar(int);
11937 * int foo(int f)
11938 * {
11939 * return bar(f);
11940 * }
11941 * int bar(int b)
11942 * {
11943 * ...
11944 * }
11945 * foo() will be verified first for R1=any_scalar_value. During verification it
11946 * will be assumed that bar() already verified successfully and call to bar()
11947 * from foo() will be checked for type match only. Later bar() will be verified
11948 * independently to check that it's safe for R1=any_scalar_value.
11949 */
11950static int do_check_subprogs(struct bpf_verifier_env *env)
11951{
11952 struct bpf_prog_aux *aux = env->prog->aux;
11953 int i, ret;
11954
11955 if (!aux->func_info)
11956 return 0;
11957
11958 for (i = 1; i < env->subprog_cnt; i++) {
11959 if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
11960 continue;
11961 env->insn_idx = env->subprog_info[i].start;
11962 WARN_ON_ONCE(env->insn_idx == 0);
11963 ret = do_check_common(env, i);
11964 if (ret) {
11965 return ret;
11966 } else if (env->log.level & BPF_LOG_LEVEL) {
11967 verbose(env,
11968 "Func#%d is safe for any args that match its prototype\n",
11969 i);
11970 }
11971 }
11972 return 0;
11973}
11974
11975static int do_check_main(struct bpf_verifier_env *env)
11976{
11977 int ret;
11978
11979 env->insn_idx = 0;
11980 ret = do_check_common(env, 0);
11981 if (!ret)
11982 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
11983 return ret;
11984}
11985
11986
06ee7115
AS
11987static void print_verification_stats(struct bpf_verifier_env *env)
11988{
11989 int i;
11990
11991 if (env->log.level & BPF_LOG_STATS) {
11992 verbose(env, "verification time %lld usec\n",
11993 div_u64(env->verification_time, 1000));
11994 verbose(env, "stack depth ");
11995 for (i = 0; i < env->subprog_cnt; i++) {
11996 u32 depth = env->subprog_info[i].stack_depth;
11997
11998 verbose(env, "%d", depth);
11999 if (i + 1 < env->subprog_cnt)
12000 verbose(env, "+");
12001 }
12002 verbose(env, "\n");
12003 }
12004 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
12005 "total_states %d peak_states %d mark_read %d\n",
12006 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
12007 env->max_states_per_insn, env->total_states,
12008 env->peak_states, env->longest_mark_read_walk);
f1bca824
AS
12009}
12010
27ae7997
MKL
12011static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
12012{
12013 const struct btf_type *t, *func_proto;
12014 const struct bpf_struct_ops *st_ops;
12015 const struct btf_member *member;
12016 struct bpf_prog *prog = env->prog;
12017 u32 btf_id, member_idx;
12018 const char *mname;
12019
ddc0da05
THJ
12020 if (!prog->gpl_compatible) {
12021 verbose(env, "struct ops programs must have a GPL compatible license\n");
12022 return -EINVAL;
12023 }
12024
27ae7997
MKL
12025 btf_id = prog->aux->attach_btf_id;
12026 st_ops = bpf_struct_ops_find(btf_id);
12027 if (!st_ops) {
12028 verbose(env, "attach_btf_id %u is not a supported struct\n",
12029 btf_id);
12030 return -ENOTSUPP;
12031 }
12032
12033 t = st_ops->type;
12034 member_idx = prog->expected_attach_type;
12035 if (member_idx >= btf_type_vlen(t)) {
12036 verbose(env, "attach to invalid member idx %u of struct %s\n",
12037 member_idx, st_ops->name);
12038 return -EINVAL;
12039 }
12040
12041 member = &btf_type_member(t)[member_idx];
12042 mname = btf_name_by_offset(btf_vmlinux, member->name_off);
12043 func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
12044 NULL);
12045 if (!func_proto) {
12046 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
12047 mname, member_idx, st_ops->name);
12048 return -EINVAL;
12049 }
12050
12051 if (st_ops->check_member) {
12052 int err = st_ops->check_member(t, member);
12053
12054 if (err) {
12055 verbose(env, "attach to unsupported member %s of struct %s\n",
12056 mname, st_ops->name);
12057 return err;
12058 }
12059 }
12060
12061 prog->aux->attach_func_proto = func_proto;
12062 prog->aux->attach_func_name = mname;
12063 env->ops = st_ops->verifier_ops;
12064
12065 return 0;
12066}
6ba43b76
KS
12067#define SECURITY_PREFIX "security_"
12068
f7b12b6f 12069static int check_attach_modify_return(unsigned long addr, const char *func_name)
6ba43b76 12070{
69191754 12071 if (within_error_injection_list(addr) ||
f7b12b6f 12072 !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
6ba43b76 12073 return 0;
6ba43b76 12074
6ba43b76
KS
12075 return -EINVAL;
12076}
27ae7997 12077
1e6c62a8
AS
12078/* list of non-sleepable functions that are otherwise on
12079 * ALLOW_ERROR_INJECTION list
12080 */
12081BTF_SET_START(btf_non_sleepable_error_inject)
12082/* Three functions below can be called from sleepable and non-sleepable context.
12083 * Assume non-sleepable from bpf safety point of view.
12084 */
12085BTF_ID(func, __add_to_page_cache_locked)
12086BTF_ID(func, should_fail_alloc_page)
12087BTF_ID(func, should_failslab)
12088BTF_SET_END(btf_non_sleepable_error_inject)
12089
12090static int check_non_sleepable_error_inject(u32 btf_id)
12091{
12092 return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
12093}
12094
f7b12b6f
THJ
12095int bpf_check_attach_target(struct bpf_verifier_log *log,
12096 const struct bpf_prog *prog,
12097 const struct bpf_prog *tgt_prog,
12098 u32 btf_id,
12099 struct bpf_attach_target_info *tgt_info)
38207291 12100{
be8704ff 12101 bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
f1b9509c 12102 const char prefix[] = "btf_trace_";
5b92a28a 12103 int ret = 0, subprog = -1, i;
38207291 12104 const struct btf_type *t;
5b92a28a 12105 bool conservative = true;
38207291 12106 const char *tname;
5b92a28a 12107 struct btf *btf;
f7b12b6f 12108 long addr = 0;
38207291 12109
f1b9509c 12110 if (!btf_id) {
efc68158 12111 bpf_log(log, "Tracing programs must provide btf_id\n");
f1b9509c
AS
12112 return -EINVAL;
12113 }
22dc4a0f 12114 btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
5b92a28a 12115 if (!btf) {
efc68158 12116 bpf_log(log,
5b92a28a
AS
12117 "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
12118 return -EINVAL;
12119 }
12120 t = btf_type_by_id(btf, btf_id);
f1b9509c 12121 if (!t) {
efc68158 12122 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
f1b9509c
AS
12123 return -EINVAL;
12124 }
5b92a28a 12125 tname = btf_name_by_offset(btf, t->name_off);
f1b9509c 12126 if (!tname) {
efc68158 12127 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
f1b9509c
AS
12128 return -EINVAL;
12129 }
5b92a28a
AS
12130 if (tgt_prog) {
12131 struct bpf_prog_aux *aux = tgt_prog->aux;
12132
12133 for (i = 0; i < aux->func_info_cnt; i++)
12134 if (aux->func_info[i].type_id == btf_id) {
12135 subprog = i;
12136 break;
12137 }
12138 if (subprog == -1) {
efc68158 12139 bpf_log(log, "Subprog %s doesn't exist\n", tname);
5b92a28a
AS
12140 return -EINVAL;
12141 }
12142 conservative = aux->func_info_aux[subprog].unreliable;
be8704ff
AS
12143 if (prog_extension) {
12144 if (conservative) {
efc68158 12145 bpf_log(log,
be8704ff
AS
12146 "Cannot replace static functions\n");
12147 return -EINVAL;
12148 }
12149 if (!prog->jit_requested) {
efc68158 12150 bpf_log(log,
be8704ff
AS
12151 "Extension programs should be JITed\n");
12152 return -EINVAL;
12153 }
be8704ff
AS
12154 }
12155 if (!tgt_prog->jited) {
efc68158 12156 bpf_log(log, "Can attach to only JITed progs\n");
be8704ff
AS
12157 return -EINVAL;
12158 }
12159 if (tgt_prog->type == prog->type) {
12160 /* Cannot fentry/fexit another fentry/fexit program.
12161 * Cannot attach program extension to another extension.
12162 * It's ok to attach fentry/fexit to extension program.
12163 */
efc68158 12164 bpf_log(log, "Cannot recursively attach\n");
be8704ff
AS
12165 return -EINVAL;
12166 }
12167 if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
12168 prog_extension &&
12169 (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
12170 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
12171 /* Program extensions can extend all program types
12172 * except fentry/fexit. The reason is the following.
12173 * The fentry/fexit programs are used for performance
12174 * analysis, stats and can be attached to any program
12175 * type except themselves. When extension program is
12176 * replacing XDP function it is necessary to allow
12177 * performance analysis of all functions. Both original
12178 * XDP program and its program extension. Hence
12179 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
12180 * allowed. If extending of fentry/fexit was allowed it
12181 * would be possible to create long call chain
12182 * fentry->extension->fentry->extension beyond
12183 * reasonable stack size. Hence extending fentry is not
12184 * allowed.
12185 */
efc68158 12186 bpf_log(log, "Cannot extend fentry/fexit\n");
be8704ff
AS
12187 return -EINVAL;
12188 }
5b92a28a 12189 } else {
be8704ff 12190 if (prog_extension) {
efc68158 12191 bpf_log(log, "Cannot replace kernel functions\n");
be8704ff
AS
12192 return -EINVAL;
12193 }
5b92a28a 12194 }
f1b9509c
AS
12195
12196 switch (prog->expected_attach_type) {
12197 case BPF_TRACE_RAW_TP:
5b92a28a 12198 if (tgt_prog) {
efc68158 12199 bpf_log(log,
5b92a28a
AS
12200 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
12201 return -EINVAL;
12202 }
38207291 12203 if (!btf_type_is_typedef(t)) {
efc68158 12204 bpf_log(log, "attach_btf_id %u is not a typedef\n",
38207291
MKL
12205 btf_id);
12206 return -EINVAL;
12207 }
f1b9509c 12208 if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
efc68158 12209 bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
38207291
MKL
12210 btf_id, tname);
12211 return -EINVAL;
12212 }
12213 tname += sizeof(prefix) - 1;
5b92a28a 12214 t = btf_type_by_id(btf, t->type);
38207291
MKL
12215 if (!btf_type_is_ptr(t))
12216 /* should never happen in valid vmlinux build */
12217 return -EINVAL;
5b92a28a 12218 t = btf_type_by_id(btf, t->type);
38207291
MKL
12219 if (!btf_type_is_func_proto(t))
12220 /* should never happen in valid vmlinux build */
12221 return -EINVAL;
12222
f7b12b6f 12223 break;
15d83c4d
YS
12224 case BPF_TRACE_ITER:
12225 if (!btf_type_is_func(t)) {
efc68158 12226 bpf_log(log, "attach_btf_id %u is not a function\n",
15d83c4d
YS
12227 btf_id);
12228 return -EINVAL;
12229 }
12230 t = btf_type_by_id(btf, t->type);
12231 if (!btf_type_is_func_proto(t))
12232 return -EINVAL;
f7b12b6f
THJ
12233 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
12234 if (ret)
12235 return ret;
12236 break;
be8704ff
AS
12237 default:
12238 if (!prog_extension)
12239 return -EINVAL;
df561f66 12240 fallthrough;
ae240823 12241 case BPF_MODIFY_RETURN:
9e4e01df 12242 case BPF_LSM_MAC:
fec56f58
AS
12243 case BPF_TRACE_FENTRY:
12244 case BPF_TRACE_FEXIT:
12245 if (!btf_type_is_func(t)) {
efc68158 12246 bpf_log(log, "attach_btf_id %u is not a function\n",
fec56f58
AS
12247 btf_id);
12248 return -EINVAL;
12249 }
be8704ff 12250 if (prog_extension &&
efc68158 12251 btf_check_type_match(log, prog, btf, t))
be8704ff 12252 return -EINVAL;
5b92a28a 12253 t = btf_type_by_id(btf, t->type);
fec56f58
AS
12254 if (!btf_type_is_func_proto(t))
12255 return -EINVAL;
f7b12b6f 12256
4a1e7c0c
THJ
12257 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
12258 (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
12259 prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
12260 return -EINVAL;
12261
f7b12b6f 12262 if (tgt_prog && conservative)
5b92a28a 12263 t = NULL;
f7b12b6f
THJ
12264
12265 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
fec56f58 12266 if (ret < 0)
f7b12b6f
THJ
12267 return ret;
12268
5b92a28a 12269 if (tgt_prog) {
e9eeec58
YS
12270 if (subprog == 0)
12271 addr = (long) tgt_prog->bpf_func;
12272 else
12273 addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
5b92a28a
AS
12274 } else {
12275 addr = kallsyms_lookup_name(tname);
12276 if (!addr) {
efc68158 12277 bpf_log(log,
5b92a28a
AS
12278 "The address of function %s cannot be found\n",
12279 tname);
f7b12b6f 12280 return -ENOENT;
5b92a28a 12281 }
fec56f58 12282 }
18644cec 12283
1e6c62a8
AS
12284 if (prog->aux->sleepable) {
12285 ret = -EINVAL;
12286 switch (prog->type) {
12287 case BPF_PROG_TYPE_TRACING:
12288 /* fentry/fexit/fmod_ret progs can be sleepable only if they are
12289 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
12290 */
12291 if (!check_non_sleepable_error_inject(btf_id) &&
12292 within_error_injection_list(addr))
12293 ret = 0;
12294 break;
12295 case BPF_PROG_TYPE_LSM:
12296 /* LSM progs check that they are attached to bpf_lsm_*() funcs.
12297 * Only some of them are sleepable.
12298 */
423f1610 12299 if (bpf_lsm_is_sleepable_hook(btf_id))
1e6c62a8
AS
12300 ret = 0;
12301 break;
12302 default:
12303 break;
12304 }
f7b12b6f
THJ
12305 if (ret) {
12306 bpf_log(log, "%s is not sleepable\n", tname);
12307 return ret;
12308 }
1e6c62a8 12309 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
1af9270e 12310 if (tgt_prog) {
efc68158 12311 bpf_log(log, "can't modify return codes of BPF programs\n");
f7b12b6f
THJ
12312 return -EINVAL;
12313 }
12314 ret = check_attach_modify_return(addr, tname);
12315 if (ret) {
12316 bpf_log(log, "%s() is not modifiable\n", tname);
12317 return ret;
1af9270e 12318 }
18644cec 12319 }
f7b12b6f
THJ
12320
12321 break;
12322 }
12323 tgt_info->tgt_addr = addr;
12324 tgt_info->tgt_name = tname;
12325 tgt_info->tgt_type = t;
12326 return 0;
12327}
12328
12329static int check_attach_btf_id(struct bpf_verifier_env *env)
12330{
12331 struct bpf_prog *prog = env->prog;
3aac1ead 12332 struct bpf_prog *tgt_prog = prog->aux->dst_prog;
f7b12b6f
THJ
12333 struct bpf_attach_target_info tgt_info = {};
12334 u32 btf_id = prog->aux->attach_btf_id;
12335 struct bpf_trampoline *tr;
12336 int ret;
12337 u64 key;
12338
12339 if (prog->aux->sleepable && prog->type != BPF_PROG_TYPE_TRACING &&
12340 prog->type != BPF_PROG_TYPE_LSM) {
12341 verbose(env, "Only fentry/fexit/fmod_ret and lsm programs can be sleepable\n");
12342 return -EINVAL;
12343 }
12344
12345 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
12346 return check_struct_ops_btf_id(env);
12347
12348 if (prog->type != BPF_PROG_TYPE_TRACING &&
12349 prog->type != BPF_PROG_TYPE_LSM &&
12350 prog->type != BPF_PROG_TYPE_EXT)
12351 return 0;
12352
12353 ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
12354 if (ret)
fec56f58 12355 return ret;
f7b12b6f
THJ
12356
12357 if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
3aac1ead
THJ
12358 /* to make freplace equivalent to their targets, they need to
12359 * inherit env->ops and expected_attach_type for the rest of the
12360 * verification
12361 */
f7b12b6f
THJ
12362 env->ops = bpf_verifier_ops[tgt_prog->type];
12363 prog->expected_attach_type = tgt_prog->expected_attach_type;
12364 }
12365
12366 /* store info about the attachment target that will be used later */
12367 prog->aux->attach_func_proto = tgt_info.tgt_type;
12368 prog->aux->attach_func_name = tgt_info.tgt_name;
12369
4a1e7c0c
THJ
12370 if (tgt_prog) {
12371 prog->aux->saved_dst_prog_type = tgt_prog->type;
12372 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
12373 }
12374
f7b12b6f
THJ
12375 if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
12376 prog->aux->attach_btf_trace = true;
12377 return 0;
12378 } else if (prog->expected_attach_type == BPF_TRACE_ITER) {
12379 if (!bpf_iter_prog_supported(prog))
12380 return -EINVAL;
12381 return 0;
12382 }
12383
12384 if (prog->type == BPF_PROG_TYPE_LSM) {
12385 ret = bpf_lsm_verify_prog(&env->log, prog);
12386 if (ret < 0)
12387 return ret;
38207291 12388 }
f7b12b6f 12389
22dc4a0f 12390 key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
f7b12b6f
THJ
12391 tr = bpf_trampoline_get(key, &tgt_info);
12392 if (!tr)
12393 return -ENOMEM;
12394
3aac1ead 12395 prog->aux->dst_trampoline = tr;
f7b12b6f 12396 return 0;
38207291
MKL
12397}
12398
76654e67
AM
12399struct btf *bpf_get_btf_vmlinux(void)
12400{
12401 if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
12402 mutex_lock(&bpf_verifier_lock);
12403 if (!btf_vmlinux)
12404 btf_vmlinux = btf_parse_vmlinux();
12405 mutex_unlock(&bpf_verifier_lock);
12406 }
12407 return btf_vmlinux;
12408}
12409
838e9690
YS
12410int bpf_check(struct bpf_prog **prog, union bpf_attr *attr,
12411 union bpf_attr __user *uattr)
51580e79 12412{
06ee7115 12413 u64 start_time = ktime_get_ns();
58e2af8b 12414 struct bpf_verifier_env *env;
b9193c1b 12415 struct bpf_verifier_log *log;
9e4c24e7 12416 int i, len, ret = -EINVAL;
e2ae4ca2 12417 bool is_priv;
51580e79 12418
eba0c929
AB
12419 /* no program is valid */
12420 if (ARRAY_SIZE(bpf_verifier_ops) == 0)
12421 return -EINVAL;
12422
58e2af8b 12423 /* 'struct bpf_verifier_env' can be global, but since it's not small,
cbd35700
AS
12424 * allocate/free it every time bpf_check() is called
12425 */
58e2af8b 12426 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
cbd35700
AS
12427 if (!env)
12428 return -ENOMEM;
61bd5218 12429 log = &env->log;
cbd35700 12430
9e4c24e7 12431 len = (*prog)->len;
fad953ce 12432 env->insn_aux_data =
9e4c24e7 12433 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
3df126f3
JK
12434 ret = -ENOMEM;
12435 if (!env->insn_aux_data)
12436 goto err_free_env;
9e4c24e7
JK
12437 for (i = 0; i < len; i++)
12438 env->insn_aux_data[i].orig_idx = i;
9bac3d6d 12439 env->prog = *prog;
00176a34 12440 env->ops = bpf_verifier_ops[env->prog->type];
2c78ee89 12441 is_priv = bpf_capable();
0246e64d 12442
76654e67 12443 bpf_get_btf_vmlinux();
8580ac94 12444
cbd35700 12445 /* grab the mutex to protect few globals used by verifier */
45a73c17
AS
12446 if (!is_priv)
12447 mutex_lock(&bpf_verifier_lock);
cbd35700
AS
12448
12449 if (attr->log_level || attr->log_buf || attr->log_size) {
12450 /* user requested verbose verifier output
12451 * and supplied buffer to store the verification trace
12452 */
e7bf8249
JK
12453 log->level = attr->log_level;
12454 log->ubuf = (char __user *) (unsigned long) attr->log_buf;
12455 log->len_total = attr->log_size;
cbd35700
AS
12456
12457 ret = -EINVAL;
e7bf8249 12458 /* log attributes have to be sane */
7a9f5c65 12459 if (log->len_total < 128 || log->len_total > UINT_MAX >> 2 ||
06ee7115 12460 !log->level || !log->ubuf || log->level & ~BPF_LOG_MASK)
3df126f3 12461 goto err_unlock;
cbd35700 12462 }
1ad2f583 12463
8580ac94
AS
12464 if (IS_ERR(btf_vmlinux)) {
12465 /* Either gcc or pahole or kernel are broken. */
12466 verbose(env, "in-kernel BTF is malformed\n");
12467 ret = PTR_ERR(btf_vmlinux);
38207291 12468 goto skip_full_check;
8580ac94
AS
12469 }
12470
1ad2f583
DB
12471 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
12472 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
e07b98d9 12473 env->strict_alignment = true;
e9ee9efc
DM
12474 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
12475 env->strict_alignment = false;
cbd35700 12476
2c78ee89 12477 env->allow_ptr_leaks = bpf_allow_ptr_leaks();
ca5b89bf 12478 env->allow_uninit_stack = bpf_allow_uninit_stack();
41c48f3a 12479 env->allow_ptr_to_map_access = bpf_allow_ptr_to_map_access();
2c78ee89
AS
12480 env->bypass_spec_v1 = bpf_bypass_spec_v1();
12481 env->bypass_spec_v4 = bpf_bypass_spec_v4();
12482 env->bpf_capable = bpf_capable();
e2ae4ca2 12483
10d274e8
AS
12484 if (is_priv)
12485 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
12486
cae1927c 12487 if (bpf_prog_is_dev_bound(env->prog->aux)) {
a40a2632 12488 ret = bpf_prog_offload_verifier_prep(env->prog);
ab3f0063 12489 if (ret)
f4e3ec0d 12490 goto skip_full_check;
ab3f0063
JK
12491 }
12492
dc2a4ebc 12493 env->explored_states = kvcalloc(state_htab_size(env),
58e2af8b 12494 sizeof(struct bpf_verifier_state_list *),
f1bca824
AS
12495 GFP_USER);
12496 ret = -ENOMEM;
12497 if (!env->explored_states)
12498 goto skip_full_check;
12499
d9762e84 12500 ret = check_subprogs(env);
475fb78f
AS
12501 if (ret < 0)
12502 goto skip_full_check;
12503
c454a46b 12504 ret = check_btf_info(env, attr, uattr);
838e9690
YS
12505 if (ret < 0)
12506 goto skip_full_check;
12507
be8704ff
AS
12508 ret = check_attach_btf_id(env);
12509 if (ret)
12510 goto skip_full_check;
12511
4976b718
HL
12512 ret = resolve_pseudo_ldimm64(env);
12513 if (ret < 0)
12514 goto skip_full_check;
12515
d9762e84
MKL
12516 ret = check_cfg(env);
12517 if (ret < 0)
12518 goto skip_full_check;
12519
51c39bb1
AS
12520 ret = do_check_subprogs(env);
12521 ret = ret ?: do_check_main(env);
cbd35700 12522
c941ce9c
QM
12523 if (ret == 0 && bpf_prog_is_dev_bound(env->prog->aux))
12524 ret = bpf_prog_offload_finalize(env);
12525
0246e64d 12526skip_full_check:
51c39bb1 12527 kvfree(env->explored_states);
0246e64d 12528
c131187d 12529 if (ret == 0)
9b38c405 12530 ret = check_max_stack_depth(env);
c131187d 12531
9b38c405 12532 /* instruction rewrites happen after this point */
e2ae4ca2
JK
12533 if (is_priv) {
12534 if (ret == 0)
12535 opt_hard_wire_dead_code_branches(env);
52875a04
JK
12536 if (ret == 0)
12537 ret = opt_remove_dead_code(env);
a1b14abc
JK
12538 if (ret == 0)
12539 ret = opt_remove_nops(env);
52875a04
JK
12540 } else {
12541 if (ret == 0)
12542 sanitize_dead_code(env);
e2ae4ca2
JK
12543 }
12544
9bac3d6d
AS
12545 if (ret == 0)
12546 /* program is valid, convert *(u32*)(ctx + off) accesses */
12547 ret = convert_ctx_accesses(env);
12548
e245c5c6 12549 if (ret == 0)
79741b3b 12550 ret = fixup_bpf_calls(env);
e245c5c6 12551
a4b1d3c1
JW
12552 /* do 32-bit optimization after insn patching has done so those patched
12553 * insns could be handled correctly.
12554 */
d6c2308c
JW
12555 if (ret == 0 && !bpf_prog_is_dev_bound(env->prog->aux)) {
12556 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
12557 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
12558 : false;
a4b1d3c1
JW
12559 }
12560
1ea47e01
AS
12561 if (ret == 0)
12562 ret = fixup_call_args(env);
12563
06ee7115
AS
12564 env->verification_time = ktime_get_ns() - start_time;
12565 print_verification_stats(env);
12566
a2a7d570 12567 if (log->level && bpf_verifier_log_full(log))
cbd35700 12568 ret = -ENOSPC;
a2a7d570 12569 if (log->level && !log->ubuf) {
cbd35700 12570 ret = -EFAULT;
a2a7d570 12571 goto err_release_maps;
cbd35700
AS
12572 }
12573
0246e64d
AS
12574 if (ret == 0 && env->used_map_cnt) {
12575 /* if program passed verifier, update used_maps in bpf_prog_info */
9bac3d6d
AS
12576 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
12577 sizeof(env->used_maps[0]),
12578 GFP_KERNEL);
0246e64d 12579
9bac3d6d 12580 if (!env->prog->aux->used_maps) {
0246e64d 12581 ret = -ENOMEM;
a2a7d570 12582 goto err_release_maps;
0246e64d
AS
12583 }
12584
9bac3d6d 12585 memcpy(env->prog->aux->used_maps, env->used_maps,
0246e64d 12586 sizeof(env->used_maps[0]) * env->used_map_cnt);
9bac3d6d 12587 env->prog->aux->used_map_cnt = env->used_map_cnt;
0246e64d
AS
12588
12589 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
12590 * bpf_ld_imm64 instructions
12591 */
12592 convert_pseudo_ld_imm64(env);
12593 }
cbd35700 12594
ba64e7d8
YS
12595 if (ret == 0)
12596 adjust_btf_func(env);
12597
a2a7d570 12598err_release_maps:
9bac3d6d 12599 if (!env->prog->aux->used_maps)
0246e64d 12600 /* if we didn't copy map pointers into bpf_prog_info, release
ab7f5bf0 12601 * them now. Otherwise free_used_maps() will release them.
0246e64d
AS
12602 */
12603 release_maps(env);
03f87c0b
THJ
12604
12605 /* extension progs temporarily inherit the attach_type of their targets
12606 for verification purposes, so set it back to zero before returning
12607 */
12608 if (env->prog->type == BPF_PROG_TYPE_EXT)
12609 env->prog->expected_attach_type = 0;
12610
9bac3d6d 12611 *prog = env->prog;
3df126f3 12612err_unlock:
45a73c17
AS
12613 if (!is_priv)
12614 mutex_unlock(&bpf_verifier_lock);
3df126f3
JK
12615 vfree(env->insn_aux_data);
12616err_free_env:
12617 kfree(env);
51580e79
AS
12618 return ret;
12619}