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