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