bpf, x86: Fall back to interpreter mode when extra pass fails
[linux-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>
aef2feda 7#include <linux/bpf-cgroup.h>
51580e79
AS
8#include <linux/kernel.h>
9#include <linux/types.h>
10#include <linux/slab.h>
11#include <linux/bpf.h>
838e9690 12#include <linux/btf.h>
58e2af8b 13#include <linux/bpf_verifier.h>
51580e79
AS
14#include <linux/filter.h>
15#include <net/netlink.h>
16#include <linux/file.h>
17#include <linux/vmalloc.h>
ebb676da 18#include <linux/stringify.h>
cc8b0b92
AS
19#include <linux/bsearch.h>
20#include <linux/sort.h>
c195651e 21#include <linux/perf_event.h>
d9762e84 22#include <linux/ctype.h>
6ba43b76 23#include <linux/error-injection.h>
9e4e01df 24#include <linux/bpf_lsm.h>
1e6c62a8 25#include <linux/btf_ids.h>
51580e79 26
f4ac7e0b
JK
27#include "disasm.h"
28
00176a34 29static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
91cc1a99 30#define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
00176a34
JK
31 [_id] = & _name ## _verifier_ops,
32#define BPF_MAP_TYPE(_id, _ops)
f2e10bff 33#define BPF_LINK_TYPE(_id, _name)
00176a34
JK
34#include <linux/bpf_types.h>
35#undef BPF_PROG_TYPE
36#undef BPF_MAP_TYPE
f2e10bff 37#undef BPF_LINK_TYPE
00176a34
JK
38};
39
51580e79
AS
40/* bpf_check() is a static code analyzer that walks eBPF program
41 * instruction by instruction and updates register/stack state.
42 * All paths of conditional branches are analyzed until 'bpf_exit' insn.
43 *
44 * The first pass is depth-first-search to check that the program is a DAG.
45 * It rejects the following programs:
46 * - larger than BPF_MAXINSNS insns
47 * - if loop is present (detected via back-edge)
48 * - unreachable insns exist (shouldn't be a forest. program = one function)
49 * - out of bounds or malformed jumps
50 * The second pass is all possible path descent from the 1st insn.
8fb33b60 51 * Since it's analyzing all paths through the program, the length of the
eba38a96 52 * analysis is limited to 64k insn, which may be hit even if total number of
51580e79
AS
53 * insn is less then 4K, but there are too many branches that change stack/regs.
54 * Number of 'branches to be analyzed' is limited to 1k
55 *
56 * On entry to each instruction, each register has a type, and the instruction
57 * changes the types of the registers depending on instruction semantics.
58 * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
59 * copied to R1.
60 *
61 * All registers are 64-bit.
62 * R0 - return register
63 * R1-R5 argument passing registers
64 * R6-R9 callee saved registers
65 * R10 - frame pointer read-only
66 *
67 * At the start of BPF program the register R1 contains a pointer to bpf_context
68 * and has type PTR_TO_CTX.
69 *
70 * Verifier tracks arithmetic operations on pointers in case:
71 * BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
72 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
73 * 1st insn copies R10 (which has FRAME_PTR) type into R1
74 * and 2nd arithmetic instruction is pattern matched to recognize
75 * that it wants to construct a pointer to some element within stack.
76 * So after 2nd insn, the register R1 has type PTR_TO_STACK
77 * (and -20 constant is saved for further stack bounds checking).
78 * Meaning that this reg is a pointer to stack plus known immediate constant.
79 *
f1174f77 80 * Most of the time the registers have SCALAR_VALUE type, which
51580e79 81 * means the register has some value, but it's not a valid pointer.
f1174f77 82 * (like pointer plus pointer becomes SCALAR_VALUE type)
51580e79
AS
83 *
84 * When verifier sees load or store instructions the type of base register
c64b7983
JS
85 * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are
86 * four pointer types recognized by check_mem_access() function.
51580e79
AS
87 *
88 * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
89 * and the range of [ptr, ptr + map's value_size) is accessible.
90 *
91 * registers used to pass values to function calls are checked against
92 * function argument constraints.
93 *
94 * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
95 * It means that the register type passed to this function must be
96 * PTR_TO_STACK and it will be used inside the function as
97 * 'pointer to map element key'
98 *
99 * For example the argument constraints for bpf_map_lookup_elem():
100 * .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
101 * .arg1_type = ARG_CONST_MAP_PTR,
102 * .arg2_type = ARG_PTR_TO_MAP_KEY,
103 *
104 * ret_type says that this function returns 'pointer to map elem value or null'
105 * function expects 1st argument to be a const pointer to 'struct bpf_map' and
106 * 2nd argument should be a pointer to stack, which will be used inside
107 * the helper function as a pointer to map element key.
108 *
109 * On the kernel side the helper function looks like:
110 * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
111 * {
112 * struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
113 * void *key = (void *) (unsigned long) r2;
114 * void *value;
115 *
116 * here kernel can access 'key' and 'map' pointers safely, knowing that
117 * [key, key + map->key_size) bytes are valid and were initialized on
118 * the stack of eBPF program.
119 * }
120 *
121 * Corresponding eBPF program may look like:
122 * BPF_MOV64_REG(BPF_REG_2, BPF_REG_10), // after this insn R2 type is FRAME_PTR
123 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
124 * BPF_LD_MAP_FD(BPF_REG_1, map_fd), // after this insn R1 type is CONST_PTR_TO_MAP
125 * BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
126 * here verifier looks at prototype of map_lookup_elem() and sees:
127 * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
128 * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
129 *
130 * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
131 * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
132 * and were initialized prior to this call.
133 * If it's ok, then verifier allows this BPF_CALL insn and looks at
134 * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
135 * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
8fb33b60 136 * returns either pointer to map value or NULL.
51580e79
AS
137 *
138 * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
139 * insn, the register holding that pointer in the true branch changes state to
140 * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
141 * branch. See check_cond_jmp_op().
142 *
143 * After the call R0 is set to return type of the function and registers R1-R5
144 * are set to NOT_INIT to indicate that they are no longer readable.
fd978bf7
JS
145 *
146 * The following reference types represent a potential reference to a kernel
147 * resource which, after first being allocated, must be checked and freed by
148 * the BPF program:
149 * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET
150 *
151 * When the verifier sees a helper call return a reference type, it allocates a
152 * pointer id for the reference and stores it in the current function state.
153 * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into
154 * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type
155 * passes through a NULL-check conditional. For the branch wherein the state is
156 * changed to CONST_IMM, the verifier releases the reference.
6acc9b43
JS
157 *
158 * For each helper function that allocates a reference, such as
159 * bpf_sk_lookup_tcp(), there is a corresponding release function, such as
160 * bpf_sk_release(). When a reference type passes into the release function,
161 * the verifier also releases the reference. If any unchecked or unreleased
162 * reference remains at the end of the program, the verifier rejects it.
51580e79
AS
163 */
164
17a52670 165/* verifier_state + insn_idx are pushed to stack when branch is encountered */
58e2af8b 166struct bpf_verifier_stack_elem {
17a52670
AS
167 /* verifer state is 'st'
168 * before processing instruction 'insn_idx'
169 * and after processing instruction 'prev_insn_idx'
170 */
58e2af8b 171 struct bpf_verifier_state st;
17a52670
AS
172 int insn_idx;
173 int prev_insn_idx;
58e2af8b 174 struct bpf_verifier_stack_elem *next;
6f8a57cc
AN
175 /* length of verifier log at the time this state was pushed on stack */
176 u32 log_pos;
cbd35700
AS
177};
178
b285fcb7 179#define BPF_COMPLEXITY_LIMIT_JMP_SEQ 8192
ceefbc96 180#define BPF_COMPLEXITY_LIMIT_STATES 64
07016151 181
d2e4c1e6
DB
182#define BPF_MAP_KEY_POISON (1ULL << 63)
183#define BPF_MAP_KEY_SEEN (1ULL << 62)
184
c93552c4
DB
185#define BPF_MAP_PTR_UNPRIV 1UL
186#define BPF_MAP_PTR_POISON ((void *)((0xeB9FUL << 1) + \
187 POISON_POINTER_DELTA))
188#define BPF_MAP_PTR(X) ((struct bpf_map *)((X) & ~BPF_MAP_PTR_UNPRIV))
189
190static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux)
191{
d2e4c1e6 192 return BPF_MAP_PTR(aux->map_ptr_state) == BPF_MAP_PTR_POISON;
c93552c4
DB
193}
194
195static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux)
196{
d2e4c1e6 197 return aux->map_ptr_state & BPF_MAP_PTR_UNPRIV;
c93552c4
DB
198}
199
200static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
201 const struct bpf_map *map, bool unpriv)
202{
203 BUILD_BUG_ON((unsigned long)BPF_MAP_PTR_POISON & BPF_MAP_PTR_UNPRIV);
204 unpriv |= bpf_map_ptr_unpriv(aux);
d2e4c1e6
DB
205 aux->map_ptr_state = (unsigned long)map |
206 (unpriv ? BPF_MAP_PTR_UNPRIV : 0UL);
207}
208
209static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux)
210{
211 return aux->map_key_state & BPF_MAP_KEY_POISON;
212}
213
214static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux)
215{
216 return !(aux->map_key_state & BPF_MAP_KEY_SEEN);
217}
218
219static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux)
220{
221 return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON);
222}
223
224static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state)
225{
226 bool poisoned = bpf_map_key_poisoned(aux);
227
228 aux->map_key_state = state | BPF_MAP_KEY_SEEN |
229 (poisoned ? BPF_MAP_KEY_POISON : 0ULL);
c93552c4 230}
fad73a1a 231
23a2d70c
YS
232static bool bpf_pseudo_call(const struct bpf_insn *insn)
233{
234 return insn->code == (BPF_JMP | BPF_CALL) &&
235 insn->src_reg == BPF_PSEUDO_CALL;
236}
237
e6ac2450
MKL
238static bool bpf_pseudo_kfunc_call(const struct bpf_insn *insn)
239{
240 return insn->code == (BPF_JMP | BPF_CALL) &&
241 insn->src_reg == BPF_PSEUDO_KFUNC_CALL;
242}
243
33ff9823
DB
244struct bpf_call_arg_meta {
245 struct bpf_map *map_ptr;
435faee1 246 bool raw_mode;
36bbef52 247 bool pkt_access;
435faee1
DB
248 int regno;
249 int access_size;
457f4436 250 int mem_size;
10060503 251 u64 msize_max_value;
1b986589 252 int ref_obj_id;
3e8ce298 253 int map_uid;
d83525ca 254 int func_id;
22dc4a0f 255 struct btf *btf;
eaa6bcb7 256 u32 btf_id;
22dc4a0f 257 struct btf *ret_btf;
eaa6bcb7 258 u32 ret_btf_id;
69c087ba 259 u32 subprogno;
33ff9823
DB
260};
261
8580ac94
AS
262struct btf *btf_vmlinux;
263
cbd35700
AS
264static DEFINE_MUTEX(bpf_verifier_lock);
265
d9762e84
MKL
266static const struct bpf_line_info *
267find_linfo(const struct bpf_verifier_env *env, u32 insn_off)
268{
269 const struct bpf_line_info *linfo;
270 const struct bpf_prog *prog;
271 u32 i, nr_linfo;
272
273 prog = env->prog;
274 nr_linfo = prog->aux->nr_linfo;
275
276 if (!nr_linfo || insn_off >= prog->len)
277 return NULL;
278
279 linfo = prog->aux->linfo;
280 for (i = 1; i < nr_linfo; i++)
281 if (insn_off < linfo[i].insn_off)
282 break;
283
284 return &linfo[i - 1];
285}
286
77d2e05a
MKL
287void bpf_verifier_vlog(struct bpf_verifier_log *log, const char *fmt,
288 va_list args)
cbd35700 289{
a2a7d570 290 unsigned int n;
cbd35700 291
a2a7d570 292 n = vscnprintf(log->kbuf, BPF_VERIFIER_TMP_LOG_SIZE, fmt, args);
a2a7d570
JK
293
294 WARN_ONCE(n >= BPF_VERIFIER_TMP_LOG_SIZE - 1,
295 "verifier log line truncated - local buffer too short\n");
296
8580ac94 297 if (log->level == BPF_LOG_KERNEL) {
436d404c
HT
298 bool newline = n > 0 && log->kbuf[n - 1] == '\n';
299
300 pr_err("BPF: %s%s", log->kbuf, newline ? "" : "\n");
8580ac94
AS
301 return;
302 }
436d404c
HT
303
304 n = min(log->len_total - log->len_used - 1, n);
305 log->kbuf[n] = '\0';
a2a7d570
JK
306 if (!copy_to_user(log->ubuf + log->len_used, log->kbuf, n + 1))
307 log->len_used += n;
308 else
309 log->ubuf = NULL;
cbd35700 310}
abe08840 311
6f8a57cc
AN
312static void bpf_vlog_reset(struct bpf_verifier_log *log, u32 new_pos)
313{
314 char zero = 0;
315
316 if (!bpf_verifier_log_needed(log))
317 return;
318
319 log->len_used = new_pos;
320 if (put_user(zero, log->ubuf + new_pos))
321 log->ubuf = NULL;
322}
323
abe08840
JO
324/* log_level controls verbosity level of eBPF verifier.
325 * bpf_verifier_log_write() is used to dump the verification trace to the log,
326 * so the user can figure out what's wrong with the program
430e68d1 327 */
abe08840
JO
328__printf(2, 3) void bpf_verifier_log_write(struct bpf_verifier_env *env,
329 const char *fmt, ...)
330{
331 va_list args;
332
77d2e05a
MKL
333 if (!bpf_verifier_log_needed(&env->log))
334 return;
335
abe08840 336 va_start(args, fmt);
77d2e05a 337 bpf_verifier_vlog(&env->log, fmt, args);
abe08840
JO
338 va_end(args);
339}
340EXPORT_SYMBOL_GPL(bpf_verifier_log_write);
341
342__printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
343{
77d2e05a 344 struct bpf_verifier_env *env = private_data;
abe08840
JO
345 va_list args;
346
77d2e05a
MKL
347 if (!bpf_verifier_log_needed(&env->log))
348 return;
349
abe08840 350 va_start(args, fmt);
77d2e05a 351 bpf_verifier_vlog(&env->log, fmt, args);
abe08840
JO
352 va_end(args);
353}
cbd35700 354
9e15db66
AS
355__printf(2, 3) void bpf_log(struct bpf_verifier_log *log,
356 const char *fmt, ...)
357{
358 va_list args;
359
360 if (!bpf_verifier_log_needed(log))
361 return;
362
363 va_start(args, fmt);
364 bpf_verifier_vlog(log, fmt, args);
365 va_end(args);
366}
367
d9762e84
MKL
368static const char *ltrim(const char *s)
369{
370 while (isspace(*s))
371 s++;
372
373 return s;
374}
375
376__printf(3, 4) static void verbose_linfo(struct bpf_verifier_env *env,
377 u32 insn_off,
378 const char *prefix_fmt, ...)
379{
380 const struct bpf_line_info *linfo;
381
382 if (!bpf_verifier_log_needed(&env->log))
383 return;
384
385 linfo = find_linfo(env, insn_off);
386 if (!linfo || linfo == env->prev_linfo)
387 return;
388
389 if (prefix_fmt) {
390 va_list args;
391
392 va_start(args, prefix_fmt);
393 bpf_verifier_vlog(&env->log, prefix_fmt, args);
394 va_end(args);
395 }
396
397 verbose(env, "%s\n",
398 ltrim(btf_name_by_offset(env->prog->aux->btf,
399 linfo->line_off)));
400
401 env->prev_linfo = linfo;
402}
403
bc2591d6
YS
404static void verbose_invalid_scalar(struct bpf_verifier_env *env,
405 struct bpf_reg_state *reg,
406 struct tnum *range, const char *ctx,
407 const char *reg_name)
408{
409 char tn_buf[48];
410
411 verbose(env, "At %s the register %s ", ctx, reg_name);
412 if (!tnum_is_unknown(reg->var_off)) {
413 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
414 verbose(env, "has value %s", tn_buf);
415 } else {
416 verbose(env, "has unknown scalar value");
417 }
418 tnum_strn(tn_buf, sizeof(tn_buf), *range);
419 verbose(env, " should have been in %s\n", tn_buf);
420}
421
de8f3a83
DB
422static bool type_is_pkt_pointer(enum bpf_reg_type type)
423{
424 return type == PTR_TO_PACKET ||
425 type == PTR_TO_PACKET_META;
426}
427
46f8bc92
MKL
428static bool type_is_sk_pointer(enum bpf_reg_type type)
429{
430 return type == PTR_TO_SOCKET ||
655a51e5 431 type == PTR_TO_SOCK_COMMON ||
fada7fdc
JL
432 type == PTR_TO_TCP_SOCK ||
433 type == PTR_TO_XDP_SOCK;
46f8bc92
MKL
434}
435
cac616db
JF
436static bool reg_type_not_null(enum bpf_reg_type type)
437{
438 return type == PTR_TO_SOCKET ||
439 type == PTR_TO_TCP_SOCK ||
440 type == PTR_TO_MAP_VALUE ||
69c087ba 441 type == PTR_TO_MAP_KEY ||
01c66c48 442 type == PTR_TO_SOCK_COMMON;
cac616db
JF
443}
444
d83525ca
AS
445static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
446{
447 return reg->type == PTR_TO_MAP_VALUE &&
448 map_value_has_spin_lock(reg->map_ptr);
449}
450
cba368c1
MKL
451static bool reg_type_may_be_refcounted_or_null(enum bpf_reg_type type)
452{
c25b2ae1
HL
453 return base_type(type) == PTR_TO_SOCKET ||
454 base_type(type) == PTR_TO_TCP_SOCK ||
5c073f26
KKD
455 base_type(type) == PTR_TO_MEM ||
456 base_type(type) == PTR_TO_BTF_ID;
cba368c1
MKL
457}
458
20b2aff4
HL
459static bool type_is_rdonly_mem(u32 type)
460{
461 return type & MEM_RDONLY;
cba368c1
MKL
462}
463
1b986589 464static bool arg_type_may_be_refcounted(enum bpf_arg_type type)
fd978bf7 465{
1b986589 466 return type == ARG_PTR_TO_SOCK_COMMON;
fd978bf7
JS
467}
468
48946bd6 469static bool type_may_be_null(u32 type)
fd1b0d60 470{
48946bd6 471 return type & PTR_MAYBE_NULL;
fd1b0d60
LB
472}
473
fd978bf7
JS
474/* Determine whether the function releases some resources allocated by another
475 * function call. The first reference type argument will be assumed to be
476 * released by release_reference().
477 */
478static bool is_release_function(enum bpf_func_id func_id)
479{
457f4436
AN
480 return func_id == BPF_FUNC_sk_release ||
481 func_id == BPF_FUNC_ringbuf_submit ||
482 func_id == BPF_FUNC_ringbuf_discard;
840b9615
JS
483}
484
64d85290 485static bool may_be_acquire_function(enum bpf_func_id func_id)
46f8bc92
MKL
486{
487 return func_id == BPF_FUNC_sk_lookup_tcp ||
edbf8c01 488 func_id == BPF_FUNC_sk_lookup_udp ||
64d85290 489 func_id == BPF_FUNC_skc_lookup_tcp ||
457f4436
AN
490 func_id == BPF_FUNC_map_lookup_elem ||
491 func_id == BPF_FUNC_ringbuf_reserve;
64d85290
JS
492}
493
494static bool is_acquire_function(enum bpf_func_id func_id,
495 const struct bpf_map *map)
496{
497 enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
498
499 if (func_id == BPF_FUNC_sk_lookup_tcp ||
500 func_id == BPF_FUNC_sk_lookup_udp ||
457f4436
AN
501 func_id == BPF_FUNC_skc_lookup_tcp ||
502 func_id == BPF_FUNC_ringbuf_reserve)
64d85290
JS
503 return true;
504
505 if (func_id == BPF_FUNC_map_lookup_elem &&
506 (map_type == BPF_MAP_TYPE_SOCKMAP ||
507 map_type == BPF_MAP_TYPE_SOCKHASH))
508 return true;
509
510 return false;
46f8bc92
MKL
511}
512
1b986589
MKL
513static bool is_ptr_cast_function(enum bpf_func_id func_id)
514{
515 return func_id == BPF_FUNC_tcp_sock ||
1df8f55a
MKL
516 func_id == BPF_FUNC_sk_fullsock ||
517 func_id == BPF_FUNC_skc_to_tcp_sock ||
518 func_id == BPF_FUNC_skc_to_tcp6_sock ||
519 func_id == BPF_FUNC_skc_to_udp6_sock ||
520 func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
521 func_id == BPF_FUNC_skc_to_tcp_request_sock;
1b986589
MKL
522}
523
39491867
BJ
524static bool is_cmpxchg_insn(const struct bpf_insn *insn)
525{
526 return BPF_CLASS(insn->code) == BPF_STX &&
527 BPF_MODE(insn->code) == BPF_ATOMIC &&
528 insn->imm == BPF_CMPXCHG;
529}
530
c25b2ae1
HL
531/* string representation of 'enum bpf_reg_type'
532 *
533 * Note that reg_type_str() can not appear more than once in a single verbose()
534 * statement.
535 */
536static const char *reg_type_str(struct bpf_verifier_env *env,
537 enum bpf_reg_type type)
538{
c6f1bfe8 539 char postfix[16] = {0}, prefix[32] = {0};
c25b2ae1
HL
540 static const char * const str[] = {
541 [NOT_INIT] = "?",
7df5072c 542 [SCALAR_VALUE] = "scalar",
c25b2ae1
HL
543 [PTR_TO_CTX] = "ctx",
544 [CONST_PTR_TO_MAP] = "map_ptr",
545 [PTR_TO_MAP_VALUE] = "map_value",
546 [PTR_TO_STACK] = "fp",
547 [PTR_TO_PACKET] = "pkt",
548 [PTR_TO_PACKET_META] = "pkt_meta",
549 [PTR_TO_PACKET_END] = "pkt_end",
550 [PTR_TO_FLOW_KEYS] = "flow_keys",
551 [PTR_TO_SOCKET] = "sock",
552 [PTR_TO_SOCK_COMMON] = "sock_common",
553 [PTR_TO_TCP_SOCK] = "tcp_sock",
554 [PTR_TO_TP_BUFFER] = "tp_buffer",
555 [PTR_TO_XDP_SOCK] = "xdp_sock",
556 [PTR_TO_BTF_ID] = "ptr_",
c25b2ae1 557 [PTR_TO_MEM] = "mem",
20b2aff4 558 [PTR_TO_BUF] = "buf",
c25b2ae1
HL
559 [PTR_TO_FUNC] = "func",
560 [PTR_TO_MAP_KEY] = "map_key",
561 };
562
563 if (type & PTR_MAYBE_NULL) {
5844101a 564 if (base_type(type) == PTR_TO_BTF_ID)
c25b2ae1
HL
565 strncpy(postfix, "or_null_", 16);
566 else
567 strncpy(postfix, "_or_null", 16);
568 }
569
20b2aff4 570 if (type & MEM_RDONLY)
c6f1bfe8 571 strncpy(prefix, "rdonly_", 32);
a672b2e3 572 if (type & MEM_ALLOC)
c6f1bfe8
YS
573 strncpy(prefix, "alloc_", 32);
574 if (type & MEM_USER)
575 strncpy(prefix, "user_", 32);
5844101a
HL
576 if (type & MEM_PERCPU)
577 strncpy(prefix, "percpu_", 32);
20b2aff4
HL
578
579 snprintf(env->type_str_buf, TYPE_STR_BUF_LEN, "%s%s%s",
580 prefix, str[base_type(type)], postfix);
c25b2ae1
HL
581 return env->type_str_buf;
582}
17a52670 583
8efea21d
EC
584static char slot_type_char[] = {
585 [STACK_INVALID] = '?',
586 [STACK_SPILL] = 'r',
587 [STACK_MISC] = 'm',
588 [STACK_ZERO] = '0',
589};
590
4e92024a
AS
591static void print_liveness(struct bpf_verifier_env *env,
592 enum bpf_reg_liveness live)
593{
9242b5f5 594 if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE))
4e92024a
AS
595 verbose(env, "_");
596 if (live & REG_LIVE_READ)
597 verbose(env, "r");
598 if (live & REG_LIVE_WRITTEN)
599 verbose(env, "w");
9242b5f5
AS
600 if (live & REG_LIVE_DONE)
601 verbose(env, "D");
4e92024a
AS
602}
603
f4d7e40a
AS
604static struct bpf_func_state *func(struct bpf_verifier_env *env,
605 const struct bpf_reg_state *reg)
606{
607 struct bpf_verifier_state *cur = env->cur_state;
608
609 return cur->frame[reg->frameno];
610}
611
22dc4a0f 612static const char *kernel_type_name(const struct btf* btf, u32 id)
9e15db66 613{
22dc4a0f 614 return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off);
9e15db66
AS
615}
616
0f55f9ed
CL
617static void mark_reg_scratched(struct bpf_verifier_env *env, u32 regno)
618{
619 env->scratched_regs |= 1U << regno;
620}
621
622static void mark_stack_slot_scratched(struct bpf_verifier_env *env, u32 spi)
623{
343e5375 624 env->scratched_stack_slots |= 1ULL << spi;
0f55f9ed
CL
625}
626
627static bool reg_scratched(const struct bpf_verifier_env *env, u32 regno)
628{
629 return (env->scratched_regs >> regno) & 1;
630}
631
632static bool stack_slot_scratched(const struct bpf_verifier_env *env, u64 regno)
633{
634 return (env->scratched_stack_slots >> regno) & 1;
635}
636
637static bool verifier_state_scratched(const struct bpf_verifier_env *env)
638{
639 return env->scratched_regs || env->scratched_stack_slots;
640}
641
642static void mark_verifier_state_clean(struct bpf_verifier_env *env)
643{
644 env->scratched_regs = 0U;
343e5375 645 env->scratched_stack_slots = 0ULL;
0f55f9ed
CL
646}
647
648/* Used for printing the entire verifier state. */
649static void mark_verifier_state_scratched(struct bpf_verifier_env *env)
650{
651 env->scratched_regs = ~0U;
343e5375 652 env->scratched_stack_slots = ~0ULL;
0f55f9ed
CL
653}
654
27113c59
MKL
655/* The reg state of a pointer or a bounded scalar was saved when
656 * it was spilled to the stack.
657 */
658static bool is_spilled_reg(const struct bpf_stack_state *stack)
659{
660 return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL;
661}
662
354e8f19
MKL
663static void scrub_spilled_slot(u8 *stype)
664{
665 if (*stype != STACK_INVALID)
666 *stype = STACK_MISC;
667}
668
61bd5218 669static void print_verifier_state(struct bpf_verifier_env *env,
0f55f9ed
CL
670 const struct bpf_func_state *state,
671 bool print_all)
17a52670 672{
f4d7e40a 673 const struct bpf_reg_state *reg;
17a52670
AS
674 enum bpf_reg_type t;
675 int i;
676
f4d7e40a
AS
677 if (state->frameno)
678 verbose(env, " frame%d:", state->frameno);
17a52670 679 for (i = 0; i < MAX_BPF_REG; i++) {
1a0dc1ac
AS
680 reg = &state->regs[i];
681 t = reg->type;
17a52670
AS
682 if (t == NOT_INIT)
683 continue;
0f55f9ed
CL
684 if (!print_all && !reg_scratched(env, i))
685 continue;
4e92024a
AS
686 verbose(env, " R%d", i);
687 print_liveness(env, reg->live);
7df5072c 688 verbose(env, "=");
b5dc0163
AS
689 if (t == SCALAR_VALUE && reg->precise)
690 verbose(env, "P");
f1174f77
EC
691 if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
692 tnum_is_const(reg->var_off)) {
693 /* reg->off should be 0 for SCALAR_VALUE */
7df5072c 694 verbose(env, "%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t));
61bd5218 695 verbose(env, "%lld", reg->var_off.value + reg->off);
f1174f77 696 } else {
7df5072c
ML
697 const char *sep = "";
698
699 verbose(env, "%s", reg_type_str(env, t));
5844101a 700 if (base_type(t) == PTR_TO_BTF_ID)
22dc4a0f 701 verbose(env, "%s", kernel_type_name(reg->btf, reg->btf_id));
7df5072c
ML
702 verbose(env, "(");
703/*
704 * _a stands for append, was shortened to avoid multiline statements below.
705 * This macro is used to output a comma separated list of attributes.
706 */
707#define verbose_a(fmt, ...) ({ verbose(env, "%s" fmt, sep, __VA_ARGS__); sep = ","; })
708
709 if (reg->id)
710 verbose_a("id=%d", reg->id);
711 if (reg_type_may_be_refcounted_or_null(t) && reg->ref_obj_id)
712 verbose_a("ref_obj_id=%d", reg->ref_obj_id);
f1174f77 713 if (t != SCALAR_VALUE)
7df5072c 714 verbose_a("off=%d", reg->off);
de8f3a83 715 if (type_is_pkt_pointer(t))
7df5072c 716 verbose_a("r=%d", reg->range);
c25b2ae1
HL
717 else if (base_type(t) == CONST_PTR_TO_MAP ||
718 base_type(t) == PTR_TO_MAP_KEY ||
719 base_type(t) == PTR_TO_MAP_VALUE)
7df5072c
ML
720 verbose_a("ks=%d,vs=%d",
721 reg->map_ptr->key_size,
722 reg->map_ptr->value_size);
7d1238f2
EC
723 if (tnum_is_const(reg->var_off)) {
724 /* Typically an immediate SCALAR_VALUE, but
725 * could be a pointer whose offset is too big
726 * for reg->off
727 */
7df5072c 728 verbose_a("imm=%llx", reg->var_off.value);
7d1238f2
EC
729 } else {
730 if (reg->smin_value != reg->umin_value &&
731 reg->smin_value != S64_MIN)
7df5072c 732 verbose_a("smin=%lld", (long long)reg->smin_value);
7d1238f2
EC
733 if (reg->smax_value != reg->umax_value &&
734 reg->smax_value != S64_MAX)
7df5072c 735 verbose_a("smax=%lld", (long long)reg->smax_value);
7d1238f2 736 if (reg->umin_value != 0)
7df5072c 737 verbose_a("umin=%llu", (unsigned long long)reg->umin_value);
7d1238f2 738 if (reg->umax_value != U64_MAX)
7df5072c 739 verbose_a("umax=%llu", (unsigned long long)reg->umax_value);
7d1238f2
EC
740 if (!tnum_is_unknown(reg->var_off)) {
741 char tn_buf[48];
f1174f77 742
7d1238f2 743 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7df5072c 744 verbose_a("var_off=%s", tn_buf);
7d1238f2 745 }
3f50f132
JF
746 if (reg->s32_min_value != reg->smin_value &&
747 reg->s32_min_value != S32_MIN)
7df5072c 748 verbose_a("s32_min=%d", (int)(reg->s32_min_value));
3f50f132
JF
749 if (reg->s32_max_value != reg->smax_value &&
750 reg->s32_max_value != S32_MAX)
7df5072c 751 verbose_a("s32_max=%d", (int)(reg->s32_max_value));
3f50f132
JF
752 if (reg->u32_min_value != reg->umin_value &&
753 reg->u32_min_value != U32_MIN)
7df5072c 754 verbose_a("u32_min=%d", (int)(reg->u32_min_value));
3f50f132
JF
755 if (reg->u32_max_value != reg->umax_value &&
756 reg->u32_max_value != U32_MAX)
7df5072c 757 verbose_a("u32_max=%d", (int)(reg->u32_max_value));
f1174f77 758 }
7df5072c
ML
759#undef verbose_a
760
61bd5218 761 verbose(env, ")");
f1174f77 762 }
17a52670 763 }
638f5b90 764 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
8efea21d
EC
765 char types_buf[BPF_REG_SIZE + 1];
766 bool valid = false;
767 int j;
768
769 for (j = 0; j < BPF_REG_SIZE; j++) {
770 if (state->stack[i].slot_type[j] != STACK_INVALID)
771 valid = true;
772 types_buf[j] = slot_type_char[
773 state->stack[i].slot_type[j]];
774 }
775 types_buf[BPF_REG_SIZE] = 0;
776 if (!valid)
777 continue;
0f55f9ed
CL
778 if (!print_all && !stack_slot_scratched(env, i))
779 continue;
8efea21d
EC
780 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
781 print_liveness(env, state->stack[i].spilled_ptr.live);
27113c59 782 if (is_spilled_reg(&state->stack[i])) {
b5dc0163
AS
783 reg = &state->stack[i].spilled_ptr;
784 t = reg->type;
7df5072c 785 verbose(env, "=%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t));
b5dc0163
AS
786 if (t == SCALAR_VALUE && reg->precise)
787 verbose(env, "P");
788 if (t == SCALAR_VALUE && tnum_is_const(reg->var_off))
789 verbose(env, "%lld", reg->var_off.value + reg->off);
790 } else {
8efea21d 791 verbose(env, "=%s", types_buf);
b5dc0163 792 }
17a52670 793 }
fd978bf7
JS
794 if (state->acquired_refs && state->refs[0].id) {
795 verbose(env, " refs=%d", state->refs[0].id);
796 for (i = 1; i < state->acquired_refs; i++)
797 if (state->refs[i].id)
798 verbose(env, ",%d", state->refs[i].id);
799 }
bfc6bb74
AS
800 if (state->in_callback_fn)
801 verbose(env, " cb");
802 if (state->in_async_callback_fn)
803 verbose(env, " async_cb");
61bd5218 804 verbose(env, "\n");
0f55f9ed 805 mark_verifier_state_clean(env);
17a52670
AS
806}
807
2e576648
CL
808static inline u32 vlog_alignment(u32 pos)
809{
810 return round_up(max(pos + BPF_LOG_MIN_ALIGNMENT / 2, BPF_LOG_ALIGNMENT),
811 BPF_LOG_MIN_ALIGNMENT) - pos - 1;
812}
813
814static void print_insn_state(struct bpf_verifier_env *env,
815 const struct bpf_func_state *state)
816{
817 if (env->prev_log_len && env->prev_log_len == env->log.len_used) {
818 /* remove new line character */
819 bpf_vlog_reset(&env->log, env->prev_log_len - 1);
820 verbose(env, "%*c;", vlog_alignment(env->prev_insn_print_len), ' ');
821 } else {
822 verbose(env, "%d:", env->insn_idx);
823 }
824 print_verifier_state(env, state, false);
17a52670
AS
825}
826
c69431aa
LB
827/* copy array src of length n * size bytes to dst. dst is reallocated if it's too
828 * small to hold src. This is different from krealloc since we don't want to preserve
829 * the contents of dst.
830 *
831 * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could
832 * not be allocated.
638f5b90 833 */
c69431aa 834static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags)
638f5b90 835{
c69431aa
LB
836 size_t bytes;
837
838 if (ZERO_OR_NULL_PTR(src))
839 goto out;
840
841 if (unlikely(check_mul_overflow(n, size, &bytes)))
842 return NULL;
843
844 if (ksize(dst) < bytes) {
845 kfree(dst);
846 dst = kmalloc_track_caller(bytes, flags);
847 if (!dst)
848 return NULL;
849 }
850
851 memcpy(dst, src, bytes);
852out:
853 return dst ? dst : ZERO_SIZE_PTR;
854}
855
856/* resize an array from old_n items to new_n items. the array is reallocated if it's too
857 * small to hold new_n items. new items are zeroed out if the array grows.
858 *
859 * Contrary to krealloc_array, does not free arr if new_n is zero.
860 */
861static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size)
862{
863 if (!new_n || old_n == new_n)
864 goto out;
865
866 arr = krealloc_array(arr, new_n, size, GFP_KERNEL);
867 if (!arr)
868 return NULL;
869
870 if (new_n > old_n)
871 memset(arr + old_n * size, 0, (new_n - old_n) * size);
872
873out:
874 return arr ? arr : ZERO_SIZE_PTR;
875}
876
877static int copy_reference_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
878{
879 dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs,
880 sizeof(struct bpf_reference_state), GFP_KERNEL);
881 if (!dst->refs)
882 return -ENOMEM;
883
884 dst->acquired_refs = src->acquired_refs;
885 return 0;
886}
887
888static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
889{
890 size_t n = src->allocated_stack / BPF_REG_SIZE;
891
892 dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state),
893 GFP_KERNEL);
894 if (!dst->stack)
895 return -ENOMEM;
896
897 dst->allocated_stack = src->allocated_stack;
898 return 0;
899}
900
901static int resize_reference_state(struct bpf_func_state *state, size_t n)
902{
903 state->refs = realloc_array(state->refs, state->acquired_refs, n,
904 sizeof(struct bpf_reference_state));
905 if (!state->refs)
906 return -ENOMEM;
907
908 state->acquired_refs = n;
909 return 0;
910}
911
912static int grow_stack_state(struct bpf_func_state *state, int size)
913{
914 size_t old_n = state->allocated_stack / BPF_REG_SIZE, n = size / BPF_REG_SIZE;
915
916 if (old_n >= n)
917 return 0;
918
919 state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state));
920 if (!state->stack)
921 return -ENOMEM;
922
923 state->allocated_stack = size;
924 return 0;
fd978bf7
JS
925}
926
927/* Acquire a pointer id from the env and update the state->refs to include
928 * this new pointer reference.
929 * On success, returns a valid pointer id to associate with the register
930 * On failure, returns a negative errno.
638f5b90 931 */
fd978bf7 932static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
638f5b90 933{
fd978bf7
JS
934 struct bpf_func_state *state = cur_func(env);
935 int new_ofs = state->acquired_refs;
936 int id, err;
937
c69431aa 938 err = resize_reference_state(state, state->acquired_refs + 1);
fd978bf7
JS
939 if (err)
940 return err;
941 id = ++env->id_gen;
942 state->refs[new_ofs].id = id;
943 state->refs[new_ofs].insn_idx = insn_idx;
638f5b90 944
fd978bf7
JS
945 return id;
946}
947
948/* release function corresponding to acquire_reference_state(). Idempotent. */
46f8bc92 949static int release_reference_state(struct bpf_func_state *state, int ptr_id)
fd978bf7
JS
950{
951 int i, last_idx;
952
fd978bf7
JS
953 last_idx = state->acquired_refs - 1;
954 for (i = 0; i < state->acquired_refs; i++) {
955 if (state->refs[i].id == ptr_id) {
956 if (last_idx && i != last_idx)
957 memcpy(&state->refs[i], &state->refs[last_idx],
958 sizeof(*state->refs));
959 memset(&state->refs[last_idx], 0, sizeof(*state->refs));
960 state->acquired_refs--;
638f5b90 961 return 0;
638f5b90 962 }
638f5b90 963 }
46f8bc92 964 return -EINVAL;
fd978bf7
JS
965}
966
f4d7e40a
AS
967static void free_func_state(struct bpf_func_state *state)
968{
5896351e
AS
969 if (!state)
970 return;
fd978bf7 971 kfree(state->refs);
f4d7e40a
AS
972 kfree(state->stack);
973 kfree(state);
974}
975
b5dc0163
AS
976static void clear_jmp_history(struct bpf_verifier_state *state)
977{
978 kfree(state->jmp_history);
979 state->jmp_history = NULL;
980 state->jmp_history_cnt = 0;
981}
982
1969db47
AS
983static void free_verifier_state(struct bpf_verifier_state *state,
984 bool free_self)
638f5b90 985{
f4d7e40a
AS
986 int i;
987
988 for (i = 0; i <= state->curframe; i++) {
989 free_func_state(state->frame[i]);
990 state->frame[i] = NULL;
991 }
b5dc0163 992 clear_jmp_history(state);
1969db47
AS
993 if (free_self)
994 kfree(state);
638f5b90
AS
995}
996
997/* copy verifier state from src to dst growing dst stack space
998 * when necessary to accommodate larger src stack
999 */
f4d7e40a
AS
1000static int copy_func_state(struct bpf_func_state *dst,
1001 const struct bpf_func_state *src)
638f5b90
AS
1002{
1003 int err;
1004
fd978bf7
JS
1005 memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
1006 err = copy_reference_state(dst, src);
638f5b90
AS
1007 if (err)
1008 return err;
638f5b90
AS
1009 return copy_stack_state(dst, src);
1010}
1011
f4d7e40a
AS
1012static int copy_verifier_state(struct bpf_verifier_state *dst_state,
1013 const struct bpf_verifier_state *src)
1014{
1015 struct bpf_func_state *dst;
1016 int i, err;
1017
06ab6a50
LB
1018 dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history,
1019 src->jmp_history_cnt, sizeof(struct bpf_idx_pair),
1020 GFP_USER);
1021 if (!dst_state->jmp_history)
1022 return -ENOMEM;
b5dc0163
AS
1023 dst_state->jmp_history_cnt = src->jmp_history_cnt;
1024
f4d7e40a
AS
1025 /* if dst has more stack frames then src frame, free them */
1026 for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
1027 free_func_state(dst_state->frame[i]);
1028 dst_state->frame[i] = NULL;
1029 }
979d63d5 1030 dst_state->speculative = src->speculative;
f4d7e40a 1031 dst_state->curframe = src->curframe;
d83525ca 1032 dst_state->active_spin_lock = src->active_spin_lock;
2589726d
AS
1033 dst_state->branches = src->branches;
1034 dst_state->parent = src->parent;
b5dc0163
AS
1035 dst_state->first_insn_idx = src->first_insn_idx;
1036 dst_state->last_insn_idx = src->last_insn_idx;
f4d7e40a
AS
1037 for (i = 0; i <= src->curframe; i++) {
1038 dst = dst_state->frame[i];
1039 if (!dst) {
1040 dst = kzalloc(sizeof(*dst), GFP_KERNEL);
1041 if (!dst)
1042 return -ENOMEM;
1043 dst_state->frame[i] = dst;
1044 }
1045 err = copy_func_state(dst, src->frame[i]);
1046 if (err)
1047 return err;
1048 }
1049 return 0;
1050}
1051
2589726d
AS
1052static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
1053{
1054 while (st) {
1055 u32 br = --st->branches;
1056
1057 /* WARN_ON(br > 1) technically makes sense here,
1058 * but see comment in push_stack(), hence:
1059 */
1060 WARN_ONCE((int)br < 0,
1061 "BUG update_branch_counts:branches_to_explore=%d\n",
1062 br);
1063 if (br)
1064 break;
1065 st = st->parent;
1066 }
1067}
1068
638f5b90 1069static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
6f8a57cc 1070 int *insn_idx, bool pop_log)
638f5b90
AS
1071{
1072 struct bpf_verifier_state *cur = env->cur_state;
1073 struct bpf_verifier_stack_elem *elem, *head = env->head;
1074 int err;
17a52670
AS
1075
1076 if (env->head == NULL)
638f5b90 1077 return -ENOENT;
17a52670 1078
638f5b90
AS
1079 if (cur) {
1080 err = copy_verifier_state(cur, &head->st);
1081 if (err)
1082 return err;
1083 }
6f8a57cc
AN
1084 if (pop_log)
1085 bpf_vlog_reset(&env->log, head->log_pos);
638f5b90
AS
1086 if (insn_idx)
1087 *insn_idx = head->insn_idx;
17a52670 1088 if (prev_insn_idx)
638f5b90
AS
1089 *prev_insn_idx = head->prev_insn_idx;
1090 elem = head->next;
1969db47 1091 free_verifier_state(&head->st, false);
638f5b90 1092 kfree(head);
17a52670
AS
1093 env->head = elem;
1094 env->stack_size--;
638f5b90 1095 return 0;
17a52670
AS
1096}
1097
58e2af8b 1098static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
979d63d5
DB
1099 int insn_idx, int prev_insn_idx,
1100 bool speculative)
17a52670 1101{
638f5b90 1102 struct bpf_verifier_state *cur = env->cur_state;
58e2af8b 1103 struct bpf_verifier_stack_elem *elem;
638f5b90 1104 int err;
17a52670 1105
638f5b90 1106 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
17a52670
AS
1107 if (!elem)
1108 goto err;
1109
17a52670
AS
1110 elem->insn_idx = insn_idx;
1111 elem->prev_insn_idx = prev_insn_idx;
1112 elem->next = env->head;
6f8a57cc 1113 elem->log_pos = env->log.len_used;
17a52670
AS
1114 env->head = elem;
1115 env->stack_size++;
1969db47
AS
1116 err = copy_verifier_state(&elem->st, cur);
1117 if (err)
1118 goto err;
979d63d5 1119 elem->st.speculative |= speculative;
b285fcb7
AS
1120 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1121 verbose(env, "The sequence of %d jumps is too complex.\n",
1122 env->stack_size);
17a52670
AS
1123 goto err;
1124 }
2589726d
AS
1125 if (elem->st.parent) {
1126 ++elem->st.parent->branches;
1127 /* WARN_ON(branches > 2) technically makes sense here,
1128 * but
1129 * 1. speculative states will bump 'branches' for non-branch
1130 * instructions
1131 * 2. is_state_visited() heuristics may decide not to create
1132 * a new state for a sequence of branches and all such current
1133 * and cloned states will be pointing to a single parent state
1134 * which might have large 'branches' count.
1135 */
1136 }
17a52670
AS
1137 return &elem->st;
1138err:
5896351e
AS
1139 free_verifier_state(env->cur_state, true);
1140 env->cur_state = NULL;
17a52670 1141 /* pop all elements and return */
6f8a57cc 1142 while (!pop_stack(env, NULL, NULL, false));
17a52670
AS
1143 return NULL;
1144}
1145
1146#define CALLER_SAVED_REGS 6
1147static const int caller_saved[CALLER_SAVED_REGS] = {
1148 BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
1149};
1150
f54c7898
DB
1151static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1152 struct bpf_reg_state *reg);
f1174f77 1153
e688c3db
AS
1154/* This helper doesn't clear reg->id */
1155static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
b03c9f9f 1156{
b03c9f9f
EC
1157 reg->var_off = tnum_const(imm);
1158 reg->smin_value = (s64)imm;
1159 reg->smax_value = (s64)imm;
1160 reg->umin_value = imm;
1161 reg->umax_value = imm;
3f50f132
JF
1162
1163 reg->s32_min_value = (s32)imm;
1164 reg->s32_max_value = (s32)imm;
1165 reg->u32_min_value = (u32)imm;
1166 reg->u32_max_value = (u32)imm;
1167}
1168
e688c3db
AS
1169/* Mark the unknown part of a register (variable offset or scalar value) as
1170 * known to have the value @imm.
1171 */
1172static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1173{
1174 /* Clear id, off, and union(map_ptr, range) */
1175 memset(((u8 *)reg) + sizeof(reg->type), 0,
1176 offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
1177 ___mark_reg_known(reg, imm);
1178}
1179
3f50f132
JF
1180static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1181{
1182 reg->var_off = tnum_const_subreg(reg->var_off, imm);
1183 reg->s32_min_value = (s32)imm;
1184 reg->s32_max_value = (s32)imm;
1185 reg->u32_min_value = (u32)imm;
1186 reg->u32_max_value = (u32)imm;
b03c9f9f
EC
1187}
1188
f1174f77
EC
1189/* Mark the 'variable offset' part of a register as zero. This should be
1190 * used only on registers holding a pointer type.
1191 */
1192static void __mark_reg_known_zero(struct bpf_reg_state *reg)
a9789ef9 1193{
b03c9f9f 1194 __mark_reg_known(reg, 0);
f1174f77 1195}
a9789ef9 1196
cc2b14d5
AS
1197static void __mark_reg_const_zero(struct bpf_reg_state *reg)
1198{
1199 __mark_reg_known(reg, 0);
cc2b14d5
AS
1200 reg->type = SCALAR_VALUE;
1201}
1202
61bd5218
JK
1203static void mark_reg_known_zero(struct bpf_verifier_env *env,
1204 struct bpf_reg_state *regs, u32 regno)
f1174f77
EC
1205{
1206 if (WARN_ON(regno >= MAX_BPF_REG)) {
61bd5218 1207 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
f1174f77
EC
1208 /* Something bad happened, let's kill all regs */
1209 for (regno = 0; regno < MAX_BPF_REG; regno++)
f54c7898 1210 __mark_reg_not_init(env, regs + regno);
f1174f77
EC
1211 return;
1212 }
1213 __mark_reg_known_zero(regs + regno);
1214}
1215
4ddb7416
DB
1216static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
1217{
c25b2ae1 1218 if (base_type(reg->type) == PTR_TO_MAP_VALUE) {
4ddb7416
DB
1219 const struct bpf_map *map = reg->map_ptr;
1220
1221 if (map->inner_map_meta) {
1222 reg->type = CONST_PTR_TO_MAP;
1223 reg->map_ptr = map->inner_map_meta;
3e8ce298
AS
1224 /* transfer reg's id which is unique for every map_lookup_elem
1225 * as UID of the inner map.
1226 */
34d11a44
AS
1227 if (map_value_has_timer(map->inner_map_meta))
1228 reg->map_uid = reg->id;
4ddb7416
DB
1229 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
1230 reg->type = PTR_TO_XDP_SOCK;
1231 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
1232 map->map_type == BPF_MAP_TYPE_SOCKHASH) {
1233 reg->type = PTR_TO_SOCKET;
1234 } else {
1235 reg->type = PTR_TO_MAP_VALUE;
1236 }
c25b2ae1 1237 return;
4ddb7416 1238 }
c25b2ae1
HL
1239
1240 reg->type &= ~PTR_MAYBE_NULL;
4ddb7416
DB
1241}
1242
de8f3a83
DB
1243static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1244{
1245 return type_is_pkt_pointer(reg->type);
1246}
1247
1248static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
1249{
1250 return reg_is_pkt_pointer(reg) ||
1251 reg->type == PTR_TO_PACKET_END;
1252}
1253
1254/* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
1255static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
1256 enum bpf_reg_type which)
1257{
1258 /* The register can already have a range from prior markings.
1259 * This is fine as long as it hasn't been advanced from its
1260 * origin.
1261 */
1262 return reg->type == which &&
1263 reg->id == 0 &&
1264 reg->off == 0 &&
1265 tnum_equals_const(reg->var_off, 0);
1266}
1267
3f50f132
JF
1268/* Reset the min/max bounds of a register */
1269static void __mark_reg_unbounded(struct bpf_reg_state *reg)
1270{
1271 reg->smin_value = S64_MIN;
1272 reg->smax_value = S64_MAX;
1273 reg->umin_value = 0;
1274 reg->umax_value = U64_MAX;
1275
1276 reg->s32_min_value = S32_MIN;
1277 reg->s32_max_value = S32_MAX;
1278 reg->u32_min_value = 0;
1279 reg->u32_max_value = U32_MAX;
1280}
1281
1282static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
1283{
1284 reg->smin_value = S64_MIN;
1285 reg->smax_value = S64_MAX;
1286 reg->umin_value = 0;
1287 reg->umax_value = U64_MAX;
1288}
1289
1290static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
1291{
1292 reg->s32_min_value = S32_MIN;
1293 reg->s32_max_value = S32_MAX;
1294 reg->u32_min_value = 0;
1295 reg->u32_max_value = U32_MAX;
1296}
1297
1298static void __update_reg32_bounds(struct bpf_reg_state *reg)
1299{
1300 struct tnum var32_off = tnum_subreg(reg->var_off);
1301
1302 /* min signed is max(sign bit) | min(other bits) */
1303 reg->s32_min_value = max_t(s32, reg->s32_min_value,
1304 var32_off.value | (var32_off.mask & S32_MIN));
1305 /* max signed is min(sign bit) | max(other bits) */
1306 reg->s32_max_value = min_t(s32, reg->s32_max_value,
1307 var32_off.value | (var32_off.mask & S32_MAX));
1308 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
1309 reg->u32_max_value = min(reg->u32_max_value,
1310 (u32)(var32_off.value | var32_off.mask));
1311}
1312
1313static void __update_reg64_bounds(struct bpf_reg_state *reg)
b03c9f9f
EC
1314{
1315 /* min signed is max(sign bit) | min(other bits) */
1316 reg->smin_value = max_t(s64, reg->smin_value,
1317 reg->var_off.value | (reg->var_off.mask & S64_MIN));
1318 /* max signed is min(sign bit) | max(other bits) */
1319 reg->smax_value = min_t(s64, reg->smax_value,
1320 reg->var_off.value | (reg->var_off.mask & S64_MAX));
1321 reg->umin_value = max(reg->umin_value, reg->var_off.value);
1322 reg->umax_value = min(reg->umax_value,
1323 reg->var_off.value | reg->var_off.mask);
1324}
1325
3f50f132
JF
1326static void __update_reg_bounds(struct bpf_reg_state *reg)
1327{
1328 __update_reg32_bounds(reg);
1329 __update_reg64_bounds(reg);
1330}
1331
b03c9f9f 1332/* Uses signed min/max values to inform unsigned, and vice-versa */
3f50f132
JF
1333static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
1334{
1335 /* Learn sign from signed bounds.
1336 * If we cannot cross the sign boundary, then signed and unsigned bounds
1337 * are the same, so combine. This works even in the negative case, e.g.
1338 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1339 */
1340 if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) {
1341 reg->s32_min_value = reg->u32_min_value =
1342 max_t(u32, reg->s32_min_value, reg->u32_min_value);
1343 reg->s32_max_value = reg->u32_max_value =
1344 min_t(u32, reg->s32_max_value, reg->u32_max_value);
1345 return;
1346 }
1347 /* Learn sign from unsigned bounds. Signed bounds cross the sign
1348 * boundary, so we must be careful.
1349 */
1350 if ((s32)reg->u32_max_value >= 0) {
1351 /* Positive. We can't learn anything from the smin, but smax
1352 * is positive, hence safe.
1353 */
1354 reg->s32_min_value = reg->u32_min_value;
1355 reg->s32_max_value = reg->u32_max_value =
1356 min_t(u32, reg->s32_max_value, reg->u32_max_value);
1357 } else if ((s32)reg->u32_min_value < 0) {
1358 /* Negative. We can't learn anything from the smax, but smin
1359 * is negative, hence safe.
1360 */
1361 reg->s32_min_value = reg->u32_min_value =
1362 max_t(u32, reg->s32_min_value, reg->u32_min_value);
1363 reg->s32_max_value = reg->u32_max_value;
1364 }
1365}
1366
1367static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
b03c9f9f
EC
1368{
1369 /* Learn sign from signed bounds.
1370 * If we cannot cross the sign boundary, then signed and unsigned bounds
1371 * are the same, so combine. This works even in the negative case, e.g.
1372 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1373 */
1374 if (reg->smin_value >= 0 || reg->smax_value < 0) {
1375 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1376 reg->umin_value);
1377 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1378 reg->umax_value);
1379 return;
1380 }
1381 /* Learn sign from unsigned bounds. Signed bounds cross the sign
1382 * boundary, so we must be careful.
1383 */
1384 if ((s64)reg->umax_value >= 0) {
1385 /* Positive. We can't learn anything from the smin, but smax
1386 * is positive, hence safe.
1387 */
1388 reg->smin_value = reg->umin_value;
1389 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1390 reg->umax_value);
1391 } else if ((s64)reg->umin_value < 0) {
1392 /* Negative. We can't learn anything from the smax, but smin
1393 * is negative, hence safe.
1394 */
1395 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1396 reg->umin_value);
1397 reg->smax_value = reg->umax_value;
1398 }
1399}
1400
3f50f132
JF
1401static void __reg_deduce_bounds(struct bpf_reg_state *reg)
1402{
1403 __reg32_deduce_bounds(reg);
1404 __reg64_deduce_bounds(reg);
1405}
1406
b03c9f9f
EC
1407/* Attempts to improve var_off based on unsigned min/max information */
1408static void __reg_bound_offset(struct bpf_reg_state *reg)
1409{
3f50f132
JF
1410 struct tnum var64_off = tnum_intersect(reg->var_off,
1411 tnum_range(reg->umin_value,
1412 reg->umax_value));
1413 struct tnum var32_off = tnum_intersect(tnum_subreg(reg->var_off),
1414 tnum_range(reg->u32_min_value,
1415 reg->u32_max_value));
1416
1417 reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
b03c9f9f
EC
1418}
1419
e572ff80
DB
1420static bool __reg32_bound_s64(s32 a)
1421{
1422 return a >= 0 && a <= S32_MAX;
1423}
1424
3f50f132 1425static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
b03c9f9f 1426{
3f50f132
JF
1427 reg->umin_value = reg->u32_min_value;
1428 reg->umax_value = reg->u32_max_value;
e572ff80
DB
1429
1430 /* Attempt to pull 32-bit signed bounds into 64-bit bounds but must
1431 * be positive otherwise set to worse case bounds and refine later
1432 * from tnum.
3f50f132 1433 */
e572ff80
DB
1434 if (__reg32_bound_s64(reg->s32_min_value) &&
1435 __reg32_bound_s64(reg->s32_max_value)) {
3a71dc36 1436 reg->smin_value = reg->s32_min_value;
e572ff80
DB
1437 reg->smax_value = reg->s32_max_value;
1438 } else {
3a71dc36 1439 reg->smin_value = 0;
e572ff80
DB
1440 reg->smax_value = U32_MAX;
1441 }
3f50f132
JF
1442}
1443
1444static void __reg_combine_32_into_64(struct bpf_reg_state *reg)
1445{
1446 /* special case when 64-bit register has upper 32-bit register
1447 * zeroed. Typically happens after zext or <<32, >>32 sequence
1448 * allowing us to use 32-bit bounds directly,
1449 */
1450 if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) {
1451 __reg_assign_32_into_64(reg);
1452 } else {
1453 /* Otherwise the best we can do is push lower 32bit known and
1454 * unknown bits into register (var_off set from jmp logic)
1455 * then learn as much as possible from the 64-bit tnum
1456 * known and unknown bits. The previous smin/smax bounds are
1457 * invalid here because of jmp32 compare so mark them unknown
1458 * so they do not impact tnum bounds calculation.
1459 */
1460 __mark_reg64_unbounded(reg);
1461 __update_reg_bounds(reg);
1462 }
1463
1464 /* Intersecting with the old var_off might have improved our bounds
1465 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1466 * then new var_off is (0; 0x7f...fc) which improves our umax.
1467 */
1468 __reg_deduce_bounds(reg);
1469 __reg_bound_offset(reg);
1470 __update_reg_bounds(reg);
1471}
1472
1473static bool __reg64_bound_s32(s64 a)
1474{
388e2c0b 1475 return a >= S32_MIN && a <= S32_MAX;
3f50f132
JF
1476}
1477
1478static bool __reg64_bound_u32(u64 a)
1479{
b9979db8 1480 return a >= U32_MIN && a <= U32_MAX;
3f50f132
JF
1481}
1482
1483static void __reg_combine_64_into_32(struct bpf_reg_state *reg)
1484{
1485 __mark_reg32_unbounded(reg);
1486
b0270958 1487 if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) {
3f50f132 1488 reg->s32_min_value = (s32)reg->smin_value;
3f50f132 1489 reg->s32_max_value = (s32)reg->smax_value;
b0270958 1490 }
10bf4e83 1491 if (__reg64_bound_u32(reg->umin_value) && __reg64_bound_u32(reg->umax_value)) {
3f50f132 1492 reg->u32_min_value = (u32)reg->umin_value;
3f50f132 1493 reg->u32_max_value = (u32)reg->umax_value;
10bf4e83 1494 }
3f50f132
JF
1495
1496 /* Intersecting with the old var_off might have improved our bounds
1497 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1498 * then new var_off is (0; 0x7f...fc) which improves our umax.
1499 */
1500 __reg_deduce_bounds(reg);
1501 __reg_bound_offset(reg);
1502 __update_reg_bounds(reg);
b03c9f9f
EC
1503}
1504
f1174f77 1505/* Mark a register as having a completely unknown (scalar) value. */
f54c7898
DB
1506static void __mark_reg_unknown(const struct bpf_verifier_env *env,
1507 struct bpf_reg_state *reg)
f1174f77 1508{
a9c676bc
AS
1509 /*
1510 * Clear type, id, off, and union(map_ptr, range) and
1511 * padding between 'type' and union
1512 */
1513 memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
f1174f77 1514 reg->type = SCALAR_VALUE;
f1174f77 1515 reg->var_off = tnum_unknown;
f4d7e40a 1516 reg->frameno = 0;
2c78ee89 1517 reg->precise = env->subprog_cnt > 1 || !env->bpf_capable;
b03c9f9f 1518 __mark_reg_unbounded(reg);
f1174f77
EC
1519}
1520
61bd5218
JK
1521static void mark_reg_unknown(struct bpf_verifier_env *env,
1522 struct bpf_reg_state *regs, u32 regno)
f1174f77
EC
1523{
1524 if (WARN_ON(regno >= MAX_BPF_REG)) {
61bd5218 1525 verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
19ceb417
AS
1526 /* Something bad happened, let's kill all regs except FP */
1527 for (regno = 0; regno < BPF_REG_FP; regno++)
f54c7898 1528 __mark_reg_not_init(env, regs + regno);
f1174f77
EC
1529 return;
1530 }
f54c7898 1531 __mark_reg_unknown(env, regs + regno);
f1174f77
EC
1532}
1533
f54c7898
DB
1534static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1535 struct bpf_reg_state *reg)
f1174f77 1536{
f54c7898 1537 __mark_reg_unknown(env, reg);
f1174f77
EC
1538 reg->type = NOT_INIT;
1539}
1540
61bd5218
JK
1541static void mark_reg_not_init(struct bpf_verifier_env *env,
1542 struct bpf_reg_state *regs, u32 regno)
f1174f77
EC
1543{
1544 if (WARN_ON(regno >= MAX_BPF_REG)) {
61bd5218 1545 verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
19ceb417
AS
1546 /* Something bad happened, let's kill all regs except FP */
1547 for (regno = 0; regno < BPF_REG_FP; regno++)
f54c7898 1548 __mark_reg_not_init(env, regs + regno);
f1174f77
EC
1549 return;
1550 }
f54c7898 1551 __mark_reg_not_init(env, regs + regno);
a9789ef9
DB
1552}
1553
41c48f3a
AI
1554static void mark_btf_ld_reg(struct bpf_verifier_env *env,
1555 struct bpf_reg_state *regs, u32 regno,
22dc4a0f 1556 enum bpf_reg_type reg_type,
c6f1bfe8
YS
1557 struct btf *btf, u32 btf_id,
1558 enum bpf_type_flag flag)
41c48f3a
AI
1559{
1560 if (reg_type == SCALAR_VALUE) {
1561 mark_reg_unknown(env, regs, regno);
1562 return;
1563 }
1564 mark_reg_known_zero(env, regs, regno);
c6f1bfe8 1565 regs[regno].type = PTR_TO_BTF_ID | flag;
22dc4a0f 1566 regs[regno].btf = btf;
41c48f3a
AI
1567 regs[regno].btf_id = btf_id;
1568}
1569
5327ed3d 1570#define DEF_NOT_SUBREG (0)
61bd5218 1571static void init_reg_state(struct bpf_verifier_env *env,
f4d7e40a 1572 struct bpf_func_state *state)
17a52670 1573{
f4d7e40a 1574 struct bpf_reg_state *regs = state->regs;
17a52670
AS
1575 int i;
1576
dc503a8a 1577 for (i = 0; i < MAX_BPF_REG; i++) {
61bd5218 1578 mark_reg_not_init(env, regs, i);
dc503a8a 1579 regs[i].live = REG_LIVE_NONE;
679c782d 1580 regs[i].parent = NULL;
5327ed3d 1581 regs[i].subreg_def = DEF_NOT_SUBREG;
dc503a8a 1582 }
17a52670
AS
1583
1584 /* frame pointer */
f1174f77 1585 regs[BPF_REG_FP].type = PTR_TO_STACK;
61bd5218 1586 mark_reg_known_zero(env, regs, BPF_REG_FP);
f4d7e40a 1587 regs[BPF_REG_FP].frameno = state->frameno;
6760bf2d
DB
1588}
1589
f4d7e40a
AS
1590#define BPF_MAIN_FUNC (-1)
1591static void init_func_state(struct bpf_verifier_env *env,
1592 struct bpf_func_state *state,
1593 int callsite, int frameno, int subprogno)
1594{
1595 state->callsite = callsite;
1596 state->frameno = frameno;
1597 state->subprogno = subprogno;
1598 init_reg_state(env, state);
0f55f9ed 1599 mark_verifier_state_scratched(env);
f4d7e40a
AS
1600}
1601
bfc6bb74
AS
1602/* Similar to push_stack(), but for async callbacks */
1603static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env,
1604 int insn_idx, int prev_insn_idx,
1605 int subprog)
1606{
1607 struct bpf_verifier_stack_elem *elem;
1608 struct bpf_func_state *frame;
1609
1610 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1611 if (!elem)
1612 goto err;
1613
1614 elem->insn_idx = insn_idx;
1615 elem->prev_insn_idx = prev_insn_idx;
1616 elem->next = env->head;
1617 elem->log_pos = env->log.len_used;
1618 env->head = elem;
1619 env->stack_size++;
1620 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1621 verbose(env,
1622 "The sequence of %d jumps is too complex for async cb.\n",
1623 env->stack_size);
1624 goto err;
1625 }
1626 /* Unlike push_stack() do not copy_verifier_state().
1627 * The caller state doesn't matter.
1628 * This is async callback. It starts in a fresh stack.
1629 * Initialize it similar to do_check_common().
1630 */
1631 elem->st.branches = 1;
1632 frame = kzalloc(sizeof(*frame), GFP_KERNEL);
1633 if (!frame)
1634 goto err;
1635 init_func_state(env, frame,
1636 BPF_MAIN_FUNC /* callsite */,
1637 0 /* frameno within this callchain */,
1638 subprog /* subprog number within this prog */);
1639 elem->st.frame[0] = frame;
1640 return &elem->st;
1641err:
1642 free_verifier_state(env->cur_state, true);
1643 env->cur_state = NULL;
1644 /* pop all elements and return */
1645 while (!pop_stack(env, NULL, NULL, false));
1646 return NULL;
1647}
1648
1649
17a52670
AS
1650enum reg_arg_type {
1651 SRC_OP, /* register is used as source operand */
1652 DST_OP, /* register is used as destination operand */
1653 DST_OP_NO_MARK /* same as above, check only, don't mark */
1654};
1655
cc8b0b92
AS
1656static int cmp_subprogs(const void *a, const void *b)
1657{
9c8105bd
JW
1658 return ((struct bpf_subprog_info *)a)->start -
1659 ((struct bpf_subprog_info *)b)->start;
cc8b0b92
AS
1660}
1661
1662static int find_subprog(struct bpf_verifier_env *env, int off)
1663{
9c8105bd 1664 struct bpf_subprog_info *p;
cc8b0b92 1665
9c8105bd
JW
1666 p = bsearch(&off, env->subprog_info, env->subprog_cnt,
1667 sizeof(env->subprog_info[0]), cmp_subprogs);
cc8b0b92
AS
1668 if (!p)
1669 return -ENOENT;
9c8105bd 1670 return p - env->subprog_info;
cc8b0b92
AS
1671
1672}
1673
1674static int add_subprog(struct bpf_verifier_env *env, int off)
1675{
1676 int insn_cnt = env->prog->len;
1677 int ret;
1678
1679 if (off >= insn_cnt || off < 0) {
1680 verbose(env, "call to invalid destination\n");
1681 return -EINVAL;
1682 }
1683 ret = find_subprog(env, off);
1684 if (ret >= 0)
282a0f46 1685 return ret;
4cb3d99c 1686 if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
cc8b0b92
AS
1687 verbose(env, "too many subprograms\n");
1688 return -E2BIG;
1689 }
e6ac2450 1690 /* determine subprog starts. The end is one before the next starts */
9c8105bd
JW
1691 env->subprog_info[env->subprog_cnt++].start = off;
1692 sort(env->subprog_info, env->subprog_cnt,
1693 sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
282a0f46 1694 return env->subprog_cnt - 1;
cc8b0b92
AS
1695}
1696
2357672c
KKD
1697#define MAX_KFUNC_DESCS 256
1698#define MAX_KFUNC_BTFS 256
1699
e6ac2450
MKL
1700struct bpf_kfunc_desc {
1701 struct btf_func_model func_model;
1702 u32 func_id;
1703 s32 imm;
2357672c
KKD
1704 u16 offset;
1705};
1706
1707struct bpf_kfunc_btf {
1708 struct btf *btf;
1709 struct module *module;
1710 u16 offset;
e6ac2450
MKL
1711};
1712
e6ac2450
MKL
1713struct bpf_kfunc_desc_tab {
1714 struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS];
1715 u32 nr_descs;
1716};
1717
2357672c
KKD
1718struct bpf_kfunc_btf_tab {
1719 struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS];
1720 u32 nr_descs;
1721};
1722
1723static int kfunc_desc_cmp_by_id_off(const void *a, const void *b)
e6ac2450
MKL
1724{
1725 const struct bpf_kfunc_desc *d0 = a;
1726 const struct bpf_kfunc_desc *d1 = b;
1727
1728 /* func_id is not greater than BTF_MAX_TYPE */
2357672c
KKD
1729 return d0->func_id - d1->func_id ?: d0->offset - d1->offset;
1730}
1731
1732static int kfunc_btf_cmp_by_off(const void *a, const void *b)
1733{
1734 const struct bpf_kfunc_btf *d0 = a;
1735 const struct bpf_kfunc_btf *d1 = b;
1736
1737 return d0->offset - d1->offset;
e6ac2450
MKL
1738}
1739
1740static const struct bpf_kfunc_desc *
2357672c 1741find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset)
e6ac2450
MKL
1742{
1743 struct bpf_kfunc_desc desc = {
1744 .func_id = func_id,
2357672c 1745 .offset = offset,
e6ac2450
MKL
1746 };
1747 struct bpf_kfunc_desc_tab *tab;
1748
1749 tab = prog->aux->kfunc_tab;
1750 return bsearch(&desc, tab->descs, tab->nr_descs,
2357672c
KKD
1751 sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off);
1752}
1753
1754static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env,
b202d844 1755 s16 offset)
2357672c
KKD
1756{
1757 struct bpf_kfunc_btf kf_btf = { .offset = offset };
1758 struct bpf_kfunc_btf_tab *tab;
1759 struct bpf_kfunc_btf *b;
1760 struct module *mod;
1761 struct btf *btf;
1762 int btf_fd;
1763
1764 tab = env->prog->aux->kfunc_btf_tab;
1765 b = bsearch(&kf_btf, tab->descs, tab->nr_descs,
1766 sizeof(tab->descs[0]), kfunc_btf_cmp_by_off);
1767 if (!b) {
1768 if (tab->nr_descs == MAX_KFUNC_BTFS) {
1769 verbose(env, "too many different module BTFs\n");
1770 return ERR_PTR(-E2BIG);
1771 }
1772
1773 if (bpfptr_is_null(env->fd_array)) {
1774 verbose(env, "kfunc offset > 0 without fd_array is invalid\n");
1775 return ERR_PTR(-EPROTO);
1776 }
1777
1778 if (copy_from_bpfptr_offset(&btf_fd, env->fd_array,
1779 offset * sizeof(btf_fd),
1780 sizeof(btf_fd)))
1781 return ERR_PTR(-EFAULT);
1782
1783 btf = btf_get_by_fd(btf_fd);
588cd7ef
KKD
1784 if (IS_ERR(btf)) {
1785 verbose(env, "invalid module BTF fd specified\n");
2357672c 1786 return btf;
588cd7ef 1787 }
2357672c
KKD
1788
1789 if (!btf_is_module(btf)) {
1790 verbose(env, "BTF fd for kfunc is not a module BTF\n");
1791 btf_put(btf);
1792 return ERR_PTR(-EINVAL);
1793 }
1794
1795 mod = btf_try_get_module(btf);
1796 if (!mod) {
1797 btf_put(btf);
1798 return ERR_PTR(-ENXIO);
1799 }
1800
1801 b = &tab->descs[tab->nr_descs++];
1802 b->btf = btf;
1803 b->module = mod;
1804 b->offset = offset;
1805
1806 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
1807 kfunc_btf_cmp_by_off, NULL);
1808 }
2357672c 1809 return b->btf;
e6ac2450
MKL
1810}
1811
2357672c
KKD
1812void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab)
1813{
1814 if (!tab)
1815 return;
1816
1817 while (tab->nr_descs--) {
1818 module_put(tab->descs[tab->nr_descs].module);
1819 btf_put(tab->descs[tab->nr_descs].btf);
1820 }
1821 kfree(tab);
1822}
1823
1824static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env,
b202d844 1825 u32 func_id, s16 offset)
2357672c 1826{
2357672c
KKD
1827 if (offset) {
1828 if (offset < 0) {
1829 /* In the future, this can be allowed to increase limit
1830 * of fd index into fd_array, interpreted as u16.
1831 */
1832 verbose(env, "negative offset disallowed for kernel module function call\n");
1833 return ERR_PTR(-EINVAL);
1834 }
1835
b202d844 1836 return __find_kfunc_desc_btf(env, offset);
2357672c
KKD
1837 }
1838 return btf_vmlinux ?: ERR_PTR(-ENOENT);
e6ac2450
MKL
1839}
1840
2357672c 1841static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset)
e6ac2450
MKL
1842{
1843 const struct btf_type *func, *func_proto;
2357672c 1844 struct bpf_kfunc_btf_tab *btf_tab;
e6ac2450
MKL
1845 struct bpf_kfunc_desc_tab *tab;
1846 struct bpf_prog_aux *prog_aux;
1847 struct bpf_kfunc_desc *desc;
1848 const char *func_name;
2357672c 1849 struct btf *desc_btf;
8cbf062a 1850 unsigned long call_imm;
e6ac2450
MKL
1851 unsigned long addr;
1852 int err;
1853
1854 prog_aux = env->prog->aux;
1855 tab = prog_aux->kfunc_tab;
2357672c 1856 btf_tab = prog_aux->kfunc_btf_tab;
e6ac2450
MKL
1857 if (!tab) {
1858 if (!btf_vmlinux) {
1859 verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
1860 return -ENOTSUPP;
1861 }
1862
1863 if (!env->prog->jit_requested) {
1864 verbose(env, "JIT is required for calling kernel function\n");
1865 return -ENOTSUPP;
1866 }
1867
1868 if (!bpf_jit_supports_kfunc_call()) {
1869 verbose(env, "JIT does not support calling kernel function\n");
1870 return -ENOTSUPP;
1871 }
1872
1873 if (!env->prog->gpl_compatible) {
1874 verbose(env, "cannot call kernel function from non-GPL compatible program\n");
1875 return -EINVAL;
1876 }
1877
1878 tab = kzalloc(sizeof(*tab), GFP_KERNEL);
1879 if (!tab)
1880 return -ENOMEM;
1881 prog_aux->kfunc_tab = tab;
1882 }
1883
a5d82727
KKD
1884 /* func_id == 0 is always invalid, but instead of returning an error, be
1885 * conservative and wait until the code elimination pass before returning
1886 * error, so that invalid calls that get pruned out can be in BPF programs
1887 * loaded from userspace. It is also required that offset be untouched
1888 * for such calls.
1889 */
1890 if (!func_id && !offset)
1891 return 0;
1892
2357672c
KKD
1893 if (!btf_tab && offset) {
1894 btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL);
1895 if (!btf_tab)
1896 return -ENOMEM;
1897 prog_aux->kfunc_btf_tab = btf_tab;
1898 }
1899
b202d844 1900 desc_btf = find_kfunc_desc_btf(env, func_id, offset);
2357672c
KKD
1901 if (IS_ERR(desc_btf)) {
1902 verbose(env, "failed to find BTF for kernel function\n");
1903 return PTR_ERR(desc_btf);
1904 }
1905
1906 if (find_kfunc_desc(env->prog, func_id, offset))
e6ac2450
MKL
1907 return 0;
1908
1909 if (tab->nr_descs == MAX_KFUNC_DESCS) {
1910 verbose(env, "too many different kernel function calls\n");
1911 return -E2BIG;
1912 }
1913
2357672c 1914 func = btf_type_by_id(desc_btf, func_id);
e6ac2450
MKL
1915 if (!func || !btf_type_is_func(func)) {
1916 verbose(env, "kernel btf_id %u is not a function\n",
1917 func_id);
1918 return -EINVAL;
1919 }
2357672c 1920 func_proto = btf_type_by_id(desc_btf, func->type);
e6ac2450
MKL
1921 if (!func_proto || !btf_type_is_func_proto(func_proto)) {
1922 verbose(env, "kernel function btf_id %u does not have a valid func_proto\n",
1923 func_id);
1924 return -EINVAL;
1925 }
1926
2357672c 1927 func_name = btf_name_by_offset(desc_btf, func->name_off);
e6ac2450
MKL
1928 addr = kallsyms_lookup_name(func_name);
1929 if (!addr) {
1930 verbose(env, "cannot find address for kernel function %s\n",
1931 func_name);
1932 return -EINVAL;
1933 }
1934
8cbf062a
HT
1935 call_imm = BPF_CALL_IMM(addr);
1936 /* Check whether or not the relative offset overflows desc->imm */
1937 if ((unsigned long)(s32)call_imm != call_imm) {
1938 verbose(env, "address of kernel function %s is out of range\n",
1939 func_name);
1940 return -EINVAL;
1941 }
1942
e6ac2450
MKL
1943 desc = &tab->descs[tab->nr_descs++];
1944 desc->func_id = func_id;
8cbf062a 1945 desc->imm = call_imm;
2357672c
KKD
1946 desc->offset = offset;
1947 err = btf_distill_func_proto(&env->log, desc_btf,
e6ac2450
MKL
1948 func_proto, func_name,
1949 &desc->func_model);
1950 if (!err)
1951 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2357672c 1952 kfunc_desc_cmp_by_id_off, NULL);
e6ac2450
MKL
1953 return err;
1954}
1955
1956static int kfunc_desc_cmp_by_imm(const void *a, const void *b)
1957{
1958 const struct bpf_kfunc_desc *d0 = a;
1959 const struct bpf_kfunc_desc *d1 = b;
1960
1961 if (d0->imm > d1->imm)
1962 return 1;
1963 else if (d0->imm < d1->imm)
1964 return -1;
1965 return 0;
1966}
1967
1968static void sort_kfunc_descs_by_imm(struct bpf_prog *prog)
1969{
1970 struct bpf_kfunc_desc_tab *tab;
1971
1972 tab = prog->aux->kfunc_tab;
1973 if (!tab)
1974 return;
1975
1976 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
1977 kfunc_desc_cmp_by_imm, NULL);
1978}
1979
1980bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
1981{
1982 return !!prog->aux->kfunc_tab;
1983}
1984
1985const struct btf_func_model *
1986bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
1987 const struct bpf_insn *insn)
1988{
1989 const struct bpf_kfunc_desc desc = {
1990 .imm = insn->imm,
1991 };
1992 const struct bpf_kfunc_desc *res;
1993 struct bpf_kfunc_desc_tab *tab;
1994
1995 tab = prog->aux->kfunc_tab;
1996 res = bsearch(&desc, tab->descs, tab->nr_descs,
1997 sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm);
1998
1999 return res ? &res->func_model : NULL;
2000}
2001
2002static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
cc8b0b92 2003{
9c8105bd 2004 struct bpf_subprog_info *subprog = env->subprog_info;
cc8b0b92 2005 struct bpf_insn *insn = env->prog->insnsi;
e6ac2450 2006 int i, ret, insn_cnt = env->prog->len;
cc8b0b92 2007
f910cefa
JW
2008 /* Add entry function. */
2009 ret = add_subprog(env, 0);
e6ac2450 2010 if (ret)
f910cefa
JW
2011 return ret;
2012
e6ac2450
MKL
2013 for (i = 0; i < insn_cnt; i++, insn++) {
2014 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
2015 !bpf_pseudo_kfunc_call(insn))
cc8b0b92 2016 continue;
e6ac2450 2017
2c78ee89 2018 if (!env->bpf_capable) {
e6ac2450 2019 verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
cc8b0b92
AS
2020 return -EPERM;
2021 }
e6ac2450 2022
3990ed4c 2023 if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn))
e6ac2450 2024 ret = add_subprog(env, i + insn->imm + 1);
3990ed4c 2025 else
2357672c 2026 ret = add_kfunc_call(env, insn->imm, insn->off);
e6ac2450 2027
cc8b0b92
AS
2028 if (ret < 0)
2029 return ret;
2030 }
2031
4cb3d99c
JW
2032 /* Add a fake 'exit' subprog which could simplify subprog iteration
2033 * logic. 'subprog_cnt' should not be increased.
2034 */
2035 subprog[env->subprog_cnt].start = insn_cnt;
2036
06ee7115 2037 if (env->log.level & BPF_LOG_LEVEL2)
cc8b0b92 2038 for (i = 0; i < env->subprog_cnt; i++)
9c8105bd 2039 verbose(env, "func#%d @%d\n", i, subprog[i].start);
cc8b0b92 2040
e6ac2450
MKL
2041 return 0;
2042}
2043
2044static int check_subprogs(struct bpf_verifier_env *env)
2045{
2046 int i, subprog_start, subprog_end, off, cur_subprog = 0;
2047 struct bpf_subprog_info *subprog = env->subprog_info;
2048 struct bpf_insn *insn = env->prog->insnsi;
2049 int insn_cnt = env->prog->len;
2050
cc8b0b92 2051 /* now check that all jumps are within the same subprog */
4cb3d99c
JW
2052 subprog_start = subprog[cur_subprog].start;
2053 subprog_end = subprog[cur_subprog + 1].start;
cc8b0b92
AS
2054 for (i = 0; i < insn_cnt; i++) {
2055 u8 code = insn[i].code;
2056
7f6e4312
MF
2057 if (code == (BPF_JMP | BPF_CALL) &&
2058 insn[i].imm == BPF_FUNC_tail_call &&
2059 insn[i].src_reg != BPF_PSEUDO_CALL)
2060 subprog[cur_subprog].has_tail_call = true;
09b28d76
AS
2061 if (BPF_CLASS(code) == BPF_LD &&
2062 (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
2063 subprog[cur_subprog].has_ld_abs = true;
092ed096 2064 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
cc8b0b92
AS
2065 goto next;
2066 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
2067 goto next;
2068 off = i + insn[i].off + 1;
2069 if (off < subprog_start || off >= subprog_end) {
2070 verbose(env, "jump out of range from insn %d to %d\n", i, off);
2071 return -EINVAL;
2072 }
2073next:
2074 if (i == subprog_end - 1) {
2075 /* to avoid fall-through from one subprog into another
2076 * the last insn of the subprog should be either exit
2077 * or unconditional jump back
2078 */
2079 if (code != (BPF_JMP | BPF_EXIT) &&
2080 code != (BPF_JMP | BPF_JA)) {
2081 verbose(env, "last insn is not an exit or jmp\n");
2082 return -EINVAL;
2083 }
2084 subprog_start = subprog_end;
4cb3d99c
JW
2085 cur_subprog++;
2086 if (cur_subprog < env->subprog_cnt)
9c8105bd 2087 subprog_end = subprog[cur_subprog + 1].start;
cc8b0b92
AS
2088 }
2089 }
2090 return 0;
2091}
2092
679c782d
EC
2093/* Parentage chain of this register (or stack slot) should take care of all
2094 * issues like callee-saved registers, stack slot allocation time, etc.
2095 */
f4d7e40a 2096static int mark_reg_read(struct bpf_verifier_env *env,
679c782d 2097 const struct bpf_reg_state *state,
5327ed3d 2098 struct bpf_reg_state *parent, u8 flag)
f4d7e40a
AS
2099{
2100 bool writes = parent == state->parent; /* Observe write marks */
06ee7115 2101 int cnt = 0;
dc503a8a
EC
2102
2103 while (parent) {
2104 /* if read wasn't screened by an earlier write ... */
679c782d 2105 if (writes && state->live & REG_LIVE_WRITTEN)
dc503a8a 2106 break;
9242b5f5
AS
2107 if (parent->live & REG_LIVE_DONE) {
2108 verbose(env, "verifier BUG type %s var_off %lld off %d\n",
c25b2ae1 2109 reg_type_str(env, parent->type),
9242b5f5
AS
2110 parent->var_off.value, parent->off);
2111 return -EFAULT;
2112 }
5327ed3d
JW
2113 /* The first condition is more likely to be true than the
2114 * second, checked it first.
2115 */
2116 if ((parent->live & REG_LIVE_READ) == flag ||
2117 parent->live & REG_LIVE_READ64)
25af32da
AS
2118 /* The parentage chain never changes and
2119 * this parent was already marked as LIVE_READ.
2120 * There is no need to keep walking the chain again and
2121 * keep re-marking all parents as LIVE_READ.
2122 * This case happens when the same register is read
2123 * multiple times without writes into it in-between.
5327ed3d
JW
2124 * Also, if parent has the stronger REG_LIVE_READ64 set,
2125 * then no need to set the weak REG_LIVE_READ32.
25af32da
AS
2126 */
2127 break;
dc503a8a 2128 /* ... then we depend on parent's value */
5327ed3d
JW
2129 parent->live |= flag;
2130 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
2131 if (flag == REG_LIVE_READ64)
2132 parent->live &= ~REG_LIVE_READ32;
dc503a8a
EC
2133 state = parent;
2134 parent = state->parent;
f4d7e40a 2135 writes = true;
06ee7115 2136 cnt++;
dc503a8a 2137 }
06ee7115
AS
2138
2139 if (env->longest_mark_read_walk < cnt)
2140 env->longest_mark_read_walk = cnt;
f4d7e40a 2141 return 0;
dc503a8a
EC
2142}
2143
5327ed3d
JW
2144/* This function is supposed to be used by the following 32-bit optimization
2145 * code only. It returns TRUE if the source or destination register operates
2146 * on 64-bit, otherwise return FALSE.
2147 */
2148static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
2149 u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
2150{
2151 u8 code, class, op;
2152
2153 code = insn->code;
2154 class = BPF_CLASS(code);
2155 op = BPF_OP(code);
2156 if (class == BPF_JMP) {
2157 /* BPF_EXIT for "main" will reach here. Return TRUE
2158 * conservatively.
2159 */
2160 if (op == BPF_EXIT)
2161 return true;
2162 if (op == BPF_CALL) {
2163 /* BPF to BPF call will reach here because of marking
2164 * caller saved clobber with DST_OP_NO_MARK for which we
2165 * don't care the register def because they are anyway
2166 * marked as NOT_INIT already.
2167 */
2168 if (insn->src_reg == BPF_PSEUDO_CALL)
2169 return false;
2170 /* Helper call will reach here because of arg type
2171 * check, conservatively return TRUE.
2172 */
2173 if (t == SRC_OP)
2174 return true;
2175
2176 return false;
2177 }
2178 }
2179
2180 if (class == BPF_ALU64 || class == BPF_JMP ||
2181 /* BPF_END always use BPF_ALU class. */
2182 (class == BPF_ALU && op == BPF_END && insn->imm == 64))
2183 return true;
2184
2185 if (class == BPF_ALU || class == BPF_JMP32)
2186 return false;
2187
2188 if (class == BPF_LDX) {
2189 if (t != SRC_OP)
2190 return BPF_SIZE(code) == BPF_DW;
2191 /* LDX source must be ptr. */
2192 return true;
2193 }
2194
2195 if (class == BPF_STX) {
83a28819
IL
2196 /* BPF_STX (including atomic variants) has multiple source
2197 * operands, one of which is a ptr. Check whether the caller is
2198 * asking about it.
2199 */
2200 if (t == SRC_OP && reg->type != SCALAR_VALUE)
5327ed3d
JW
2201 return true;
2202 return BPF_SIZE(code) == BPF_DW;
2203 }
2204
2205 if (class == BPF_LD) {
2206 u8 mode = BPF_MODE(code);
2207
2208 /* LD_IMM64 */
2209 if (mode == BPF_IMM)
2210 return true;
2211
2212 /* Both LD_IND and LD_ABS return 32-bit data. */
2213 if (t != SRC_OP)
2214 return false;
2215
2216 /* Implicit ctx ptr. */
2217 if (regno == BPF_REG_6)
2218 return true;
2219
2220 /* Explicit source could be any width. */
2221 return true;
2222 }
2223
2224 if (class == BPF_ST)
2225 /* The only source register for BPF_ST is a ptr. */
2226 return true;
2227
2228 /* Conservatively return true at default. */
2229 return true;
2230}
2231
83a28819
IL
2232/* Return the regno defined by the insn, or -1. */
2233static int insn_def_regno(const struct bpf_insn *insn)
b325fbca 2234{
83a28819
IL
2235 switch (BPF_CLASS(insn->code)) {
2236 case BPF_JMP:
2237 case BPF_JMP32:
2238 case BPF_ST:
2239 return -1;
2240 case BPF_STX:
2241 if (BPF_MODE(insn->code) == BPF_ATOMIC &&
2242 (insn->imm & BPF_FETCH)) {
2243 if (insn->imm == BPF_CMPXCHG)
2244 return BPF_REG_0;
2245 else
2246 return insn->src_reg;
2247 } else {
2248 return -1;
2249 }
2250 default:
2251 return insn->dst_reg;
2252 }
b325fbca
JW
2253}
2254
2255/* Return TRUE if INSN has defined any 32-bit value explicitly. */
2256static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
2257{
83a28819
IL
2258 int dst_reg = insn_def_regno(insn);
2259
2260 if (dst_reg == -1)
b325fbca
JW
2261 return false;
2262
83a28819 2263 return !is_reg64(env, insn, dst_reg, NULL, DST_OP);
b325fbca
JW
2264}
2265
5327ed3d
JW
2266static void mark_insn_zext(struct bpf_verifier_env *env,
2267 struct bpf_reg_state *reg)
2268{
2269 s32 def_idx = reg->subreg_def;
2270
2271 if (def_idx == DEF_NOT_SUBREG)
2272 return;
2273
2274 env->insn_aux_data[def_idx - 1].zext_dst = true;
2275 /* The dst will be zero extended, so won't be sub-register anymore. */
2276 reg->subreg_def = DEF_NOT_SUBREG;
2277}
2278
dc503a8a 2279static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
17a52670
AS
2280 enum reg_arg_type t)
2281{
f4d7e40a
AS
2282 struct bpf_verifier_state *vstate = env->cur_state;
2283 struct bpf_func_state *state = vstate->frame[vstate->curframe];
5327ed3d 2284 struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
c342dc10 2285 struct bpf_reg_state *reg, *regs = state->regs;
5327ed3d 2286 bool rw64;
dc503a8a 2287
17a52670 2288 if (regno >= MAX_BPF_REG) {
61bd5218 2289 verbose(env, "R%d is invalid\n", regno);
17a52670
AS
2290 return -EINVAL;
2291 }
2292
0f55f9ed
CL
2293 mark_reg_scratched(env, regno);
2294
c342dc10 2295 reg = &regs[regno];
5327ed3d 2296 rw64 = is_reg64(env, insn, regno, reg, t);
17a52670
AS
2297 if (t == SRC_OP) {
2298 /* check whether register used as source operand can be read */
c342dc10 2299 if (reg->type == NOT_INIT) {
61bd5218 2300 verbose(env, "R%d !read_ok\n", regno);
17a52670
AS
2301 return -EACCES;
2302 }
679c782d 2303 /* We don't need to worry about FP liveness because it's read-only */
c342dc10
JW
2304 if (regno == BPF_REG_FP)
2305 return 0;
2306
5327ed3d
JW
2307 if (rw64)
2308 mark_insn_zext(env, reg);
2309
2310 return mark_reg_read(env, reg, reg->parent,
2311 rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
17a52670
AS
2312 } else {
2313 /* check whether register used as dest operand can be written to */
2314 if (regno == BPF_REG_FP) {
61bd5218 2315 verbose(env, "frame pointer is read only\n");
17a52670
AS
2316 return -EACCES;
2317 }
c342dc10 2318 reg->live |= REG_LIVE_WRITTEN;
5327ed3d 2319 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
17a52670 2320 if (t == DST_OP)
61bd5218 2321 mark_reg_unknown(env, regs, regno);
17a52670
AS
2322 }
2323 return 0;
2324}
2325
b5dc0163
AS
2326/* for any branch, call, exit record the history of jmps in the given state */
2327static int push_jmp_history(struct bpf_verifier_env *env,
2328 struct bpf_verifier_state *cur)
2329{
2330 u32 cnt = cur->jmp_history_cnt;
2331 struct bpf_idx_pair *p;
2332
2333 cnt++;
2334 p = krealloc(cur->jmp_history, cnt * sizeof(*p), GFP_USER);
2335 if (!p)
2336 return -ENOMEM;
2337 p[cnt - 1].idx = env->insn_idx;
2338 p[cnt - 1].prev_idx = env->prev_insn_idx;
2339 cur->jmp_history = p;
2340 cur->jmp_history_cnt = cnt;
2341 return 0;
2342}
2343
2344/* Backtrack one insn at a time. If idx is not at the top of recorded
2345 * history then previous instruction came from straight line execution.
2346 */
2347static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
2348 u32 *history)
2349{
2350 u32 cnt = *history;
2351
2352 if (cnt && st->jmp_history[cnt - 1].idx == i) {
2353 i = st->jmp_history[cnt - 1].prev_idx;
2354 (*history)--;
2355 } else {
2356 i--;
2357 }
2358 return i;
2359}
2360
e6ac2450
MKL
2361static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
2362{
2363 const struct btf_type *func;
2357672c 2364 struct btf *desc_btf;
e6ac2450
MKL
2365
2366 if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
2367 return NULL;
2368
b202d844 2369 desc_btf = find_kfunc_desc_btf(data, insn->imm, insn->off);
2357672c
KKD
2370 if (IS_ERR(desc_btf))
2371 return "<error>";
2372
2373 func = btf_type_by_id(desc_btf, insn->imm);
2374 return btf_name_by_offset(desc_btf, func->name_off);
e6ac2450
MKL
2375}
2376
b5dc0163
AS
2377/* For given verifier state backtrack_insn() is called from the last insn to
2378 * the first insn. Its purpose is to compute a bitmask of registers and
2379 * stack slots that needs precision in the parent verifier state.
2380 */
2381static int backtrack_insn(struct bpf_verifier_env *env, int idx,
2382 u32 *reg_mask, u64 *stack_mask)
2383{
2384 const struct bpf_insn_cbs cbs = {
e6ac2450 2385 .cb_call = disasm_kfunc_name,
b5dc0163
AS
2386 .cb_print = verbose,
2387 .private_data = env,
2388 };
2389 struct bpf_insn *insn = env->prog->insnsi + idx;
2390 u8 class = BPF_CLASS(insn->code);
2391 u8 opcode = BPF_OP(insn->code);
2392 u8 mode = BPF_MODE(insn->code);
2393 u32 dreg = 1u << insn->dst_reg;
2394 u32 sreg = 1u << insn->src_reg;
2395 u32 spi;
2396
2397 if (insn->code == 0)
2398 return 0;
496f3324 2399 if (env->log.level & BPF_LOG_LEVEL2) {
b5dc0163
AS
2400 verbose(env, "regs=%x stack=%llx before ", *reg_mask, *stack_mask);
2401 verbose(env, "%d: ", idx);
2402 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
2403 }
2404
2405 if (class == BPF_ALU || class == BPF_ALU64) {
2406 if (!(*reg_mask & dreg))
2407 return 0;
2408 if (opcode == BPF_MOV) {
2409 if (BPF_SRC(insn->code) == BPF_X) {
2410 /* dreg = sreg
2411 * dreg needs precision after this insn
2412 * sreg needs precision before this insn
2413 */
2414 *reg_mask &= ~dreg;
2415 *reg_mask |= sreg;
2416 } else {
2417 /* dreg = K
2418 * dreg needs precision after this insn.
2419 * Corresponding register is already marked
2420 * as precise=true in this verifier state.
2421 * No further markings in parent are necessary
2422 */
2423 *reg_mask &= ~dreg;
2424 }
2425 } else {
2426 if (BPF_SRC(insn->code) == BPF_X) {
2427 /* dreg += sreg
2428 * both dreg and sreg need precision
2429 * before this insn
2430 */
2431 *reg_mask |= sreg;
2432 } /* else dreg += K
2433 * dreg still needs precision before this insn
2434 */
2435 }
2436 } else if (class == BPF_LDX) {
2437 if (!(*reg_mask & dreg))
2438 return 0;
2439 *reg_mask &= ~dreg;
2440
2441 /* scalars can only be spilled into stack w/o losing precision.
2442 * Load from any other memory can be zero extended.
2443 * The desire to keep that precision is already indicated
2444 * by 'precise' mark in corresponding register of this state.
2445 * No further tracking necessary.
2446 */
2447 if (insn->src_reg != BPF_REG_FP)
2448 return 0;
b5dc0163
AS
2449
2450 /* dreg = *(u64 *)[fp - off] was a fill from the stack.
2451 * that [fp - off] slot contains scalar that needs to be
2452 * tracked with precision
2453 */
2454 spi = (-insn->off - 1) / BPF_REG_SIZE;
2455 if (spi >= 64) {
2456 verbose(env, "BUG spi %d\n", spi);
2457 WARN_ONCE(1, "verifier backtracking bug");
2458 return -EFAULT;
2459 }
2460 *stack_mask |= 1ull << spi;
b3b50f05 2461 } else if (class == BPF_STX || class == BPF_ST) {
b5dc0163 2462 if (*reg_mask & dreg)
b3b50f05 2463 /* stx & st shouldn't be using _scalar_ dst_reg
b5dc0163
AS
2464 * to access memory. It means backtracking
2465 * encountered a case of pointer subtraction.
2466 */
2467 return -ENOTSUPP;
2468 /* scalars can only be spilled into stack */
2469 if (insn->dst_reg != BPF_REG_FP)
2470 return 0;
b5dc0163
AS
2471 spi = (-insn->off - 1) / BPF_REG_SIZE;
2472 if (spi >= 64) {
2473 verbose(env, "BUG spi %d\n", spi);
2474 WARN_ONCE(1, "verifier backtracking bug");
2475 return -EFAULT;
2476 }
2477 if (!(*stack_mask & (1ull << spi)))
2478 return 0;
2479 *stack_mask &= ~(1ull << spi);
b3b50f05
AN
2480 if (class == BPF_STX)
2481 *reg_mask |= sreg;
b5dc0163
AS
2482 } else if (class == BPF_JMP || class == BPF_JMP32) {
2483 if (opcode == BPF_CALL) {
2484 if (insn->src_reg == BPF_PSEUDO_CALL)
2485 return -ENOTSUPP;
2486 /* regular helper call sets R0 */
2487 *reg_mask &= ~1;
2488 if (*reg_mask & 0x3f) {
2489 /* if backtracing was looking for registers R1-R5
2490 * they should have been found already.
2491 */
2492 verbose(env, "BUG regs %x\n", *reg_mask);
2493 WARN_ONCE(1, "verifier backtracking bug");
2494 return -EFAULT;
2495 }
2496 } else if (opcode == BPF_EXIT) {
2497 return -ENOTSUPP;
2498 }
2499 } else if (class == BPF_LD) {
2500 if (!(*reg_mask & dreg))
2501 return 0;
2502 *reg_mask &= ~dreg;
2503 /* It's ld_imm64 or ld_abs or ld_ind.
2504 * For ld_imm64 no further tracking of precision
2505 * into parent is necessary
2506 */
2507 if (mode == BPF_IND || mode == BPF_ABS)
2508 /* to be analyzed */
2509 return -ENOTSUPP;
b5dc0163
AS
2510 }
2511 return 0;
2512}
2513
2514/* the scalar precision tracking algorithm:
2515 * . at the start all registers have precise=false.
2516 * . scalar ranges are tracked as normal through alu and jmp insns.
2517 * . once precise value of the scalar register is used in:
2518 * . ptr + scalar alu
2519 * . if (scalar cond K|scalar)
2520 * . helper_call(.., scalar, ...) where ARG_CONST is expected
2521 * backtrack through the verifier states and mark all registers and
2522 * stack slots with spilled constants that these scalar regisers
2523 * should be precise.
2524 * . during state pruning two registers (or spilled stack slots)
2525 * are equivalent if both are not precise.
2526 *
2527 * Note the verifier cannot simply walk register parentage chain,
2528 * since many different registers and stack slots could have been
2529 * used to compute single precise scalar.
2530 *
2531 * The approach of starting with precise=true for all registers and then
2532 * backtrack to mark a register as not precise when the verifier detects
2533 * that program doesn't care about specific value (e.g., when helper
2534 * takes register as ARG_ANYTHING parameter) is not safe.
2535 *
2536 * It's ok to walk single parentage chain of the verifier states.
2537 * It's possible that this backtracking will go all the way till 1st insn.
2538 * All other branches will be explored for needing precision later.
2539 *
2540 * The backtracking needs to deal with cases like:
2541 * 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)
2542 * r9 -= r8
2543 * r5 = r9
2544 * if r5 > 0x79f goto pc+7
2545 * R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
2546 * r5 += 1
2547 * ...
2548 * call bpf_perf_event_output#25
2549 * where .arg5_type = ARG_CONST_SIZE_OR_ZERO
2550 *
2551 * and this case:
2552 * r6 = 1
2553 * call foo // uses callee's r6 inside to compute r0
2554 * r0 += r6
2555 * if r0 == 0 goto
2556 *
2557 * to track above reg_mask/stack_mask needs to be independent for each frame.
2558 *
2559 * Also if parent's curframe > frame where backtracking started,
2560 * the verifier need to mark registers in both frames, otherwise callees
2561 * may incorrectly prune callers. This is similar to
2562 * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
2563 *
2564 * For now backtracking falls back into conservative marking.
2565 */
2566static void mark_all_scalars_precise(struct bpf_verifier_env *env,
2567 struct bpf_verifier_state *st)
2568{
2569 struct bpf_func_state *func;
2570 struct bpf_reg_state *reg;
2571 int i, j;
2572
2573 /* big hammer: mark all scalars precise in this path.
2574 * pop_stack may still get !precise scalars.
2575 */
2576 for (; st; st = st->parent)
2577 for (i = 0; i <= st->curframe; i++) {
2578 func = st->frame[i];
2579 for (j = 0; j < BPF_REG_FP; j++) {
2580 reg = &func->regs[j];
2581 if (reg->type != SCALAR_VALUE)
2582 continue;
2583 reg->precise = true;
2584 }
2585 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
27113c59 2586 if (!is_spilled_reg(&func->stack[j]))
b5dc0163
AS
2587 continue;
2588 reg = &func->stack[j].spilled_ptr;
2589 if (reg->type != SCALAR_VALUE)
2590 continue;
2591 reg->precise = true;
2592 }
2593 }
2594}
2595
a3ce685d
AS
2596static int __mark_chain_precision(struct bpf_verifier_env *env, int regno,
2597 int spi)
b5dc0163
AS
2598{
2599 struct bpf_verifier_state *st = env->cur_state;
2600 int first_idx = st->first_insn_idx;
2601 int last_idx = env->insn_idx;
2602 struct bpf_func_state *func;
2603 struct bpf_reg_state *reg;
a3ce685d
AS
2604 u32 reg_mask = regno >= 0 ? 1u << regno : 0;
2605 u64 stack_mask = spi >= 0 ? 1ull << spi : 0;
b5dc0163 2606 bool skip_first = true;
a3ce685d 2607 bool new_marks = false;
b5dc0163
AS
2608 int i, err;
2609
2c78ee89 2610 if (!env->bpf_capable)
b5dc0163
AS
2611 return 0;
2612
2613 func = st->frame[st->curframe];
a3ce685d
AS
2614 if (regno >= 0) {
2615 reg = &func->regs[regno];
2616 if (reg->type != SCALAR_VALUE) {
2617 WARN_ONCE(1, "backtracing misuse");
2618 return -EFAULT;
2619 }
2620 if (!reg->precise)
2621 new_marks = true;
2622 else
2623 reg_mask = 0;
2624 reg->precise = true;
b5dc0163 2625 }
b5dc0163 2626
a3ce685d 2627 while (spi >= 0) {
27113c59 2628 if (!is_spilled_reg(&func->stack[spi])) {
a3ce685d
AS
2629 stack_mask = 0;
2630 break;
2631 }
2632 reg = &func->stack[spi].spilled_ptr;
2633 if (reg->type != SCALAR_VALUE) {
2634 stack_mask = 0;
2635 break;
2636 }
2637 if (!reg->precise)
2638 new_marks = true;
2639 else
2640 stack_mask = 0;
2641 reg->precise = true;
2642 break;
2643 }
2644
2645 if (!new_marks)
2646 return 0;
2647 if (!reg_mask && !stack_mask)
2648 return 0;
b5dc0163
AS
2649 for (;;) {
2650 DECLARE_BITMAP(mask, 64);
b5dc0163
AS
2651 u32 history = st->jmp_history_cnt;
2652
496f3324 2653 if (env->log.level & BPF_LOG_LEVEL2)
b5dc0163
AS
2654 verbose(env, "last_idx %d first_idx %d\n", last_idx, first_idx);
2655 for (i = last_idx;;) {
2656 if (skip_first) {
2657 err = 0;
2658 skip_first = false;
2659 } else {
2660 err = backtrack_insn(env, i, &reg_mask, &stack_mask);
2661 }
2662 if (err == -ENOTSUPP) {
2663 mark_all_scalars_precise(env, st);
2664 return 0;
2665 } else if (err) {
2666 return err;
2667 }
2668 if (!reg_mask && !stack_mask)
2669 /* Found assignment(s) into tracked register in this state.
2670 * Since this state is already marked, just return.
2671 * Nothing to be tracked further in the parent state.
2672 */
2673 return 0;
2674 if (i == first_idx)
2675 break;
2676 i = get_prev_insn_idx(st, i, &history);
2677 if (i >= env->prog->len) {
2678 /* This can happen if backtracking reached insn 0
2679 * and there are still reg_mask or stack_mask
2680 * to backtrack.
2681 * It means the backtracking missed the spot where
2682 * particular register was initialized with a constant.
2683 */
2684 verbose(env, "BUG backtracking idx %d\n", i);
2685 WARN_ONCE(1, "verifier backtracking bug");
2686 return -EFAULT;
2687 }
2688 }
2689 st = st->parent;
2690 if (!st)
2691 break;
2692
a3ce685d 2693 new_marks = false;
b5dc0163
AS
2694 func = st->frame[st->curframe];
2695 bitmap_from_u64(mask, reg_mask);
2696 for_each_set_bit(i, mask, 32) {
2697 reg = &func->regs[i];
a3ce685d
AS
2698 if (reg->type != SCALAR_VALUE) {
2699 reg_mask &= ~(1u << i);
b5dc0163 2700 continue;
a3ce685d 2701 }
b5dc0163
AS
2702 if (!reg->precise)
2703 new_marks = true;
2704 reg->precise = true;
2705 }
2706
2707 bitmap_from_u64(mask, stack_mask);
2708 for_each_set_bit(i, mask, 64) {
2709 if (i >= func->allocated_stack / BPF_REG_SIZE) {
2339cd6c
AS
2710 /* the sequence of instructions:
2711 * 2: (bf) r3 = r10
2712 * 3: (7b) *(u64 *)(r3 -8) = r0
2713 * 4: (79) r4 = *(u64 *)(r10 -8)
2714 * doesn't contain jmps. It's backtracked
2715 * as a single block.
2716 * During backtracking insn 3 is not recognized as
2717 * stack access, so at the end of backtracking
2718 * stack slot fp-8 is still marked in stack_mask.
2719 * However the parent state may not have accessed
2720 * fp-8 and it's "unallocated" stack space.
2721 * In such case fallback to conservative.
b5dc0163 2722 */
2339cd6c
AS
2723 mark_all_scalars_precise(env, st);
2724 return 0;
b5dc0163
AS
2725 }
2726
27113c59 2727 if (!is_spilled_reg(&func->stack[i])) {
a3ce685d 2728 stack_mask &= ~(1ull << i);
b5dc0163 2729 continue;
a3ce685d 2730 }
b5dc0163 2731 reg = &func->stack[i].spilled_ptr;
a3ce685d
AS
2732 if (reg->type != SCALAR_VALUE) {
2733 stack_mask &= ~(1ull << i);
b5dc0163 2734 continue;
a3ce685d 2735 }
b5dc0163
AS
2736 if (!reg->precise)
2737 new_marks = true;
2738 reg->precise = true;
2739 }
496f3324 2740 if (env->log.level & BPF_LOG_LEVEL2) {
2e576648 2741 verbose(env, "parent %s regs=%x stack=%llx marks:",
b5dc0163
AS
2742 new_marks ? "didn't have" : "already had",
2743 reg_mask, stack_mask);
2e576648 2744 print_verifier_state(env, func, true);
b5dc0163
AS
2745 }
2746
a3ce685d
AS
2747 if (!reg_mask && !stack_mask)
2748 break;
b5dc0163
AS
2749 if (!new_marks)
2750 break;
2751
2752 last_idx = st->last_insn_idx;
2753 first_idx = st->first_insn_idx;
2754 }
2755 return 0;
2756}
2757
a3ce685d
AS
2758static int mark_chain_precision(struct bpf_verifier_env *env, int regno)
2759{
2760 return __mark_chain_precision(env, regno, -1);
2761}
2762
2763static int mark_chain_precision_stack(struct bpf_verifier_env *env, int spi)
2764{
2765 return __mark_chain_precision(env, -1, spi);
2766}
b5dc0163 2767
1be7f75d
AS
2768static bool is_spillable_regtype(enum bpf_reg_type type)
2769{
c25b2ae1 2770 switch (base_type(type)) {
1be7f75d 2771 case PTR_TO_MAP_VALUE:
1be7f75d
AS
2772 case PTR_TO_STACK:
2773 case PTR_TO_CTX:
969bf05e 2774 case PTR_TO_PACKET:
de8f3a83 2775 case PTR_TO_PACKET_META:
969bf05e 2776 case PTR_TO_PACKET_END:
d58e468b 2777 case PTR_TO_FLOW_KEYS:
1be7f75d 2778 case CONST_PTR_TO_MAP:
c64b7983 2779 case PTR_TO_SOCKET:
46f8bc92 2780 case PTR_TO_SOCK_COMMON:
655a51e5 2781 case PTR_TO_TCP_SOCK:
fada7fdc 2782 case PTR_TO_XDP_SOCK:
65726b5b 2783 case PTR_TO_BTF_ID:
20b2aff4 2784 case PTR_TO_BUF:
744ea4e3 2785 case PTR_TO_MEM:
69c087ba
YS
2786 case PTR_TO_FUNC:
2787 case PTR_TO_MAP_KEY:
1be7f75d
AS
2788 return true;
2789 default:
2790 return false;
2791 }
2792}
2793
cc2b14d5
AS
2794/* Does this register contain a constant zero? */
2795static bool register_is_null(struct bpf_reg_state *reg)
2796{
2797 return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
2798}
2799
f7cf25b2
AS
2800static bool register_is_const(struct bpf_reg_state *reg)
2801{
2802 return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
2803}
2804
5689d49b
YS
2805static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
2806{
2807 return tnum_is_unknown(reg->var_off) &&
2808 reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
2809 reg->umin_value == 0 && reg->umax_value == U64_MAX &&
2810 reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
2811 reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
2812}
2813
2814static bool register_is_bounded(struct bpf_reg_state *reg)
2815{
2816 return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
2817}
2818
6e7e63cb
JH
2819static bool __is_pointer_value(bool allow_ptr_leaks,
2820 const struct bpf_reg_state *reg)
2821{
2822 if (allow_ptr_leaks)
2823 return false;
2824
2825 return reg->type != SCALAR_VALUE;
2826}
2827
f7cf25b2 2828static void save_register_state(struct bpf_func_state *state,
354e8f19
MKL
2829 int spi, struct bpf_reg_state *reg,
2830 int size)
f7cf25b2
AS
2831{
2832 int i;
2833
2834 state->stack[spi].spilled_ptr = *reg;
354e8f19
MKL
2835 if (size == BPF_REG_SIZE)
2836 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
f7cf25b2 2837
354e8f19
MKL
2838 for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
2839 state->stack[spi].slot_type[i - 1] = STACK_SPILL;
f7cf25b2 2840
354e8f19
MKL
2841 /* size < 8 bytes spill */
2842 for (; i; i--)
2843 scrub_spilled_slot(&state->stack[spi].slot_type[i - 1]);
f7cf25b2
AS
2844}
2845
01f810ac 2846/* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
17a52670
AS
2847 * stack boundary and alignment are checked in check_mem_access()
2848 */
01f810ac
AM
2849static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
2850 /* stack frame we're writing to */
2851 struct bpf_func_state *state,
2852 int off, int size, int value_regno,
2853 int insn_idx)
17a52670 2854{
f4d7e40a 2855 struct bpf_func_state *cur; /* state of the current function */
638f5b90 2856 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
b5dc0163 2857 u32 dst_reg = env->prog->insnsi[insn_idx].dst_reg;
f7cf25b2 2858 struct bpf_reg_state *reg = NULL;
638f5b90 2859
c69431aa 2860 err = grow_stack_state(state, round_up(slot + 1, BPF_REG_SIZE));
638f5b90
AS
2861 if (err)
2862 return err;
9c399760
AS
2863 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
2864 * so it's aligned access and [off, off + size) are within stack limits
2865 */
638f5b90
AS
2866 if (!env->allow_ptr_leaks &&
2867 state->stack[spi].slot_type[0] == STACK_SPILL &&
2868 size != BPF_REG_SIZE) {
2869 verbose(env, "attempt to corrupt spilled pointer on stack\n");
2870 return -EACCES;
2871 }
17a52670 2872
f4d7e40a 2873 cur = env->cur_state->frame[env->cur_state->curframe];
f7cf25b2
AS
2874 if (value_regno >= 0)
2875 reg = &cur->regs[value_regno];
2039f26f
DB
2876 if (!env->bypass_spec_v4) {
2877 bool sanitize = reg && is_spillable_regtype(reg->type);
2878
2879 for (i = 0; i < size; i++) {
2880 if (state->stack[spi].slot_type[i] == STACK_INVALID) {
2881 sanitize = true;
2882 break;
2883 }
2884 }
2885
2886 if (sanitize)
2887 env->insn_aux_data[insn_idx].sanitize_stack_spill = true;
2888 }
17a52670 2889
0f55f9ed 2890 mark_stack_slot_scratched(env, spi);
354e8f19 2891 if (reg && !(off % BPF_REG_SIZE) && register_is_bounded(reg) &&
2c78ee89 2892 !register_is_null(reg) && env->bpf_capable) {
b5dc0163
AS
2893 if (dst_reg != BPF_REG_FP) {
2894 /* The backtracking logic can only recognize explicit
2895 * stack slot address like [fp - 8]. Other spill of
8fb33b60 2896 * scalar via different register has to be conservative.
b5dc0163
AS
2897 * Backtrack from here and mark all registers as precise
2898 * that contributed into 'reg' being a constant.
2899 */
2900 err = mark_chain_precision(env, value_regno);
2901 if (err)
2902 return err;
2903 }
354e8f19 2904 save_register_state(state, spi, reg, size);
f7cf25b2 2905 } else if (reg && is_spillable_regtype(reg->type)) {
17a52670 2906 /* register containing pointer is being spilled into stack */
9c399760 2907 if (size != BPF_REG_SIZE) {
f7cf25b2 2908 verbose_linfo(env, insn_idx, "; ");
61bd5218 2909 verbose(env, "invalid size of register spill\n");
17a52670
AS
2910 return -EACCES;
2911 }
f7cf25b2 2912 if (state != cur && reg->type == PTR_TO_STACK) {
f4d7e40a
AS
2913 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
2914 return -EINVAL;
2915 }
354e8f19 2916 save_register_state(state, spi, reg, size);
9c399760 2917 } else {
cc2b14d5
AS
2918 u8 type = STACK_MISC;
2919
679c782d
EC
2920 /* regular write of data into stack destroys any spilled ptr */
2921 state->stack[spi].spilled_ptr.type = NOT_INIT;
0bae2d4d 2922 /* Mark slots as STACK_MISC if they belonged to spilled ptr. */
27113c59 2923 if (is_spilled_reg(&state->stack[spi]))
0bae2d4d 2924 for (i = 0; i < BPF_REG_SIZE; i++)
354e8f19 2925 scrub_spilled_slot(&state->stack[spi].slot_type[i]);
9c399760 2926
cc2b14d5
AS
2927 /* only mark the slot as written if all 8 bytes were written
2928 * otherwise read propagation may incorrectly stop too soon
2929 * when stack slots are partially written.
2930 * This heuristic means that read propagation will be
2931 * conservative, since it will add reg_live_read marks
2932 * to stack slots all the way to first state when programs
2933 * writes+reads less than 8 bytes
2934 */
2935 if (size == BPF_REG_SIZE)
2936 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
2937
2938 /* when we zero initialize stack slots mark them as such */
b5dc0163
AS
2939 if (reg && register_is_null(reg)) {
2940 /* backtracking doesn't work for STACK_ZERO yet. */
2941 err = mark_chain_precision(env, value_regno);
2942 if (err)
2943 return err;
cc2b14d5 2944 type = STACK_ZERO;
b5dc0163 2945 }
cc2b14d5 2946
0bae2d4d 2947 /* Mark slots affected by this stack write. */
9c399760 2948 for (i = 0; i < size; i++)
638f5b90 2949 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
cc2b14d5 2950 type;
17a52670
AS
2951 }
2952 return 0;
2953}
2954
01f810ac
AM
2955/* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
2956 * known to contain a variable offset.
2957 * This function checks whether the write is permitted and conservatively
2958 * tracks the effects of the write, considering that each stack slot in the
2959 * dynamic range is potentially written to.
2960 *
2961 * 'off' includes 'regno->off'.
2962 * 'value_regno' can be -1, meaning that an unknown value is being written to
2963 * the stack.
2964 *
2965 * Spilled pointers in range are not marked as written because we don't know
2966 * what's going to be actually written. This means that read propagation for
2967 * future reads cannot be terminated by this write.
2968 *
2969 * For privileged programs, uninitialized stack slots are considered
2970 * initialized by this write (even though we don't know exactly what offsets
2971 * are going to be written to). The idea is that we don't want the verifier to
2972 * reject future reads that access slots written to through variable offsets.
2973 */
2974static int check_stack_write_var_off(struct bpf_verifier_env *env,
2975 /* func where register points to */
2976 struct bpf_func_state *state,
2977 int ptr_regno, int off, int size,
2978 int value_regno, int insn_idx)
2979{
2980 struct bpf_func_state *cur; /* state of the current function */
2981 int min_off, max_off;
2982 int i, err;
2983 struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
2984 bool writing_zero = false;
2985 /* set if the fact that we're writing a zero is used to let any
2986 * stack slots remain STACK_ZERO
2987 */
2988 bool zero_used = false;
2989
2990 cur = env->cur_state->frame[env->cur_state->curframe];
2991 ptr_reg = &cur->regs[ptr_regno];
2992 min_off = ptr_reg->smin_value + off;
2993 max_off = ptr_reg->smax_value + off + size;
2994 if (value_regno >= 0)
2995 value_reg = &cur->regs[value_regno];
2996 if (value_reg && register_is_null(value_reg))
2997 writing_zero = true;
2998
c69431aa 2999 err = grow_stack_state(state, round_up(-min_off, BPF_REG_SIZE));
01f810ac
AM
3000 if (err)
3001 return err;
3002
3003
3004 /* Variable offset writes destroy any spilled pointers in range. */
3005 for (i = min_off; i < max_off; i++) {
3006 u8 new_type, *stype;
3007 int slot, spi;
3008
3009 slot = -i - 1;
3010 spi = slot / BPF_REG_SIZE;
3011 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
0f55f9ed 3012 mark_stack_slot_scratched(env, spi);
01f810ac
AM
3013
3014 if (!env->allow_ptr_leaks
3015 && *stype != NOT_INIT
3016 && *stype != SCALAR_VALUE) {
3017 /* Reject the write if there's are spilled pointers in
3018 * range. If we didn't reject here, the ptr status
3019 * would be erased below (even though not all slots are
3020 * actually overwritten), possibly opening the door to
3021 * leaks.
3022 */
3023 verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
3024 insn_idx, i);
3025 return -EINVAL;
3026 }
3027
3028 /* Erase all spilled pointers. */
3029 state->stack[spi].spilled_ptr.type = NOT_INIT;
3030
3031 /* Update the slot type. */
3032 new_type = STACK_MISC;
3033 if (writing_zero && *stype == STACK_ZERO) {
3034 new_type = STACK_ZERO;
3035 zero_used = true;
3036 }
3037 /* If the slot is STACK_INVALID, we check whether it's OK to
3038 * pretend that it will be initialized by this write. The slot
3039 * might not actually be written to, and so if we mark it as
3040 * initialized future reads might leak uninitialized memory.
3041 * For privileged programs, we will accept such reads to slots
3042 * that may or may not be written because, if we're reject
3043 * them, the error would be too confusing.
3044 */
3045 if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
3046 verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
3047 insn_idx, i);
3048 return -EINVAL;
3049 }
3050 *stype = new_type;
3051 }
3052 if (zero_used) {
3053 /* backtracking doesn't work for STACK_ZERO yet. */
3054 err = mark_chain_precision(env, value_regno);
3055 if (err)
3056 return err;
3057 }
3058 return 0;
3059}
3060
3061/* When register 'dst_regno' is assigned some values from stack[min_off,
3062 * max_off), we set the register's type according to the types of the
3063 * respective stack slots. If all the stack values are known to be zeros, then
3064 * so is the destination reg. Otherwise, the register is considered to be
3065 * SCALAR. This function does not deal with register filling; the caller must
3066 * ensure that all spilled registers in the stack range have been marked as
3067 * read.
3068 */
3069static void mark_reg_stack_read(struct bpf_verifier_env *env,
3070 /* func where src register points to */
3071 struct bpf_func_state *ptr_state,
3072 int min_off, int max_off, int dst_regno)
3073{
3074 struct bpf_verifier_state *vstate = env->cur_state;
3075 struct bpf_func_state *state = vstate->frame[vstate->curframe];
3076 int i, slot, spi;
3077 u8 *stype;
3078 int zeros = 0;
3079
3080 for (i = min_off; i < max_off; i++) {
3081 slot = -i - 1;
3082 spi = slot / BPF_REG_SIZE;
3083 stype = ptr_state->stack[spi].slot_type;
3084 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
3085 break;
3086 zeros++;
3087 }
3088 if (zeros == max_off - min_off) {
3089 /* any access_size read into register is zero extended,
3090 * so the whole register == const_zero
3091 */
3092 __mark_reg_const_zero(&state->regs[dst_regno]);
3093 /* backtracking doesn't support STACK_ZERO yet,
3094 * so mark it precise here, so that later
3095 * backtracking can stop here.
3096 * Backtracking may not need this if this register
3097 * doesn't participate in pointer adjustment.
3098 * Forward propagation of precise flag is not
3099 * necessary either. This mark is only to stop
3100 * backtracking. Any register that contributed
3101 * to const 0 was marked precise before spill.
3102 */
3103 state->regs[dst_regno].precise = true;
3104 } else {
3105 /* have read misc data from the stack */
3106 mark_reg_unknown(env, state->regs, dst_regno);
3107 }
3108 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3109}
3110
3111/* Read the stack at 'off' and put the results into the register indicated by
3112 * 'dst_regno'. It handles reg filling if the addressed stack slot is a
3113 * spilled reg.
3114 *
3115 * 'dst_regno' can be -1, meaning that the read value is not going to a
3116 * register.
3117 *
3118 * The access is assumed to be within the current stack bounds.
3119 */
3120static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
3121 /* func where src register points to */
3122 struct bpf_func_state *reg_state,
3123 int off, int size, int dst_regno)
17a52670 3124{
f4d7e40a
AS
3125 struct bpf_verifier_state *vstate = env->cur_state;
3126 struct bpf_func_state *state = vstate->frame[vstate->curframe];
638f5b90 3127 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
f7cf25b2 3128 struct bpf_reg_state *reg;
354e8f19 3129 u8 *stype, type;
17a52670 3130
f4d7e40a 3131 stype = reg_state->stack[spi].slot_type;
f7cf25b2 3132 reg = &reg_state->stack[spi].spilled_ptr;
17a52670 3133
27113c59 3134 if (is_spilled_reg(&reg_state->stack[spi])) {
f30d4968
MKL
3135 u8 spill_size = 1;
3136
3137 for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--)
3138 spill_size++;
354e8f19 3139
f30d4968 3140 if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
f7cf25b2
AS
3141 if (reg->type != SCALAR_VALUE) {
3142 verbose_linfo(env, env->insn_idx, "; ");
3143 verbose(env, "invalid size of register fill\n");
3144 return -EACCES;
3145 }
354e8f19
MKL
3146
3147 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3148 if (dst_regno < 0)
3149 return 0;
3150
f30d4968 3151 if (!(off % BPF_REG_SIZE) && size == spill_size) {
354e8f19
MKL
3152 /* The earlier check_reg_arg() has decided the
3153 * subreg_def for this insn. Save it first.
3154 */
3155 s32 subreg_def = state->regs[dst_regno].subreg_def;
3156
3157 state->regs[dst_regno] = *reg;
3158 state->regs[dst_regno].subreg_def = subreg_def;
3159 } else {
3160 for (i = 0; i < size; i++) {
3161 type = stype[(slot - i) % BPF_REG_SIZE];
3162 if (type == STACK_SPILL)
3163 continue;
3164 if (type == STACK_MISC)
3165 continue;
3166 verbose(env, "invalid read from stack off %d+%d size %d\n",
3167 off, i, size);
3168 return -EACCES;
3169 }
01f810ac 3170 mark_reg_unknown(env, state->regs, dst_regno);
f7cf25b2 3171 }
354e8f19 3172 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
f7cf25b2 3173 return 0;
17a52670 3174 }
17a52670 3175
01f810ac 3176 if (dst_regno >= 0) {
17a52670 3177 /* restore register state from stack */
01f810ac 3178 state->regs[dst_regno] = *reg;
2f18f62e
AS
3179 /* mark reg as written since spilled pointer state likely
3180 * has its liveness marks cleared by is_state_visited()
3181 * which resets stack/reg liveness for state transitions
3182 */
01f810ac 3183 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
6e7e63cb 3184 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
01f810ac 3185 /* If dst_regno==-1, the caller is asking us whether
6e7e63cb
JH
3186 * it is acceptable to use this value as a SCALAR_VALUE
3187 * (e.g. for XADD).
3188 * We must not allow unprivileged callers to do that
3189 * with spilled pointers.
3190 */
3191 verbose(env, "leaking pointer from stack off %d\n",
3192 off);
3193 return -EACCES;
dc503a8a 3194 }
f7cf25b2 3195 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
17a52670
AS
3196 } else {
3197 for (i = 0; i < size; i++) {
01f810ac
AM
3198 type = stype[(slot - i) % BPF_REG_SIZE];
3199 if (type == STACK_MISC)
cc2b14d5 3200 continue;
01f810ac 3201 if (type == STACK_ZERO)
cc2b14d5 3202 continue;
cc2b14d5
AS
3203 verbose(env, "invalid read from stack off %d+%d size %d\n",
3204 off, i, size);
3205 return -EACCES;
3206 }
f7cf25b2 3207 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
01f810ac
AM
3208 if (dst_regno >= 0)
3209 mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
17a52670 3210 }
f7cf25b2 3211 return 0;
17a52670
AS
3212}
3213
01f810ac
AM
3214enum stack_access_src {
3215 ACCESS_DIRECT = 1, /* the access is performed by an instruction */
3216 ACCESS_HELPER = 2, /* the access is performed by a helper */
3217};
3218
3219static int check_stack_range_initialized(struct bpf_verifier_env *env,
3220 int regno, int off, int access_size,
3221 bool zero_size_allowed,
3222 enum stack_access_src type,
3223 struct bpf_call_arg_meta *meta);
3224
3225static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
3226{
3227 return cur_regs(env) + regno;
3228}
3229
3230/* Read the stack at 'ptr_regno + off' and put the result into the register
3231 * 'dst_regno'.
3232 * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
3233 * but not its variable offset.
3234 * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
3235 *
3236 * As opposed to check_stack_read_fixed_off, this function doesn't deal with
3237 * filling registers (i.e. reads of spilled register cannot be detected when
3238 * the offset is not fixed). We conservatively mark 'dst_regno' as containing
3239 * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
3240 * offset; for a fixed offset check_stack_read_fixed_off should be used
3241 * instead.
3242 */
3243static int check_stack_read_var_off(struct bpf_verifier_env *env,
3244 int ptr_regno, int off, int size, int dst_regno)
e4298d25 3245{
01f810ac
AM
3246 /* The state of the source register. */
3247 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3248 struct bpf_func_state *ptr_state = func(env, reg);
3249 int err;
3250 int min_off, max_off;
3251
3252 /* Note that we pass a NULL meta, so raw access will not be permitted.
e4298d25 3253 */
01f810ac
AM
3254 err = check_stack_range_initialized(env, ptr_regno, off, size,
3255 false, ACCESS_DIRECT, NULL);
3256 if (err)
3257 return err;
3258
3259 min_off = reg->smin_value + off;
3260 max_off = reg->smax_value + off;
3261 mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
3262 return 0;
3263}
3264
3265/* check_stack_read dispatches to check_stack_read_fixed_off or
3266 * check_stack_read_var_off.
3267 *
3268 * The caller must ensure that the offset falls within the allocated stack
3269 * bounds.
3270 *
3271 * 'dst_regno' is a register which will receive the value from the stack. It
3272 * can be -1, meaning that the read value is not going to a register.
3273 */
3274static int check_stack_read(struct bpf_verifier_env *env,
3275 int ptr_regno, int off, int size,
3276 int dst_regno)
3277{
3278 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3279 struct bpf_func_state *state = func(env, reg);
3280 int err;
3281 /* Some accesses are only permitted with a static offset. */
3282 bool var_off = !tnum_is_const(reg->var_off);
3283
3284 /* The offset is required to be static when reads don't go to a
3285 * register, in order to not leak pointers (see
3286 * check_stack_read_fixed_off).
3287 */
3288 if (dst_regno < 0 && var_off) {
e4298d25
DB
3289 char tn_buf[48];
3290
3291 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
01f810ac 3292 verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
e4298d25
DB
3293 tn_buf, off, size);
3294 return -EACCES;
3295 }
01f810ac
AM
3296 /* Variable offset is prohibited for unprivileged mode for simplicity
3297 * since it requires corresponding support in Spectre masking for stack
3298 * ALU. See also retrieve_ptr_limit().
3299 */
3300 if (!env->bypass_spec_v1 && var_off) {
3301 char tn_buf[48];
e4298d25 3302
01f810ac
AM
3303 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3304 verbose(env, "R%d variable offset stack access prohibited for !root, var_off=%s\n",
3305 ptr_regno, tn_buf);
e4298d25
DB
3306 return -EACCES;
3307 }
3308
01f810ac
AM
3309 if (!var_off) {
3310 off += reg->var_off.value;
3311 err = check_stack_read_fixed_off(env, state, off, size,
3312 dst_regno);
3313 } else {
3314 /* Variable offset stack reads need more conservative handling
3315 * than fixed offset ones. Note that dst_regno >= 0 on this
3316 * branch.
3317 */
3318 err = check_stack_read_var_off(env, ptr_regno, off, size,
3319 dst_regno);
3320 }
3321 return err;
3322}
3323
3324
3325/* check_stack_write dispatches to check_stack_write_fixed_off or
3326 * check_stack_write_var_off.
3327 *
3328 * 'ptr_regno' is the register used as a pointer into the stack.
3329 * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
3330 * 'value_regno' is the register whose value we're writing to the stack. It can
3331 * be -1, meaning that we're not writing from a register.
3332 *
3333 * The caller must ensure that the offset falls within the maximum stack size.
3334 */
3335static int check_stack_write(struct bpf_verifier_env *env,
3336 int ptr_regno, int off, int size,
3337 int value_regno, int insn_idx)
3338{
3339 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3340 struct bpf_func_state *state = func(env, reg);
3341 int err;
3342
3343 if (tnum_is_const(reg->var_off)) {
3344 off += reg->var_off.value;
3345 err = check_stack_write_fixed_off(env, state, off, size,
3346 value_regno, insn_idx);
3347 } else {
3348 /* Variable offset stack reads need more conservative handling
3349 * than fixed offset ones.
3350 */
3351 err = check_stack_write_var_off(env, state,
3352 ptr_regno, off, size,
3353 value_regno, insn_idx);
3354 }
3355 return err;
e4298d25
DB
3356}
3357
591fe988
DB
3358static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
3359 int off, int size, enum bpf_access_type type)
3360{
3361 struct bpf_reg_state *regs = cur_regs(env);
3362 struct bpf_map *map = regs[regno].map_ptr;
3363 u32 cap = bpf_map_flags_to_cap(map);
3364
3365 if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
3366 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
3367 map->value_size, off, size);
3368 return -EACCES;
3369 }
3370
3371 if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
3372 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
3373 map->value_size, off, size);
3374 return -EACCES;
3375 }
3376
3377 return 0;
3378}
3379
457f4436
AN
3380/* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
3381static int __check_mem_access(struct bpf_verifier_env *env, int regno,
3382 int off, int size, u32 mem_size,
3383 bool zero_size_allowed)
17a52670 3384{
457f4436
AN
3385 bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
3386 struct bpf_reg_state *reg;
3387
3388 if (off >= 0 && size_ok && (u64)off + size <= mem_size)
3389 return 0;
17a52670 3390
457f4436
AN
3391 reg = &cur_regs(env)[regno];
3392 switch (reg->type) {
69c087ba
YS
3393 case PTR_TO_MAP_KEY:
3394 verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
3395 mem_size, off, size);
3396 break;
457f4436 3397 case PTR_TO_MAP_VALUE:
61bd5218 3398 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
457f4436
AN
3399 mem_size, off, size);
3400 break;
3401 case PTR_TO_PACKET:
3402 case PTR_TO_PACKET_META:
3403 case PTR_TO_PACKET_END:
3404 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
3405 off, size, regno, reg->id, off, mem_size);
3406 break;
3407 case PTR_TO_MEM:
3408 default:
3409 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
3410 mem_size, off, size);
17a52670 3411 }
457f4436
AN
3412
3413 return -EACCES;
17a52670
AS
3414}
3415
457f4436
AN
3416/* check read/write into a memory region with possible variable offset */
3417static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
3418 int off, int size, u32 mem_size,
3419 bool zero_size_allowed)
dbcfe5f7 3420{
f4d7e40a
AS
3421 struct bpf_verifier_state *vstate = env->cur_state;
3422 struct bpf_func_state *state = vstate->frame[vstate->curframe];
dbcfe5f7
GB
3423 struct bpf_reg_state *reg = &state->regs[regno];
3424 int err;
3425
457f4436 3426 /* We may have adjusted the register pointing to memory region, so we
f1174f77
EC
3427 * need to try adding each of min_value and max_value to off
3428 * to make sure our theoretical access will be safe.
2e576648
CL
3429 *
3430 * The minimum value is only important with signed
dbcfe5f7
GB
3431 * comparisons where we can't assume the floor of a
3432 * value is 0. If we are using signed variables for our
3433 * index'es we need to make sure that whatever we use
3434 * will have a set floor within our range.
3435 */
b7137c4e
DB
3436 if (reg->smin_value < 0 &&
3437 (reg->smin_value == S64_MIN ||
3438 (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
3439 reg->smin_value + off < 0)) {
61bd5218 3440 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
dbcfe5f7
GB
3441 regno);
3442 return -EACCES;
3443 }
457f4436
AN
3444 err = __check_mem_access(env, regno, reg->smin_value + off, size,
3445 mem_size, zero_size_allowed);
dbcfe5f7 3446 if (err) {
457f4436 3447 verbose(env, "R%d min value is outside of the allowed memory range\n",
61bd5218 3448 regno);
dbcfe5f7
GB
3449 return err;
3450 }
3451
b03c9f9f
EC
3452 /* If we haven't set a max value then we need to bail since we can't be
3453 * sure we won't do bad things.
3454 * If reg->umax_value + off could overflow, treat that as unbounded too.
dbcfe5f7 3455 */
b03c9f9f 3456 if (reg->umax_value >= BPF_MAX_VAR_OFF) {
457f4436 3457 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
dbcfe5f7
GB
3458 regno);
3459 return -EACCES;
3460 }
457f4436
AN
3461 err = __check_mem_access(env, regno, reg->umax_value + off, size,
3462 mem_size, zero_size_allowed);
3463 if (err) {
3464 verbose(env, "R%d max value is outside of the allowed memory range\n",
61bd5218 3465 regno);
457f4436
AN
3466 return err;
3467 }
3468
3469 return 0;
3470}
d83525ca 3471
457f4436
AN
3472/* check read/write into a map element with possible variable offset */
3473static int check_map_access(struct bpf_verifier_env *env, u32 regno,
3474 int off, int size, bool zero_size_allowed)
3475{
3476 struct bpf_verifier_state *vstate = env->cur_state;
3477 struct bpf_func_state *state = vstate->frame[vstate->curframe];
3478 struct bpf_reg_state *reg = &state->regs[regno];
3479 struct bpf_map *map = reg->map_ptr;
3480 int err;
3481
3482 err = check_mem_region_access(env, regno, off, size, map->value_size,
3483 zero_size_allowed);
3484 if (err)
3485 return err;
3486
3487 if (map_value_has_spin_lock(map)) {
3488 u32 lock = map->spin_lock_off;
d83525ca
AS
3489
3490 /* if any part of struct bpf_spin_lock can be touched by
3491 * load/store reject this program.
3492 * To check that [x1, x2) overlaps with [y1, y2)
3493 * it is sufficient to check x1 < y2 && y1 < x2.
3494 */
3495 if (reg->smin_value + off < lock + sizeof(struct bpf_spin_lock) &&
3496 lock < reg->umax_value + off + size) {
3497 verbose(env, "bpf_spin_lock cannot be accessed directly by load/store\n");
3498 return -EACCES;
3499 }
3500 }
68134668
AS
3501 if (map_value_has_timer(map)) {
3502 u32 t = map->timer_off;
3503
3504 if (reg->smin_value + off < t + sizeof(struct bpf_timer) &&
3505 t < reg->umax_value + off + size) {
3506 verbose(env, "bpf_timer cannot be accessed directly by load/store\n");
3507 return -EACCES;
3508 }
3509 }
f1174f77 3510 return err;
dbcfe5f7
GB
3511}
3512
969bf05e
AS
3513#define MAX_PACKET_OFF 0xffff
3514
58e2af8b 3515static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
3a0af8fd
TG
3516 const struct bpf_call_arg_meta *meta,
3517 enum bpf_access_type t)
4acf6c0b 3518{
7e40781c
UP
3519 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
3520
3521 switch (prog_type) {
5d66fa7d 3522 /* Program types only with direct read access go here! */
3a0af8fd
TG
3523 case BPF_PROG_TYPE_LWT_IN:
3524 case BPF_PROG_TYPE_LWT_OUT:
004d4b27 3525 case BPF_PROG_TYPE_LWT_SEG6LOCAL:
2dbb9b9e 3526 case BPF_PROG_TYPE_SK_REUSEPORT:
5d66fa7d 3527 case BPF_PROG_TYPE_FLOW_DISSECTOR:
d5563d36 3528 case BPF_PROG_TYPE_CGROUP_SKB:
3a0af8fd
TG
3529 if (t == BPF_WRITE)
3530 return false;
8731745e 3531 fallthrough;
5d66fa7d
DB
3532
3533 /* Program types with direct read + write access go here! */
36bbef52
DB
3534 case BPF_PROG_TYPE_SCHED_CLS:
3535 case BPF_PROG_TYPE_SCHED_ACT:
4acf6c0b 3536 case BPF_PROG_TYPE_XDP:
3a0af8fd 3537 case BPF_PROG_TYPE_LWT_XMIT:
8a31db56 3538 case BPF_PROG_TYPE_SK_SKB:
4f738adb 3539 case BPF_PROG_TYPE_SK_MSG:
36bbef52
DB
3540 if (meta)
3541 return meta->pkt_access;
3542
3543 env->seen_direct_write = true;
4acf6c0b 3544 return true;
0d01da6a
SF
3545
3546 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
3547 if (t == BPF_WRITE)
3548 env->seen_direct_write = true;
3549
3550 return true;
3551
4acf6c0b
BB
3552 default:
3553 return false;
3554 }
3555}
3556
f1174f77 3557static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
9fd29c08 3558 int size, bool zero_size_allowed)
f1174f77 3559{
638f5b90 3560 struct bpf_reg_state *regs = cur_regs(env);
f1174f77
EC
3561 struct bpf_reg_state *reg = &regs[regno];
3562 int err;
3563
3564 /* We may have added a variable offset to the packet pointer; but any
3565 * reg->range we have comes after that. We are only checking the fixed
3566 * offset.
3567 */
3568
3569 /* We don't allow negative numbers, because we aren't tracking enough
3570 * detail to prove they're safe.
3571 */
b03c9f9f 3572 if (reg->smin_value < 0) {
61bd5218 3573 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
f1174f77
EC
3574 regno);
3575 return -EACCES;
3576 }
6d94e741
AS
3577
3578 err = reg->range < 0 ? -EINVAL :
3579 __check_mem_access(env, regno, off, size, reg->range,
457f4436 3580 zero_size_allowed);
f1174f77 3581 if (err) {
61bd5218 3582 verbose(env, "R%d offset is outside of the packet\n", regno);
f1174f77
EC
3583 return err;
3584 }
e647815a 3585
457f4436 3586 /* __check_mem_access has made sure "off + size - 1" is within u16.
e647815a
JW
3587 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
3588 * otherwise find_good_pkt_pointers would have refused to set range info
457f4436 3589 * that __check_mem_access would have rejected this pkt access.
e647815a
JW
3590 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
3591 */
3592 env->prog->aux->max_pkt_offset =
3593 max_t(u32, env->prog->aux->max_pkt_offset,
3594 off + reg->umax_value + size - 1);
3595
f1174f77
EC
3596 return err;
3597}
3598
3599/* check access to 'struct bpf_context' fields. Supports fixed offsets only */
31fd8581 3600static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
9e15db66 3601 enum bpf_access_type t, enum bpf_reg_type *reg_type,
22dc4a0f 3602 struct btf **btf, u32 *btf_id)
17a52670 3603{
f96da094
DB
3604 struct bpf_insn_access_aux info = {
3605 .reg_type = *reg_type,
9e15db66 3606 .log = &env->log,
f96da094 3607 };
31fd8581 3608
4f9218aa 3609 if (env->ops->is_valid_access &&
5e43f899 3610 env->ops->is_valid_access(off, size, t, env->prog, &info)) {
f96da094
DB
3611 /* A non zero info.ctx_field_size indicates that this field is a
3612 * candidate for later verifier transformation to load the whole
3613 * field and then apply a mask when accessed with a narrower
3614 * access than actual ctx access size. A zero info.ctx_field_size
3615 * will only allow for whole field access and rejects any other
3616 * type of narrower access.
31fd8581 3617 */
23994631 3618 *reg_type = info.reg_type;
31fd8581 3619
c25b2ae1 3620 if (base_type(*reg_type) == PTR_TO_BTF_ID) {
22dc4a0f 3621 *btf = info.btf;
9e15db66 3622 *btf_id = info.btf_id;
22dc4a0f 3623 } else {
9e15db66 3624 env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
22dc4a0f 3625 }
32bbe007
AS
3626 /* remember the offset of last byte accessed in ctx */
3627 if (env->prog->aux->max_ctx_offset < off + size)
3628 env->prog->aux->max_ctx_offset = off + size;
17a52670 3629 return 0;
32bbe007 3630 }
17a52670 3631
61bd5218 3632 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
17a52670
AS
3633 return -EACCES;
3634}
3635
d58e468b
PP
3636static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
3637 int size)
3638{
3639 if (size < 0 || off < 0 ||
3640 (u64)off + size > sizeof(struct bpf_flow_keys)) {
3641 verbose(env, "invalid access to flow keys off=%d size=%d\n",
3642 off, size);
3643 return -EACCES;
3644 }
3645 return 0;
3646}
3647
5f456649
MKL
3648static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
3649 u32 regno, int off, int size,
3650 enum bpf_access_type t)
c64b7983
JS
3651{
3652 struct bpf_reg_state *regs = cur_regs(env);
3653 struct bpf_reg_state *reg = &regs[regno];
5f456649 3654 struct bpf_insn_access_aux info = {};
46f8bc92 3655 bool valid;
c64b7983
JS
3656
3657 if (reg->smin_value < 0) {
3658 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3659 regno);
3660 return -EACCES;
3661 }
3662
46f8bc92
MKL
3663 switch (reg->type) {
3664 case PTR_TO_SOCK_COMMON:
3665 valid = bpf_sock_common_is_valid_access(off, size, t, &info);
3666 break;
3667 case PTR_TO_SOCKET:
3668 valid = bpf_sock_is_valid_access(off, size, t, &info);
3669 break;
655a51e5
MKL
3670 case PTR_TO_TCP_SOCK:
3671 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
3672 break;
fada7fdc
JL
3673 case PTR_TO_XDP_SOCK:
3674 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
3675 break;
46f8bc92
MKL
3676 default:
3677 valid = false;
c64b7983
JS
3678 }
3679
5f456649 3680
46f8bc92
MKL
3681 if (valid) {
3682 env->insn_aux_data[insn_idx].ctx_field_size =
3683 info.ctx_field_size;
3684 return 0;
3685 }
3686
3687 verbose(env, "R%d invalid %s access off=%d size=%d\n",
c25b2ae1 3688 regno, reg_type_str(env, reg->type), off, size);
46f8bc92
MKL
3689
3690 return -EACCES;
c64b7983
JS
3691}
3692
4cabc5b1
DB
3693static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
3694{
2a159c6f 3695 return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
4cabc5b1
DB
3696}
3697
f37a8cb8
DB
3698static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
3699{
2a159c6f 3700 const struct bpf_reg_state *reg = reg_state(env, regno);
f37a8cb8 3701
46f8bc92
MKL
3702 return reg->type == PTR_TO_CTX;
3703}
3704
3705static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
3706{
3707 const struct bpf_reg_state *reg = reg_state(env, regno);
3708
3709 return type_is_sk_pointer(reg->type);
f37a8cb8
DB
3710}
3711
ca369602
DB
3712static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
3713{
2a159c6f 3714 const struct bpf_reg_state *reg = reg_state(env, regno);
ca369602
DB
3715
3716 return type_is_pkt_pointer(reg->type);
3717}
3718
4b5defde
DB
3719static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
3720{
3721 const struct bpf_reg_state *reg = reg_state(env, regno);
3722
3723 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
3724 return reg->type == PTR_TO_FLOW_KEYS;
3725}
3726
61bd5218
JK
3727static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
3728 const struct bpf_reg_state *reg,
d1174416 3729 int off, int size, bool strict)
969bf05e 3730{
f1174f77 3731 struct tnum reg_off;
e07b98d9 3732 int ip_align;
d1174416
DM
3733
3734 /* Byte size accesses are always allowed. */
3735 if (!strict || size == 1)
3736 return 0;
3737
e4eda884
DM
3738 /* For platforms that do not have a Kconfig enabling
3739 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
3740 * NET_IP_ALIGN is universally set to '2'. And on platforms
3741 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
3742 * to this code only in strict mode where we want to emulate
3743 * the NET_IP_ALIGN==2 checking. Therefore use an
3744 * unconditional IP align value of '2'.
e07b98d9 3745 */
e4eda884 3746 ip_align = 2;
f1174f77
EC
3747
3748 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
3749 if (!tnum_is_aligned(reg_off, size)) {
3750 char tn_buf[48];
3751
3752 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
61bd5218
JK
3753 verbose(env,
3754 "misaligned packet access off %d+%s+%d+%d size %d\n",
f1174f77 3755 ip_align, tn_buf, reg->off, off, size);
969bf05e
AS
3756 return -EACCES;
3757 }
79adffcd 3758
969bf05e
AS
3759 return 0;
3760}
3761
61bd5218
JK
3762static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
3763 const struct bpf_reg_state *reg,
f1174f77
EC
3764 const char *pointer_desc,
3765 int off, int size, bool strict)
79adffcd 3766{
f1174f77
EC
3767 struct tnum reg_off;
3768
3769 /* Byte size accesses are always allowed. */
3770 if (!strict || size == 1)
3771 return 0;
3772
3773 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
3774 if (!tnum_is_aligned(reg_off, size)) {
3775 char tn_buf[48];
3776
3777 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
61bd5218 3778 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
f1174f77 3779 pointer_desc, tn_buf, reg->off, off, size);
79adffcd
DB
3780 return -EACCES;
3781 }
3782
969bf05e
AS
3783 return 0;
3784}
3785
e07b98d9 3786static int check_ptr_alignment(struct bpf_verifier_env *env,
ca369602
DB
3787 const struct bpf_reg_state *reg, int off,
3788 int size, bool strict_alignment_once)
79adffcd 3789{
ca369602 3790 bool strict = env->strict_alignment || strict_alignment_once;
f1174f77 3791 const char *pointer_desc = "";
d1174416 3792
79adffcd
DB
3793 switch (reg->type) {
3794 case PTR_TO_PACKET:
de8f3a83
DB
3795 case PTR_TO_PACKET_META:
3796 /* Special case, because of NET_IP_ALIGN. Given metadata sits
3797 * right in front, treat it the very same way.
3798 */
61bd5218 3799 return check_pkt_ptr_alignment(env, reg, off, size, strict);
d58e468b
PP
3800 case PTR_TO_FLOW_KEYS:
3801 pointer_desc = "flow keys ";
3802 break;
69c087ba
YS
3803 case PTR_TO_MAP_KEY:
3804 pointer_desc = "key ";
3805 break;
f1174f77
EC
3806 case PTR_TO_MAP_VALUE:
3807 pointer_desc = "value ";
3808 break;
3809 case PTR_TO_CTX:
3810 pointer_desc = "context ";
3811 break;
3812 case PTR_TO_STACK:
3813 pointer_desc = "stack ";
01f810ac
AM
3814 /* The stack spill tracking logic in check_stack_write_fixed_off()
3815 * and check_stack_read_fixed_off() relies on stack accesses being
a5ec6ae1
JH
3816 * aligned.
3817 */
3818 strict = true;
f1174f77 3819 break;
c64b7983
JS
3820 case PTR_TO_SOCKET:
3821 pointer_desc = "sock ";
3822 break;
46f8bc92
MKL
3823 case PTR_TO_SOCK_COMMON:
3824 pointer_desc = "sock_common ";
3825 break;
655a51e5
MKL
3826 case PTR_TO_TCP_SOCK:
3827 pointer_desc = "tcp_sock ";
3828 break;
fada7fdc
JL
3829 case PTR_TO_XDP_SOCK:
3830 pointer_desc = "xdp_sock ";
3831 break;
79adffcd 3832 default:
f1174f77 3833 break;
79adffcd 3834 }
61bd5218
JK
3835 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
3836 strict);
79adffcd
DB
3837}
3838
f4d7e40a
AS
3839static int update_stack_depth(struct bpf_verifier_env *env,
3840 const struct bpf_func_state *func,
3841 int off)
3842{
9c8105bd 3843 u16 stack = env->subprog_info[func->subprogno].stack_depth;
f4d7e40a
AS
3844
3845 if (stack >= -off)
3846 return 0;
3847
3848 /* update known max for given subprogram */
9c8105bd 3849 env->subprog_info[func->subprogno].stack_depth = -off;
70a87ffe
AS
3850 return 0;
3851}
f4d7e40a 3852
70a87ffe
AS
3853/* starting from main bpf function walk all instructions of the function
3854 * and recursively walk all callees that given function can call.
3855 * Ignore jump and exit insns.
3856 * Since recursion is prevented by check_cfg() this algorithm
3857 * only needs a local stack of MAX_CALL_FRAMES to remember callsites
3858 */
3859static int check_max_stack_depth(struct bpf_verifier_env *env)
3860{
9c8105bd
JW
3861 int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
3862 struct bpf_subprog_info *subprog = env->subprog_info;
70a87ffe 3863 struct bpf_insn *insn = env->prog->insnsi;
ebf7d1f5 3864 bool tail_call_reachable = false;
70a87ffe
AS
3865 int ret_insn[MAX_CALL_FRAMES];
3866 int ret_prog[MAX_CALL_FRAMES];
ebf7d1f5 3867 int j;
f4d7e40a 3868
70a87ffe 3869process_func:
7f6e4312
MF
3870 /* protect against potential stack overflow that might happen when
3871 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
3872 * depth for such case down to 256 so that the worst case scenario
3873 * would result in 8k stack size (32 which is tailcall limit * 256 =
3874 * 8k).
3875 *
3876 * To get the idea what might happen, see an example:
3877 * func1 -> sub rsp, 128
3878 * subfunc1 -> sub rsp, 256
3879 * tailcall1 -> add rsp, 256
3880 * func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
3881 * subfunc2 -> sub rsp, 64
3882 * subfunc22 -> sub rsp, 128
3883 * tailcall2 -> add rsp, 128
3884 * func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
3885 *
3886 * tailcall will unwind the current stack frame but it will not get rid
3887 * of caller's stack as shown on the example above.
3888 */
3889 if (idx && subprog[idx].has_tail_call && depth >= 256) {
3890 verbose(env,
3891 "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
3892 depth);
3893 return -EACCES;
3894 }
70a87ffe
AS
3895 /* round up to 32-bytes, since this is granularity
3896 * of interpreter stack size
3897 */
9c8105bd 3898 depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
70a87ffe 3899 if (depth > MAX_BPF_STACK) {
f4d7e40a 3900 verbose(env, "combined stack size of %d calls is %d. Too large\n",
70a87ffe 3901 frame + 1, depth);
f4d7e40a
AS
3902 return -EACCES;
3903 }
70a87ffe 3904continue_func:
4cb3d99c 3905 subprog_end = subprog[idx + 1].start;
70a87ffe 3906 for (; i < subprog_end; i++) {
7ddc80a4
AS
3907 int next_insn;
3908
69c087ba 3909 if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
70a87ffe
AS
3910 continue;
3911 /* remember insn and function to return to */
3912 ret_insn[frame] = i + 1;
9c8105bd 3913 ret_prog[frame] = idx;
70a87ffe
AS
3914
3915 /* find the callee */
7ddc80a4
AS
3916 next_insn = i + insn[i].imm + 1;
3917 idx = find_subprog(env, next_insn);
9c8105bd 3918 if (idx < 0) {
70a87ffe 3919 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
7ddc80a4 3920 next_insn);
70a87ffe
AS
3921 return -EFAULT;
3922 }
7ddc80a4
AS
3923 if (subprog[idx].is_async_cb) {
3924 if (subprog[idx].has_tail_call) {
3925 verbose(env, "verifier bug. subprog has tail_call and async cb\n");
3926 return -EFAULT;
3927 }
3928 /* async callbacks don't increase bpf prog stack size */
3929 continue;
3930 }
3931 i = next_insn;
ebf7d1f5
MF
3932
3933 if (subprog[idx].has_tail_call)
3934 tail_call_reachable = true;
3935
70a87ffe
AS
3936 frame++;
3937 if (frame >= MAX_CALL_FRAMES) {
927cb781
PC
3938 verbose(env, "the call stack of %d frames is too deep !\n",
3939 frame);
3940 return -E2BIG;
70a87ffe
AS
3941 }
3942 goto process_func;
3943 }
ebf7d1f5
MF
3944 /* if tail call got detected across bpf2bpf calls then mark each of the
3945 * currently present subprog frames as tail call reachable subprogs;
3946 * this info will be utilized by JIT so that we will be preserving the
3947 * tail call counter throughout bpf2bpf calls combined with tailcalls
3948 */
3949 if (tail_call_reachable)
3950 for (j = 0; j < frame; j++)
3951 subprog[ret_prog[j]].tail_call_reachable = true;
5dd0a6b8
DB
3952 if (subprog[0].tail_call_reachable)
3953 env->prog->aux->tail_call_reachable = true;
ebf7d1f5 3954
70a87ffe
AS
3955 /* end of for() loop means the last insn of the 'subprog'
3956 * was reached. Doesn't matter whether it was JA or EXIT
3957 */
3958 if (frame == 0)
3959 return 0;
9c8105bd 3960 depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
70a87ffe
AS
3961 frame--;
3962 i = ret_insn[frame];
9c8105bd 3963 idx = ret_prog[frame];
70a87ffe 3964 goto continue_func;
f4d7e40a
AS
3965}
3966
19d28fbd 3967#ifndef CONFIG_BPF_JIT_ALWAYS_ON
1ea47e01
AS
3968static int get_callee_stack_depth(struct bpf_verifier_env *env,
3969 const struct bpf_insn *insn, int idx)
3970{
3971 int start = idx + insn->imm + 1, subprog;
3972
3973 subprog = find_subprog(env, start);
3974 if (subprog < 0) {
3975 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
3976 start);
3977 return -EFAULT;
3978 }
9c8105bd 3979 return env->subprog_info[subprog].stack_depth;
1ea47e01 3980}
19d28fbd 3981#endif
1ea47e01 3982
6788ab23
DB
3983static int __check_ptr_off_reg(struct bpf_verifier_env *env,
3984 const struct bpf_reg_state *reg, int regno,
3985 bool fixed_off_ok)
58990d1f 3986{
be80a1d3
DB
3987 /* Access to this pointer-typed register or passing it to a helper
3988 * is only allowed in its original, unmodified form.
58990d1f
DB
3989 */
3990
e1fad0ff
KKD
3991 if (reg->off < 0) {
3992 verbose(env, "negative offset %s ptr R%d off=%d disallowed\n",
3993 reg_type_str(env, reg->type), regno, reg->off);
3994 return -EACCES;
3995 }
3996
6788ab23 3997 if (!fixed_off_ok && reg->off) {
be80a1d3
DB
3998 verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n",
3999 reg_type_str(env, reg->type), regno, reg->off);
58990d1f
DB
4000 return -EACCES;
4001 }
4002
4003 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4004 char tn_buf[48];
4005
4006 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
be80a1d3
DB
4007 verbose(env, "variable %s access var_off=%s disallowed\n",
4008 reg_type_str(env, reg->type), tn_buf);
58990d1f
DB
4009 return -EACCES;
4010 }
4011
4012 return 0;
4013}
4014
6788ab23
DB
4015int check_ptr_off_reg(struct bpf_verifier_env *env,
4016 const struct bpf_reg_state *reg, int regno)
4017{
4018 return __check_ptr_off_reg(env, reg, regno, false);
4019}
4020
afbf21dc
YS
4021static int __check_buffer_access(struct bpf_verifier_env *env,
4022 const char *buf_info,
4023 const struct bpf_reg_state *reg,
4024 int regno, int off, int size)
9df1c28b
MM
4025{
4026 if (off < 0) {
4027 verbose(env,
4fc00b79 4028 "R%d invalid %s buffer access: off=%d, size=%d\n",
afbf21dc 4029 regno, buf_info, off, size);
9df1c28b
MM
4030 return -EACCES;
4031 }
4032 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4033 char tn_buf[48];
4034
4035 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4036 verbose(env,
4fc00b79 4037 "R%d invalid variable buffer offset: off=%d, var_off=%s\n",
9df1c28b
MM
4038 regno, off, tn_buf);
4039 return -EACCES;
4040 }
afbf21dc
YS
4041
4042 return 0;
4043}
4044
4045static int check_tp_buffer_access(struct bpf_verifier_env *env,
4046 const struct bpf_reg_state *reg,
4047 int regno, int off, int size)
4048{
4049 int err;
4050
4051 err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
4052 if (err)
4053 return err;
4054
9df1c28b
MM
4055 if (off + size > env->prog->aux->max_tp_access)
4056 env->prog->aux->max_tp_access = off + size;
4057
4058 return 0;
4059}
4060
afbf21dc
YS
4061static int check_buffer_access(struct bpf_verifier_env *env,
4062 const struct bpf_reg_state *reg,
4063 int regno, int off, int size,
4064 bool zero_size_allowed,
afbf21dc
YS
4065 u32 *max_access)
4066{
44e9a741 4067 const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr";
afbf21dc
YS
4068 int err;
4069
4070 err = __check_buffer_access(env, buf_info, reg, regno, off, size);
4071 if (err)
4072 return err;
4073
4074 if (off + size > *max_access)
4075 *max_access = off + size;
4076
4077 return 0;
4078}
4079
3f50f132
JF
4080/* BPF architecture zero extends alu32 ops into 64-bit registesr */
4081static void zext_32_to_64(struct bpf_reg_state *reg)
4082{
4083 reg->var_off = tnum_subreg(reg->var_off);
4084 __reg_assign_32_into_64(reg);
4085}
9df1c28b 4086
0c17d1d2
JH
4087/* truncate register to smaller size (in bytes)
4088 * must be called with size < BPF_REG_SIZE
4089 */
4090static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
4091{
4092 u64 mask;
4093
4094 /* clear high bits in bit representation */
4095 reg->var_off = tnum_cast(reg->var_off, size);
4096
4097 /* fix arithmetic bounds */
4098 mask = ((u64)1 << (size * 8)) - 1;
4099 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
4100 reg->umin_value &= mask;
4101 reg->umax_value &= mask;
4102 } else {
4103 reg->umin_value = 0;
4104 reg->umax_value = mask;
4105 }
4106 reg->smin_value = reg->umin_value;
4107 reg->smax_value = reg->umax_value;
3f50f132
JF
4108
4109 /* If size is smaller than 32bit register the 32bit register
4110 * values are also truncated so we push 64-bit bounds into
4111 * 32-bit bounds. Above were truncated < 32-bits already.
4112 */
4113 if (size >= 4)
4114 return;
4115 __reg_combine_64_into_32(reg);
0c17d1d2
JH
4116}
4117
a23740ec
AN
4118static bool bpf_map_is_rdonly(const struct bpf_map *map)
4119{
353050be
DB
4120 /* A map is considered read-only if the following condition are true:
4121 *
4122 * 1) BPF program side cannot change any of the map content. The
4123 * BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
4124 * and was set at map creation time.
4125 * 2) The map value(s) have been initialized from user space by a
4126 * loader and then "frozen", such that no new map update/delete
4127 * operations from syscall side are possible for the rest of
4128 * the map's lifetime from that point onwards.
4129 * 3) Any parallel/pending map update/delete operations from syscall
4130 * side have been completed. Only after that point, it's safe to
4131 * assume that map value(s) are immutable.
4132 */
4133 return (map->map_flags & BPF_F_RDONLY_PROG) &&
4134 READ_ONCE(map->frozen) &&
4135 !bpf_map_write_active(map);
a23740ec
AN
4136}
4137
4138static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val)
4139{
4140 void *ptr;
4141 u64 addr;
4142 int err;
4143
4144 err = map->ops->map_direct_value_addr(map, &addr, off);
4145 if (err)
4146 return err;
2dedd7d2 4147 ptr = (void *)(long)addr + off;
a23740ec
AN
4148
4149 switch (size) {
4150 case sizeof(u8):
4151 *val = (u64)*(u8 *)ptr;
4152 break;
4153 case sizeof(u16):
4154 *val = (u64)*(u16 *)ptr;
4155 break;
4156 case sizeof(u32):
4157 *val = (u64)*(u32 *)ptr;
4158 break;
4159 case sizeof(u64):
4160 *val = *(u64 *)ptr;
4161 break;
4162 default:
4163 return -EINVAL;
4164 }
4165 return 0;
4166}
4167
9e15db66
AS
4168static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
4169 struct bpf_reg_state *regs,
4170 int regno, int off, int size,
4171 enum bpf_access_type atype,
4172 int value_regno)
4173{
4174 struct bpf_reg_state *reg = regs + regno;
22dc4a0f
AN
4175 const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
4176 const char *tname = btf_name_by_offset(reg->btf, t->name_off);
c6f1bfe8 4177 enum bpf_type_flag flag = 0;
9e15db66
AS
4178 u32 btf_id;
4179 int ret;
4180
9e15db66
AS
4181 if (off < 0) {
4182 verbose(env,
4183 "R%d is ptr_%s invalid negative access: off=%d\n",
4184 regno, tname, off);
4185 return -EACCES;
4186 }
4187 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4188 char tn_buf[48];
4189
4190 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4191 verbose(env,
4192 "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
4193 regno, tname, off, tn_buf);
4194 return -EACCES;
4195 }
4196
c6f1bfe8
YS
4197 if (reg->type & MEM_USER) {
4198 verbose(env,
4199 "R%d is ptr_%s access user memory: off=%d\n",
4200 regno, tname, off);
4201 return -EACCES;
4202 }
4203
5844101a
HL
4204 if (reg->type & MEM_PERCPU) {
4205 verbose(env,
4206 "R%d is ptr_%s access percpu memory: off=%d\n",
4207 regno, tname, off);
4208 return -EACCES;
4209 }
4210
27ae7997 4211 if (env->ops->btf_struct_access) {
22dc4a0f 4212 ret = env->ops->btf_struct_access(&env->log, reg->btf, t,
c6f1bfe8 4213 off, size, atype, &btf_id, &flag);
27ae7997
MKL
4214 } else {
4215 if (atype != BPF_READ) {
4216 verbose(env, "only read is supported\n");
4217 return -EACCES;
4218 }
4219
22dc4a0f 4220 ret = btf_struct_access(&env->log, reg->btf, t, off, size,
c6f1bfe8 4221 atype, &btf_id, &flag);
27ae7997
MKL
4222 }
4223
9e15db66
AS
4224 if (ret < 0)
4225 return ret;
4226
41c48f3a 4227 if (atype == BPF_READ && value_regno >= 0)
c6f1bfe8 4228 mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag);
41c48f3a
AI
4229
4230 return 0;
4231}
4232
4233static int check_ptr_to_map_access(struct bpf_verifier_env *env,
4234 struct bpf_reg_state *regs,
4235 int regno, int off, int size,
4236 enum bpf_access_type atype,
4237 int value_regno)
4238{
4239 struct bpf_reg_state *reg = regs + regno;
4240 struct bpf_map *map = reg->map_ptr;
c6f1bfe8 4241 enum bpf_type_flag flag = 0;
41c48f3a
AI
4242 const struct btf_type *t;
4243 const char *tname;
4244 u32 btf_id;
4245 int ret;
4246
4247 if (!btf_vmlinux) {
4248 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
4249 return -ENOTSUPP;
4250 }
4251
4252 if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
4253 verbose(env, "map_ptr access not supported for map type %d\n",
4254 map->map_type);
4255 return -ENOTSUPP;
4256 }
4257
4258 t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
4259 tname = btf_name_by_offset(btf_vmlinux, t->name_off);
4260
4261 if (!env->allow_ptr_to_map_access) {
4262 verbose(env,
4263 "%s access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
4264 tname);
4265 return -EPERM;
9e15db66 4266 }
27ae7997 4267
41c48f3a
AI
4268 if (off < 0) {
4269 verbose(env, "R%d is %s invalid negative access: off=%d\n",
4270 regno, tname, off);
4271 return -EACCES;
4272 }
4273
4274 if (atype != BPF_READ) {
4275 verbose(env, "only read from %s is supported\n", tname);
4276 return -EACCES;
4277 }
4278
c6f1bfe8 4279 ret = btf_struct_access(&env->log, btf_vmlinux, t, off, size, atype, &btf_id, &flag);
41c48f3a
AI
4280 if (ret < 0)
4281 return ret;
4282
4283 if (value_regno >= 0)
c6f1bfe8 4284 mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag);
41c48f3a 4285
9e15db66
AS
4286 return 0;
4287}
4288
01f810ac
AM
4289/* Check that the stack access at the given offset is within bounds. The
4290 * maximum valid offset is -1.
4291 *
4292 * The minimum valid offset is -MAX_BPF_STACK for writes, and
4293 * -state->allocated_stack for reads.
4294 */
4295static int check_stack_slot_within_bounds(int off,
4296 struct bpf_func_state *state,
4297 enum bpf_access_type t)
4298{
4299 int min_valid_off;
4300
4301 if (t == BPF_WRITE)
4302 min_valid_off = -MAX_BPF_STACK;
4303 else
4304 min_valid_off = -state->allocated_stack;
4305
4306 if (off < min_valid_off || off > -1)
4307 return -EACCES;
4308 return 0;
4309}
4310
4311/* Check that the stack access at 'regno + off' falls within the maximum stack
4312 * bounds.
4313 *
4314 * 'off' includes `regno->offset`, but not its dynamic part (if any).
4315 */
4316static int check_stack_access_within_bounds(
4317 struct bpf_verifier_env *env,
4318 int regno, int off, int access_size,
4319 enum stack_access_src src, enum bpf_access_type type)
4320{
4321 struct bpf_reg_state *regs = cur_regs(env);
4322 struct bpf_reg_state *reg = regs + regno;
4323 struct bpf_func_state *state = func(env, reg);
4324 int min_off, max_off;
4325 int err;
4326 char *err_extra;
4327
4328 if (src == ACCESS_HELPER)
4329 /* We don't know if helpers are reading or writing (or both). */
4330 err_extra = " indirect access to";
4331 else if (type == BPF_READ)
4332 err_extra = " read from";
4333 else
4334 err_extra = " write to";
4335
4336 if (tnum_is_const(reg->var_off)) {
4337 min_off = reg->var_off.value + off;
4338 if (access_size > 0)
4339 max_off = min_off + access_size - 1;
4340 else
4341 max_off = min_off;
4342 } else {
4343 if (reg->smax_value >= BPF_MAX_VAR_OFF ||
4344 reg->smin_value <= -BPF_MAX_VAR_OFF) {
4345 verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
4346 err_extra, regno);
4347 return -EACCES;
4348 }
4349 min_off = reg->smin_value + off;
4350 if (access_size > 0)
4351 max_off = reg->smax_value + off + access_size - 1;
4352 else
4353 max_off = min_off;
4354 }
4355
4356 err = check_stack_slot_within_bounds(min_off, state, type);
4357 if (!err)
4358 err = check_stack_slot_within_bounds(max_off, state, type);
4359
4360 if (err) {
4361 if (tnum_is_const(reg->var_off)) {
4362 verbose(env, "invalid%s stack R%d off=%d size=%d\n",
4363 err_extra, regno, off, access_size);
4364 } else {
4365 char tn_buf[48];
4366
4367 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4368 verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
4369 err_extra, regno, tn_buf, access_size);
4370 }
4371 }
4372 return err;
4373}
41c48f3a 4374
17a52670
AS
4375/* check whether memory at (regno + off) is accessible for t = (read | write)
4376 * if t==write, value_regno is a register which value is stored into memory
4377 * if t==read, value_regno is a register which will receive the value from memory
4378 * if t==write && value_regno==-1, some unknown value is stored into memory
4379 * if t==read && value_regno==-1, don't care what we read from memory
4380 */
ca369602
DB
4381static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
4382 int off, int bpf_size, enum bpf_access_type t,
4383 int value_regno, bool strict_alignment_once)
17a52670 4384{
638f5b90
AS
4385 struct bpf_reg_state *regs = cur_regs(env);
4386 struct bpf_reg_state *reg = regs + regno;
f4d7e40a 4387 struct bpf_func_state *state;
17a52670
AS
4388 int size, err = 0;
4389
4390 size = bpf_size_to_bytes(bpf_size);
4391 if (size < 0)
4392 return size;
4393
f1174f77 4394 /* alignment checks will add in reg->off themselves */
ca369602 4395 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
969bf05e
AS
4396 if (err)
4397 return err;
17a52670 4398
f1174f77
EC
4399 /* for access checks, reg->off is just part of off */
4400 off += reg->off;
4401
69c087ba
YS
4402 if (reg->type == PTR_TO_MAP_KEY) {
4403 if (t == BPF_WRITE) {
4404 verbose(env, "write to change key R%d not allowed\n", regno);
4405 return -EACCES;
4406 }
4407
4408 err = check_mem_region_access(env, regno, off, size,
4409 reg->map_ptr->key_size, false);
4410 if (err)
4411 return err;
4412 if (value_regno >= 0)
4413 mark_reg_unknown(env, regs, value_regno);
4414 } else if (reg->type == PTR_TO_MAP_VALUE) {
1be7f75d
AS
4415 if (t == BPF_WRITE && value_regno >= 0 &&
4416 is_pointer_value(env, value_regno)) {
61bd5218 4417 verbose(env, "R%d leaks addr into map\n", value_regno);
1be7f75d
AS
4418 return -EACCES;
4419 }
591fe988
DB
4420 err = check_map_access_type(env, regno, off, size, t);
4421 if (err)
4422 return err;
9fd29c08 4423 err = check_map_access(env, regno, off, size, false);
a23740ec
AN
4424 if (!err && t == BPF_READ && value_regno >= 0) {
4425 struct bpf_map *map = reg->map_ptr;
4426
4427 /* if map is read-only, track its contents as scalars */
4428 if (tnum_is_const(reg->var_off) &&
4429 bpf_map_is_rdonly(map) &&
4430 map->ops->map_direct_value_addr) {
4431 int map_off = off + reg->var_off.value;
4432 u64 val = 0;
4433
4434 err = bpf_map_direct_read(map, map_off, size,
4435 &val);
4436 if (err)
4437 return err;
4438
4439 regs[value_regno].type = SCALAR_VALUE;
4440 __mark_reg_known(&regs[value_regno], val);
4441 } else {
4442 mark_reg_unknown(env, regs, value_regno);
4443 }
4444 }
34d3a78c
HL
4445 } else if (base_type(reg->type) == PTR_TO_MEM) {
4446 bool rdonly_mem = type_is_rdonly_mem(reg->type);
4447
4448 if (type_may_be_null(reg->type)) {
4449 verbose(env, "R%d invalid mem access '%s'\n", regno,
4450 reg_type_str(env, reg->type));
4451 return -EACCES;
4452 }
4453
4454 if (t == BPF_WRITE && rdonly_mem) {
4455 verbose(env, "R%d cannot write into %s\n",
4456 regno, reg_type_str(env, reg->type));
4457 return -EACCES;
4458 }
4459
457f4436
AN
4460 if (t == BPF_WRITE && value_regno >= 0 &&
4461 is_pointer_value(env, value_regno)) {
4462 verbose(env, "R%d leaks addr into mem\n", value_regno);
4463 return -EACCES;
4464 }
34d3a78c 4465
457f4436
AN
4466 err = check_mem_region_access(env, regno, off, size,
4467 reg->mem_size, false);
34d3a78c 4468 if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
457f4436 4469 mark_reg_unknown(env, regs, value_regno);
1a0dc1ac 4470 } else if (reg->type == PTR_TO_CTX) {
f1174f77 4471 enum bpf_reg_type reg_type = SCALAR_VALUE;
22dc4a0f 4472 struct btf *btf = NULL;
9e15db66 4473 u32 btf_id = 0;
19de99f7 4474
1be7f75d
AS
4475 if (t == BPF_WRITE && value_regno >= 0 &&
4476 is_pointer_value(env, value_regno)) {
61bd5218 4477 verbose(env, "R%d leaks addr into ctx\n", value_regno);
1be7f75d
AS
4478 return -EACCES;
4479 }
f1174f77 4480
be80a1d3 4481 err = check_ptr_off_reg(env, reg, regno);
58990d1f
DB
4482 if (err < 0)
4483 return err;
4484
c6f1bfe8
YS
4485 err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf,
4486 &btf_id);
9e15db66
AS
4487 if (err)
4488 verbose_linfo(env, insn_idx, "; ");
969bf05e 4489 if (!err && t == BPF_READ && value_regno >= 0) {
f1174f77 4490 /* ctx access returns either a scalar, or a
de8f3a83
DB
4491 * PTR_TO_PACKET[_META,_END]. In the latter
4492 * case, we know the offset is zero.
f1174f77 4493 */
46f8bc92 4494 if (reg_type == SCALAR_VALUE) {
638f5b90 4495 mark_reg_unknown(env, regs, value_regno);
46f8bc92 4496 } else {
638f5b90 4497 mark_reg_known_zero(env, regs,
61bd5218 4498 value_regno);
c25b2ae1 4499 if (type_may_be_null(reg_type))
46f8bc92 4500 regs[value_regno].id = ++env->id_gen;
5327ed3d
JW
4501 /* A load of ctx field could have different
4502 * actual load size with the one encoded in the
4503 * insn. When the dst is PTR, it is for sure not
4504 * a sub-register.
4505 */
4506 regs[value_regno].subreg_def = DEF_NOT_SUBREG;
c25b2ae1 4507 if (base_type(reg_type) == PTR_TO_BTF_ID) {
22dc4a0f 4508 regs[value_regno].btf = btf;
9e15db66 4509 regs[value_regno].btf_id = btf_id;
22dc4a0f 4510 }
46f8bc92 4511 }
638f5b90 4512 regs[value_regno].type = reg_type;
969bf05e 4513 }
17a52670 4514
f1174f77 4515 } else if (reg->type == PTR_TO_STACK) {
01f810ac
AM
4516 /* Basic bounds checks. */
4517 err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
e4298d25
DB
4518 if (err)
4519 return err;
8726679a 4520
f4d7e40a
AS
4521 state = func(env, reg);
4522 err = update_stack_depth(env, state, off);
4523 if (err)
4524 return err;
8726679a 4525
01f810ac
AM
4526 if (t == BPF_READ)
4527 err = check_stack_read(env, regno, off, size,
61bd5218 4528 value_regno);
01f810ac
AM
4529 else
4530 err = check_stack_write(env, regno, off, size,
4531 value_regno, insn_idx);
de8f3a83 4532 } else if (reg_is_pkt_pointer(reg)) {
3a0af8fd 4533 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
61bd5218 4534 verbose(env, "cannot write into packet\n");
969bf05e
AS
4535 return -EACCES;
4536 }
4acf6c0b
BB
4537 if (t == BPF_WRITE && value_regno >= 0 &&
4538 is_pointer_value(env, value_regno)) {
61bd5218
JK
4539 verbose(env, "R%d leaks addr into packet\n",
4540 value_regno);
4acf6c0b
BB
4541 return -EACCES;
4542 }
9fd29c08 4543 err = check_packet_access(env, regno, off, size, false);
969bf05e 4544 if (!err && t == BPF_READ && value_regno >= 0)
638f5b90 4545 mark_reg_unknown(env, regs, value_regno);
d58e468b
PP
4546 } else if (reg->type == PTR_TO_FLOW_KEYS) {
4547 if (t == BPF_WRITE && value_regno >= 0 &&
4548 is_pointer_value(env, value_regno)) {
4549 verbose(env, "R%d leaks addr into flow keys\n",
4550 value_regno);
4551 return -EACCES;
4552 }
4553
4554 err = check_flow_keys_access(env, off, size);
4555 if (!err && t == BPF_READ && value_regno >= 0)
4556 mark_reg_unknown(env, regs, value_regno);
46f8bc92 4557 } else if (type_is_sk_pointer(reg->type)) {
c64b7983 4558 if (t == BPF_WRITE) {
46f8bc92 4559 verbose(env, "R%d cannot write into %s\n",
c25b2ae1 4560 regno, reg_type_str(env, reg->type));
c64b7983
JS
4561 return -EACCES;
4562 }
5f456649 4563 err = check_sock_access(env, insn_idx, regno, off, size, t);
c64b7983
JS
4564 if (!err && value_regno >= 0)
4565 mark_reg_unknown(env, regs, value_regno);
9df1c28b
MM
4566 } else if (reg->type == PTR_TO_TP_BUFFER) {
4567 err = check_tp_buffer_access(env, reg, regno, off, size);
4568 if (!err && t == BPF_READ && value_regno >= 0)
4569 mark_reg_unknown(env, regs, value_regno);
bff61f6f
HL
4570 } else if (base_type(reg->type) == PTR_TO_BTF_ID &&
4571 !type_may_be_null(reg->type)) {
9e15db66
AS
4572 err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
4573 value_regno);
41c48f3a
AI
4574 } else if (reg->type == CONST_PTR_TO_MAP) {
4575 err = check_ptr_to_map_access(env, regs, regno, off, size, t,
4576 value_regno);
20b2aff4
HL
4577 } else if (base_type(reg->type) == PTR_TO_BUF) {
4578 bool rdonly_mem = type_is_rdonly_mem(reg->type);
20b2aff4
HL
4579 u32 *max_access;
4580
4581 if (rdonly_mem) {
4582 if (t == BPF_WRITE) {
4583 verbose(env, "R%d cannot write into %s\n",
4584 regno, reg_type_str(env, reg->type));
4585 return -EACCES;
4586 }
20b2aff4
HL
4587 max_access = &env->prog->aux->max_rdonly_access;
4588 } else {
20b2aff4 4589 max_access = &env->prog->aux->max_rdwr_access;
afbf21dc 4590 }
20b2aff4 4591
f6dfbe31 4592 err = check_buffer_access(env, reg, regno, off, size, false,
44e9a741 4593 max_access);
20b2aff4
HL
4594
4595 if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
afbf21dc 4596 mark_reg_unknown(env, regs, value_regno);
17a52670 4597 } else {
61bd5218 4598 verbose(env, "R%d invalid mem access '%s'\n", regno,
c25b2ae1 4599 reg_type_str(env, reg->type));
17a52670
AS
4600 return -EACCES;
4601 }
969bf05e 4602
f1174f77 4603 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
638f5b90 4604 regs[value_regno].type == SCALAR_VALUE) {
f1174f77 4605 /* b/h/w load zero-extends, mark upper bits as known 0 */
0c17d1d2 4606 coerce_reg_to_size(&regs[value_regno], size);
969bf05e 4607 }
17a52670
AS
4608 return err;
4609}
4610
91c960b0 4611static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
17a52670 4612{
5ffa2550 4613 int load_reg;
17a52670
AS
4614 int err;
4615
5ca419f2
BJ
4616 switch (insn->imm) {
4617 case BPF_ADD:
4618 case BPF_ADD | BPF_FETCH:
981f94c3
BJ
4619 case BPF_AND:
4620 case BPF_AND | BPF_FETCH:
4621 case BPF_OR:
4622 case BPF_OR | BPF_FETCH:
4623 case BPF_XOR:
4624 case BPF_XOR | BPF_FETCH:
5ffa2550
BJ
4625 case BPF_XCHG:
4626 case BPF_CMPXCHG:
5ca419f2
BJ
4627 break;
4628 default:
91c960b0
BJ
4629 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
4630 return -EINVAL;
4631 }
4632
4633 if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
4634 verbose(env, "invalid atomic operand size\n");
17a52670
AS
4635 return -EINVAL;
4636 }
4637
4638 /* check src1 operand */
dc503a8a 4639 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17a52670
AS
4640 if (err)
4641 return err;
4642
4643 /* check src2 operand */
dc503a8a 4644 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17a52670
AS
4645 if (err)
4646 return err;
4647
5ffa2550
BJ
4648 if (insn->imm == BPF_CMPXCHG) {
4649 /* Check comparison of R0 with memory location */
a82fe085
DB
4650 const u32 aux_reg = BPF_REG_0;
4651
4652 err = check_reg_arg(env, aux_reg, SRC_OP);
5ffa2550
BJ
4653 if (err)
4654 return err;
a82fe085
DB
4655
4656 if (is_pointer_value(env, aux_reg)) {
4657 verbose(env, "R%d leaks addr into mem\n", aux_reg);
4658 return -EACCES;
4659 }
5ffa2550
BJ
4660 }
4661
6bdf6abc 4662 if (is_pointer_value(env, insn->src_reg)) {
61bd5218 4663 verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
6bdf6abc
DB
4664 return -EACCES;
4665 }
4666
ca369602 4667 if (is_ctx_reg(env, insn->dst_reg) ||
4b5defde 4668 is_pkt_reg(env, insn->dst_reg) ||
46f8bc92
MKL
4669 is_flow_key_reg(env, insn->dst_reg) ||
4670 is_sk_reg(env, insn->dst_reg)) {
91c960b0 4671 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
2a159c6f 4672 insn->dst_reg,
c25b2ae1 4673 reg_type_str(env, reg_state(env, insn->dst_reg)->type));
f37a8cb8
DB
4674 return -EACCES;
4675 }
4676
37086bfd
BJ
4677 if (insn->imm & BPF_FETCH) {
4678 if (insn->imm == BPF_CMPXCHG)
4679 load_reg = BPF_REG_0;
4680 else
4681 load_reg = insn->src_reg;
4682
4683 /* check and record load of old value */
4684 err = check_reg_arg(env, load_reg, DST_OP);
4685 if (err)
4686 return err;
4687 } else {
4688 /* This instruction accesses a memory location but doesn't
4689 * actually load it into a register.
4690 */
4691 load_reg = -1;
4692 }
4693
7d3baf0a
DB
4694 /* Check whether we can read the memory, with second call for fetch
4695 * case to simulate the register fill.
4696 */
31fd8581 4697 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
7d3baf0a
DB
4698 BPF_SIZE(insn->code), BPF_READ, -1, true);
4699 if (!err && load_reg >= 0)
4700 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
4701 BPF_SIZE(insn->code), BPF_READ, load_reg,
4702 true);
17a52670
AS
4703 if (err)
4704 return err;
4705
7d3baf0a 4706 /* Check whether we can write into the same memory. */
5ca419f2
BJ
4707 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
4708 BPF_SIZE(insn->code), BPF_WRITE, -1, true);
4709 if (err)
4710 return err;
4711
5ca419f2 4712 return 0;
17a52670
AS
4713}
4714
01f810ac
AM
4715/* When register 'regno' is used to read the stack (either directly or through
4716 * a helper function) make sure that it's within stack boundary and, depending
4717 * on the access type, that all elements of the stack are initialized.
4718 *
4719 * 'off' includes 'regno->off', but not its dynamic part (if any).
4720 *
4721 * All registers that have been spilled on the stack in the slots within the
4722 * read offsets are marked as read.
4723 */
4724static int check_stack_range_initialized(
4725 struct bpf_verifier_env *env, int regno, int off,
4726 int access_size, bool zero_size_allowed,
4727 enum stack_access_src type, struct bpf_call_arg_meta *meta)
2011fccf
AI
4728{
4729 struct bpf_reg_state *reg = reg_state(env, regno);
01f810ac
AM
4730 struct bpf_func_state *state = func(env, reg);
4731 int err, min_off, max_off, i, j, slot, spi;
4732 char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
4733 enum bpf_access_type bounds_check_type;
4734 /* Some accesses can write anything into the stack, others are
4735 * read-only.
4736 */
4737 bool clobber = false;
2011fccf 4738
01f810ac
AM
4739 if (access_size == 0 && !zero_size_allowed) {
4740 verbose(env, "invalid zero-sized read\n");
2011fccf
AI
4741 return -EACCES;
4742 }
2011fccf 4743
01f810ac
AM
4744 if (type == ACCESS_HELPER) {
4745 /* The bounds checks for writes are more permissive than for
4746 * reads. However, if raw_mode is not set, we'll do extra
4747 * checks below.
4748 */
4749 bounds_check_type = BPF_WRITE;
4750 clobber = true;
4751 } else {
4752 bounds_check_type = BPF_READ;
4753 }
4754 err = check_stack_access_within_bounds(env, regno, off, access_size,
4755 type, bounds_check_type);
4756 if (err)
4757 return err;
4758
17a52670 4759
2011fccf 4760 if (tnum_is_const(reg->var_off)) {
01f810ac 4761 min_off = max_off = reg->var_off.value + off;
2011fccf 4762 } else {
088ec26d
AI
4763 /* Variable offset is prohibited for unprivileged mode for
4764 * simplicity since it requires corresponding support in
4765 * Spectre masking for stack ALU.
4766 * See also retrieve_ptr_limit().
4767 */
2c78ee89 4768 if (!env->bypass_spec_v1) {
088ec26d 4769 char tn_buf[48];
f1174f77 4770
088ec26d 4771 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
01f810ac
AM
4772 verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
4773 regno, err_extra, tn_buf);
088ec26d
AI
4774 return -EACCES;
4775 }
f2bcd05e
AI
4776 /* Only initialized buffer on stack is allowed to be accessed
4777 * with variable offset. With uninitialized buffer it's hard to
4778 * guarantee that whole memory is marked as initialized on
4779 * helper return since specific bounds are unknown what may
4780 * cause uninitialized stack leaking.
4781 */
4782 if (meta && meta->raw_mode)
4783 meta = NULL;
4784
01f810ac
AM
4785 min_off = reg->smin_value + off;
4786 max_off = reg->smax_value + off;
17a52670
AS
4787 }
4788
435faee1
DB
4789 if (meta && meta->raw_mode) {
4790 meta->access_size = access_size;
4791 meta->regno = regno;
4792 return 0;
4793 }
4794
2011fccf 4795 for (i = min_off; i < max_off + access_size; i++) {
cc2b14d5
AS
4796 u8 *stype;
4797
2011fccf 4798 slot = -i - 1;
638f5b90 4799 spi = slot / BPF_REG_SIZE;
cc2b14d5
AS
4800 if (state->allocated_stack <= slot)
4801 goto err;
4802 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
4803 if (*stype == STACK_MISC)
4804 goto mark;
4805 if (*stype == STACK_ZERO) {
01f810ac
AM
4806 if (clobber) {
4807 /* helper can write anything into the stack */
4808 *stype = STACK_MISC;
4809 }
cc2b14d5 4810 goto mark;
17a52670 4811 }
1d68f22b 4812
27113c59 4813 if (is_spilled_reg(&state->stack[spi]) &&
5844101a 4814 base_type(state->stack[spi].spilled_ptr.type) == PTR_TO_BTF_ID)
1d68f22b
YS
4815 goto mark;
4816
27113c59 4817 if (is_spilled_reg(&state->stack[spi]) &&
cd17d38f
YS
4818 (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
4819 env->allow_ptr_leaks)) {
01f810ac
AM
4820 if (clobber) {
4821 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
4822 for (j = 0; j < BPF_REG_SIZE; j++)
354e8f19 4823 scrub_spilled_slot(&state->stack[spi].slot_type[j]);
01f810ac 4824 }
f7cf25b2
AS
4825 goto mark;
4826 }
4827
cc2b14d5 4828err:
2011fccf 4829 if (tnum_is_const(reg->var_off)) {
01f810ac
AM
4830 verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
4831 err_extra, regno, min_off, i - min_off, access_size);
2011fccf
AI
4832 } else {
4833 char tn_buf[48];
4834
4835 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
01f810ac
AM
4836 verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
4837 err_extra, regno, tn_buf, i - min_off, access_size);
2011fccf 4838 }
cc2b14d5
AS
4839 return -EACCES;
4840mark:
4841 /* reading any byte out of 8-byte 'spill_slot' will cause
4842 * the whole slot to be marked as 'read'
4843 */
679c782d 4844 mark_reg_read(env, &state->stack[spi].spilled_ptr,
5327ed3d
JW
4845 state->stack[spi].spilled_ptr.parent,
4846 REG_LIVE_READ64);
17a52670 4847 }
2011fccf 4848 return update_stack_depth(env, state, min_off);
17a52670
AS
4849}
4850
06c1c049
GB
4851static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
4852 int access_size, bool zero_size_allowed,
4853 struct bpf_call_arg_meta *meta)
4854{
638f5b90 4855 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
20b2aff4 4856 u32 *max_access;
06c1c049 4857
20b2aff4 4858 switch (base_type(reg->type)) {
06c1c049 4859 case PTR_TO_PACKET:
de8f3a83 4860 case PTR_TO_PACKET_META:
9fd29c08
YS
4861 return check_packet_access(env, regno, reg->off, access_size,
4862 zero_size_allowed);
69c087ba
YS
4863 case PTR_TO_MAP_KEY:
4864 return check_mem_region_access(env, regno, reg->off, access_size,
4865 reg->map_ptr->key_size, false);
06c1c049 4866 case PTR_TO_MAP_VALUE:
591fe988
DB
4867 if (check_map_access_type(env, regno, reg->off, access_size,
4868 meta && meta->raw_mode ? BPF_WRITE :
4869 BPF_READ))
4870 return -EACCES;
9fd29c08
YS
4871 return check_map_access(env, regno, reg->off, access_size,
4872 zero_size_allowed);
457f4436
AN
4873 case PTR_TO_MEM:
4874 return check_mem_region_access(env, regno, reg->off,
4875 access_size, reg->mem_size,
4876 zero_size_allowed);
20b2aff4
HL
4877 case PTR_TO_BUF:
4878 if (type_is_rdonly_mem(reg->type)) {
4879 if (meta && meta->raw_mode)
4880 return -EACCES;
4881
20b2aff4
HL
4882 max_access = &env->prog->aux->max_rdonly_access;
4883 } else {
20b2aff4
HL
4884 max_access = &env->prog->aux->max_rdwr_access;
4885 }
afbf21dc
YS
4886 return check_buffer_access(env, reg, regno, reg->off,
4887 access_size, zero_size_allowed,
44e9a741 4888 max_access);
0d004c02 4889 case PTR_TO_STACK:
01f810ac
AM
4890 return check_stack_range_initialized(
4891 env,
4892 regno, reg->off, access_size,
4893 zero_size_allowed, ACCESS_HELPER, meta);
0d004c02
LB
4894 default: /* scalar_value or invalid ptr */
4895 /* Allow zero-byte read from NULL, regardless of pointer type */
4896 if (zero_size_allowed && access_size == 0 &&
4897 register_is_null(reg))
4898 return 0;
4899
c25b2ae1
HL
4900 verbose(env, "R%d type=%s ", regno,
4901 reg_type_str(env, reg->type));
4902 verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
0d004c02 4903 return -EACCES;
06c1c049
GB
4904 }
4905}
4906
d583691c
KKD
4907static int check_mem_size_reg(struct bpf_verifier_env *env,
4908 struct bpf_reg_state *reg, u32 regno,
4909 bool zero_size_allowed,
4910 struct bpf_call_arg_meta *meta)
4911{
4912 int err;
4913
4914 /* This is used to refine r0 return value bounds for helpers
4915 * that enforce this value as an upper bound on return values.
4916 * See do_refine_retval_range() for helpers that can refine
4917 * the return value. C type of helper is u32 so we pull register
4918 * bound from umax_value however, if negative verifier errors
4919 * out. Only upper bounds can be learned because retval is an
4920 * int type and negative retvals are allowed.
4921 */
4922 if (meta)
4923 meta->msize_max_value = reg->umax_value;
4924
4925 /* The register is SCALAR_VALUE; the access check
4926 * happens using its boundaries.
4927 */
4928 if (!tnum_is_const(reg->var_off))
4929 /* For unprivileged variable accesses, disable raw
4930 * mode so that the program is required to
4931 * initialize all the memory that the helper could
4932 * just partially fill up.
4933 */
4934 meta = NULL;
4935
4936 if (reg->smin_value < 0) {
4937 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
4938 regno);
4939 return -EACCES;
4940 }
4941
4942 if (reg->umin_value == 0) {
4943 err = check_helper_mem_access(env, regno - 1, 0,
4944 zero_size_allowed,
4945 meta);
4946 if (err)
4947 return err;
4948 }
4949
4950 if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
4951 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
4952 regno);
4953 return -EACCES;
4954 }
4955 err = check_helper_mem_access(env, regno - 1,
4956 reg->umax_value,
4957 zero_size_allowed, meta);
4958 if (!err)
4959 err = mark_chain_precision(env, regno);
4960 return err;
4961}
4962
e5069b9c
DB
4963int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
4964 u32 regno, u32 mem_size)
4965{
4966 if (register_is_null(reg))
4967 return 0;
4968
c25b2ae1 4969 if (type_may_be_null(reg->type)) {
e5069b9c
DB
4970 /* Assuming that the register contains a value check if the memory
4971 * access is safe. Temporarily save and restore the register's state as
4972 * the conversion shouldn't be visible to a caller.
4973 */
4974 const struct bpf_reg_state saved_reg = *reg;
4975 int rv;
4976
4977 mark_ptr_not_null_reg(reg);
4978 rv = check_helper_mem_access(env, regno, mem_size, true, NULL);
4979 *reg = saved_reg;
4980 return rv;
4981 }
4982
4983 return check_helper_mem_access(env, regno, mem_size, true, NULL);
4984}
4985
d583691c
KKD
4986int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
4987 u32 regno)
4988{
4989 struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1];
4990 bool may_be_null = type_may_be_null(mem_reg->type);
4991 struct bpf_reg_state saved_reg;
4992 int err;
4993
4994 WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5);
4995
4996 if (may_be_null) {
4997 saved_reg = *mem_reg;
4998 mark_ptr_not_null_reg(mem_reg);
4999 }
5000
5001 err = check_mem_size_reg(env, reg, regno, true, NULL);
5002
5003 if (may_be_null)
5004 *mem_reg = saved_reg;
5005 return err;
5006}
5007
d83525ca
AS
5008/* Implementation details:
5009 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL
5010 * Two bpf_map_lookups (even with the same key) will have different reg->id.
5011 * For traditional PTR_TO_MAP_VALUE the verifier clears reg->id after
5012 * value_or_null->value transition, since the verifier only cares about
5013 * the range of access to valid map value pointer and doesn't care about actual
5014 * address of the map element.
5015 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
5016 * reg->id > 0 after value_or_null->value transition. By doing so
5017 * two bpf_map_lookups will be considered two different pointers that
5018 * point to different bpf_spin_locks.
5019 * The verifier allows taking only one bpf_spin_lock at a time to avoid
5020 * dead-locks.
5021 * Since only one bpf_spin_lock is allowed the checks are simpler than
5022 * reg_is_refcounted() logic. The verifier needs to remember only
5023 * one spin_lock instead of array of acquired_refs.
5024 * cur_state->active_spin_lock remembers which map value element got locked
5025 * and clears it after bpf_spin_unlock.
5026 */
5027static int process_spin_lock(struct bpf_verifier_env *env, int regno,
5028 bool is_lock)
5029{
5030 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5031 struct bpf_verifier_state *cur = env->cur_state;
5032 bool is_const = tnum_is_const(reg->var_off);
5033 struct bpf_map *map = reg->map_ptr;
5034 u64 val = reg->var_off.value;
5035
d83525ca
AS
5036 if (!is_const) {
5037 verbose(env,
5038 "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
5039 regno);
5040 return -EINVAL;
5041 }
5042 if (!map->btf) {
5043 verbose(env,
5044 "map '%s' has to have BTF in order to use bpf_spin_lock\n",
5045 map->name);
5046 return -EINVAL;
5047 }
5048 if (!map_value_has_spin_lock(map)) {
5049 if (map->spin_lock_off == -E2BIG)
5050 verbose(env,
5051 "map '%s' has more than one 'struct bpf_spin_lock'\n",
5052 map->name);
5053 else if (map->spin_lock_off == -ENOENT)
5054 verbose(env,
5055 "map '%s' doesn't have 'struct bpf_spin_lock'\n",
5056 map->name);
5057 else
5058 verbose(env,
5059 "map '%s' is not a struct type or bpf_spin_lock is mangled\n",
5060 map->name);
5061 return -EINVAL;
5062 }
5063 if (map->spin_lock_off != val + reg->off) {
5064 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock'\n",
5065 val + reg->off);
5066 return -EINVAL;
5067 }
5068 if (is_lock) {
5069 if (cur->active_spin_lock) {
5070 verbose(env,
5071 "Locking two bpf_spin_locks are not allowed\n");
5072 return -EINVAL;
5073 }
5074 cur->active_spin_lock = reg->id;
5075 } else {
5076 if (!cur->active_spin_lock) {
5077 verbose(env, "bpf_spin_unlock without taking a lock\n");
5078 return -EINVAL;
5079 }
5080 if (cur->active_spin_lock != reg->id) {
5081 verbose(env, "bpf_spin_unlock of different lock\n");
5082 return -EINVAL;
5083 }
5084 cur->active_spin_lock = 0;
5085 }
5086 return 0;
5087}
5088
b00628b1
AS
5089static int process_timer_func(struct bpf_verifier_env *env, int regno,
5090 struct bpf_call_arg_meta *meta)
5091{
5092 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5093 bool is_const = tnum_is_const(reg->var_off);
5094 struct bpf_map *map = reg->map_ptr;
5095 u64 val = reg->var_off.value;
5096
5097 if (!is_const) {
5098 verbose(env,
5099 "R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n",
5100 regno);
5101 return -EINVAL;
5102 }
5103 if (!map->btf) {
5104 verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n",
5105 map->name);
5106 return -EINVAL;
5107 }
68134668
AS
5108 if (!map_value_has_timer(map)) {
5109 if (map->timer_off == -E2BIG)
5110 verbose(env,
5111 "map '%s' has more than one 'struct bpf_timer'\n",
5112 map->name);
5113 else if (map->timer_off == -ENOENT)
5114 verbose(env,
5115 "map '%s' doesn't have 'struct bpf_timer'\n",
5116 map->name);
5117 else
5118 verbose(env,
5119 "map '%s' is not a struct type or bpf_timer is mangled\n",
5120 map->name);
5121 return -EINVAL;
5122 }
5123 if (map->timer_off != val + reg->off) {
5124 verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n",
5125 val + reg->off, map->timer_off);
b00628b1
AS
5126 return -EINVAL;
5127 }
5128 if (meta->map_ptr) {
5129 verbose(env, "verifier bug. Two map pointers in a timer helper\n");
5130 return -EFAULT;
5131 }
3e8ce298 5132 meta->map_uid = reg->map_uid;
b00628b1
AS
5133 meta->map_ptr = map;
5134 return 0;
5135}
5136
90133415
DB
5137static bool arg_type_is_mem_ptr(enum bpf_arg_type type)
5138{
48946bd6
HL
5139 return base_type(type) == ARG_PTR_TO_MEM ||
5140 base_type(type) == ARG_PTR_TO_UNINIT_MEM;
90133415
DB
5141}
5142
5143static bool arg_type_is_mem_size(enum bpf_arg_type type)
5144{
5145 return type == ARG_CONST_SIZE ||
5146 type == ARG_CONST_SIZE_OR_ZERO;
5147}
5148
457f4436
AN
5149static bool arg_type_is_alloc_size(enum bpf_arg_type type)
5150{
5151 return type == ARG_CONST_ALLOC_SIZE_OR_ZERO;
5152}
5153
57c3bb72
AI
5154static bool arg_type_is_int_ptr(enum bpf_arg_type type)
5155{
5156 return type == ARG_PTR_TO_INT ||
5157 type == ARG_PTR_TO_LONG;
5158}
5159
5160static int int_ptr_type_to_size(enum bpf_arg_type type)
5161{
5162 if (type == ARG_PTR_TO_INT)
5163 return sizeof(u32);
5164 else if (type == ARG_PTR_TO_LONG)
5165 return sizeof(u64);
5166
5167 return -EINVAL;
5168}
5169
912f442c
LB
5170static int resolve_map_arg_type(struct bpf_verifier_env *env,
5171 const struct bpf_call_arg_meta *meta,
5172 enum bpf_arg_type *arg_type)
5173{
5174 if (!meta->map_ptr) {
5175 /* kernel subsystem misconfigured verifier */
5176 verbose(env, "invalid map_ptr to access map->type\n");
5177 return -EACCES;
5178 }
5179
5180 switch (meta->map_ptr->map_type) {
5181 case BPF_MAP_TYPE_SOCKMAP:
5182 case BPF_MAP_TYPE_SOCKHASH:
5183 if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
6550f2dd 5184 *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
912f442c
LB
5185 } else {
5186 verbose(env, "invalid arg_type for sockmap/sockhash\n");
5187 return -EINVAL;
5188 }
5189 break;
9330986c
JK
5190 case BPF_MAP_TYPE_BLOOM_FILTER:
5191 if (meta->func_id == BPF_FUNC_map_peek_elem)
5192 *arg_type = ARG_PTR_TO_MAP_VALUE;
5193 break;
912f442c
LB
5194 default:
5195 break;
5196 }
5197 return 0;
5198}
5199
f79e7ea5
LB
5200struct bpf_reg_types {
5201 const enum bpf_reg_type types[10];
1df8f55a 5202 u32 *btf_id;
f79e7ea5
LB
5203};
5204
5205static const struct bpf_reg_types map_key_value_types = {
5206 .types = {
5207 PTR_TO_STACK,
5208 PTR_TO_PACKET,
5209 PTR_TO_PACKET_META,
69c087ba 5210 PTR_TO_MAP_KEY,
f79e7ea5
LB
5211 PTR_TO_MAP_VALUE,
5212 },
5213};
5214
5215static const struct bpf_reg_types sock_types = {
5216 .types = {
5217 PTR_TO_SOCK_COMMON,
5218 PTR_TO_SOCKET,
5219 PTR_TO_TCP_SOCK,
5220 PTR_TO_XDP_SOCK,
5221 },
5222};
5223
49a2a4d4 5224#ifdef CONFIG_NET
1df8f55a
MKL
5225static const struct bpf_reg_types btf_id_sock_common_types = {
5226 .types = {
5227 PTR_TO_SOCK_COMMON,
5228 PTR_TO_SOCKET,
5229 PTR_TO_TCP_SOCK,
5230 PTR_TO_XDP_SOCK,
5231 PTR_TO_BTF_ID,
5232 },
5233 .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
5234};
49a2a4d4 5235#endif
1df8f55a 5236
f79e7ea5
LB
5237static const struct bpf_reg_types mem_types = {
5238 .types = {
5239 PTR_TO_STACK,
5240 PTR_TO_PACKET,
5241 PTR_TO_PACKET_META,
69c087ba 5242 PTR_TO_MAP_KEY,
f79e7ea5
LB
5243 PTR_TO_MAP_VALUE,
5244 PTR_TO_MEM,
a672b2e3 5245 PTR_TO_MEM | MEM_ALLOC,
20b2aff4 5246 PTR_TO_BUF,
f79e7ea5
LB
5247 },
5248};
5249
5250static const struct bpf_reg_types int_ptr_types = {
5251 .types = {
5252 PTR_TO_STACK,
5253 PTR_TO_PACKET,
5254 PTR_TO_PACKET_META,
69c087ba 5255 PTR_TO_MAP_KEY,
f79e7ea5
LB
5256 PTR_TO_MAP_VALUE,
5257 },
5258};
5259
5260static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
5261static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
5262static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
a672b2e3 5263static const struct bpf_reg_types alloc_mem_types = { .types = { PTR_TO_MEM | MEM_ALLOC } };
f79e7ea5
LB
5264static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
5265static const struct bpf_reg_types btf_ptr_types = { .types = { PTR_TO_BTF_ID } };
5266static const struct bpf_reg_types spin_lock_types = { .types = { PTR_TO_MAP_VALUE } };
5844101a 5267static const struct bpf_reg_types percpu_btf_ptr_types = { .types = { PTR_TO_BTF_ID | MEM_PERCPU } };
69c087ba
YS
5268static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
5269static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
fff13c4b 5270static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
b00628b1 5271static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
f79e7ea5 5272
0789e13b 5273static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
f79e7ea5
LB
5274 [ARG_PTR_TO_MAP_KEY] = &map_key_value_types,
5275 [ARG_PTR_TO_MAP_VALUE] = &map_key_value_types,
5276 [ARG_PTR_TO_UNINIT_MAP_VALUE] = &map_key_value_types,
f79e7ea5
LB
5277 [ARG_CONST_SIZE] = &scalar_types,
5278 [ARG_CONST_SIZE_OR_ZERO] = &scalar_types,
5279 [ARG_CONST_ALLOC_SIZE_OR_ZERO] = &scalar_types,
5280 [ARG_CONST_MAP_PTR] = &const_map_ptr_types,
5281 [ARG_PTR_TO_CTX] = &context_types,
f79e7ea5 5282 [ARG_PTR_TO_SOCK_COMMON] = &sock_types,
49a2a4d4 5283#ifdef CONFIG_NET
1df8f55a 5284 [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types,
49a2a4d4 5285#endif
f79e7ea5 5286 [ARG_PTR_TO_SOCKET] = &fullsock_types,
f79e7ea5
LB
5287 [ARG_PTR_TO_BTF_ID] = &btf_ptr_types,
5288 [ARG_PTR_TO_SPIN_LOCK] = &spin_lock_types,
5289 [ARG_PTR_TO_MEM] = &mem_types,
f79e7ea5
LB
5290 [ARG_PTR_TO_UNINIT_MEM] = &mem_types,
5291 [ARG_PTR_TO_ALLOC_MEM] = &alloc_mem_types,
f79e7ea5
LB
5292 [ARG_PTR_TO_INT] = &int_ptr_types,
5293 [ARG_PTR_TO_LONG] = &int_ptr_types,
eaa6bcb7 5294 [ARG_PTR_TO_PERCPU_BTF_ID] = &percpu_btf_ptr_types,
69c087ba 5295 [ARG_PTR_TO_FUNC] = &func_ptr_types,
48946bd6 5296 [ARG_PTR_TO_STACK] = &stack_ptr_types,
fff13c4b 5297 [ARG_PTR_TO_CONST_STR] = &const_str_ptr_types,
b00628b1 5298 [ARG_PTR_TO_TIMER] = &timer_types,
f79e7ea5
LB
5299};
5300
5301static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
a968d5e2
MKL
5302 enum bpf_arg_type arg_type,
5303 const u32 *arg_btf_id)
f79e7ea5
LB
5304{
5305 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5306 enum bpf_reg_type expected, type = reg->type;
a968d5e2 5307 const struct bpf_reg_types *compatible;
f79e7ea5
LB
5308 int i, j;
5309
48946bd6 5310 compatible = compatible_reg_types[base_type(arg_type)];
a968d5e2
MKL
5311 if (!compatible) {
5312 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
5313 return -EFAULT;
5314 }
5315
216e3cd2
HL
5316 /* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
5317 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
5318 *
5319 * Same for MAYBE_NULL:
5320 *
5321 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
5322 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
5323 *
5324 * Therefore we fold these flags depending on the arg_type before comparison.
5325 */
5326 if (arg_type & MEM_RDONLY)
5327 type &= ~MEM_RDONLY;
5328 if (arg_type & PTR_MAYBE_NULL)
5329 type &= ~PTR_MAYBE_NULL;
5330
f79e7ea5
LB
5331 for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
5332 expected = compatible->types[i];
5333 if (expected == NOT_INIT)
5334 break;
5335
5336 if (type == expected)
a968d5e2 5337 goto found;
f79e7ea5
LB
5338 }
5339
216e3cd2 5340 verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type));
f79e7ea5 5341 for (j = 0; j + 1 < i; j++)
c25b2ae1
HL
5342 verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
5343 verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
f79e7ea5 5344 return -EACCES;
a968d5e2
MKL
5345
5346found:
216e3cd2 5347 if (reg->type == PTR_TO_BTF_ID) {
1df8f55a
MKL
5348 if (!arg_btf_id) {
5349 if (!compatible->btf_id) {
5350 verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
5351 return -EFAULT;
5352 }
5353 arg_btf_id = compatible->btf_id;
5354 }
5355
22dc4a0f
AN
5356 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
5357 btf_vmlinux, *arg_btf_id)) {
a968d5e2 5358 verbose(env, "R%d is of type %s but %s is expected\n",
22dc4a0f
AN
5359 regno, kernel_type_name(reg->btf, reg->btf_id),
5360 kernel_type_name(btf_vmlinux, *arg_btf_id));
a968d5e2
MKL
5361 return -EACCES;
5362 }
a968d5e2
MKL
5363 }
5364
5365 return 0;
f79e7ea5
LB
5366}
5367
25b35dd2
KKD
5368int check_func_arg_reg_off(struct bpf_verifier_env *env,
5369 const struct bpf_reg_state *reg, int regno,
24d5bb80
KKD
5370 enum bpf_arg_type arg_type,
5371 bool is_release_func)
25b35dd2 5372{
24d5bb80 5373 bool fixed_off_ok = false, release_reg;
25b35dd2 5374 enum bpf_reg_type type = reg->type;
25b35dd2
KKD
5375
5376 switch ((u32)type) {
5377 case SCALAR_VALUE:
5378 /* Pointer types where reg offset is explicitly allowed: */
5379 case PTR_TO_PACKET:
5380 case PTR_TO_PACKET_META:
5381 case PTR_TO_MAP_KEY:
5382 case PTR_TO_MAP_VALUE:
5383 case PTR_TO_MEM:
5384 case PTR_TO_MEM | MEM_RDONLY:
5385 case PTR_TO_MEM | MEM_ALLOC:
5386 case PTR_TO_BUF:
5387 case PTR_TO_BUF | MEM_RDONLY:
5388 case PTR_TO_STACK:
5389 /* Some of the argument types nevertheless require a
5390 * zero register offset.
5391 */
5392 if (arg_type != ARG_PTR_TO_ALLOC_MEM)
5393 return 0;
5394 break;
5395 /* All the rest must be rejected, except PTR_TO_BTF_ID which allows
5396 * fixed offset.
5397 */
5398 case PTR_TO_BTF_ID:
24d5bb80
KKD
5399 /* When referenced PTR_TO_BTF_ID is passed to release function,
5400 * it's fixed offset must be 0. We rely on the property that
5401 * only one referenced register can be passed to BPF helpers and
5402 * kfuncs. In the other cases, fixed offset can be non-zero.
5403 */
5404 release_reg = is_release_func && reg->ref_obj_id;
5405 if (release_reg && reg->off) {
5406 verbose(env, "R%d must have zero offset when passed to release func\n",
5407 regno);
5408 return -EINVAL;
5409 }
5410 /* For release_reg == true, fixed_off_ok must be false, but we
5411 * already checked and rejected reg->off != 0 above, so set to
5412 * true to allow fixed offset for all other cases.
5413 */
25b35dd2
KKD
5414 fixed_off_ok = true;
5415 break;
5416 default:
5417 break;
5418 }
5419 return __check_ptr_off_reg(env, reg, regno, fixed_off_ok);
5420}
5421
af7ec138
YS
5422static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
5423 struct bpf_call_arg_meta *meta,
5424 const struct bpf_func_proto *fn)
17a52670 5425{
af7ec138 5426 u32 regno = BPF_REG_1 + arg;
638f5b90 5427 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
af7ec138 5428 enum bpf_arg_type arg_type = fn->arg_type[arg];
f79e7ea5 5429 enum bpf_reg_type type = reg->type;
17a52670
AS
5430 int err = 0;
5431
80f1d68c 5432 if (arg_type == ARG_DONTCARE)
17a52670
AS
5433 return 0;
5434
dc503a8a
EC
5435 err = check_reg_arg(env, regno, SRC_OP);
5436 if (err)
5437 return err;
17a52670 5438
1be7f75d
AS
5439 if (arg_type == ARG_ANYTHING) {
5440 if (is_pointer_value(env, regno)) {
61bd5218
JK
5441 verbose(env, "R%d leaks addr into helper function\n",
5442 regno);
1be7f75d
AS
5443 return -EACCES;
5444 }
80f1d68c 5445 return 0;
1be7f75d 5446 }
80f1d68c 5447
de8f3a83 5448 if (type_is_pkt_pointer(type) &&
3a0af8fd 5449 !may_access_direct_pkt_data(env, meta, BPF_READ)) {
61bd5218 5450 verbose(env, "helper access to the packet is not allowed\n");
6841de8b
AS
5451 return -EACCES;
5452 }
5453
48946bd6
HL
5454 if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE ||
5455 base_type(arg_type) == ARG_PTR_TO_UNINIT_MAP_VALUE) {
912f442c
LB
5456 err = resolve_map_arg_type(env, meta, &arg_type);
5457 if (err)
5458 return err;
5459 }
5460
48946bd6 5461 if (register_is_null(reg) && type_may_be_null(arg_type))
fd1b0d60
LB
5462 /* A NULL register has a SCALAR_VALUE type, so skip
5463 * type checking.
5464 */
5465 goto skip_type_check;
5466
a968d5e2 5467 err = check_reg_type(env, regno, arg_type, fn->arg_btf_id[arg]);
f79e7ea5
LB
5468 if (err)
5469 return err;
5470
24d5bb80 5471 err = check_func_arg_reg_off(env, reg, regno, arg_type, is_release_function(meta->func_id));
25b35dd2
KKD
5472 if (err)
5473 return err;
d7b9454a 5474
fd1b0d60 5475skip_type_check:
24d5bb80
KKD
5476 /* check_func_arg_reg_off relies on only one referenced register being
5477 * allowed for BPF helpers.
5478 */
02f7c958 5479 if (reg->ref_obj_id) {
457f4436
AN
5480 if (meta->ref_obj_id) {
5481 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
5482 regno, reg->ref_obj_id,
5483 meta->ref_obj_id);
5484 return -EFAULT;
5485 }
5486 meta->ref_obj_id = reg->ref_obj_id;
17a52670
AS
5487 }
5488
17a52670
AS
5489 if (arg_type == ARG_CONST_MAP_PTR) {
5490 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
3e8ce298
AS
5491 if (meta->map_ptr) {
5492 /* Use map_uid (which is unique id of inner map) to reject:
5493 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
5494 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
5495 * if (inner_map1 && inner_map2) {
5496 * timer = bpf_map_lookup_elem(inner_map1);
5497 * if (timer)
5498 * // mismatch would have been allowed
5499 * bpf_timer_init(timer, inner_map2);
5500 * }
5501 *
5502 * Comparing map_ptr is enough to distinguish normal and outer maps.
5503 */
5504 if (meta->map_ptr != reg->map_ptr ||
5505 meta->map_uid != reg->map_uid) {
5506 verbose(env,
5507 "timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
5508 meta->map_uid, reg->map_uid);
5509 return -EINVAL;
5510 }
b00628b1 5511 }
33ff9823 5512 meta->map_ptr = reg->map_ptr;
3e8ce298 5513 meta->map_uid = reg->map_uid;
17a52670
AS
5514 } else if (arg_type == ARG_PTR_TO_MAP_KEY) {
5515 /* bpf_map_xxx(..., map_ptr, ..., key) call:
5516 * check that [key, key + map->key_size) are within
5517 * stack limits and initialized
5518 */
33ff9823 5519 if (!meta->map_ptr) {
17a52670
AS
5520 /* in function declaration map_ptr must come before
5521 * map_key, so that it's verified and known before
5522 * we have to check map_key here. Otherwise it means
5523 * that kernel subsystem misconfigured verifier
5524 */
61bd5218 5525 verbose(env, "invalid map_ptr to access map->key\n");
17a52670
AS
5526 return -EACCES;
5527 }
d71962f3
PC
5528 err = check_helper_mem_access(env, regno,
5529 meta->map_ptr->key_size, false,
5530 NULL);
48946bd6
HL
5531 } else if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE ||
5532 base_type(arg_type) == ARG_PTR_TO_UNINIT_MAP_VALUE) {
5533 if (type_may_be_null(arg_type) && register_is_null(reg))
5534 return 0;
5535
17a52670
AS
5536 /* bpf_map_xxx(..., map_ptr, ..., value) call:
5537 * check [value, value + map->value_size) validity
5538 */
33ff9823 5539 if (!meta->map_ptr) {
17a52670 5540 /* kernel subsystem misconfigured verifier */
61bd5218 5541 verbose(env, "invalid map_ptr to access map->value\n");
17a52670
AS
5542 return -EACCES;
5543 }
2ea864c5 5544 meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE);
d71962f3
PC
5545 err = check_helper_mem_access(env, regno,
5546 meta->map_ptr->value_size, false,
2ea864c5 5547 meta);
eaa6bcb7
HL
5548 } else if (arg_type == ARG_PTR_TO_PERCPU_BTF_ID) {
5549 if (!reg->btf_id) {
5550 verbose(env, "Helper has invalid btf_id in R%d\n", regno);
5551 return -EACCES;
5552 }
22dc4a0f 5553 meta->ret_btf = reg->btf;
eaa6bcb7 5554 meta->ret_btf_id = reg->btf_id;
c18f0b6a
LB
5555 } else if (arg_type == ARG_PTR_TO_SPIN_LOCK) {
5556 if (meta->func_id == BPF_FUNC_spin_lock) {
5557 if (process_spin_lock(env, regno, true))
5558 return -EACCES;
5559 } else if (meta->func_id == BPF_FUNC_spin_unlock) {
5560 if (process_spin_lock(env, regno, false))
5561 return -EACCES;
5562 } else {
5563 verbose(env, "verifier internal error\n");
5564 return -EFAULT;
5565 }
b00628b1
AS
5566 } else if (arg_type == ARG_PTR_TO_TIMER) {
5567 if (process_timer_func(env, regno, meta))
5568 return -EACCES;
69c087ba
YS
5569 } else if (arg_type == ARG_PTR_TO_FUNC) {
5570 meta->subprogno = reg->subprogno;
a2bbe7cc
LB
5571 } else if (arg_type_is_mem_ptr(arg_type)) {
5572 /* The access to this pointer is only checked when we hit the
5573 * next is_mem_size argument below.
5574 */
5575 meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MEM);
90133415 5576 } else if (arg_type_is_mem_size(arg_type)) {
39f19ebb 5577 bool zero_size_allowed = (arg_type == ARG_CONST_SIZE_OR_ZERO);
17a52670 5578
d583691c 5579 err = check_mem_size_reg(env, reg, regno, zero_size_allowed, meta);
457f4436
AN
5580 } else if (arg_type_is_alloc_size(arg_type)) {
5581 if (!tnum_is_const(reg->var_off)) {
28a8add6 5582 verbose(env, "R%d is not a known constant'\n",
457f4436
AN
5583 regno);
5584 return -EACCES;
5585 }
5586 meta->mem_size = reg->var_off.value;
57c3bb72
AI
5587 } else if (arg_type_is_int_ptr(arg_type)) {
5588 int size = int_ptr_type_to_size(arg_type);
5589
5590 err = check_helper_mem_access(env, regno, size, false, meta);
5591 if (err)
5592 return err;
5593 err = check_ptr_alignment(env, reg, 0, size, true);
fff13c4b
FR
5594 } else if (arg_type == ARG_PTR_TO_CONST_STR) {
5595 struct bpf_map *map = reg->map_ptr;
5596 int map_off;
5597 u64 map_addr;
5598 char *str_ptr;
5599
a8fad73e 5600 if (!bpf_map_is_rdonly(map)) {
fff13c4b
FR
5601 verbose(env, "R%d does not point to a readonly map'\n", regno);
5602 return -EACCES;
5603 }
5604
5605 if (!tnum_is_const(reg->var_off)) {
5606 verbose(env, "R%d is not a constant address'\n", regno);
5607 return -EACCES;
5608 }
5609
5610 if (!map->ops->map_direct_value_addr) {
5611 verbose(env, "no direct value access support for this map type\n");
5612 return -EACCES;
5613 }
5614
5615 err = check_map_access(env, regno, reg->off,
5616 map->value_size - reg->off, false);
5617 if (err)
5618 return err;
5619
5620 map_off = reg->off + reg->var_off.value;
5621 err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
5622 if (err) {
5623 verbose(env, "direct value access on string failed\n");
5624 return err;
5625 }
5626
5627 str_ptr = (char *)(long)(map_addr);
5628 if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
5629 verbose(env, "string is not zero-terminated\n");
5630 return -EINVAL;
5631 }
17a52670
AS
5632 }
5633
5634 return err;
5635}
5636
0126240f
LB
5637static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
5638{
5639 enum bpf_attach_type eatype = env->prog->expected_attach_type;
7e40781c 5640 enum bpf_prog_type type = resolve_prog_type(env->prog);
0126240f
LB
5641
5642 if (func_id != BPF_FUNC_map_update_elem)
5643 return false;
5644
5645 /* It's not possible to get access to a locked struct sock in these
5646 * contexts, so updating is safe.
5647 */
5648 switch (type) {
5649 case BPF_PROG_TYPE_TRACING:
5650 if (eatype == BPF_TRACE_ITER)
5651 return true;
5652 break;
5653 case BPF_PROG_TYPE_SOCKET_FILTER:
5654 case BPF_PROG_TYPE_SCHED_CLS:
5655 case BPF_PROG_TYPE_SCHED_ACT:
5656 case BPF_PROG_TYPE_XDP:
5657 case BPF_PROG_TYPE_SK_REUSEPORT:
5658 case BPF_PROG_TYPE_FLOW_DISSECTOR:
5659 case BPF_PROG_TYPE_SK_LOOKUP:
5660 return true;
5661 default:
5662 break;
5663 }
5664
5665 verbose(env, "cannot update sockmap in this context\n");
5666 return false;
5667}
5668
e411901c
MF
5669static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
5670{
5671 return env->prog->jit_requested && IS_ENABLED(CONFIG_X86_64);
5672}
5673
61bd5218
JK
5674static int check_map_func_compatibility(struct bpf_verifier_env *env,
5675 struct bpf_map *map, int func_id)
35578d79 5676{
35578d79
KX
5677 if (!map)
5678 return 0;
5679
6aff67c8
AS
5680 /* We need a two way check, first is from map perspective ... */
5681 switch (map->map_type) {
5682 case BPF_MAP_TYPE_PROG_ARRAY:
5683 if (func_id != BPF_FUNC_tail_call)
5684 goto error;
5685 break;
5686 case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
5687 if (func_id != BPF_FUNC_perf_event_read &&
908432ca 5688 func_id != BPF_FUNC_perf_event_output &&
a7658e1a 5689 func_id != BPF_FUNC_skb_output &&
d831ee84
EC
5690 func_id != BPF_FUNC_perf_event_read_value &&
5691 func_id != BPF_FUNC_xdp_output)
6aff67c8
AS
5692 goto error;
5693 break;
457f4436
AN
5694 case BPF_MAP_TYPE_RINGBUF:
5695 if (func_id != BPF_FUNC_ringbuf_output &&
5696 func_id != BPF_FUNC_ringbuf_reserve &&
457f4436
AN
5697 func_id != BPF_FUNC_ringbuf_query)
5698 goto error;
5699 break;
6aff67c8
AS
5700 case BPF_MAP_TYPE_STACK_TRACE:
5701 if (func_id != BPF_FUNC_get_stackid)
5702 goto error;
5703 break;
4ed8ec52 5704 case BPF_MAP_TYPE_CGROUP_ARRAY:
60747ef4 5705 if (func_id != BPF_FUNC_skb_under_cgroup &&
60d20f91 5706 func_id != BPF_FUNC_current_task_under_cgroup)
4a482f34
MKL
5707 goto error;
5708 break;
cd339431 5709 case BPF_MAP_TYPE_CGROUP_STORAGE:
b741f163 5710 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
cd339431
RG
5711 if (func_id != BPF_FUNC_get_local_storage)
5712 goto error;
5713 break;
546ac1ff 5714 case BPF_MAP_TYPE_DEVMAP:
6f9d451a 5715 case BPF_MAP_TYPE_DEVMAP_HASH:
0cdbb4b0
THJ
5716 if (func_id != BPF_FUNC_redirect_map &&
5717 func_id != BPF_FUNC_map_lookup_elem)
546ac1ff
JF
5718 goto error;
5719 break;
fbfc504a
BT
5720 /* Restrict bpf side of cpumap and xskmap, open when use-cases
5721 * appear.
5722 */
6710e112
JDB
5723 case BPF_MAP_TYPE_CPUMAP:
5724 if (func_id != BPF_FUNC_redirect_map)
5725 goto error;
5726 break;
fada7fdc
JL
5727 case BPF_MAP_TYPE_XSKMAP:
5728 if (func_id != BPF_FUNC_redirect_map &&
5729 func_id != BPF_FUNC_map_lookup_elem)
5730 goto error;
5731 break;
56f668df 5732 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
bcc6b1b7 5733 case BPF_MAP_TYPE_HASH_OF_MAPS:
56f668df
MKL
5734 if (func_id != BPF_FUNC_map_lookup_elem)
5735 goto error;
16a43625 5736 break;
174a79ff
JF
5737 case BPF_MAP_TYPE_SOCKMAP:
5738 if (func_id != BPF_FUNC_sk_redirect_map &&
5739 func_id != BPF_FUNC_sock_map_update &&
4f738adb 5740 func_id != BPF_FUNC_map_delete_elem &&
9fed9000 5741 func_id != BPF_FUNC_msg_redirect_map &&
64d85290 5742 func_id != BPF_FUNC_sk_select_reuseport &&
0126240f
LB
5743 func_id != BPF_FUNC_map_lookup_elem &&
5744 !may_update_sockmap(env, func_id))
174a79ff
JF
5745 goto error;
5746 break;
81110384
JF
5747 case BPF_MAP_TYPE_SOCKHASH:
5748 if (func_id != BPF_FUNC_sk_redirect_hash &&
5749 func_id != BPF_FUNC_sock_hash_update &&
5750 func_id != BPF_FUNC_map_delete_elem &&
9fed9000 5751 func_id != BPF_FUNC_msg_redirect_hash &&
64d85290 5752 func_id != BPF_FUNC_sk_select_reuseport &&
0126240f
LB
5753 func_id != BPF_FUNC_map_lookup_elem &&
5754 !may_update_sockmap(env, func_id))
81110384
JF
5755 goto error;
5756 break;
2dbb9b9e
MKL
5757 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
5758 if (func_id != BPF_FUNC_sk_select_reuseport)
5759 goto error;
5760 break;
f1a2e44a
MV
5761 case BPF_MAP_TYPE_QUEUE:
5762 case BPF_MAP_TYPE_STACK:
5763 if (func_id != BPF_FUNC_map_peek_elem &&
5764 func_id != BPF_FUNC_map_pop_elem &&
5765 func_id != BPF_FUNC_map_push_elem)
5766 goto error;
5767 break;
6ac99e8f
MKL
5768 case BPF_MAP_TYPE_SK_STORAGE:
5769 if (func_id != BPF_FUNC_sk_storage_get &&
5770 func_id != BPF_FUNC_sk_storage_delete)
5771 goto error;
5772 break;
8ea63684
KS
5773 case BPF_MAP_TYPE_INODE_STORAGE:
5774 if (func_id != BPF_FUNC_inode_storage_get &&
5775 func_id != BPF_FUNC_inode_storage_delete)
5776 goto error;
5777 break;
4cf1bc1f
KS
5778 case BPF_MAP_TYPE_TASK_STORAGE:
5779 if (func_id != BPF_FUNC_task_storage_get &&
5780 func_id != BPF_FUNC_task_storage_delete)
5781 goto error;
5782 break;
9330986c
JK
5783 case BPF_MAP_TYPE_BLOOM_FILTER:
5784 if (func_id != BPF_FUNC_map_peek_elem &&
5785 func_id != BPF_FUNC_map_push_elem)
5786 goto error;
5787 break;
6aff67c8
AS
5788 default:
5789 break;
5790 }
5791
5792 /* ... and second from the function itself. */
5793 switch (func_id) {
5794 case BPF_FUNC_tail_call:
5795 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
5796 goto error;
e411901c
MF
5797 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
5798 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
f4d7e40a
AS
5799 return -EINVAL;
5800 }
6aff67c8
AS
5801 break;
5802 case BPF_FUNC_perf_event_read:
5803 case BPF_FUNC_perf_event_output:
908432ca 5804 case BPF_FUNC_perf_event_read_value:
a7658e1a 5805 case BPF_FUNC_skb_output:
d831ee84 5806 case BPF_FUNC_xdp_output:
6aff67c8
AS
5807 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
5808 goto error;
5809 break;
5b029a32
DB
5810 case BPF_FUNC_ringbuf_output:
5811 case BPF_FUNC_ringbuf_reserve:
5812 case BPF_FUNC_ringbuf_query:
5813 if (map->map_type != BPF_MAP_TYPE_RINGBUF)
5814 goto error;
5815 break;
6aff67c8
AS
5816 case BPF_FUNC_get_stackid:
5817 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
5818 goto error;
5819 break;
60d20f91 5820 case BPF_FUNC_current_task_under_cgroup:
747ea55e 5821 case BPF_FUNC_skb_under_cgroup:
4a482f34
MKL
5822 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
5823 goto error;
5824 break;
97f91a7c 5825 case BPF_FUNC_redirect_map:
9c270af3 5826 if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
6f9d451a 5827 map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
fbfc504a
BT
5828 map->map_type != BPF_MAP_TYPE_CPUMAP &&
5829 map->map_type != BPF_MAP_TYPE_XSKMAP)
97f91a7c
JF
5830 goto error;
5831 break;
174a79ff 5832 case BPF_FUNC_sk_redirect_map:
4f738adb 5833 case BPF_FUNC_msg_redirect_map:
81110384 5834 case BPF_FUNC_sock_map_update:
174a79ff
JF
5835 if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
5836 goto error;
5837 break;
81110384
JF
5838 case BPF_FUNC_sk_redirect_hash:
5839 case BPF_FUNC_msg_redirect_hash:
5840 case BPF_FUNC_sock_hash_update:
5841 if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
174a79ff
JF
5842 goto error;
5843 break;
cd339431 5844 case BPF_FUNC_get_local_storage:
b741f163
RG
5845 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
5846 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
cd339431
RG
5847 goto error;
5848 break;
2dbb9b9e 5849 case BPF_FUNC_sk_select_reuseport:
9fed9000
JS
5850 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
5851 map->map_type != BPF_MAP_TYPE_SOCKMAP &&
5852 map->map_type != BPF_MAP_TYPE_SOCKHASH)
2dbb9b9e
MKL
5853 goto error;
5854 break;
f1a2e44a 5855 case BPF_FUNC_map_pop_elem:
f1a2e44a
MV
5856 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
5857 map->map_type != BPF_MAP_TYPE_STACK)
5858 goto error;
5859 break;
9330986c
JK
5860 case BPF_FUNC_map_peek_elem:
5861 case BPF_FUNC_map_push_elem:
5862 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
5863 map->map_type != BPF_MAP_TYPE_STACK &&
5864 map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
5865 goto error;
5866 break;
6ac99e8f
MKL
5867 case BPF_FUNC_sk_storage_get:
5868 case BPF_FUNC_sk_storage_delete:
5869 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
5870 goto error;
5871 break;
8ea63684
KS
5872 case BPF_FUNC_inode_storage_get:
5873 case BPF_FUNC_inode_storage_delete:
5874 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
5875 goto error;
5876 break;
4cf1bc1f
KS
5877 case BPF_FUNC_task_storage_get:
5878 case BPF_FUNC_task_storage_delete:
5879 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
5880 goto error;
5881 break;
6aff67c8
AS
5882 default:
5883 break;
35578d79
KX
5884 }
5885
5886 return 0;
6aff67c8 5887error:
61bd5218 5888 verbose(env, "cannot pass map_type %d into func %s#%d\n",
ebb676da 5889 map->map_type, func_id_name(func_id), func_id);
6aff67c8 5890 return -EINVAL;
35578d79
KX
5891}
5892
90133415 5893static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
435faee1
DB
5894{
5895 int count = 0;
5896
39f19ebb 5897 if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
435faee1 5898 count++;
39f19ebb 5899 if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
435faee1 5900 count++;
39f19ebb 5901 if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
435faee1 5902 count++;
39f19ebb 5903 if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
435faee1 5904 count++;
39f19ebb 5905 if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
435faee1
DB
5906 count++;
5907
90133415
DB
5908 /* We only support one arg being in raw mode at the moment,
5909 * which is sufficient for the helper functions we have
5910 * right now.
5911 */
5912 return count <= 1;
5913}
5914
5915static bool check_args_pair_invalid(enum bpf_arg_type arg_curr,
5916 enum bpf_arg_type arg_next)
5917{
5918 return (arg_type_is_mem_ptr(arg_curr) &&
5919 !arg_type_is_mem_size(arg_next)) ||
5920 (!arg_type_is_mem_ptr(arg_curr) &&
5921 arg_type_is_mem_size(arg_next));
5922}
5923
5924static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
5925{
5926 /* bpf_xxx(..., buf, len) call will access 'len'
5927 * bytes from memory 'buf'. Both arg types need
5928 * to be paired, so make sure there's no buggy
5929 * helper function specification.
5930 */
5931 if (arg_type_is_mem_size(fn->arg1_type) ||
5932 arg_type_is_mem_ptr(fn->arg5_type) ||
5933 check_args_pair_invalid(fn->arg1_type, fn->arg2_type) ||
5934 check_args_pair_invalid(fn->arg2_type, fn->arg3_type) ||
5935 check_args_pair_invalid(fn->arg3_type, fn->arg4_type) ||
5936 check_args_pair_invalid(fn->arg4_type, fn->arg5_type))
5937 return false;
5938
5939 return true;
5940}
5941
1b986589 5942static bool check_refcount_ok(const struct bpf_func_proto *fn, int func_id)
fd978bf7
JS
5943{
5944 int count = 0;
5945
1b986589 5946 if (arg_type_may_be_refcounted(fn->arg1_type))
fd978bf7 5947 count++;
1b986589 5948 if (arg_type_may_be_refcounted(fn->arg2_type))
fd978bf7 5949 count++;
1b986589 5950 if (arg_type_may_be_refcounted(fn->arg3_type))
fd978bf7 5951 count++;
1b986589 5952 if (arg_type_may_be_refcounted(fn->arg4_type))
fd978bf7 5953 count++;
1b986589 5954 if (arg_type_may_be_refcounted(fn->arg5_type))
fd978bf7
JS
5955 count++;
5956
1b986589
MKL
5957 /* A reference acquiring function cannot acquire
5958 * another refcounted ptr.
5959 */
64d85290 5960 if (may_be_acquire_function(func_id) && count)
1b986589
MKL
5961 return false;
5962
fd978bf7
JS
5963 /* We only support one arg being unreferenced at the moment,
5964 * which is sufficient for the helper functions we have right now.
5965 */
5966 return count <= 1;
5967}
5968
9436ef6e
LB
5969static bool check_btf_id_ok(const struct bpf_func_proto *fn)
5970{
5971 int i;
5972
1df8f55a 5973 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
9436ef6e
LB
5974 if (fn->arg_type[i] == ARG_PTR_TO_BTF_ID && !fn->arg_btf_id[i])
5975 return false;
5976
1df8f55a
MKL
5977 if (fn->arg_type[i] != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i])
5978 return false;
5979 }
5980
9436ef6e
LB
5981 return true;
5982}
5983
1b986589 5984static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
90133415
DB
5985{
5986 return check_raw_mode_ok(fn) &&
fd978bf7 5987 check_arg_pair_ok(fn) &&
9436ef6e 5988 check_btf_id_ok(fn) &&
1b986589 5989 check_refcount_ok(fn, func_id) ? 0 : -EINVAL;
435faee1
DB
5990}
5991
de8f3a83
DB
5992/* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
5993 * are now invalid, so turn them into unknown SCALAR_VALUE.
f1174f77 5994 */
f4d7e40a
AS
5995static void __clear_all_pkt_pointers(struct bpf_verifier_env *env,
5996 struct bpf_func_state *state)
969bf05e 5997{
58e2af8b 5998 struct bpf_reg_state *regs = state->regs, *reg;
969bf05e
AS
5999 int i;
6000
6001 for (i = 0; i < MAX_BPF_REG; i++)
de8f3a83 6002 if (reg_is_pkt_pointer_any(&regs[i]))
61bd5218 6003 mark_reg_unknown(env, regs, i);
969bf05e 6004
f3709f69
JS
6005 bpf_for_each_spilled_reg(i, state, reg) {
6006 if (!reg)
969bf05e 6007 continue;
de8f3a83 6008 if (reg_is_pkt_pointer_any(reg))
f54c7898 6009 __mark_reg_unknown(env, reg);
969bf05e
AS
6010 }
6011}
6012
f4d7e40a
AS
6013static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
6014{
6015 struct bpf_verifier_state *vstate = env->cur_state;
6016 int i;
6017
6018 for (i = 0; i <= vstate->curframe; i++)
6019 __clear_all_pkt_pointers(env, vstate->frame[i]);
6020}
6021
6d94e741
AS
6022enum {
6023 AT_PKT_END = -1,
6024 BEYOND_PKT_END = -2,
6025};
6026
6027static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
6028{
6029 struct bpf_func_state *state = vstate->frame[vstate->curframe];
6030 struct bpf_reg_state *reg = &state->regs[regn];
6031
6032 if (reg->type != PTR_TO_PACKET)
6033 /* PTR_TO_PACKET_META is not supported yet */
6034 return;
6035
6036 /* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
6037 * How far beyond pkt_end it goes is unknown.
6038 * if (!range_open) it's the case of pkt >= pkt_end
6039 * if (range_open) it's the case of pkt > pkt_end
6040 * hence this pointer is at least 1 byte bigger than pkt_end
6041 */
6042 if (range_open)
6043 reg->range = BEYOND_PKT_END;
6044 else
6045 reg->range = AT_PKT_END;
6046}
6047
fd978bf7 6048static void release_reg_references(struct bpf_verifier_env *env,
1b986589
MKL
6049 struct bpf_func_state *state,
6050 int ref_obj_id)
fd978bf7
JS
6051{
6052 struct bpf_reg_state *regs = state->regs, *reg;
6053 int i;
6054
6055 for (i = 0; i < MAX_BPF_REG; i++)
1b986589 6056 if (regs[i].ref_obj_id == ref_obj_id)
fd978bf7
JS
6057 mark_reg_unknown(env, regs, i);
6058
6059 bpf_for_each_spilled_reg(i, state, reg) {
6060 if (!reg)
6061 continue;
1b986589 6062 if (reg->ref_obj_id == ref_obj_id)
f54c7898 6063 __mark_reg_unknown(env, reg);
fd978bf7
JS
6064 }
6065}
6066
6067/* The pointer with the specified id has released its reference to kernel
6068 * resources. Identify all copies of the same pointer and clear the reference.
6069 */
6070static int release_reference(struct bpf_verifier_env *env,
1b986589 6071 int ref_obj_id)
fd978bf7
JS
6072{
6073 struct bpf_verifier_state *vstate = env->cur_state;
1b986589 6074 int err;
fd978bf7
JS
6075 int i;
6076
1b986589
MKL
6077 err = release_reference_state(cur_func(env), ref_obj_id);
6078 if (err)
6079 return err;
6080
fd978bf7 6081 for (i = 0; i <= vstate->curframe; i++)
1b986589 6082 release_reg_references(env, vstate->frame[i], ref_obj_id);
fd978bf7 6083
1b986589 6084 return 0;
fd978bf7
JS
6085}
6086
51c39bb1
AS
6087static void clear_caller_saved_regs(struct bpf_verifier_env *env,
6088 struct bpf_reg_state *regs)
6089{
6090 int i;
6091
6092 /* after the call registers r0 - r5 were scratched */
6093 for (i = 0; i < CALLER_SAVED_REGS; i++) {
6094 mark_reg_not_init(env, regs, caller_saved[i]);
6095 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
6096 }
6097}
6098
14351375
YS
6099typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
6100 struct bpf_func_state *caller,
6101 struct bpf_func_state *callee,
6102 int insn_idx);
6103
6104static int __check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
6105 int *insn_idx, int subprog,
6106 set_callee_state_fn set_callee_state_cb)
f4d7e40a
AS
6107{
6108 struct bpf_verifier_state *state = env->cur_state;
51c39bb1 6109 struct bpf_func_info_aux *func_info_aux;
f4d7e40a 6110 struct bpf_func_state *caller, *callee;
14351375 6111 int err;
51c39bb1 6112 bool is_global = false;
f4d7e40a 6113
aada9ce6 6114 if (state->curframe + 1 >= MAX_CALL_FRAMES) {
f4d7e40a 6115 verbose(env, "the call stack of %d frames is too deep\n",
aada9ce6 6116 state->curframe + 2);
f4d7e40a
AS
6117 return -E2BIG;
6118 }
6119
f4d7e40a
AS
6120 caller = state->frame[state->curframe];
6121 if (state->frame[state->curframe + 1]) {
6122 verbose(env, "verifier bug. Frame %d already allocated\n",
6123 state->curframe + 1);
6124 return -EFAULT;
6125 }
6126
51c39bb1
AS
6127 func_info_aux = env->prog->aux->func_info_aux;
6128 if (func_info_aux)
6129 is_global = func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
34747c41 6130 err = btf_check_subprog_arg_match(env, subprog, caller->regs);
51c39bb1
AS
6131 if (err == -EFAULT)
6132 return err;
6133 if (is_global) {
6134 if (err) {
6135 verbose(env, "Caller passes invalid args into func#%d\n",
6136 subprog);
6137 return err;
6138 } else {
6139 if (env->log.level & BPF_LOG_LEVEL)
6140 verbose(env,
6141 "Func#%d is global and valid. Skipping.\n",
6142 subprog);
6143 clear_caller_saved_regs(env, caller->regs);
6144
45159b27 6145 /* All global functions return a 64-bit SCALAR_VALUE */
51c39bb1 6146 mark_reg_unknown(env, caller->regs, BPF_REG_0);
45159b27 6147 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
51c39bb1
AS
6148
6149 /* continue with next insn after call */
6150 return 0;
6151 }
6152 }
6153
bfc6bb74 6154 if (insn->code == (BPF_JMP | BPF_CALL) &&
a5bebc4f 6155 insn->src_reg == 0 &&
bfc6bb74
AS
6156 insn->imm == BPF_FUNC_timer_set_callback) {
6157 struct bpf_verifier_state *async_cb;
6158
6159 /* there is no real recursion here. timer callbacks are async */
7ddc80a4 6160 env->subprog_info[subprog].is_async_cb = true;
bfc6bb74
AS
6161 async_cb = push_async_cb(env, env->subprog_info[subprog].start,
6162 *insn_idx, subprog);
6163 if (!async_cb)
6164 return -EFAULT;
6165 callee = async_cb->frame[0];
6166 callee->async_entry_cnt = caller->async_entry_cnt + 1;
6167
6168 /* Convert bpf_timer_set_callback() args into timer callback args */
6169 err = set_callee_state_cb(env, caller, callee, *insn_idx);
6170 if (err)
6171 return err;
6172
6173 clear_caller_saved_regs(env, caller->regs);
6174 mark_reg_unknown(env, caller->regs, BPF_REG_0);
6175 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
6176 /* continue with next insn after call */
6177 return 0;
6178 }
6179
f4d7e40a
AS
6180 callee = kzalloc(sizeof(*callee), GFP_KERNEL);
6181 if (!callee)
6182 return -ENOMEM;
6183 state->frame[state->curframe + 1] = callee;
6184
6185 /* callee cannot access r0, r6 - r9 for reading and has to write
6186 * into its own stack before reading from it.
6187 * callee can read/write into caller's stack
6188 */
6189 init_func_state(env, callee,
6190 /* remember the callsite, it will be used by bpf_exit */
6191 *insn_idx /* callsite */,
6192 state->curframe + 1 /* frameno within this callchain */,
f910cefa 6193 subprog /* subprog number within this prog */);
f4d7e40a 6194
fd978bf7 6195 /* Transfer references to the callee */
c69431aa 6196 err = copy_reference_state(callee, caller);
fd978bf7
JS
6197 if (err)
6198 return err;
6199
14351375
YS
6200 err = set_callee_state_cb(env, caller, callee, *insn_idx);
6201 if (err)
6202 return err;
f4d7e40a 6203
51c39bb1 6204 clear_caller_saved_regs(env, caller->regs);
f4d7e40a
AS
6205
6206 /* only increment it after check_reg_arg() finished */
6207 state->curframe++;
6208
6209 /* and go analyze first insn of the callee */
14351375 6210 *insn_idx = env->subprog_info[subprog].start - 1;
f4d7e40a 6211
06ee7115 6212 if (env->log.level & BPF_LOG_LEVEL) {
f4d7e40a 6213 verbose(env, "caller:\n");
0f55f9ed 6214 print_verifier_state(env, caller, true);
f4d7e40a 6215 verbose(env, "callee:\n");
0f55f9ed 6216 print_verifier_state(env, callee, true);
f4d7e40a
AS
6217 }
6218 return 0;
6219}
6220
314ee05e
YS
6221int map_set_for_each_callback_args(struct bpf_verifier_env *env,
6222 struct bpf_func_state *caller,
6223 struct bpf_func_state *callee)
6224{
6225 /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
6226 * void *callback_ctx, u64 flags);
6227 * callback_fn(struct bpf_map *map, void *key, void *value,
6228 * void *callback_ctx);
6229 */
6230 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
6231
6232 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
6233 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
6234 callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
6235
6236 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
6237 __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
6238 callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
6239
6240 /* pointer to stack or null */
6241 callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
6242
6243 /* unused */
6244 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
6245 return 0;
6246}
6247
14351375
YS
6248static int set_callee_state(struct bpf_verifier_env *env,
6249 struct bpf_func_state *caller,
6250 struct bpf_func_state *callee, int insn_idx)
6251{
6252 int i;
6253
6254 /* copy r1 - r5 args that callee can access. The copy includes parent
6255 * pointers, which connects us up to the liveness chain
6256 */
6257 for (i = BPF_REG_1; i <= BPF_REG_5; i++)
6258 callee->regs[i] = caller->regs[i];
6259 return 0;
6260}
6261
6262static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
6263 int *insn_idx)
6264{
6265 int subprog, target_insn;
6266
6267 target_insn = *insn_idx + insn->imm + 1;
6268 subprog = find_subprog(env, target_insn);
6269 if (subprog < 0) {
6270 verbose(env, "verifier bug. No program starts at insn %d\n",
6271 target_insn);
6272 return -EFAULT;
6273 }
6274
6275 return __check_func_call(env, insn, insn_idx, subprog, set_callee_state);
6276}
6277
69c087ba
YS
6278static int set_map_elem_callback_state(struct bpf_verifier_env *env,
6279 struct bpf_func_state *caller,
6280 struct bpf_func_state *callee,
6281 int insn_idx)
6282{
6283 struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
6284 struct bpf_map *map;
6285 int err;
6286
6287 if (bpf_map_ptr_poisoned(insn_aux)) {
6288 verbose(env, "tail_call abusing map_ptr\n");
6289 return -EINVAL;
6290 }
6291
6292 map = BPF_MAP_PTR(insn_aux->map_ptr_state);
6293 if (!map->ops->map_set_for_each_callback_args ||
6294 !map->ops->map_for_each_callback) {
6295 verbose(env, "callback function not allowed for map\n");
6296 return -ENOTSUPP;
6297 }
6298
6299 err = map->ops->map_set_for_each_callback_args(env, caller, callee);
6300 if (err)
6301 return err;
6302
6303 callee->in_callback_fn = true;
6304 return 0;
6305}
6306
e6f2dd0f
JK
6307static int set_loop_callback_state(struct bpf_verifier_env *env,
6308 struct bpf_func_state *caller,
6309 struct bpf_func_state *callee,
6310 int insn_idx)
6311{
6312 /* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
6313 * u64 flags);
6314 * callback_fn(u32 index, void *callback_ctx);
6315 */
6316 callee->regs[BPF_REG_1].type = SCALAR_VALUE;
6317 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
6318
6319 /* unused */
6320 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
6321 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
6322 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
6323
6324 callee->in_callback_fn = true;
6325 return 0;
6326}
6327
b00628b1
AS
6328static int set_timer_callback_state(struct bpf_verifier_env *env,
6329 struct bpf_func_state *caller,
6330 struct bpf_func_state *callee,
6331 int insn_idx)
6332{
6333 struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
6334
6335 /* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
6336 * callback_fn(struct bpf_map *map, void *key, void *value);
6337 */
6338 callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
6339 __mark_reg_known_zero(&callee->regs[BPF_REG_1]);
6340 callee->regs[BPF_REG_1].map_ptr = map_ptr;
6341
6342 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
6343 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
6344 callee->regs[BPF_REG_2].map_ptr = map_ptr;
6345
6346 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
6347 __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
6348 callee->regs[BPF_REG_3].map_ptr = map_ptr;
6349
6350 /* unused */
6351 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
6352 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
bfc6bb74 6353 callee->in_async_callback_fn = true;
b00628b1
AS
6354 return 0;
6355}
6356
7c7e3d31
SL
6357static int set_find_vma_callback_state(struct bpf_verifier_env *env,
6358 struct bpf_func_state *caller,
6359 struct bpf_func_state *callee,
6360 int insn_idx)
6361{
6362 /* bpf_find_vma(struct task_struct *task, u64 addr,
6363 * void *callback_fn, void *callback_ctx, u64 flags)
6364 * (callback_fn)(struct task_struct *task,
6365 * struct vm_area_struct *vma, void *callback_ctx);
6366 */
6367 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
6368
6369 callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
6370 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
6371 callee->regs[BPF_REG_2].btf = btf_vmlinux;
d19ddb47 6372 callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA],
7c7e3d31
SL
6373
6374 /* pointer to stack or null */
6375 callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
6376
6377 /* unused */
6378 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
6379 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
6380 callee->in_callback_fn = true;
6381 return 0;
6382}
6383
f4d7e40a
AS
6384static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
6385{
6386 struct bpf_verifier_state *state = env->cur_state;
6387 struct bpf_func_state *caller, *callee;
6388 struct bpf_reg_state *r0;
fd978bf7 6389 int err;
f4d7e40a
AS
6390
6391 callee = state->frame[state->curframe];
6392 r0 = &callee->regs[BPF_REG_0];
6393 if (r0->type == PTR_TO_STACK) {
6394 /* technically it's ok to return caller's stack pointer
6395 * (or caller's caller's pointer) back to the caller,
6396 * since these pointers are valid. Only current stack
6397 * pointer will be invalid as soon as function exits,
6398 * but let's be conservative
6399 */
6400 verbose(env, "cannot return stack pointer to the caller\n");
6401 return -EINVAL;
6402 }
6403
6404 state->curframe--;
6405 caller = state->frame[state->curframe];
69c087ba
YS
6406 if (callee->in_callback_fn) {
6407 /* enforce R0 return value range [0, 1]. */
6408 struct tnum range = tnum_range(0, 1);
6409
6410 if (r0->type != SCALAR_VALUE) {
6411 verbose(env, "R0 not a scalar value\n");
6412 return -EACCES;
6413 }
6414 if (!tnum_in(range, r0->var_off)) {
6415 verbose_invalid_scalar(env, r0, &range, "callback return", "R0");
6416 return -EINVAL;
6417 }
6418 } else {
6419 /* return to the caller whatever r0 had in the callee */
6420 caller->regs[BPF_REG_0] = *r0;
6421 }
f4d7e40a 6422
fd978bf7 6423 /* Transfer references to the caller */
c69431aa 6424 err = copy_reference_state(caller, callee);
fd978bf7
JS
6425 if (err)
6426 return err;
6427
f4d7e40a 6428 *insn_idx = callee->callsite + 1;
06ee7115 6429 if (env->log.level & BPF_LOG_LEVEL) {
f4d7e40a 6430 verbose(env, "returning from callee:\n");
0f55f9ed 6431 print_verifier_state(env, callee, true);
f4d7e40a 6432 verbose(env, "to caller at %d:\n", *insn_idx);
0f55f9ed 6433 print_verifier_state(env, caller, true);
f4d7e40a
AS
6434 }
6435 /* clear everything in the callee */
6436 free_func_state(callee);
6437 state->frame[state->curframe + 1] = NULL;
6438 return 0;
6439}
6440
849fa506
YS
6441static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
6442 int func_id,
6443 struct bpf_call_arg_meta *meta)
6444{
6445 struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
6446
6447 if (ret_type != RET_INTEGER ||
6448 (func_id != BPF_FUNC_get_stack &&
fd0b88f7 6449 func_id != BPF_FUNC_get_task_stack &&
47cc0ed5
DB
6450 func_id != BPF_FUNC_probe_read_str &&
6451 func_id != BPF_FUNC_probe_read_kernel_str &&
6452 func_id != BPF_FUNC_probe_read_user_str))
849fa506
YS
6453 return;
6454
10060503 6455 ret_reg->smax_value = meta->msize_max_value;
fa123ac0 6456 ret_reg->s32_max_value = meta->msize_max_value;
b0270958
AS
6457 ret_reg->smin_value = -MAX_ERRNO;
6458 ret_reg->s32_min_value = -MAX_ERRNO;
849fa506
YS
6459 __reg_deduce_bounds(ret_reg);
6460 __reg_bound_offset(ret_reg);
10060503 6461 __update_reg_bounds(ret_reg);
849fa506
YS
6462}
6463
c93552c4
DB
6464static int
6465record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
6466 int func_id, int insn_idx)
6467{
6468 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
591fe988 6469 struct bpf_map *map = meta->map_ptr;
c93552c4
DB
6470
6471 if (func_id != BPF_FUNC_tail_call &&
09772d92
DB
6472 func_id != BPF_FUNC_map_lookup_elem &&
6473 func_id != BPF_FUNC_map_update_elem &&
f1a2e44a
MV
6474 func_id != BPF_FUNC_map_delete_elem &&
6475 func_id != BPF_FUNC_map_push_elem &&
6476 func_id != BPF_FUNC_map_pop_elem &&
69c087ba 6477 func_id != BPF_FUNC_map_peek_elem &&
e6a4750f
BT
6478 func_id != BPF_FUNC_for_each_map_elem &&
6479 func_id != BPF_FUNC_redirect_map)
c93552c4 6480 return 0;
09772d92 6481
591fe988 6482 if (map == NULL) {
c93552c4
DB
6483 verbose(env, "kernel subsystem misconfigured verifier\n");
6484 return -EINVAL;
6485 }
6486
591fe988
DB
6487 /* In case of read-only, some additional restrictions
6488 * need to be applied in order to prevent altering the
6489 * state of the map from program side.
6490 */
6491 if ((map->map_flags & BPF_F_RDONLY_PROG) &&
6492 (func_id == BPF_FUNC_map_delete_elem ||
6493 func_id == BPF_FUNC_map_update_elem ||
6494 func_id == BPF_FUNC_map_push_elem ||
6495 func_id == BPF_FUNC_map_pop_elem)) {
6496 verbose(env, "write into map forbidden\n");
6497 return -EACCES;
6498 }
6499
d2e4c1e6 6500 if (!BPF_MAP_PTR(aux->map_ptr_state))
c93552c4 6501 bpf_map_ptr_store(aux, meta->map_ptr,
2c78ee89 6502 !meta->map_ptr->bypass_spec_v1);
d2e4c1e6 6503 else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
c93552c4 6504 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
2c78ee89 6505 !meta->map_ptr->bypass_spec_v1);
c93552c4
DB
6506 return 0;
6507}
6508
d2e4c1e6
DB
6509static int
6510record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
6511 int func_id, int insn_idx)
6512{
6513 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
6514 struct bpf_reg_state *regs = cur_regs(env), *reg;
6515 struct bpf_map *map = meta->map_ptr;
6516 struct tnum range;
6517 u64 val;
cc52d914 6518 int err;
d2e4c1e6
DB
6519
6520 if (func_id != BPF_FUNC_tail_call)
6521 return 0;
6522 if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
6523 verbose(env, "kernel subsystem misconfigured verifier\n");
6524 return -EINVAL;
6525 }
6526
6527 range = tnum_range(0, map->max_entries - 1);
6528 reg = &regs[BPF_REG_3];
6529
6530 if (!register_is_const(reg) || !tnum_in(range, reg->var_off)) {
6531 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
6532 return 0;
6533 }
6534
cc52d914
DB
6535 err = mark_chain_precision(env, BPF_REG_3);
6536 if (err)
6537 return err;
6538
d2e4c1e6
DB
6539 val = reg->var_off.value;
6540 if (bpf_map_key_unseen(aux))
6541 bpf_map_key_store(aux, val);
6542 else if (!bpf_map_key_poisoned(aux) &&
6543 bpf_map_key_immediate(aux) != val)
6544 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
6545 return 0;
6546}
6547
fd978bf7
JS
6548static int check_reference_leak(struct bpf_verifier_env *env)
6549{
6550 struct bpf_func_state *state = cur_func(env);
6551 int i;
6552
6553 for (i = 0; i < state->acquired_refs; i++) {
6554 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
6555 state->refs[i].id, state->refs[i].insn_idx);
6556 }
6557 return state->acquired_refs ? -EINVAL : 0;
6558}
6559
7b15523a
FR
6560static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
6561 struct bpf_reg_state *regs)
6562{
6563 struct bpf_reg_state *fmt_reg = &regs[BPF_REG_3];
6564 struct bpf_reg_state *data_len_reg = &regs[BPF_REG_5];
6565 struct bpf_map *fmt_map = fmt_reg->map_ptr;
6566 int err, fmt_map_off, num_args;
6567 u64 fmt_addr;
6568 char *fmt;
6569
6570 /* data must be an array of u64 */
6571 if (data_len_reg->var_off.value % 8)
6572 return -EINVAL;
6573 num_args = data_len_reg->var_off.value / 8;
6574
6575 /* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
6576 * and map_direct_value_addr is set.
6577 */
6578 fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
6579 err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
6580 fmt_map_off);
8e8ee109
FR
6581 if (err) {
6582 verbose(env, "verifier bug\n");
6583 return -EFAULT;
6584 }
7b15523a
FR
6585 fmt = (char *)(long)fmt_addr + fmt_map_off;
6586
6587 /* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
6588 * can focus on validating the format specifiers.
6589 */
48cac3f4 6590 err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, NULL, num_args);
7b15523a
FR
6591 if (err < 0)
6592 verbose(env, "Invalid format string\n");
6593
6594 return err;
6595}
6596
9b99edca
JO
6597static int check_get_func_ip(struct bpf_verifier_env *env)
6598{
9b99edca
JO
6599 enum bpf_prog_type type = resolve_prog_type(env->prog);
6600 int func_id = BPF_FUNC_get_func_ip;
6601
6602 if (type == BPF_PROG_TYPE_TRACING) {
f92c1e18 6603 if (!bpf_prog_has_trampoline(env->prog)) {
9b99edca
JO
6604 verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
6605 func_id_name(func_id), func_id);
6606 return -ENOTSUPP;
6607 }
6608 return 0;
9ffd9f3f
JO
6609 } else if (type == BPF_PROG_TYPE_KPROBE) {
6610 return 0;
9b99edca
JO
6611 }
6612
6613 verbose(env, "func %s#%d not supported for program type %d\n",
6614 func_id_name(func_id), func_id, type);
6615 return -ENOTSUPP;
6616}
6617
69c087ba
YS
6618static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
6619 int *insn_idx_p)
17a52670 6620{
17a52670 6621 const struct bpf_func_proto *fn = NULL;
3c480732 6622 enum bpf_return_type ret_type;
c25b2ae1 6623 enum bpf_type_flag ret_flag;
638f5b90 6624 struct bpf_reg_state *regs;
33ff9823 6625 struct bpf_call_arg_meta meta;
69c087ba 6626 int insn_idx = *insn_idx_p;
969bf05e 6627 bool changes_data;
69c087ba 6628 int i, err, func_id;
17a52670
AS
6629
6630 /* find function prototype */
69c087ba 6631 func_id = insn->imm;
17a52670 6632 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
61bd5218
JK
6633 verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
6634 func_id);
17a52670
AS
6635 return -EINVAL;
6636 }
6637
00176a34 6638 if (env->ops->get_func_proto)
5e43f899 6639 fn = env->ops->get_func_proto(func_id, env->prog);
17a52670 6640 if (!fn) {
61bd5218
JK
6641 verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
6642 func_id);
17a52670
AS
6643 return -EINVAL;
6644 }
6645
6646 /* eBPF programs must be GPL compatible to use GPL-ed functions */
24701ece 6647 if (!env->prog->gpl_compatible && fn->gpl_only) {
3fe2867c 6648 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
17a52670
AS
6649 return -EINVAL;
6650 }
6651
eae2e83e
JO
6652 if (fn->allowed && !fn->allowed(env->prog)) {
6653 verbose(env, "helper call is not allowed in probe\n");
6654 return -EINVAL;
6655 }
6656
04514d13 6657 /* With LD_ABS/IND some JITs save/restore skb from r1. */
17bedab2 6658 changes_data = bpf_helper_changes_pkt_data(fn->func);
04514d13
DB
6659 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
6660 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
6661 func_id_name(func_id), func_id);
6662 return -EINVAL;
6663 }
969bf05e 6664
33ff9823 6665 memset(&meta, 0, sizeof(meta));
36bbef52 6666 meta.pkt_access = fn->pkt_access;
33ff9823 6667
1b986589 6668 err = check_func_proto(fn, func_id);
435faee1 6669 if (err) {
61bd5218 6670 verbose(env, "kernel subsystem misconfigured func %s#%d\n",
ebb676da 6671 func_id_name(func_id), func_id);
435faee1
DB
6672 return err;
6673 }
6674
d83525ca 6675 meta.func_id = func_id;
17a52670 6676 /* check args */
523a4cf4 6677 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
af7ec138 6678 err = check_func_arg(env, i, &meta, fn);
a7658e1a
AS
6679 if (err)
6680 return err;
6681 }
17a52670 6682
c93552c4
DB
6683 err = record_func_map(env, &meta, func_id, insn_idx);
6684 if (err)
6685 return err;
6686
d2e4c1e6
DB
6687 err = record_func_key(env, &meta, func_id, insn_idx);
6688 if (err)
6689 return err;
6690
435faee1
DB
6691 /* Mark slots with STACK_MISC in case of raw mode, stack offset
6692 * is inferred from register state.
6693 */
6694 for (i = 0; i < meta.access_size; i++) {
ca369602
DB
6695 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
6696 BPF_WRITE, -1, false);
435faee1
DB
6697 if (err)
6698 return err;
6699 }
6700
e6f2dd0f 6701 if (is_release_function(func_id)) {
1b986589 6702 err = release_reference(env, meta.ref_obj_id);
46f8bc92
MKL
6703 if (err) {
6704 verbose(env, "func %s#%d reference has not been acquired before\n",
6705 func_id_name(func_id), func_id);
fd978bf7 6706 return err;
46f8bc92 6707 }
fd978bf7
JS
6708 }
6709
638f5b90 6710 regs = cur_regs(env);
cd339431 6711
e6f2dd0f
JK
6712 switch (func_id) {
6713 case BPF_FUNC_tail_call:
6714 err = check_reference_leak(env);
6715 if (err) {
6716 verbose(env, "tail_call would lead to reference leak\n");
6717 return err;
6718 }
6719 break;
6720 case BPF_FUNC_get_local_storage:
6721 /* check that flags argument in get_local_storage(map, flags) is 0,
6722 * this is required because get_local_storage() can't return an error.
6723 */
6724 if (!register_is_null(&regs[BPF_REG_2])) {
6725 verbose(env, "get_local_storage() doesn't support non-zero flags\n");
6726 return -EINVAL;
6727 }
6728 break;
6729 case BPF_FUNC_for_each_map_elem:
69c087ba
YS
6730 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
6731 set_map_elem_callback_state);
e6f2dd0f
JK
6732 break;
6733 case BPF_FUNC_timer_set_callback:
b00628b1
AS
6734 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
6735 set_timer_callback_state);
e6f2dd0f
JK
6736 break;
6737 case BPF_FUNC_find_vma:
7c7e3d31
SL
6738 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
6739 set_find_vma_callback_state);
e6f2dd0f
JK
6740 break;
6741 case BPF_FUNC_snprintf:
7b15523a 6742 err = check_bpf_snprintf_call(env, regs);
e6f2dd0f
JK
6743 break;
6744 case BPF_FUNC_loop:
6745 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
6746 set_loop_callback_state);
6747 break;
7b15523a
FR
6748 }
6749
e6f2dd0f
JK
6750 if (err)
6751 return err;
6752
17a52670 6753 /* reset caller saved regs */
dc503a8a 6754 for (i = 0; i < CALLER_SAVED_REGS; i++) {
61bd5218 6755 mark_reg_not_init(env, regs, caller_saved[i]);
dc503a8a
EC
6756 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
6757 }
17a52670 6758
5327ed3d
JW
6759 /* helper call returns 64-bit value. */
6760 regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
6761
dc503a8a 6762 /* update return register (already marked as written above) */
3c480732 6763 ret_type = fn->ret_type;
c25b2ae1 6764 ret_flag = type_flag(fn->ret_type);
3c480732 6765 if (ret_type == RET_INTEGER) {
f1174f77 6766 /* sets type to SCALAR_VALUE */
61bd5218 6767 mark_reg_unknown(env, regs, BPF_REG_0);
3c480732 6768 } else if (ret_type == RET_VOID) {
17a52670 6769 regs[BPF_REG_0].type = NOT_INIT;
3c480732 6770 } else if (base_type(ret_type) == RET_PTR_TO_MAP_VALUE) {
f1174f77 6771 /* There is no offset yet applied, variable or fixed */
61bd5218 6772 mark_reg_known_zero(env, regs, BPF_REG_0);
17a52670
AS
6773 /* remember map_ptr, so that check_map_access()
6774 * can check 'value_size' boundary of memory access
6775 * to map element returned from bpf_map_lookup_elem()
6776 */
33ff9823 6777 if (meta.map_ptr == NULL) {
61bd5218
JK
6778 verbose(env,
6779 "kernel subsystem misconfigured verifier\n");
17a52670
AS
6780 return -EINVAL;
6781 }
33ff9823 6782 regs[BPF_REG_0].map_ptr = meta.map_ptr;
3e8ce298 6783 regs[BPF_REG_0].map_uid = meta.map_uid;
c25b2ae1
HL
6784 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
6785 if (!type_may_be_null(ret_type) &&
6786 map_value_has_spin_lock(meta.map_ptr)) {
6787 regs[BPF_REG_0].id = ++env->id_gen;
4d31f301 6788 }
3c480732 6789 } else if (base_type(ret_type) == RET_PTR_TO_SOCKET) {
c64b7983 6790 mark_reg_known_zero(env, regs, BPF_REG_0);
c25b2ae1 6791 regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
3c480732 6792 } else if (base_type(ret_type) == RET_PTR_TO_SOCK_COMMON) {
85a51f8c 6793 mark_reg_known_zero(env, regs, BPF_REG_0);
c25b2ae1 6794 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
3c480732 6795 } else if (base_type(ret_type) == RET_PTR_TO_TCP_SOCK) {
655a51e5 6796 mark_reg_known_zero(env, regs, BPF_REG_0);
c25b2ae1 6797 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
3c480732 6798 } else if (base_type(ret_type) == RET_PTR_TO_ALLOC_MEM) {
457f4436 6799 mark_reg_known_zero(env, regs, BPF_REG_0);
c25b2ae1 6800 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
457f4436 6801 regs[BPF_REG_0].mem_size = meta.mem_size;
3c480732 6802 } else if (base_type(ret_type) == RET_PTR_TO_MEM_OR_BTF_ID) {
eaa6bcb7
HL
6803 const struct btf_type *t;
6804
6805 mark_reg_known_zero(env, regs, BPF_REG_0);
22dc4a0f 6806 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
eaa6bcb7
HL
6807 if (!btf_type_is_struct(t)) {
6808 u32 tsize;
6809 const struct btf_type *ret;
6810 const char *tname;
6811
6812 /* resolve the type size of ksym. */
22dc4a0f 6813 ret = btf_resolve_size(meta.ret_btf, t, &tsize);
eaa6bcb7 6814 if (IS_ERR(ret)) {
22dc4a0f 6815 tname = btf_name_by_offset(meta.ret_btf, t->name_off);
eaa6bcb7
HL
6816 verbose(env, "unable to resolve the size of type '%s': %ld\n",
6817 tname, PTR_ERR(ret));
6818 return -EINVAL;
6819 }
c25b2ae1 6820 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
eaa6bcb7
HL
6821 regs[BPF_REG_0].mem_size = tsize;
6822 } else {
34d3a78c
HL
6823 /* MEM_RDONLY may be carried from ret_flag, but it
6824 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
6825 * it will confuse the check of PTR_TO_BTF_ID in
6826 * check_mem_access().
6827 */
6828 ret_flag &= ~MEM_RDONLY;
6829
c25b2ae1 6830 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
22dc4a0f 6831 regs[BPF_REG_0].btf = meta.ret_btf;
eaa6bcb7
HL
6832 regs[BPF_REG_0].btf_id = meta.ret_btf_id;
6833 }
3c480732 6834 } else if (base_type(ret_type) == RET_PTR_TO_BTF_ID) {
af7ec138
YS
6835 int ret_btf_id;
6836
6837 mark_reg_known_zero(env, regs, BPF_REG_0);
c25b2ae1 6838 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
af7ec138
YS
6839 ret_btf_id = *fn->ret_btf_id;
6840 if (ret_btf_id == 0) {
3c480732
HL
6841 verbose(env, "invalid return type %u of func %s#%d\n",
6842 base_type(ret_type), func_id_name(func_id),
6843 func_id);
af7ec138
YS
6844 return -EINVAL;
6845 }
22dc4a0f
AN
6846 /* current BPF helper definitions are only coming from
6847 * built-in code with type IDs from vmlinux BTF
6848 */
6849 regs[BPF_REG_0].btf = btf_vmlinux;
af7ec138 6850 regs[BPF_REG_0].btf_id = ret_btf_id;
17a52670 6851 } else {
3c480732
HL
6852 verbose(env, "unknown return type %u of func %s#%d\n",
6853 base_type(ret_type), func_id_name(func_id), func_id);
17a52670
AS
6854 return -EINVAL;
6855 }
04fd61ab 6856
c25b2ae1 6857 if (type_may_be_null(regs[BPF_REG_0].type))
93c230e3
MKL
6858 regs[BPF_REG_0].id = ++env->id_gen;
6859
0f3adc28 6860 if (is_ptr_cast_function(func_id)) {
1b986589
MKL
6861 /* For release_reference() */
6862 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
64d85290 6863 } else if (is_acquire_function(func_id, meta.map_ptr)) {
0f3adc28
LB
6864 int id = acquire_reference_state(env, insn_idx);
6865
6866 if (id < 0)
6867 return id;
6868 /* For mark_ptr_or_null_reg() */
6869 regs[BPF_REG_0].id = id;
6870 /* For release_reference() */
6871 regs[BPF_REG_0].ref_obj_id = id;
6872 }
1b986589 6873
849fa506
YS
6874 do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
6875
61bd5218 6876 err = check_map_func_compatibility(env, meta.map_ptr, func_id);
35578d79
KX
6877 if (err)
6878 return err;
04fd61ab 6879
fa28dcb8
SL
6880 if ((func_id == BPF_FUNC_get_stack ||
6881 func_id == BPF_FUNC_get_task_stack) &&
6882 !env->prog->has_callchain_buf) {
c195651e
YS
6883 const char *err_str;
6884
6885#ifdef CONFIG_PERF_EVENTS
6886 err = get_callchain_buffers(sysctl_perf_event_max_stack);
6887 err_str = "cannot get callchain buffer for func %s#%d\n";
6888#else
6889 err = -ENOTSUPP;
6890 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
6891#endif
6892 if (err) {
6893 verbose(env, err_str, func_id_name(func_id), func_id);
6894 return err;
6895 }
6896
6897 env->prog->has_callchain_buf = true;
6898 }
6899
5d99cb2c
SL
6900 if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
6901 env->prog->call_get_stack = true;
6902
9b99edca
JO
6903 if (func_id == BPF_FUNC_get_func_ip) {
6904 if (check_get_func_ip(env))
6905 return -ENOTSUPP;
6906 env->prog->call_get_func_ip = true;
6907 }
6908
969bf05e
AS
6909 if (changes_data)
6910 clear_all_pkt_pointers(env);
6911 return 0;
6912}
6913
e6ac2450
MKL
6914/* mark_btf_func_reg_size() is used when the reg size is determined by
6915 * the BTF func_proto's return value size and argument.
6916 */
6917static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
6918 size_t reg_size)
6919{
6920 struct bpf_reg_state *reg = &cur_regs(env)[regno];
6921
6922 if (regno == BPF_REG_0) {
6923 /* Function return value */
6924 reg->live |= REG_LIVE_WRITTEN;
6925 reg->subreg_def = reg_size == sizeof(u64) ?
6926 DEF_NOT_SUBREG : env->insn_idx + 1;
6927 } else {
6928 /* Function argument */
6929 if (reg_size == sizeof(u64)) {
6930 mark_insn_zext(env, reg);
6931 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
6932 } else {
6933 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
6934 }
6935 }
6936}
6937
5c073f26
KKD
6938static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
6939 int *insn_idx_p)
e6ac2450
MKL
6940{
6941 const struct btf_type *t, *func, *func_proto, *ptr_type;
6942 struct bpf_reg_state *regs = cur_regs(env);
6943 const char *func_name, *ptr_type_name;
6944 u32 i, nargs, func_id, ptr_type_id;
5c073f26 6945 int err, insn_idx = *insn_idx_p;
e6ac2450 6946 const struct btf_param *args;
2357672c 6947 struct btf *desc_btf;
5c073f26 6948 bool acq;
e6ac2450 6949
a5d82727
KKD
6950 /* skip for now, but return error when we find this in fixup_kfunc_call */
6951 if (!insn->imm)
6952 return 0;
6953
b202d844 6954 desc_btf = find_kfunc_desc_btf(env, insn->imm, insn->off);
2357672c
KKD
6955 if (IS_ERR(desc_btf))
6956 return PTR_ERR(desc_btf);
6957
e6ac2450 6958 func_id = insn->imm;
2357672c
KKD
6959 func = btf_type_by_id(desc_btf, func_id);
6960 func_name = btf_name_by_offset(desc_btf, func->name_off);
6961 func_proto = btf_type_by_id(desc_btf, func->type);
e6ac2450 6962
b202d844
KKD
6963 if (!btf_kfunc_id_set_contains(desc_btf, resolve_prog_type(env->prog),
6964 BTF_KFUNC_TYPE_CHECK, func_id)) {
e6ac2450
MKL
6965 verbose(env, "calling kernel function %s is not allowed\n",
6966 func_name);
6967 return -EACCES;
6968 }
6969
5c073f26
KKD
6970 acq = btf_kfunc_id_set_contains(desc_btf, resolve_prog_type(env->prog),
6971 BTF_KFUNC_TYPE_ACQUIRE, func_id);
6972
e6ac2450 6973 /* Check the arguments */
2357672c 6974 err = btf_check_kfunc_arg_match(env, desc_btf, func_id, regs);
5c073f26 6975 if (err < 0)
e6ac2450 6976 return err;
5c073f26
KKD
6977 /* In case of release function, we get register number of refcounted
6978 * PTR_TO_BTF_ID back from btf_check_kfunc_arg_match, do the release now
6979 */
6980 if (err) {
6981 err = release_reference(env, regs[err].ref_obj_id);
6982 if (err) {
6983 verbose(env, "kfunc %s#%d reference has not been acquired before\n",
6984 func_name, func_id);
6985 return err;
6986 }
6987 }
e6ac2450
MKL
6988
6989 for (i = 0; i < CALLER_SAVED_REGS; i++)
6990 mark_reg_not_init(env, regs, caller_saved[i]);
6991
6992 /* Check return type */
2357672c 6993 t = btf_type_skip_modifiers(desc_btf, func_proto->type, NULL);
5c073f26
KKD
6994
6995 if (acq && !btf_type_is_ptr(t)) {
6996 verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n");
6997 return -EINVAL;
6998 }
6999
e6ac2450
MKL
7000 if (btf_type_is_scalar(t)) {
7001 mark_reg_unknown(env, regs, BPF_REG_0);
7002 mark_btf_func_reg_size(env, BPF_REG_0, t->size);
7003 } else if (btf_type_is_ptr(t)) {
2357672c 7004 ptr_type = btf_type_skip_modifiers(desc_btf, t->type,
e6ac2450
MKL
7005 &ptr_type_id);
7006 if (!btf_type_is_struct(ptr_type)) {
2357672c 7007 ptr_type_name = btf_name_by_offset(desc_btf,
e6ac2450
MKL
7008 ptr_type->name_off);
7009 verbose(env, "kernel function %s returns pointer type %s %s is not supported\n",
7010 func_name, btf_type_str(ptr_type),
7011 ptr_type_name);
7012 return -EINVAL;
7013 }
7014 mark_reg_known_zero(env, regs, BPF_REG_0);
2357672c 7015 regs[BPF_REG_0].btf = desc_btf;
e6ac2450
MKL
7016 regs[BPF_REG_0].type = PTR_TO_BTF_ID;
7017 regs[BPF_REG_0].btf_id = ptr_type_id;
5c073f26
KKD
7018 if (btf_kfunc_id_set_contains(desc_btf, resolve_prog_type(env->prog),
7019 BTF_KFUNC_TYPE_RET_NULL, func_id)) {
7020 regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
7021 /* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
7022 regs[BPF_REG_0].id = ++env->id_gen;
7023 }
e6ac2450 7024 mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
5c073f26
KKD
7025 if (acq) {
7026 int id = acquire_reference_state(env, insn_idx);
7027
7028 if (id < 0)
7029 return id;
7030 regs[BPF_REG_0].id = id;
7031 regs[BPF_REG_0].ref_obj_id = id;
7032 }
e6ac2450
MKL
7033 } /* else { add_kfunc_call() ensures it is btf_type_is_void(t) } */
7034
7035 nargs = btf_type_vlen(func_proto);
7036 args = (const struct btf_param *)(func_proto + 1);
7037 for (i = 0; i < nargs; i++) {
7038 u32 regno = i + 1;
7039
2357672c 7040 t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
e6ac2450
MKL
7041 if (btf_type_is_ptr(t))
7042 mark_btf_func_reg_size(env, regno, sizeof(void *));
7043 else
7044 /* scalar. ensured by btf_check_kfunc_arg_match() */
7045 mark_btf_func_reg_size(env, regno, t->size);
7046 }
7047
7048 return 0;
7049}
7050
b03c9f9f
EC
7051static bool signed_add_overflows(s64 a, s64 b)
7052{
7053 /* Do the add in u64, where overflow is well-defined */
7054 s64 res = (s64)((u64)a + (u64)b);
7055
7056 if (b < 0)
7057 return res > a;
7058 return res < a;
7059}
7060
bc895e8b 7061static bool signed_add32_overflows(s32 a, s32 b)
3f50f132
JF
7062{
7063 /* Do the add in u32, where overflow is well-defined */
7064 s32 res = (s32)((u32)a + (u32)b);
7065
7066 if (b < 0)
7067 return res > a;
7068 return res < a;
7069}
7070
bc895e8b 7071static bool signed_sub_overflows(s64 a, s64 b)
b03c9f9f
EC
7072{
7073 /* Do the sub in u64, where overflow is well-defined */
7074 s64 res = (s64)((u64)a - (u64)b);
7075
7076 if (b < 0)
7077 return res < a;
7078 return res > a;
969bf05e
AS
7079}
7080
3f50f132
JF
7081static bool signed_sub32_overflows(s32 a, s32 b)
7082{
bc895e8b 7083 /* Do the sub in u32, where overflow is well-defined */
3f50f132
JF
7084 s32 res = (s32)((u32)a - (u32)b);
7085
7086 if (b < 0)
7087 return res < a;
7088 return res > a;
7089}
7090
bb7f0f98
AS
7091static bool check_reg_sane_offset(struct bpf_verifier_env *env,
7092 const struct bpf_reg_state *reg,
7093 enum bpf_reg_type type)
7094{
7095 bool known = tnum_is_const(reg->var_off);
7096 s64 val = reg->var_off.value;
7097 s64 smin = reg->smin_value;
7098
7099 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
7100 verbose(env, "math between %s pointer and %lld is not allowed\n",
c25b2ae1 7101 reg_type_str(env, type), val);
bb7f0f98
AS
7102 return false;
7103 }
7104
7105 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
7106 verbose(env, "%s pointer offset %d is not allowed\n",
c25b2ae1 7107 reg_type_str(env, type), reg->off);
bb7f0f98
AS
7108 return false;
7109 }
7110
7111 if (smin == S64_MIN) {
7112 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
c25b2ae1 7113 reg_type_str(env, type));
bb7f0f98
AS
7114 return false;
7115 }
7116
7117 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
7118 verbose(env, "value %lld makes %s pointer be out of bounds\n",
c25b2ae1 7119 smin, reg_type_str(env, type));
bb7f0f98
AS
7120 return false;
7121 }
7122
7123 return true;
7124}
7125
979d63d5
DB
7126static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
7127{
7128 return &env->insn_aux_data[env->insn_idx];
7129}
7130
a6aaece0
DB
7131enum {
7132 REASON_BOUNDS = -1,
7133 REASON_TYPE = -2,
7134 REASON_PATHS = -3,
7135 REASON_LIMIT = -4,
7136 REASON_STACK = -5,
7137};
7138
979d63d5 7139static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
bb01a1bb 7140 u32 *alu_limit, bool mask_to_left)
979d63d5 7141{
7fedb63a 7142 u32 max = 0, ptr_limit = 0;
979d63d5
DB
7143
7144 switch (ptr_reg->type) {
7145 case PTR_TO_STACK:
1b1597e6 7146 /* Offset 0 is out-of-bounds, but acceptable start for the
7fedb63a
DB
7147 * left direction, see BPF_REG_FP. Also, unknown scalar
7148 * offset where we would need to deal with min/max bounds is
7149 * currently prohibited for unprivileged.
1b1597e6
PK
7150 */
7151 max = MAX_BPF_STACK + mask_to_left;
7fedb63a 7152 ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
b658bbb8 7153 break;
979d63d5 7154 case PTR_TO_MAP_VALUE:
1b1597e6 7155 max = ptr_reg->map_ptr->value_size;
7fedb63a
DB
7156 ptr_limit = (mask_to_left ?
7157 ptr_reg->smin_value :
7158 ptr_reg->umax_value) + ptr_reg->off;
b658bbb8 7159 break;
979d63d5 7160 default:
a6aaece0 7161 return REASON_TYPE;
979d63d5 7162 }
b658bbb8
DB
7163
7164 if (ptr_limit >= max)
a6aaece0 7165 return REASON_LIMIT;
b658bbb8
DB
7166 *alu_limit = ptr_limit;
7167 return 0;
979d63d5
DB
7168}
7169
d3bd7413
DB
7170static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
7171 const struct bpf_insn *insn)
7172{
2c78ee89 7173 return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
d3bd7413
DB
7174}
7175
7176static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
7177 u32 alu_state, u32 alu_limit)
7178{
7179 /* If we arrived here from different branches with different
7180 * state or limits to sanitize, then this won't work.
7181 */
7182 if (aux->alu_state &&
7183 (aux->alu_state != alu_state ||
7184 aux->alu_limit != alu_limit))
a6aaece0 7185 return REASON_PATHS;
d3bd7413 7186
e6ac5933 7187 /* Corresponding fixup done in do_misc_fixups(). */
d3bd7413
DB
7188 aux->alu_state = alu_state;
7189 aux->alu_limit = alu_limit;
7190 return 0;
7191}
7192
7193static int sanitize_val_alu(struct bpf_verifier_env *env,
7194 struct bpf_insn *insn)
7195{
7196 struct bpf_insn_aux_data *aux = cur_aux(env);
7197
7198 if (can_skip_alu_sanitation(env, insn))
7199 return 0;
7200
7201 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
7202}
7203
f5288193
DB
7204static bool sanitize_needed(u8 opcode)
7205{
7206 return opcode == BPF_ADD || opcode == BPF_SUB;
7207}
7208
3d0220f6
DB
7209struct bpf_sanitize_info {
7210 struct bpf_insn_aux_data aux;
bb01a1bb 7211 bool mask_to_left;
3d0220f6
DB
7212};
7213
9183671a
DB
7214static struct bpf_verifier_state *
7215sanitize_speculative_path(struct bpf_verifier_env *env,
7216 const struct bpf_insn *insn,
7217 u32 next_idx, u32 curr_idx)
7218{
7219 struct bpf_verifier_state *branch;
7220 struct bpf_reg_state *regs;
7221
7222 branch = push_stack(env, next_idx, curr_idx, true);
7223 if (branch && insn) {
7224 regs = branch->frame[branch->curframe]->regs;
7225 if (BPF_SRC(insn->code) == BPF_K) {
7226 mark_reg_unknown(env, regs, insn->dst_reg);
7227 } else if (BPF_SRC(insn->code) == BPF_X) {
7228 mark_reg_unknown(env, regs, insn->dst_reg);
7229 mark_reg_unknown(env, regs, insn->src_reg);
7230 }
7231 }
7232 return branch;
7233}
7234
979d63d5
DB
7235static int sanitize_ptr_alu(struct bpf_verifier_env *env,
7236 struct bpf_insn *insn,
7237 const struct bpf_reg_state *ptr_reg,
6f55b2f2 7238 const struct bpf_reg_state *off_reg,
979d63d5 7239 struct bpf_reg_state *dst_reg,
3d0220f6 7240 struct bpf_sanitize_info *info,
7fedb63a 7241 const bool commit_window)
979d63d5 7242{
3d0220f6 7243 struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
979d63d5 7244 struct bpf_verifier_state *vstate = env->cur_state;
801c6058 7245 bool off_is_imm = tnum_is_const(off_reg->var_off);
6f55b2f2 7246 bool off_is_neg = off_reg->smin_value < 0;
979d63d5
DB
7247 bool ptr_is_dst_reg = ptr_reg == dst_reg;
7248 u8 opcode = BPF_OP(insn->code);
7249 u32 alu_state, alu_limit;
7250 struct bpf_reg_state tmp;
7251 bool ret;
f232326f 7252 int err;
979d63d5 7253
d3bd7413 7254 if (can_skip_alu_sanitation(env, insn))
979d63d5
DB
7255 return 0;
7256
7257 /* We already marked aux for masking from non-speculative
7258 * paths, thus we got here in the first place. We only care
7259 * to explore bad access from here.
7260 */
7261 if (vstate->speculative)
7262 goto do_sim;
7263
bb01a1bb
DB
7264 if (!commit_window) {
7265 if (!tnum_is_const(off_reg->var_off) &&
7266 (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
7267 return REASON_BOUNDS;
7268
7269 info->mask_to_left = (opcode == BPF_ADD && off_is_neg) ||
7270 (opcode == BPF_SUB && !off_is_neg);
7271 }
7272
7273 err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
f232326f
PK
7274 if (err < 0)
7275 return err;
7276
7fedb63a
DB
7277 if (commit_window) {
7278 /* In commit phase we narrow the masking window based on
7279 * the observed pointer move after the simulated operation.
7280 */
3d0220f6
DB
7281 alu_state = info->aux.alu_state;
7282 alu_limit = abs(info->aux.alu_limit - alu_limit);
7fedb63a
DB
7283 } else {
7284 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
801c6058 7285 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
7fedb63a
DB
7286 alu_state |= ptr_is_dst_reg ?
7287 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
e042aa53
DB
7288
7289 /* Limit pruning on unknown scalars to enable deep search for
7290 * potential masking differences from other program paths.
7291 */
7292 if (!off_is_imm)
7293 env->explore_alu_limits = true;
7fedb63a
DB
7294 }
7295
f232326f
PK
7296 err = update_alu_sanitation_state(aux, alu_state, alu_limit);
7297 if (err < 0)
7298 return err;
979d63d5 7299do_sim:
7fedb63a
DB
7300 /* If we're in commit phase, we're done here given we already
7301 * pushed the truncated dst_reg into the speculative verification
7302 * stack.
a7036191
DB
7303 *
7304 * Also, when register is a known constant, we rewrite register-based
7305 * operation to immediate-based, and thus do not need masking (and as
7306 * a consequence, do not need to simulate the zero-truncation either).
7fedb63a 7307 */
a7036191 7308 if (commit_window || off_is_imm)
7fedb63a
DB
7309 return 0;
7310
979d63d5
DB
7311 /* Simulate and find potential out-of-bounds access under
7312 * speculative execution from truncation as a result of
7313 * masking when off was not within expected range. If off
7314 * sits in dst, then we temporarily need to move ptr there
7315 * to simulate dst (== 0) +/-= ptr. Needed, for example,
7316 * for cases where we use K-based arithmetic in one direction
7317 * and truncated reg-based in the other in order to explore
7318 * bad access.
7319 */
7320 if (!ptr_is_dst_reg) {
7321 tmp = *dst_reg;
7322 *dst_reg = *ptr_reg;
7323 }
9183671a
DB
7324 ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
7325 env->insn_idx);
0803278b 7326 if (!ptr_is_dst_reg && ret)
979d63d5 7327 *dst_reg = tmp;
a6aaece0
DB
7328 return !ret ? REASON_STACK : 0;
7329}
7330
fe9a5ca7
DB
7331static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
7332{
7333 struct bpf_verifier_state *vstate = env->cur_state;
7334
7335 /* If we simulate paths under speculation, we don't update the
7336 * insn as 'seen' such that when we verify unreachable paths in
7337 * the non-speculative domain, sanitize_dead_code() can still
7338 * rewrite/sanitize them.
7339 */
7340 if (!vstate->speculative)
7341 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
7342}
7343
a6aaece0
DB
7344static int sanitize_err(struct bpf_verifier_env *env,
7345 const struct bpf_insn *insn, int reason,
7346 const struct bpf_reg_state *off_reg,
7347 const struct bpf_reg_state *dst_reg)
7348{
7349 static const char *err = "pointer arithmetic with it prohibited for !root";
7350 const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
7351 u32 dst = insn->dst_reg, src = insn->src_reg;
7352
7353 switch (reason) {
7354 case REASON_BOUNDS:
7355 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
7356 off_reg == dst_reg ? dst : src, err);
7357 break;
7358 case REASON_TYPE:
7359 verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
7360 off_reg == dst_reg ? src : dst, err);
7361 break;
7362 case REASON_PATHS:
7363 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
7364 dst, op, err);
7365 break;
7366 case REASON_LIMIT:
7367 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
7368 dst, op, err);
7369 break;
7370 case REASON_STACK:
7371 verbose(env, "R%d could not be pushed for speculative verification, %s\n",
7372 dst, err);
7373 break;
7374 default:
7375 verbose(env, "verifier internal error: unknown reason (%d)\n",
7376 reason);
7377 break;
7378 }
7379
7380 return -EACCES;
979d63d5
DB
7381}
7382
01f810ac
AM
7383/* check that stack access falls within stack limits and that 'reg' doesn't
7384 * have a variable offset.
7385 *
7386 * Variable offset is prohibited for unprivileged mode for simplicity since it
7387 * requires corresponding support in Spectre masking for stack ALU. See also
7388 * retrieve_ptr_limit().
7389 *
7390 *
7391 * 'off' includes 'reg->off'.
7392 */
7393static int check_stack_access_for_ptr_arithmetic(
7394 struct bpf_verifier_env *env,
7395 int regno,
7396 const struct bpf_reg_state *reg,
7397 int off)
7398{
7399 if (!tnum_is_const(reg->var_off)) {
7400 char tn_buf[48];
7401
7402 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7403 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
7404 regno, tn_buf, off);
7405 return -EACCES;
7406 }
7407
7408 if (off >= 0 || off < -MAX_BPF_STACK) {
7409 verbose(env, "R%d stack pointer arithmetic goes out of range, "
7410 "prohibited for !root; off=%d\n", regno, off);
7411 return -EACCES;
7412 }
7413
7414 return 0;
7415}
7416
073815b7
DB
7417static int sanitize_check_bounds(struct bpf_verifier_env *env,
7418 const struct bpf_insn *insn,
7419 const struct bpf_reg_state *dst_reg)
7420{
7421 u32 dst = insn->dst_reg;
7422
7423 /* For unprivileged we require that resulting offset must be in bounds
7424 * in order to be able to sanitize access later on.
7425 */
7426 if (env->bypass_spec_v1)
7427 return 0;
7428
7429 switch (dst_reg->type) {
7430 case PTR_TO_STACK:
7431 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
7432 dst_reg->off + dst_reg->var_off.value))
7433 return -EACCES;
7434 break;
7435 case PTR_TO_MAP_VALUE:
7436 if (check_map_access(env, dst, dst_reg->off, 1, false)) {
7437 verbose(env, "R%d pointer arithmetic of map value goes out of range, "
7438 "prohibited for !root\n", dst);
7439 return -EACCES;
7440 }
7441 break;
7442 default:
7443 break;
7444 }
7445
7446 return 0;
7447}
01f810ac 7448
f1174f77 7449/* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
f1174f77
EC
7450 * Caller should also handle BPF_MOV case separately.
7451 * If we return -EACCES, caller may want to try again treating pointer as a
7452 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks.
7453 */
7454static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
7455 struct bpf_insn *insn,
7456 const struct bpf_reg_state *ptr_reg,
7457 const struct bpf_reg_state *off_reg)
969bf05e 7458{
f4d7e40a
AS
7459 struct bpf_verifier_state *vstate = env->cur_state;
7460 struct bpf_func_state *state = vstate->frame[vstate->curframe];
7461 struct bpf_reg_state *regs = state->regs, *dst_reg;
f1174f77 7462 bool known = tnum_is_const(off_reg->var_off);
b03c9f9f
EC
7463 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
7464 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
7465 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
7466 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
3d0220f6 7467 struct bpf_sanitize_info info = {};
969bf05e 7468 u8 opcode = BPF_OP(insn->code);
24c109bb 7469 u32 dst = insn->dst_reg;
979d63d5 7470 int ret;
969bf05e 7471
f1174f77 7472 dst_reg = &regs[dst];
969bf05e 7473
6f16101e
DB
7474 if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
7475 smin_val > smax_val || umin_val > umax_val) {
7476 /* Taint dst register if offset had invalid bounds derived from
7477 * e.g. dead branches.
7478 */
f54c7898 7479 __mark_reg_unknown(env, dst_reg);
6f16101e 7480 return 0;
f1174f77
EC
7481 }
7482
7483 if (BPF_CLASS(insn->code) != BPF_ALU64) {
7484 /* 32-bit ALU ops on pointers produce (meaningless) scalars */
6c693541
YS
7485 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
7486 __mark_reg_unknown(env, dst_reg);
7487 return 0;
7488 }
7489
82abbf8d
AS
7490 verbose(env,
7491 "R%d 32-bit pointer arithmetic prohibited\n",
7492 dst);
f1174f77 7493 return -EACCES;
969bf05e
AS
7494 }
7495
c25b2ae1 7496 if (ptr_reg->type & PTR_MAYBE_NULL) {
aad2eeaf 7497 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
c25b2ae1 7498 dst, reg_type_str(env, ptr_reg->type));
f1174f77 7499 return -EACCES;
c25b2ae1
HL
7500 }
7501
7502 switch (base_type(ptr_reg->type)) {
aad2eeaf 7503 case CONST_PTR_TO_MAP:
7c696732
YS
7504 /* smin_val represents the known value */
7505 if (known && smin_val == 0 && opcode == BPF_ADD)
7506 break;
8731745e 7507 fallthrough;
aad2eeaf 7508 case PTR_TO_PACKET_END:
c64b7983 7509 case PTR_TO_SOCKET:
46f8bc92 7510 case PTR_TO_SOCK_COMMON:
655a51e5 7511 case PTR_TO_TCP_SOCK:
fada7fdc 7512 case PTR_TO_XDP_SOCK:
aad2eeaf 7513 verbose(env, "R%d pointer arithmetic on %s prohibited\n",
c25b2ae1 7514 dst, reg_type_str(env, ptr_reg->type));
f1174f77 7515 return -EACCES;
aad2eeaf
JS
7516 default:
7517 break;
f1174f77
EC
7518 }
7519
7520 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
7521 * The id may be overwritten later if we create a new variable offset.
969bf05e 7522 */
f1174f77
EC
7523 dst_reg->type = ptr_reg->type;
7524 dst_reg->id = ptr_reg->id;
969bf05e 7525
bb7f0f98
AS
7526 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
7527 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
7528 return -EINVAL;
7529
3f50f132
JF
7530 /* pointer types do not carry 32-bit bounds at the moment. */
7531 __mark_reg32_unbounded(dst_reg);
7532
7fedb63a
DB
7533 if (sanitize_needed(opcode)) {
7534 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
3d0220f6 7535 &info, false);
a6aaece0
DB
7536 if (ret < 0)
7537 return sanitize_err(env, insn, ret, off_reg, dst_reg);
7fedb63a 7538 }
a6aaece0 7539
f1174f77
EC
7540 switch (opcode) {
7541 case BPF_ADD:
7542 /* We can take a fixed offset as long as it doesn't overflow
7543 * the s32 'off' field
969bf05e 7544 */
b03c9f9f
EC
7545 if (known && (ptr_reg->off + smin_val ==
7546 (s64)(s32)(ptr_reg->off + smin_val))) {
f1174f77 7547 /* pointer += K. Accumulate it into fixed offset */
b03c9f9f
EC
7548 dst_reg->smin_value = smin_ptr;
7549 dst_reg->smax_value = smax_ptr;
7550 dst_reg->umin_value = umin_ptr;
7551 dst_reg->umax_value = umax_ptr;
f1174f77 7552 dst_reg->var_off = ptr_reg->var_off;
b03c9f9f 7553 dst_reg->off = ptr_reg->off + smin_val;
0962590e 7554 dst_reg->raw = ptr_reg->raw;
f1174f77
EC
7555 break;
7556 }
f1174f77
EC
7557 /* A new variable offset is created. Note that off_reg->off
7558 * == 0, since it's a scalar.
7559 * dst_reg gets the pointer type and since some positive
7560 * integer value was added to the pointer, give it a new 'id'
7561 * if it's a PTR_TO_PACKET.
7562 * this creates a new 'base' pointer, off_reg (variable) gets
7563 * added into the variable offset, and we copy the fixed offset
7564 * from ptr_reg.
969bf05e 7565 */
b03c9f9f
EC
7566 if (signed_add_overflows(smin_ptr, smin_val) ||
7567 signed_add_overflows(smax_ptr, smax_val)) {
7568 dst_reg->smin_value = S64_MIN;
7569 dst_reg->smax_value = S64_MAX;
7570 } else {
7571 dst_reg->smin_value = smin_ptr + smin_val;
7572 dst_reg->smax_value = smax_ptr + smax_val;
7573 }
7574 if (umin_ptr + umin_val < umin_ptr ||
7575 umax_ptr + umax_val < umax_ptr) {
7576 dst_reg->umin_value = 0;
7577 dst_reg->umax_value = U64_MAX;
7578 } else {
7579 dst_reg->umin_value = umin_ptr + umin_val;
7580 dst_reg->umax_value = umax_ptr + umax_val;
7581 }
f1174f77
EC
7582 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
7583 dst_reg->off = ptr_reg->off;
0962590e 7584 dst_reg->raw = ptr_reg->raw;
de8f3a83 7585 if (reg_is_pkt_pointer(ptr_reg)) {
f1174f77
EC
7586 dst_reg->id = ++env->id_gen;
7587 /* something was added to pkt_ptr, set range to zero */
22dc4a0f 7588 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
f1174f77
EC
7589 }
7590 break;
7591 case BPF_SUB:
7592 if (dst_reg == off_reg) {
7593 /* scalar -= pointer. Creates an unknown scalar */
82abbf8d
AS
7594 verbose(env, "R%d tried to subtract pointer from scalar\n",
7595 dst);
f1174f77
EC
7596 return -EACCES;
7597 }
7598 /* We don't allow subtraction from FP, because (according to
7599 * test_verifier.c test "invalid fp arithmetic", JITs might not
7600 * be able to deal with it.
969bf05e 7601 */
f1174f77 7602 if (ptr_reg->type == PTR_TO_STACK) {
82abbf8d
AS
7603 verbose(env, "R%d subtraction from stack pointer prohibited\n",
7604 dst);
f1174f77
EC
7605 return -EACCES;
7606 }
b03c9f9f
EC
7607 if (known && (ptr_reg->off - smin_val ==
7608 (s64)(s32)(ptr_reg->off - smin_val))) {
f1174f77 7609 /* pointer -= K. Subtract it from fixed offset */
b03c9f9f
EC
7610 dst_reg->smin_value = smin_ptr;
7611 dst_reg->smax_value = smax_ptr;
7612 dst_reg->umin_value = umin_ptr;
7613 dst_reg->umax_value = umax_ptr;
f1174f77
EC
7614 dst_reg->var_off = ptr_reg->var_off;
7615 dst_reg->id = ptr_reg->id;
b03c9f9f 7616 dst_reg->off = ptr_reg->off - smin_val;
0962590e 7617 dst_reg->raw = ptr_reg->raw;
f1174f77
EC
7618 break;
7619 }
f1174f77
EC
7620 /* A new variable offset is created. If the subtrahend is known
7621 * nonnegative, then any reg->range we had before is still good.
969bf05e 7622 */
b03c9f9f
EC
7623 if (signed_sub_overflows(smin_ptr, smax_val) ||
7624 signed_sub_overflows(smax_ptr, smin_val)) {
7625 /* Overflow possible, we know nothing */
7626 dst_reg->smin_value = S64_MIN;
7627 dst_reg->smax_value = S64_MAX;
7628 } else {
7629 dst_reg->smin_value = smin_ptr - smax_val;
7630 dst_reg->smax_value = smax_ptr - smin_val;
7631 }
7632 if (umin_ptr < umax_val) {
7633 /* Overflow possible, we know nothing */
7634 dst_reg->umin_value = 0;
7635 dst_reg->umax_value = U64_MAX;
7636 } else {
7637 /* Cannot overflow (as long as bounds are consistent) */
7638 dst_reg->umin_value = umin_ptr - umax_val;
7639 dst_reg->umax_value = umax_ptr - umin_val;
7640 }
f1174f77
EC
7641 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
7642 dst_reg->off = ptr_reg->off;
0962590e 7643 dst_reg->raw = ptr_reg->raw;
de8f3a83 7644 if (reg_is_pkt_pointer(ptr_reg)) {
f1174f77
EC
7645 dst_reg->id = ++env->id_gen;
7646 /* something was added to pkt_ptr, set range to zero */
b03c9f9f 7647 if (smin_val < 0)
22dc4a0f 7648 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
43188702 7649 }
f1174f77
EC
7650 break;
7651 case BPF_AND:
7652 case BPF_OR:
7653 case BPF_XOR:
82abbf8d
AS
7654 /* bitwise ops on pointers are troublesome, prohibit. */
7655 verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
7656 dst, bpf_alu_string[opcode >> 4]);
f1174f77
EC
7657 return -EACCES;
7658 default:
7659 /* other operators (e.g. MUL,LSH) produce non-pointer results */
82abbf8d
AS
7660 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
7661 dst, bpf_alu_string[opcode >> 4]);
f1174f77 7662 return -EACCES;
43188702
JF
7663 }
7664
bb7f0f98
AS
7665 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
7666 return -EINVAL;
7667
b03c9f9f
EC
7668 __update_reg_bounds(dst_reg);
7669 __reg_deduce_bounds(dst_reg);
7670 __reg_bound_offset(dst_reg);
0d6303db 7671
073815b7
DB
7672 if (sanitize_check_bounds(env, insn, dst_reg) < 0)
7673 return -EACCES;
7fedb63a
DB
7674 if (sanitize_needed(opcode)) {
7675 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
3d0220f6 7676 &info, true);
7fedb63a
DB
7677 if (ret < 0)
7678 return sanitize_err(env, insn, ret, off_reg, dst_reg);
0d6303db
DB
7679 }
7680
43188702
JF
7681 return 0;
7682}
7683
3f50f132
JF
7684static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
7685 struct bpf_reg_state *src_reg)
7686{
7687 s32 smin_val = src_reg->s32_min_value;
7688 s32 smax_val = src_reg->s32_max_value;
7689 u32 umin_val = src_reg->u32_min_value;
7690 u32 umax_val = src_reg->u32_max_value;
7691
7692 if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
7693 signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
7694 dst_reg->s32_min_value = S32_MIN;
7695 dst_reg->s32_max_value = S32_MAX;
7696 } else {
7697 dst_reg->s32_min_value += smin_val;
7698 dst_reg->s32_max_value += smax_val;
7699 }
7700 if (dst_reg->u32_min_value + umin_val < umin_val ||
7701 dst_reg->u32_max_value + umax_val < umax_val) {
7702 dst_reg->u32_min_value = 0;
7703 dst_reg->u32_max_value = U32_MAX;
7704 } else {
7705 dst_reg->u32_min_value += umin_val;
7706 dst_reg->u32_max_value += umax_val;
7707 }
7708}
7709
07cd2631
JF
7710static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
7711 struct bpf_reg_state *src_reg)
7712{
7713 s64 smin_val = src_reg->smin_value;
7714 s64 smax_val = src_reg->smax_value;
7715 u64 umin_val = src_reg->umin_value;
7716 u64 umax_val = src_reg->umax_value;
7717
7718 if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
7719 signed_add_overflows(dst_reg->smax_value, smax_val)) {
7720 dst_reg->smin_value = S64_MIN;
7721 dst_reg->smax_value = S64_MAX;
7722 } else {
7723 dst_reg->smin_value += smin_val;
7724 dst_reg->smax_value += smax_val;
7725 }
7726 if (dst_reg->umin_value + umin_val < umin_val ||
7727 dst_reg->umax_value + umax_val < umax_val) {
7728 dst_reg->umin_value = 0;
7729 dst_reg->umax_value = U64_MAX;
7730 } else {
7731 dst_reg->umin_value += umin_val;
7732 dst_reg->umax_value += umax_val;
7733 }
3f50f132
JF
7734}
7735
7736static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
7737 struct bpf_reg_state *src_reg)
7738{
7739 s32 smin_val = src_reg->s32_min_value;
7740 s32 smax_val = src_reg->s32_max_value;
7741 u32 umin_val = src_reg->u32_min_value;
7742 u32 umax_val = src_reg->u32_max_value;
7743
7744 if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
7745 signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
7746 /* Overflow possible, we know nothing */
7747 dst_reg->s32_min_value = S32_MIN;
7748 dst_reg->s32_max_value = S32_MAX;
7749 } else {
7750 dst_reg->s32_min_value -= smax_val;
7751 dst_reg->s32_max_value -= smin_val;
7752 }
7753 if (dst_reg->u32_min_value < umax_val) {
7754 /* Overflow possible, we know nothing */
7755 dst_reg->u32_min_value = 0;
7756 dst_reg->u32_max_value = U32_MAX;
7757 } else {
7758 /* Cannot overflow (as long as bounds are consistent) */
7759 dst_reg->u32_min_value -= umax_val;
7760 dst_reg->u32_max_value -= umin_val;
7761 }
07cd2631
JF
7762}
7763
7764static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
7765 struct bpf_reg_state *src_reg)
7766{
7767 s64 smin_val = src_reg->smin_value;
7768 s64 smax_val = src_reg->smax_value;
7769 u64 umin_val = src_reg->umin_value;
7770 u64 umax_val = src_reg->umax_value;
7771
7772 if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
7773 signed_sub_overflows(dst_reg->smax_value, smin_val)) {
7774 /* Overflow possible, we know nothing */
7775 dst_reg->smin_value = S64_MIN;
7776 dst_reg->smax_value = S64_MAX;
7777 } else {
7778 dst_reg->smin_value -= smax_val;
7779 dst_reg->smax_value -= smin_val;
7780 }
7781 if (dst_reg->umin_value < umax_val) {
7782 /* Overflow possible, we know nothing */
7783 dst_reg->umin_value = 0;
7784 dst_reg->umax_value = U64_MAX;
7785 } else {
7786 /* Cannot overflow (as long as bounds are consistent) */
7787 dst_reg->umin_value -= umax_val;
7788 dst_reg->umax_value -= umin_val;
7789 }
3f50f132
JF
7790}
7791
7792static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
7793 struct bpf_reg_state *src_reg)
7794{
7795 s32 smin_val = src_reg->s32_min_value;
7796 u32 umin_val = src_reg->u32_min_value;
7797 u32 umax_val = src_reg->u32_max_value;
7798
7799 if (smin_val < 0 || dst_reg->s32_min_value < 0) {
7800 /* Ain't nobody got time to multiply that sign */
7801 __mark_reg32_unbounded(dst_reg);
7802 return;
7803 }
7804 /* Both values are positive, so we can work with unsigned and
7805 * copy the result to signed (unless it exceeds S32_MAX).
7806 */
7807 if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
7808 /* Potential overflow, we know nothing */
7809 __mark_reg32_unbounded(dst_reg);
7810 return;
7811 }
7812 dst_reg->u32_min_value *= umin_val;
7813 dst_reg->u32_max_value *= umax_val;
7814 if (dst_reg->u32_max_value > S32_MAX) {
7815 /* Overflow possible, we know nothing */
7816 dst_reg->s32_min_value = S32_MIN;
7817 dst_reg->s32_max_value = S32_MAX;
7818 } else {
7819 dst_reg->s32_min_value = dst_reg->u32_min_value;
7820 dst_reg->s32_max_value = dst_reg->u32_max_value;
7821 }
07cd2631
JF
7822}
7823
7824static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
7825 struct bpf_reg_state *src_reg)
7826{
7827 s64 smin_val = src_reg->smin_value;
7828 u64 umin_val = src_reg->umin_value;
7829 u64 umax_val = src_reg->umax_value;
7830
07cd2631
JF
7831 if (smin_val < 0 || dst_reg->smin_value < 0) {
7832 /* Ain't nobody got time to multiply that sign */
3f50f132 7833 __mark_reg64_unbounded(dst_reg);
07cd2631
JF
7834 return;
7835 }
7836 /* Both values are positive, so we can work with unsigned and
7837 * copy the result to signed (unless it exceeds S64_MAX).
7838 */
7839 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
7840 /* Potential overflow, we know nothing */
3f50f132 7841 __mark_reg64_unbounded(dst_reg);
07cd2631
JF
7842 return;
7843 }
7844 dst_reg->umin_value *= umin_val;
7845 dst_reg->umax_value *= umax_val;
7846 if (dst_reg->umax_value > S64_MAX) {
7847 /* Overflow possible, we know nothing */
7848 dst_reg->smin_value = S64_MIN;
7849 dst_reg->smax_value = S64_MAX;
7850 } else {
7851 dst_reg->smin_value = dst_reg->umin_value;
7852 dst_reg->smax_value = dst_reg->umax_value;
7853 }
7854}
7855
3f50f132
JF
7856static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
7857 struct bpf_reg_state *src_reg)
7858{
7859 bool src_known = tnum_subreg_is_const(src_reg->var_off);
7860 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
7861 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
7862 s32 smin_val = src_reg->s32_min_value;
7863 u32 umax_val = src_reg->u32_max_value;
7864
049c4e13
DB
7865 if (src_known && dst_known) {
7866 __mark_reg32_known(dst_reg, var32_off.value);
3f50f132 7867 return;
049c4e13 7868 }
3f50f132
JF
7869
7870 /* We get our minimum from the var_off, since that's inherently
7871 * bitwise. Our maximum is the minimum of the operands' maxima.
7872 */
7873 dst_reg->u32_min_value = var32_off.value;
7874 dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
7875 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
7876 /* Lose signed bounds when ANDing negative numbers,
7877 * ain't nobody got time for that.
7878 */
7879 dst_reg->s32_min_value = S32_MIN;
7880 dst_reg->s32_max_value = S32_MAX;
7881 } else {
7882 /* ANDing two positives gives a positive, so safe to
7883 * cast result into s64.
7884 */
7885 dst_reg->s32_min_value = dst_reg->u32_min_value;
7886 dst_reg->s32_max_value = dst_reg->u32_max_value;
7887 }
3f50f132
JF
7888}
7889
07cd2631
JF
7890static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
7891 struct bpf_reg_state *src_reg)
7892{
3f50f132
JF
7893 bool src_known = tnum_is_const(src_reg->var_off);
7894 bool dst_known = tnum_is_const(dst_reg->var_off);
07cd2631
JF
7895 s64 smin_val = src_reg->smin_value;
7896 u64 umax_val = src_reg->umax_value;
7897
3f50f132 7898 if (src_known && dst_known) {
4fbb38a3 7899 __mark_reg_known(dst_reg, dst_reg->var_off.value);
3f50f132
JF
7900 return;
7901 }
7902
07cd2631
JF
7903 /* We get our minimum from the var_off, since that's inherently
7904 * bitwise. Our maximum is the minimum of the operands' maxima.
7905 */
07cd2631
JF
7906 dst_reg->umin_value = dst_reg->var_off.value;
7907 dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
7908 if (dst_reg->smin_value < 0 || smin_val < 0) {
7909 /* Lose signed bounds when ANDing negative numbers,
7910 * ain't nobody got time for that.
7911 */
7912 dst_reg->smin_value = S64_MIN;
7913 dst_reg->smax_value = S64_MAX;
7914 } else {
7915 /* ANDing two positives gives a positive, so safe to
7916 * cast result into s64.
7917 */
7918 dst_reg->smin_value = dst_reg->umin_value;
7919 dst_reg->smax_value = dst_reg->umax_value;
7920 }
7921 /* We may learn something more from the var_off */
7922 __update_reg_bounds(dst_reg);
7923}
7924
3f50f132
JF
7925static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
7926 struct bpf_reg_state *src_reg)
7927{
7928 bool src_known = tnum_subreg_is_const(src_reg->var_off);
7929 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
7930 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
5b9fbeb7
DB
7931 s32 smin_val = src_reg->s32_min_value;
7932 u32 umin_val = src_reg->u32_min_value;
3f50f132 7933
049c4e13
DB
7934 if (src_known && dst_known) {
7935 __mark_reg32_known(dst_reg, var32_off.value);
3f50f132 7936 return;
049c4e13 7937 }
3f50f132
JF
7938
7939 /* We get our maximum from the var_off, and our minimum is the
7940 * maximum of the operands' minima
7941 */
7942 dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
7943 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
7944 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
7945 /* Lose signed bounds when ORing negative numbers,
7946 * ain't nobody got time for that.
7947 */
7948 dst_reg->s32_min_value = S32_MIN;
7949 dst_reg->s32_max_value = S32_MAX;
7950 } else {
7951 /* ORing two positives gives a positive, so safe to
7952 * cast result into s64.
7953 */
5b9fbeb7
DB
7954 dst_reg->s32_min_value = dst_reg->u32_min_value;
7955 dst_reg->s32_max_value = dst_reg->u32_max_value;
3f50f132
JF
7956 }
7957}
7958
07cd2631
JF
7959static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
7960 struct bpf_reg_state *src_reg)
7961{
3f50f132
JF
7962 bool src_known = tnum_is_const(src_reg->var_off);
7963 bool dst_known = tnum_is_const(dst_reg->var_off);
07cd2631
JF
7964 s64 smin_val = src_reg->smin_value;
7965 u64 umin_val = src_reg->umin_value;
7966
3f50f132 7967 if (src_known && dst_known) {
4fbb38a3 7968 __mark_reg_known(dst_reg, dst_reg->var_off.value);
3f50f132
JF
7969 return;
7970 }
7971
07cd2631
JF
7972 /* We get our maximum from the var_off, and our minimum is the
7973 * maximum of the operands' minima
7974 */
07cd2631
JF
7975 dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
7976 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
7977 if (dst_reg->smin_value < 0 || smin_val < 0) {
7978 /* Lose signed bounds when ORing negative numbers,
7979 * ain't nobody got time for that.
7980 */
7981 dst_reg->smin_value = S64_MIN;
7982 dst_reg->smax_value = S64_MAX;
7983 } else {
7984 /* ORing two positives gives a positive, so safe to
7985 * cast result into s64.
7986 */
7987 dst_reg->smin_value = dst_reg->umin_value;
7988 dst_reg->smax_value = dst_reg->umax_value;
7989 }
7990 /* We may learn something more from the var_off */
7991 __update_reg_bounds(dst_reg);
7992}
7993
2921c90d
YS
7994static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
7995 struct bpf_reg_state *src_reg)
7996{
7997 bool src_known = tnum_subreg_is_const(src_reg->var_off);
7998 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
7999 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
8000 s32 smin_val = src_reg->s32_min_value;
8001
049c4e13
DB
8002 if (src_known && dst_known) {
8003 __mark_reg32_known(dst_reg, var32_off.value);
2921c90d 8004 return;
049c4e13 8005 }
2921c90d
YS
8006
8007 /* We get both minimum and maximum from the var32_off. */
8008 dst_reg->u32_min_value = var32_off.value;
8009 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
8010
8011 if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
8012 /* XORing two positive sign numbers gives a positive,
8013 * so safe to cast u32 result into s32.
8014 */
8015 dst_reg->s32_min_value = dst_reg->u32_min_value;
8016 dst_reg->s32_max_value = dst_reg->u32_max_value;
8017 } else {
8018 dst_reg->s32_min_value = S32_MIN;
8019 dst_reg->s32_max_value = S32_MAX;
8020 }
8021}
8022
8023static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
8024 struct bpf_reg_state *src_reg)
8025{
8026 bool src_known = tnum_is_const(src_reg->var_off);
8027 bool dst_known = tnum_is_const(dst_reg->var_off);
8028 s64 smin_val = src_reg->smin_value;
8029
8030 if (src_known && dst_known) {
8031 /* dst_reg->var_off.value has been updated earlier */
8032 __mark_reg_known(dst_reg, dst_reg->var_off.value);
8033 return;
8034 }
8035
8036 /* We get both minimum and maximum from the var_off. */
8037 dst_reg->umin_value = dst_reg->var_off.value;
8038 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
8039
8040 if (dst_reg->smin_value >= 0 && smin_val >= 0) {
8041 /* XORing two positive sign numbers gives a positive,
8042 * so safe to cast u64 result into s64.
8043 */
8044 dst_reg->smin_value = dst_reg->umin_value;
8045 dst_reg->smax_value = dst_reg->umax_value;
8046 } else {
8047 dst_reg->smin_value = S64_MIN;
8048 dst_reg->smax_value = S64_MAX;
8049 }
8050
8051 __update_reg_bounds(dst_reg);
8052}
8053
3f50f132
JF
8054static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
8055 u64 umin_val, u64 umax_val)
07cd2631 8056{
07cd2631
JF
8057 /* We lose all sign bit information (except what we can pick
8058 * up from var_off)
8059 */
3f50f132
JF
8060 dst_reg->s32_min_value = S32_MIN;
8061 dst_reg->s32_max_value = S32_MAX;
8062 /* If we might shift our top bit out, then we know nothing */
8063 if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
8064 dst_reg->u32_min_value = 0;
8065 dst_reg->u32_max_value = U32_MAX;
8066 } else {
8067 dst_reg->u32_min_value <<= umin_val;
8068 dst_reg->u32_max_value <<= umax_val;
8069 }
8070}
8071
8072static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
8073 struct bpf_reg_state *src_reg)
8074{
8075 u32 umax_val = src_reg->u32_max_value;
8076 u32 umin_val = src_reg->u32_min_value;
8077 /* u32 alu operation will zext upper bits */
8078 struct tnum subreg = tnum_subreg(dst_reg->var_off);
8079
8080 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
8081 dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
8082 /* Not required but being careful mark reg64 bounds as unknown so
8083 * that we are forced to pick them up from tnum and zext later and
8084 * if some path skips this step we are still safe.
8085 */
8086 __mark_reg64_unbounded(dst_reg);
8087 __update_reg32_bounds(dst_reg);
8088}
8089
8090static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
8091 u64 umin_val, u64 umax_val)
8092{
8093 /* Special case <<32 because it is a common compiler pattern to sign
8094 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
8095 * positive we know this shift will also be positive so we can track
8096 * bounds correctly. Otherwise we lose all sign bit information except
8097 * what we can pick up from var_off. Perhaps we can generalize this
8098 * later to shifts of any length.
8099 */
8100 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
8101 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
8102 else
8103 dst_reg->smax_value = S64_MAX;
8104
8105 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
8106 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
8107 else
8108 dst_reg->smin_value = S64_MIN;
8109
07cd2631
JF
8110 /* If we might shift our top bit out, then we know nothing */
8111 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
8112 dst_reg->umin_value = 0;
8113 dst_reg->umax_value = U64_MAX;
8114 } else {
8115 dst_reg->umin_value <<= umin_val;
8116 dst_reg->umax_value <<= umax_val;
8117 }
3f50f132
JF
8118}
8119
8120static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
8121 struct bpf_reg_state *src_reg)
8122{
8123 u64 umax_val = src_reg->umax_value;
8124 u64 umin_val = src_reg->umin_value;
8125
8126 /* scalar64 calc uses 32bit unshifted bounds so must be called first */
8127 __scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
8128 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
8129
07cd2631
JF
8130 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
8131 /* We may learn something more from the var_off */
8132 __update_reg_bounds(dst_reg);
8133}
8134
3f50f132
JF
8135static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
8136 struct bpf_reg_state *src_reg)
8137{
8138 struct tnum subreg = tnum_subreg(dst_reg->var_off);
8139 u32 umax_val = src_reg->u32_max_value;
8140 u32 umin_val = src_reg->u32_min_value;
8141
8142 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
8143 * be negative, then either:
8144 * 1) src_reg might be zero, so the sign bit of the result is
8145 * unknown, so we lose our signed bounds
8146 * 2) it's known negative, thus the unsigned bounds capture the
8147 * signed bounds
8148 * 3) the signed bounds cross zero, so they tell us nothing
8149 * about the result
8150 * If the value in dst_reg is known nonnegative, then again the
18b24d78 8151 * unsigned bounds capture the signed bounds.
3f50f132
JF
8152 * Thus, in all cases it suffices to blow away our signed bounds
8153 * and rely on inferring new ones from the unsigned bounds and
8154 * var_off of the result.
8155 */
8156 dst_reg->s32_min_value = S32_MIN;
8157 dst_reg->s32_max_value = S32_MAX;
8158
8159 dst_reg->var_off = tnum_rshift(subreg, umin_val);
8160 dst_reg->u32_min_value >>= umax_val;
8161 dst_reg->u32_max_value >>= umin_val;
8162
8163 __mark_reg64_unbounded(dst_reg);
8164 __update_reg32_bounds(dst_reg);
8165}
8166
07cd2631
JF
8167static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
8168 struct bpf_reg_state *src_reg)
8169{
8170 u64 umax_val = src_reg->umax_value;
8171 u64 umin_val = src_reg->umin_value;
8172
8173 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
8174 * be negative, then either:
8175 * 1) src_reg might be zero, so the sign bit of the result is
8176 * unknown, so we lose our signed bounds
8177 * 2) it's known negative, thus the unsigned bounds capture the
8178 * signed bounds
8179 * 3) the signed bounds cross zero, so they tell us nothing
8180 * about the result
8181 * If the value in dst_reg is known nonnegative, then again the
18b24d78 8182 * unsigned bounds capture the signed bounds.
07cd2631
JF
8183 * Thus, in all cases it suffices to blow away our signed bounds
8184 * and rely on inferring new ones from the unsigned bounds and
8185 * var_off of the result.
8186 */
8187 dst_reg->smin_value = S64_MIN;
8188 dst_reg->smax_value = S64_MAX;
8189 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
8190 dst_reg->umin_value >>= umax_val;
8191 dst_reg->umax_value >>= umin_val;
3f50f132
JF
8192
8193 /* Its not easy to operate on alu32 bounds here because it depends
8194 * on bits being shifted in. Take easy way out and mark unbounded
8195 * so we can recalculate later from tnum.
8196 */
8197 __mark_reg32_unbounded(dst_reg);
07cd2631
JF
8198 __update_reg_bounds(dst_reg);
8199}
8200
3f50f132
JF
8201static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
8202 struct bpf_reg_state *src_reg)
07cd2631 8203{
3f50f132 8204 u64 umin_val = src_reg->u32_min_value;
07cd2631
JF
8205
8206 /* Upon reaching here, src_known is true and
8207 * umax_val is equal to umin_val.
8208 */
3f50f132
JF
8209 dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
8210 dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
07cd2631 8211
3f50f132
JF
8212 dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
8213
8214 /* blow away the dst_reg umin_value/umax_value and rely on
8215 * dst_reg var_off to refine the result.
8216 */
8217 dst_reg->u32_min_value = 0;
8218 dst_reg->u32_max_value = U32_MAX;
8219
8220 __mark_reg64_unbounded(dst_reg);
8221 __update_reg32_bounds(dst_reg);
8222}
8223
8224static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
8225 struct bpf_reg_state *src_reg)
8226{
8227 u64 umin_val = src_reg->umin_value;
8228
8229 /* Upon reaching here, src_known is true and umax_val is equal
8230 * to umin_val.
8231 */
8232 dst_reg->smin_value >>= umin_val;
8233 dst_reg->smax_value >>= umin_val;
8234
8235 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
07cd2631
JF
8236
8237 /* blow away the dst_reg umin_value/umax_value and rely on
8238 * dst_reg var_off to refine the result.
8239 */
8240 dst_reg->umin_value = 0;
8241 dst_reg->umax_value = U64_MAX;
3f50f132
JF
8242
8243 /* Its not easy to operate on alu32 bounds here because it depends
8244 * on bits being shifted in from upper 32-bits. Take easy way out
8245 * and mark unbounded so we can recalculate later from tnum.
8246 */
8247 __mark_reg32_unbounded(dst_reg);
07cd2631
JF
8248 __update_reg_bounds(dst_reg);
8249}
8250
468f6eaf
JH
8251/* WARNING: This function does calculations on 64-bit values, but the actual
8252 * execution may occur on 32-bit values. Therefore, things like bitshifts
8253 * need extra checks in the 32-bit case.
8254 */
f1174f77
EC
8255static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
8256 struct bpf_insn *insn,
8257 struct bpf_reg_state *dst_reg,
8258 struct bpf_reg_state src_reg)
969bf05e 8259{
638f5b90 8260 struct bpf_reg_state *regs = cur_regs(env);
48461135 8261 u8 opcode = BPF_OP(insn->code);
b0b3fb67 8262 bool src_known;
b03c9f9f
EC
8263 s64 smin_val, smax_val;
8264 u64 umin_val, umax_val;
3f50f132
JF
8265 s32 s32_min_val, s32_max_val;
8266 u32 u32_min_val, u32_max_val;
468f6eaf 8267 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
3f50f132 8268 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
a6aaece0 8269 int ret;
b799207e 8270
b03c9f9f
EC
8271 smin_val = src_reg.smin_value;
8272 smax_val = src_reg.smax_value;
8273 umin_val = src_reg.umin_value;
8274 umax_val = src_reg.umax_value;
f23cc643 8275
3f50f132
JF
8276 s32_min_val = src_reg.s32_min_value;
8277 s32_max_val = src_reg.s32_max_value;
8278 u32_min_val = src_reg.u32_min_value;
8279 u32_max_val = src_reg.u32_max_value;
8280
8281 if (alu32) {
8282 src_known = tnum_subreg_is_const(src_reg.var_off);
3f50f132
JF
8283 if ((src_known &&
8284 (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
8285 s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
8286 /* Taint dst register if offset had invalid bounds
8287 * derived from e.g. dead branches.
8288 */
8289 __mark_reg_unknown(env, dst_reg);
8290 return 0;
8291 }
8292 } else {
8293 src_known = tnum_is_const(src_reg.var_off);
3f50f132
JF
8294 if ((src_known &&
8295 (smin_val != smax_val || umin_val != umax_val)) ||
8296 smin_val > smax_val || umin_val > umax_val) {
8297 /* Taint dst register if offset had invalid bounds
8298 * derived from e.g. dead branches.
8299 */
8300 __mark_reg_unknown(env, dst_reg);
8301 return 0;
8302 }
6f16101e
DB
8303 }
8304
bb7f0f98
AS
8305 if (!src_known &&
8306 opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
f54c7898 8307 __mark_reg_unknown(env, dst_reg);
bb7f0f98
AS
8308 return 0;
8309 }
8310
f5288193
DB
8311 if (sanitize_needed(opcode)) {
8312 ret = sanitize_val_alu(env, insn);
8313 if (ret < 0)
8314 return sanitize_err(env, insn, ret, NULL, NULL);
8315 }
8316
3f50f132
JF
8317 /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
8318 * There are two classes of instructions: The first class we track both
8319 * alu32 and alu64 sign/unsigned bounds independently this provides the
8320 * greatest amount of precision when alu operations are mixed with jmp32
8321 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
8322 * and BPF_OR. This is possible because these ops have fairly easy to
8323 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
8324 * See alu32 verifier tests for examples. The second class of
8325 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
8326 * with regards to tracking sign/unsigned bounds because the bits may
8327 * cross subreg boundaries in the alu64 case. When this happens we mark
8328 * the reg unbounded in the subreg bound space and use the resulting
8329 * tnum to calculate an approximation of the sign/unsigned bounds.
8330 */
48461135
JB
8331 switch (opcode) {
8332 case BPF_ADD:
3f50f132 8333 scalar32_min_max_add(dst_reg, &src_reg);
07cd2631 8334 scalar_min_max_add(dst_reg, &src_reg);
3f50f132 8335 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
48461135
JB
8336 break;
8337 case BPF_SUB:
3f50f132 8338 scalar32_min_max_sub(dst_reg, &src_reg);
07cd2631 8339 scalar_min_max_sub(dst_reg, &src_reg);
3f50f132 8340 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
48461135
JB
8341 break;
8342 case BPF_MUL:
3f50f132
JF
8343 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
8344 scalar32_min_max_mul(dst_reg, &src_reg);
07cd2631 8345 scalar_min_max_mul(dst_reg, &src_reg);
48461135
JB
8346 break;
8347 case BPF_AND:
3f50f132
JF
8348 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
8349 scalar32_min_max_and(dst_reg, &src_reg);
07cd2631 8350 scalar_min_max_and(dst_reg, &src_reg);
f1174f77
EC
8351 break;
8352 case BPF_OR:
3f50f132
JF
8353 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
8354 scalar32_min_max_or(dst_reg, &src_reg);
07cd2631 8355 scalar_min_max_or(dst_reg, &src_reg);
48461135 8356 break;
2921c90d
YS
8357 case BPF_XOR:
8358 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
8359 scalar32_min_max_xor(dst_reg, &src_reg);
8360 scalar_min_max_xor(dst_reg, &src_reg);
8361 break;
48461135 8362 case BPF_LSH:
468f6eaf
JH
8363 if (umax_val >= insn_bitness) {
8364 /* Shifts greater than 31 or 63 are undefined.
8365 * This includes shifts by a negative number.
b03c9f9f 8366 */
61bd5218 8367 mark_reg_unknown(env, regs, insn->dst_reg);
f1174f77
EC
8368 break;
8369 }
3f50f132
JF
8370 if (alu32)
8371 scalar32_min_max_lsh(dst_reg, &src_reg);
8372 else
8373 scalar_min_max_lsh(dst_reg, &src_reg);
48461135
JB
8374 break;
8375 case BPF_RSH:
468f6eaf
JH
8376 if (umax_val >= insn_bitness) {
8377 /* Shifts greater than 31 or 63 are undefined.
8378 * This includes shifts by a negative number.
b03c9f9f 8379 */
61bd5218 8380 mark_reg_unknown(env, regs, insn->dst_reg);
f1174f77
EC
8381 break;
8382 }
3f50f132
JF
8383 if (alu32)
8384 scalar32_min_max_rsh(dst_reg, &src_reg);
8385 else
8386 scalar_min_max_rsh(dst_reg, &src_reg);
48461135 8387 break;
9cbe1f5a
YS
8388 case BPF_ARSH:
8389 if (umax_val >= insn_bitness) {
8390 /* Shifts greater than 31 or 63 are undefined.
8391 * This includes shifts by a negative number.
8392 */
8393 mark_reg_unknown(env, regs, insn->dst_reg);
8394 break;
8395 }
3f50f132
JF
8396 if (alu32)
8397 scalar32_min_max_arsh(dst_reg, &src_reg);
8398 else
8399 scalar_min_max_arsh(dst_reg, &src_reg);
9cbe1f5a 8400 break;
48461135 8401 default:
61bd5218 8402 mark_reg_unknown(env, regs, insn->dst_reg);
48461135
JB
8403 break;
8404 }
8405
3f50f132
JF
8406 /* ALU32 ops are zero extended into 64bit register */
8407 if (alu32)
8408 zext_32_to_64(dst_reg);
468f6eaf 8409
294f2fc6 8410 __update_reg_bounds(dst_reg);
b03c9f9f
EC
8411 __reg_deduce_bounds(dst_reg);
8412 __reg_bound_offset(dst_reg);
f1174f77
EC
8413 return 0;
8414}
8415
8416/* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
8417 * and var_off.
8418 */
8419static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
8420 struct bpf_insn *insn)
8421{
f4d7e40a
AS
8422 struct bpf_verifier_state *vstate = env->cur_state;
8423 struct bpf_func_state *state = vstate->frame[vstate->curframe];
8424 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
f1174f77
EC
8425 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
8426 u8 opcode = BPF_OP(insn->code);
b5dc0163 8427 int err;
f1174f77
EC
8428
8429 dst_reg = &regs[insn->dst_reg];
f1174f77
EC
8430 src_reg = NULL;
8431 if (dst_reg->type != SCALAR_VALUE)
8432 ptr_reg = dst_reg;
75748837
AS
8433 else
8434 /* Make sure ID is cleared otherwise dst_reg min/max could be
8435 * incorrectly propagated into other registers by find_equal_scalars()
8436 */
8437 dst_reg->id = 0;
f1174f77
EC
8438 if (BPF_SRC(insn->code) == BPF_X) {
8439 src_reg = &regs[insn->src_reg];
f1174f77
EC
8440 if (src_reg->type != SCALAR_VALUE) {
8441 if (dst_reg->type != SCALAR_VALUE) {
8442 /* Combining two pointers by any ALU op yields
82abbf8d
AS
8443 * an arbitrary scalar. Disallow all math except
8444 * pointer subtraction
f1174f77 8445 */
dd066823 8446 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
82abbf8d
AS
8447 mark_reg_unknown(env, regs, insn->dst_reg);
8448 return 0;
f1174f77 8449 }
82abbf8d
AS
8450 verbose(env, "R%d pointer %s pointer prohibited\n",
8451 insn->dst_reg,
8452 bpf_alu_string[opcode >> 4]);
8453 return -EACCES;
f1174f77
EC
8454 } else {
8455 /* scalar += pointer
8456 * This is legal, but we have to reverse our
8457 * src/dest handling in computing the range
8458 */
b5dc0163
AS
8459 err = mark_chain_precision(env, insn->dst_reg);
8460 if (err)
8461 return err;
82abbf8d
AS
8462 return adjust_ptr_min_max_vals(env, insn,
8463 src_reg, dst_reg);
f1174f77
EC
8464 }
8465 } else if (ptr_reg) {
8466 /* pointer += scalar */
b5dc0163
AS
8467 err = mark_chain_precision(env, insn->src_reg);
8468 if (err)
8469 return err;
82abbf8d
AS
8470 return adjust_ptr_min_max_vals(env, insn,
8471 dst_reg, src_reg);
f1174f77
EC
8472 }
8473 } else {
8474 /* Pretend the src is a reg with a known value, since we only
8475 * need to be able to read from this state.
8476 */
8477 off_reg.type = SCALAR_VALUE;
b03c9f9f 8478 __mark_reg_known(&off_reg, insn->imm);
f1174f77 8479 src_reg = &off_reg;
82abbf8d
AS
8480 if (ptr_reg) /* pointer += K */
8481 return adjust_ptr_min_max_vals(env, insn,
8482 ptr_reg, src_reg);
f1174f77
EC
8483 }
8484
8485 /* Got here implies adding two SCALAR_VALUEs */
8486 if (WARN_ON_ONCE(ptr_reg)) {
0f55f9ed 8487 print_verifier_state(env, state, true);
61bd5218 8488 verbose(env, "verifier internal error: unexpected ptr_reg\n");
f1174f77
EC
8489 return -EINVAL;
8490 }
8491 if (WARN_ON(!src_reg)) {
0f55f9ed 8492 print_verifier_state(env, state, true);
61bd5218 8493 verbose(env, "verifier internal error: no src_reg\n");
f1174f77
EC
8494 return -EINVAL;
8495 }
8496 return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
48461135
JB
8497}
8498
17a52670 8499/* check validity of 32-bit and 64-bit arithmetic operations */
58e2af8b 8500static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
17a52670 8501{
638f5b90 8502 struct bpf_reg_state *regs = cur_regs(env);
17a52670
AS
8503 u8 opcode = BPF_OP(insn->code);
8504 int err;
8505
8506 if (opcode == BPF_END || opcode == BPF_NEG) {
8507 if (opcode == BPF_NEG) {
8508 if (BPF_SRC(insn->code) != 0 ||
8509 insn->src_reg != BPF_REG_0 ||
8510 insn->off != 0 || insn->imm != 0) {
61bd5218 8511 verbose(env, "BPF_NEG uses reserved fields\n");
17a52670
AS
8512 return -EINVAL;
8513 }
8514 } else {
8515 if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
e67b8a68
EC
8516 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
8517 BPF_CLASS(insn->code) == BPF_ALU64) {
61bd5218 8518 verbose(env, "BPF_END uses reserved fields\n");
17a52670
AS
8519 return -EINVAL;
8520 }
8521 }
8522
8523 /* check src operand */
dc503a8a 8524 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17a52670
AS
8525 if (err)
8526 return err;
8527
1be7f75d 8528 if (is_pointer_value(env, insn->dst_reg)) {
61bd5218 8529 verbose(env, "R%d pointer arithmetic prohibited\n",
1be7f75d
AS
8530 insn->dst_reg);
8531 return -EACCES;
8532 }
8533
17a52670 8534 /* check dest operand */
dc503a8a 8535 err = check_reg_arg(env, insn->dst_reg, DST_OP);
17a52670
AS
8536 if (err)
8537 return err;
8538
8539 } else if (opcode == BPF_MOV) {
8540
8541 if (BPF_SRC(insn->code) == BPF_X) {
8542 if (insn->imm != 0 || insn->off != 0) {
61bd5218 8543 verbose(env, "BPF_MOV uses reserved fields\n");
17a52670
AS
8544 return -EINVAL;
8545 }
8546
8547 /* check src operand */
dc503a8a 8548 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17a52670
AS
8549 if (err)
8550 return err;
8551 } else {
8552 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
61bd5218 8553 verbose(env, "BPF_MOV uses reserved fields\n");
17a52670
AS
8554 return -EINVAL;
8555 }
8556 }
8557
fbeb1603
AF
8558 /* check dest operand, mark as required later */
8559 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
17a52670
AS
8560 if (err)
8561 return err;
8562
8563 if (BPF_SRC(insn->code) == BPF_X) {
e434b8cd
JW
8564 struct bpf_reg_state *src_reg = regs + insn->src_reg;
8565 struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
8566
17a52670
AS
8567 if (BPF_CLASS(insn->code) == BPF_ALU64) {
8568 /* case: R1 = R2
8569 * copy register state to dest reg
8570 */
75748837
AS
8571 if (src_reg->type == SCALAR_VALUE && !src_reg->id)
8572 /* Assign src and dst registers the same ID
8573 * that will be used by find_equal_scalars()
8574 * to propagate min/max range.
8575 */
8576 src_reg->id = ++env->id_gen;
e434b8cd
JW
8577 *dst_reg = *src_reg;
8578 dst_reg->live |= REG_LIVE_WRITTEN;
5327ed3d 8579 dst_reg->subreg_def = DEF_NOT_SUBREG;
17a52670 8580 } else {
f1174f77 8581 /* R1 = (u32) R2 */
1be7f75d 8582 if (is_pointer_value(env, insn->src_reg)) {
61bd5218
JK
8583 verbose(env,
8584 "R%d partial copy of pointer\n",
1be7f75d
AS
8585 insn->src_reg);
8586 return -EACCES;
e434b8cd
JW
8587 } else if (src_reg->type == SCALAR_VALUE) {
8588 *dst_reg = *src_reg;
75748837
AS
8589 /* Make sure ID is cleared otherwise
8590 * dst_reg min/max could be incorrectly
8591 * propagated into src_reg by find_equal_scalars()
8592 */
8593 dst_reg->id = 0;
e434b8cd 8594 dst_reg->live |= REG_LIVE_WRITTEN;
5327ed3d 8595 dst_reg->subreg_def = env->insn_idx + 1;
e434b8cd
JW
8596 } else {
8597 mark_reg_unknown(env, regs,
8598 insn->dst_reg);
1be7f75d 8599 }
3f50f132 8600 zext_32_to_64(dst_reg);
3cf2b61e
DB
8601
8602 __update_reg_bounds(dst_reg);
8603 __reg_deduce_bounds(dst_reg);
8604 __reg_bound_offset(dst_reg);
17a52670
AS
8605 }
8606 } else {
8607 /* case: R = imm
8608 * remember the value we stored into this reg
8609 */
fbeb1603
AF
8610 /* clear any state __mark_reg_known doesn't set */
8611 mark_reg_unknown(env, regs, insn->dst_reg);
f1174f77 8612 regs[insn->dst_reg].type = SCALAR_VALUE;
95a762e2
JH
8613 if (BPF_CLASS(insn->code) == BPF_ALU64) {
8614 __mark_reg_known(regs + insn->dst_reg,
8615 insn->imm);
8616 } else {
8617 __mark_reg_known(regs + insn->dst_reg,
8618 (u32)insn->imm);
8619 }
17a52670
AS
8620 }
8621
8622 } else if (opcode > BPF_END) {
61bd5218 8623 verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
17a52670
AS
8624 return -EINVAL;
8625
8626 } else { /* all other ALU ops: and, sub, xor, add, ... */
8627
17a52670
AS
8628 if (BPF_SRC(insn->code) == BPF_X) {
8629 if (insn->imm != 0 || insn->off != 0) {
61bd5218 8630 verbose(env, "BPF_ALU uses reserved fields\n");
17a52670
AS
8631 return -EINVAL;
8632 }
8633 /* check src1 operand */
dc503a8a 8634 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17a52670
AS
8635 if (err)
8636 return err;
8637 } else {
8638 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
61bd5218 8639 verbose(env, "BPF_ALU uses reserved fields\n");
17a52670
AS
8640 return -EINVAL;
8641 }
8642 }
8643
8644 /* check src2 operand */
dc503a8a 8645 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17a52670
AS
8646 if (err)
8647 return err;
8648
8649 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
8650 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
61bd5218 8651 verbose(env, "div by zero\n");
17a52670
AS
8652 return -EINVAL;
8653 }
8654
229394e8
RV
8655 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
8656 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
8657 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
8658
8659 if (insn->imm < 0 || insn->imm >= size) {
61bd5218 8660 verbose(env, "invalid shift %d\n", insn->imm);
229394e8
RV
8661 return -EINVAL;
8662 }
8663 }
8664
1a0dc1ac 8665 /* check dest operand */
dc503a8a 8666 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
1a0dc1ac
AS
8667 if (err)
8668 return err;
8669
f1174f77 8670 return adjust_reg_min_max_vals(env, insn);
17a52670
AS
8671 }
8672
8673 return 0;
8674}
8675
c6a9efa1
PC
8676static void __find_good_pkt_pointers(struct bpf_func_state *state,
8677 struct bpf_reg_state *dst_reg,
6d94e741 8678 enum bpf_reg_type type, int new_range)
c6a9efa1
PC
8679{
8680 struct bpf_reg_state *reg;
8681 int i;
8682
8683 for (i = 0; i < MAX_BPF_REG; i++) {
8684 reg = &state->regs[i];
8685 if (reg->type == type && reg->id == dst_reg->id)
8686 /* keep the maximum range already checked */
8687 reg->range = max(reg->range, new_range);
8688 }
8689
8690 bpf_for_each_spilled_reg(i, state, reg) {
8691 if (!reg)
8692 continue;
8693 if (reg->type == type && reg->id == dst_reg->id)
8694 reg->range = max(reg->range, new_range);
8695 }
8696}
8697
f4d7e40a 8698static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
de8f3a83 8699 struct bpf_reg_state *dst_reg,
f8ddadc4 8700 enum bpf_reg_type type,
fb2a311a 8701 bool range_right_open)
969bf05e 8702{
6d94e741 8703 int new_range, i;
2d2be8ca 8704
fb2a311a
DB
8705 if (dst_reg->off < 0 ||
8706 (dst_reg->off == 0 && range_right_open))
f1174f77
EC
8707 /* This doesn't give us any range */
8708 return;
8709
b03c9f9f
EC
8710 if (dst_reg->umax_value > MAX_PACKET_OFF ||
8711 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
f1174f77
EC
8712 /* Risk of overflow. For instance, ptr + (1<<63) may be less
8713 * than pkt_end, but that's because it's also less than pkt.
8714 */
8715 return;
8716
fb2a311a
DB
8717 new_range = dst_reg->off;
8718 if (range_right_open)
2fa7d94a 8719 new_range++;
fb2a311a
DB
8720
8721 /* Examples for register markings:
2d2be8ca 8722 *
fb2a311a 8723 * pkt_data in dst register:
2d2be8ca
DB
8724 *
8725 * r2 = r3;
8726 * r2 += 8;
8727 * if (r2 > pkt_end) goto <handle exception>
8728 * <access okay>
8729 *
b4e432f1
DB
8730 * r2 = r3;
8731 * r2 += 8;
8732 * if (r2 < pkt_end) goto <access okay>
8733 * <handle exception>
8734 *
2d2be8ca
DB
8735 * Where:
8736 * r2 == dst_reg, pkt_end == src_reg
8737 * r2=pkt(id=n,off=8,r=0)
8738 * r3=pkt(id=n,off=0,r=0)
8739 *
fb2a311a 8740 * pkt_data in src register:
2d2be8ca
DB
8741 *
8742 * r2 = r3;
8743 * r2 += 8;
8744 * if (pkt_end >= r2) goto <access okay>
8745 * <handle exception>
8746 *
b4e432f1
DB
8747 * r2 = r3;
8748 * r2 += 8;
8749 * if (pkt_end <= r2) goto <handle exception>
8750 * <access okay>
8751 *
2d2be8ca
DB
8752 * Where:
8753 * pkt_end == dst_reg, r2 == src_reg
8754 * r2=pkt(id=n,off=8,r=0)
8755 * r3=pkt(id=n,off=0,r=0)
8756 *
8757 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
fb2a311a
DB
8758 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
8759 * and [r3, r3 + 8-1) respectively is safe to access depending on
8760 * the check.
969bf05e 8761 */
2d2be8ca 8762
f1174f77
EC
8763 /* If our ids match, then we must have the same max_value. And we
8764 * don't care about the other reg's fixed offset, since if it's too big
8765 * the range won't allow anything.
8766 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
8767 */
c6a9efa1
PC
8768 for (i = 0; i <= vstate->curframe; i++)
8769 __find_good_pkt_pointers(vstate->frame[i], dst_reg, type,
8770 new_range);
969bf05e
AS
8771}
8772
3f50f132 8773static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
4f7b3e82 8774{
3f50f132
JF
8775 struct tnum subreg = tnum_subreg(reg->var_off);
8776 s32 sval = (s32)val;
a72dafaf 8777
3f50f132
JF
8778 switch (opcode) {
8779 case BPF_JEQ:
8780 if (tnum_is_const(subreg))
8781 return !!tnum_equals_const(subreg, val);
8782 break;
8783 case BPF_JNE:
8784 if (tnum_is_const(subreg))
8785 return !tnum_equals_const(subreg, val);
8786 break;
8787 case BPF_JSET:
8788 if ((~subreg.mask & subreg.value) & val)
8789 return 1;
8790 if (!((subreg.mask | subreg.value) & val))
8791 return 0;
8792 break;
8793 case BPF_JGT:
8794 if (reg->u32_min_value > val)
8795 return 1;
8796 else if (reg->u32_max_value <= val)
8797 return 0;
8798 break;
8799 case BPF_JSGT:
8800 if (reg->s32_min_value > sval)
8801 return 1;
ee114dd6 8802 else if (reg->s32_max_value <= sval)
3f50f132
JF
8803 return 0;
8804 break;
8805 case BPF_JLT:
8806 if (reg->u32_max_value < val)
8807 return 1;
8808 else if (reg->u32_min_value >= val)
8809 return 0;
8810 break;
8811 case BPF_JSLT:
8812 if (reg->s32_max_value < sval)
8813 return 1;
8814 else if (reg->s32_min_value >= sval)
8815 return 0;
8816 break;
8817 case BPF_JGE:
8818 if (reg->u32_min_value >= val)
8819 return 1;
8820 else if (reg->u32_max_value < val)
8821 return 0;
8822 break;
8823 case BPF_JSGE:
8824 if (reg->s32_min_value >= sval)
8825 return 1;
8826 else if (reg->s32_max_value < sval)
8827 return 0;
8828 break;
8829 case BPF_JLE:
8830 if (reg->u32_max_value <= val)
8831 return 1;
8832 else if (reg->u32_min_value > val)
8833 return 0;
8834 break;
8835 case BPF_JSLE:
8836 if (reg->s32_max_value <= sval)
8837 return 1;
8838 else if (reg->s32_min_value > sval)
8839 return 0;
8840 break;
8841 }
4f7b3e82 8842
3f50f132
JF
8843 return -1;
8844}
092ed096 8845
3f50f132
JF
8846
8847static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
8848{
8849 s64 sval = (s64)val;
a72dafaf 8850
4f7b3e82
AS
8851 switch (opcode) {
8852 case BPF_JEQ:
8853 if (tnum_is_const(reg->var_off))
8854 return !!tnum_equals_const(reg->var_off, val);
8855 break;
8856 case BPF_JNE:
8857 if (tnum_is_const(reg->var_off))
8858 return !tnum_equals_const(reg->var_off, val);
8859 break;
960ea056
JK
8860 case BPF_JSET:
8861 if ((~reg->var_off.mask & reg->var_off.value) & val)
8862 return 1;
8863 if (!((reg->var_off.mask | reg->var_off.value) & val))
8864 return 0;
8865 break;
4f7b3e82
AS
8866 case BPF_JGT:
8867 if (reg->umin_value > val)
8868 return 1;
8869 else if (reg->umax_value <= val)
8870 return 0;
8871 break;
8872 case BPF_JSGT:
a72dafaf 8873 if (reg->smin_value > sval)
4f7b3e82 8874 return 1;
ee114dd6 8875 else if (reg->smax_value <= sval)
4f7b3e82
AS
8876 return 0;
8877 break;
8878 case BPF_JLT:
8879 if (reg->umax_value < val)
8880 return 1;
8881 else if (reg->umin_value >= val)
8882 return 0;
8883 break;
8884 case BPF_JSLT:
a72dafaf 8885 if (reg->smax_value < sval)
4f7b3e82 8886 return 1;
a72dafaf 8887 else if (reg->smin_value >= sval)
4f7b3e82
AS
8888 return 0;
8889 break;
8890 case BPF_JGE:
8891 if (reg->umin_value >= val)
8892 return 1;
8893 else if (reg->umax_value < val)
8894 return 0;
8895 break;
8896 case BPF_JSGE:
a72dafaf 8897 if (reg->smin_value >= sval)
4f7b3e82 8898 return 1;
a72dafaf 8899 else if (reg->smax_value < sval)
4f7b3e82
AS
8900 return 0;
8901 break;
8902 case BPF_JLE:
8903 if (reg->umax_value <= val)
8904 return 1;
8905 else if (reg->umin_value > val)
8906 return 0;
8907 break;
8908 case BPF_JSLE:
a72dafaf 8909 if (reg->smax_value <= sval)
4f7b3e82 8910 return 1;
a72dafaf 8911 else if (reg->smin_value > sval)
4f7b3e82
AS
8912 return 0;
8913 break;
8914 }
8915
8916 return -1;
8917}
8918
3f50f132
JF
8919/* compute branch direction of the expression "if (reg opcode val) goto target;"
8920 * and return:
8921 * 1 - branch will be taken and "goto target" will be executed
8922 * 0 - branch will not be taken and fall-through to next insn
8923 * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
8924 * range [0,10]
604dca5e 8925 */
3f50f132
JF
8926static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
8927 bool is_jmp32)
604dca5e 8928{
cac616db
JF
8929 if (__is_pointer_value(false, reg)) {
8930 if (!reg_type_not_null(reg->type))
8931 return -1;
8932
8933 /* If pointer is valid tests against zero will fail so we can
8934 * use this to direct branch taken.
8935 */
8936 if (val != 0)
8937 return -1;
8938
8939 switch (opcode) {
8940 case BPF_JEQ:
8941 return 0;
8942 case BPF_JNE:
8943 return 1;
8944 default:
8945 return -1;
8946 }
8947 }
604dca5e 8948
3f50f132
JF
8949 if (is_jmp32)
8950 return is_branch32_taken(reg, val, opcode);
8951 return is_branch64_taken(reg, val, opcode);
604dca5e
JH
8952}
8953
6d94e741
AS
8954static int flip_opcode(u32 opcode)
8955{
8956 /* How can we transform "a <op> b" into "b <op> a"? */
8957 static const u8 opcode_flip[16] = {
8958 /* these stay the same */
8959 [BPF_JEQ >> 4] = BPF_JEQ,
8960 [BPF_JNE >> 4] = BPF_JNE,
8961 [BPF_JSET >> 4] = BPF_JSET,
8962 /* these swap "lesser" and "greater" (L and G in the opcodes) */
8963 [BPF_JGE >> 4] = BPF_JLE,
8964 [BPF_JGT >> 4] = BPF_JLT,
8965 [BPF_JLE >> 4] = BPF_JGE,
8966 [BPF_JLT >> 4] = BPF_JGT,
8967 [BPF_JSGE >> 4] = BPF_JSLE,
8968 [BPF_JSGT >> 4] = BPF_JSLT,
8969 [BPF_JSLE >> 4] = BPF_JSGE,
8970 [BPF_JSLT >> 4] = BPF_JSGT
8971 };
8972 return opcode_flip[opcode >> 4];
8973}
8974
8975static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
8976 struct bpf_reg_state *src_reg,
8977 u8 opcode)
8978{
8979 struct bpf_reg_state *pkt;
8980
8981 if (src_reg->type == PTR_TO_PACKET_END) {
8982 pkt = dst_reg;
8983 } else if (dst_reg->type == PTR_TO_PACKET_END) {
8984 pkt = src_reg;
8985 opcode = flip_opcode(opcode);
8986 } else {
8987 return -1;
8988 }
8989
8990 if (pkt->range >= 0)
8991 return -1;
8992
8993 switch (opcode) {
8994 case BPF_JLE:
8995 /* pkt <= pkt_end */
8996 fallthrough;
8997 case BPF_JGT:
8998 /* pkt > pkt_end */
8999 if (pkt->range == BEYOND_PKT_END)
9000 /* pkt has at last one extra byte beyond pkt_end */
9001 return opcode == BPF_JGT;
9002 break;
9003 case BPF_JLT:
9004 /* pkt < pkt_end */
9005 fallthrough;
9006 case BPF_JGE:
9007 /* pkt >= pkt_end */
9008 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
9009 return opcode == BPF_JGE;
9010 break;
9011 }
9012 return -1;
9013}
9014
48461135
JB
9015/* Adjusts the register min/max values in the case that the dst_reg is the
9016 * variable register that we are working on, and src_reg is a constant or we're
9017 * simply doing a BPF_K check.
f1174f77 9018 * In JEQ/JNE cases we also adjust the var_off values.
48461135
JB
9019 */
9020static void reg_set_min_max(struct bpf_reg_state *true_reg,
3f50f132
JF
9021 struct bpf_reg_state *false_reg,
9022 u64 val, u32 val32,
092ed096 9023 u8 opcode, bool is_jmp32)
48461135 9024{
3f50f132
JF
9025 struct tnum false_32off = tnum_subreg(false_reg->var_off);
9026 struct tnum false_64off = false_reg->var_off;
9027 struct tnum true_32off = tnum_subreg(true_reg->var_off);
9028 struct tnum true_64off = true_reg->var_off;
9029 s64 sval = (s64)val;
9030 s32 sval32 = (s32)val32;
a72dafaf 9031
f1174f77
EC
9032 /* If the dst_reg is a pointer, we can't learn anything about its
9033 * variable offset from the compare (unless src_reg were a pointer into
9034 * the same object, but we don't bother with that.
9035 * Since false_reg and true_reg have the same type by construction, we
9036 * only need to check one of them for pointerness.
9037 */
9038 if (__is_pointer_value(false, false_reg))
9039 return;
4cabc5b1 9040
48461135
JB
9041 switch (opcode) {
9042 case BPF_JEQ:
48461135 9043 case BPF_JNE:
a72dafaf
JW
9044 {
9045 struct bpf_reg_state *reg =
9046 opcode == BPF_JEQ ? true_reg : false_reg;
9047
e688c3db
AS
9048 /* JEQ/JNE comparison doesn't change the register equivalence.
9049 * r1 = r2;
9050 * if (r1 == 42) goto label;
9051 * ...
9052 * label: // here both r1 and r2 are known to be 42.
9053 *
9054 * Hence when marking register as known preserve it's ID.
48461135 9055 */
3f50f132
JF
9056 if (is_jmp32)
9057 __mark_reg32_known(reg, val32);
9058 else
e688c3db 9059 ___mark_reg_known(reg, val);
48461135 9060 break;
a72dafaf 9061 }
960ea056 9062 case BPF_JSET:
3f50f132
JF
9063 if (is_jmp32) {
9064 false_32off = tnum_and(false_32off, tnum_const(~val32));
9065 if (is_power_of_2(val32))
9066 true_32off = tnum_or(true_32off,
9067 tnum_const(val32));
9068 } else {
9069 false_64off = tnum_and(false_64off, tnum_const(~val));
9070 if (is_power_of_2(val))
9071 true_64off = tnum_or(true_64off,
9072 tnum_const(val));
9073 }
960ea056 9074 break;
48461135 9075 case BPF_JGE:
a72dafaf
JW
9076 case BPF_JGT:
9077 {
3f50f132
JF
9078 if (is_jmp32) {
9079 u32 false_umax = opcode == BPF_JGT ? val32 : val32 - 1;
9080 u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
9081
9082 false_reg->u32_max_value = min(false_reg->u32_max_value,
9083 false_umax);
9084 true_reg->u32_min_value = max(true_reg->u32_min_value,
9085 true_umin);
9086 } else {
9087 u64 false_umax = opcode == BPF_JGT ? val : val - 1;
9088 u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
9089
9090 false_reg->umax_value = min(false_reg->umax_value, false_umax);
9091 true_reg->umin_value = max(true_reg->umin_value, true_umin);
9092 }
b03c9f9f 9093 break;
a72dafaf 9094 }
48461135 9095 case BPF_JSGE:
a72dafaf
JW
9096 case BPF_JSGT:
9097 {
3f50f132
JF
9098 if (is_jmp32) {
9099 s32 false_smax = opcode == BPF_JSGT ? sval32 : sval32 - 1;
9100 s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
a72dafaf 9101
3f50f132
JF
9102 false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
9103 true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
9104 } else {
9105 s64 false_smax = opcode == BPF_JSGT ? sval : sval - 1;
9106 s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
9107
9108 false_reg->smax_value = min(false_reg->smax_value, false_smax);
9109 true_reg->smin_value = max(true_reg->smin_value, true_smin);
9110 }
48461135 9111 break;
a72dafaf 9112 }
b4e432f1 9113 case BPF_JLE:
a72dafaf
JW
9114 case BPF_JLT:
9115 {
3f50f132
JF
9116 if (is_jmp32) {
9117 u32 false_umin = opcode == BPF_JLT ? val32 : val32 + 1;
9118 u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
9119
9120 false_reg->u32_min_value = max(false_reg->u32_min_value,
9121 false_umin);
9122 true_reg->u32_max_value = min(true_reg->u32_max_value,
9123 true_umax);
9124 } else {
9125 u64 false_umin = opcode == BPF_JLT ? val : val + 1;
9126 u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
9127
9128 false_reg->umin_value = max(false_reg->umin_value, false_umin);
9129 true_reg->umax_value = min(true_reg->umax_value, true_umax);
9130 }
b4e432f1 9131 break;
a72dafaf 9132 }
b4e432f1 9133 case BPF_JSLE:
a72dafaf
JW
9134 case BPF_JSLT:
9135 {
3f50f132
JF
9136 if (is_jmp32) {
9137 s32 false_smin = opcode == BPF_JSLT ? sval32 : sval32 + 1;
9138 s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
a72dafaf 9139
3f50f132
JF
9140 false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
9141 true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
9142 } else {
9143 s64 false_smin = opcode == BPF_JSLT ? sval : sval + 1;
9144 s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
9145
9146 false_reg->smin_value = max(false_reg->smin_value, false_smin);
9147 true_reg->smax_value = min(true_reg->smax_value, true_smax);
9148 }
b4e432f1 9149 break;
a72dafaf 9150 }
48461135 9151 default:
0fc31b10 9152 return;
48461135
JB
9153 }
9154
3f50f132
JF
9155 if (is_jmp32) {
9156 false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
9157 tnum_subreg(false_32off));
9158 true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
9159 tnum_subreg(true_32off));
9160 __reg_combine_32_into_64(false_reg);
9161 __reg_combine_32_into_64(true_reg);
9162 } else {
9163 false_reg->var_off = false_64off;
9164 true_reg->var_off = true_64off;
9165 __reg_combine_64_into_32(false_reg);
9166 __reg_combine_64_into_32(true_reg);
9167 }
48461135
JB
9168}
9169
f1174f77
EC
9170/* Same as above, but for the case that dst_reg holds a constant and src_reg is
9171 * the variable reg.
48461135
JB
9172 */
9173static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
3f50f132
JF
9174 struct bpf_reg_state *false_reg,
9175 u64 val, u32 val32,
092ed096 9176 u8 opcode, bool is_jmp32)
48461135 9177{
6d94e741 9178 opcode = flip_opcode(opcode);
0fc31b10
JH
9179 /* This uses zero as "not present in table"; luckily the zero opcode,
9180 * BPF_JA, can't get here.
b03c9f9f 9181 */
0fc31b10 9182 if (opcode)
3f50f132 9183 reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
f1174f77
EC
9184}
9185
9186/* Regs are known to be equal, so intersect their min/max/var_off */
9187static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
9188 struct bpf_reg_state *dst_reg)
9189{
b03c9f9f
EC
9190 src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
9191 dst_reg->umin_value);
9192 src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
9193 dst_reg->umax_value);
9194 src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
9195 dst_reg->smin_value);
9196 src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
9197 dst_reg->smax_value);
f1174f77
EC
9198 src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
9199 dst_reg->var_off);
b03c9f9f
EC
9200 /* We might have learned new bounds from the var_off. */
9201 __update_reg_bounds(src_reg);
9202 __update_reg_bounds(dst_reg);
9203 /* We might have learned something about the sign bit. */
9204 __reg_deduce_bounds(src_reg);
9205 __reg_deduce_bounds(dst_reg);
9206 /* We might have learned some bits from the bounds. */
9207 __reg_bound_offset(src_reg);
9208 __reg_bound_offset(dst_reg);
9209 /* Intersecting with the old var_off might have improved our bounds
9210 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
9211 * then new var_off is (0; 0x7f...fc) which improves our umax.
9212 */
9213 __update_reg_bounds(src_reg);
9214 __update_reg_bounds(dst_reg);
f1174f77
EC
9215}
9216
9217static void reg_combine_min_max(struct bpf_reg_state *true_src,
9218 struct bpf_reg_state *true_dst,
9219 struct bpf_reg_state *false_src,
9220 struct bpf_reg_state *false_dst,
9221 u8 opcode)
9222{
9223 switch (opcode) {
9224 case BPF_JEQ:
9225 __reg_combine_min_max(true_src, true_dst);
9226 break;
9227 case BPF_JNE:
9228 __reg_combine_min_max(false_src, false_dst);
b03c9f9f 9229 break;
4cabc5b1 9230 }
48461135
JB
9231}
9232
fd978bf7
JS
9233static void mark_ptr_or_null_reg(struct bpf_func_state *state,
9234 struct bpf_reg_state *reg, u32 id,
840b9615 9235 bool is_null)
57a09bf0 9236{
c25b2ae1 9237 if (type_may_be_null(reg->type) && reg->id == id &&
93c230e3 9238 !WARN_ON_ONCE(!reg->id)) {
b03c9f9f
EC
9239 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value ||
9240 !tnum_equals_const(reg->var_off, 0) ||
f1174f77 9241 reg->off)) {
e60b0d12
DB
9242 /* Old offset (both fixed and variable parts) should
9243 * have been known-zero, because we don't allow pointer
9244 * arithmetic on pointers that might be NULL. If we
9245 * see this happening, don't convert the register.
9246 */
9247 return;
f1174f77
EC
9248 }
9249 if (is_null) {
9250 reg->type = SCALAR_VALUE;
1b986589
MKL
9251 /* We don't need id and ref_obj_id from this point
9252 * onwards anymore, thus we should better reset it,
9253 * so that state pruning has chances to take effect.
9254 */
9255 reg->id = 0;
9256 reg->ref_obj_id = 0;
4ddb7416
DB
9257
9258 return;
9259 }
9260
9261 mark_ptr_not_null_reg(reg);
9262
9263 if (!reg_may_point_to_spin_lock(reg)) {
1b986589
MKL
9264 /* For not-NULL ptr, reg->ref_obj_id will be reset
9265 * in release_reg_references().
9266 *
9267 * reg->id is still used by spin_lock ptr. Other
9268 * than spin_lock ptr type, reg->id can be reset.
fd978bf7
JS
9269 */
9270 reg->id = 0;
56f668df 9271 }
57a09bf0
TG
9272 }
9273}
9274
c6a9efa1
PC
9275static void __mark_ptr_or_null_regs(struct bpf_func_state *state, u32 id,
9276 bool is_null)
9277{
9278 struct bpf_reg_state *reg;
9279 int i;
9280
9281 for (i = 0; i < MAX_BPF_REG; i++)
9282 mark_ptr_or_null_reg(state, &state->regs[i], id, is_null);
9283
9284 bpf_for_each_spilled_reg(i, state, reg) {
9285 if (!reg)
9286 continue;
9287 mark_ptr_or_null_reg(state, reg, id, is_null);
9288 }
9289}
9290
57a09bf0
TG
9291/* The logic is similar to find_good_pkt_pointers(), both could eventually
9292 * be folded together at some point.
9293 */
840b9615
JS
9294static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
9295 bool is_null)
57a09bf0 9296{
f4d7e40a 9297 struct bpf_func_state *state = vstate->frame[vstate->curframe];
c6a9efa1 9298 struct bpf_reg_state *regs = state->regs;
1b986589 9299 u32 ref_obj_id = regs[regno].ref_obj_id;
a08dd0da 9300 u32 id = regs[regno].id;
c6a9efa1 9301 int i;
57a09bf0 9302
1b986589
MKL
9303 if (ref_obj_id && ref_obj_id == id && is_null)
9304 /* regs[regno] is in the " == NULL" branch.
9305 * No one could have freed the reference state before
9306 * doing the NULL check.
9307 */
9308 WARN_ON_ONCE(release_reference_state(state, id));
fd978bf7 9309
c6a9efa1
PC
9310 for (i = 0; i <= vstate->curframe; i++)
9311 __mark_ptr_or_null_regs(vstate->frame[i], id, is_null);
57a09bf0
TG
9312}
9313
5beca081
DB
9314static bool try_match_pkt_pointers(const struct bpf_insn *insn,
9315 struct bpf_reg_state *dst_reg,
9316 struct bpf_reg_state *src_reg,
9317 struct bpf_verifier_state *this_branch,
9318 struct bpf_verifier_state *other_branch)
9319{
9320 if (BPF_SRC(insn->code) != BPF_X)
9321 return false;
9322
092ed096
JW
9323 /* Pointers are always 64-bit. */
9324 if (BPF_CLASS(insn->code) == BPF_JMP32)
9325 return false;
9326
5beca081
DB
9327 switch (BPF_OP(insn->code)) {
9328 case BPF_JGT:
9329 if ((dst_reg->type == PTR_TO_PACKET &&
9330 src_reg->type == PTR_TO_PACKET_END) ||
9331 (dst_reg->type == PTR_TO_PACKET_META &&
9332 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
9333 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
9334 find_good_pkt_pointers(this_branch, dst_reg,
9335 dst_reg->type, false);
6d94e741 9336 mark_pkt_end(other_branch, insn->dst_reg, true);
5beca081
DB
9337 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
9338 src_reg->type == PTR_TO_PACKET) ||
9339 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
9340 src_reg->type == PTR_TO_PACKET_META)) {
9341 /* pkt_end > pkt_data', pkt_data > pkt_meta' */
9342 find_good_pkt_pointers(other_branch, src_reg,
9343 src_reg->type, true);
6d94e741 9344 mark_pkt_end(this_branch, insn->src_reg, false);
5beca081
DB
9345 } else {
9346 return false;
9347 }
9348 break;
9349 case BPF_JLT:
9350 if ((dst_reg->type == PTR_TO_PACKET &&
9351 src_reg->type == PTR_TO_PACKET_END) ||
9352 (dst_reg->type == PTR_TO_PACKET_META &&
9353 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
9354 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
9355 find_good_pkt_pointers(other_branch, dst_reg,
9356 dst_reg->type, true);
6d94e741 9357 mark_pkt_end(this_branch, insn->dst_reg, false);
5beca081
DB
9358 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
9359 src_reg->type == PTR_TO_PACKET) ||
9360 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
9361 src_reg->type == PTR_TO_PACKET_META)) {
9362 /* pkt_end < pkt_data', pkt_data > pkt_meta' */
9363 find_good_pkt_pointers(this_branch, src_reg,
9364 src_reg->type, false);
6d94e741 9365 mark_pkt_end(other_branch, insn->src_reg, true);
5beca081
DB
9366 } else {
9367 return false;
9368 }
9369 break;
9370 case BPF_JGE:
9371 if ((dst_reg->type == PTR_TO_PACKET &&
9372 src_reg->type == PTR_TO_PACKET_END) ||
9373 (dst_reg->type == PTR_TO_PACKET_META &&
9374 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
9375 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
9376 find_good_pkt_pointers(this_branch, dst_reg,
9377 dst_reg->type, true);
6d94e741 9378 mark_pkt_end(other_branch, insn->dst_reg, false);
5beca081
DB
9379 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
9380 src_reg->type == PTR_TO_PACKET) ||
9381 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
9382 src_reg->type == PTR_TO_PACKET_META)) {
9383 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
9384 find_good_pkt_pointers(other_branch, src_reg,
9385 src_reg->type, false);
6d94e741 9386 mark_pkt_end(this_branch, insn->src_reg, true);
5beca081
DB
9387 } else {
9388 return false;
9389 }
9390 break;
9391 case BPF_JLE:
9392 if ((dst_reg->type == PTR_TO_PACKET &&
9393 src_reg->type == PTR_TO_PACKET_END) ||
9394 (dst_reg->type == PTR_TO_PACKET_META &&
9395 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
9396 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
9397 find_good_pkt_pointers(other_branch, dst_reg,
9398 dst_reg->type, false);
6d94e741 9399 mark_pkt_end(this_branch, insn->dst_reg, true);
5beca081
DB
9400 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
9401 src_reg->type == PTR_TO_PACKET) ||
9402 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
9403 src_reg->type == PTR_TO_PACKET_META)) {
9404 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
9405 find_good_pkt_pointers(this_branch, src_reg,
9406 src_reg->type, true);
6d94e741 9407 mark_pkt_end(other_branch, insn->src_reg, false);
5beca081
DB
9408 } else {
9409 return false;
9410 }
9411 break;
9412 default:
9413 return false;
9414 }
9415
9416 return true;
9417}
9418
75748837
AS
9419static void find_equal_scalars(struct bpf_verifier_state *vstate,
9420 struct bpf_reg_state *known_reg)
9421{
9422 struct bpf_func_state *state;
9423 struct bpf_reg_state *reg;
9424 int i, j;
9425
9426 for (i = 0; i <= vstate->curframe; i++) {
9427 state = vstate->frame[i];
9428 for (j = 0; j < MAX_BPF_REG; j++) {
9429 reg = &state->regs[j];
9430 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
9431 *reg = *known_reg;
9432 }
9433
9434 bpf_for_each_spilled_reg(j, state, reg) {
9435 if (!reg)
9436 continue;
9437 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
9438 *reg = *known_reg;
9439 }
9440 }
9441}
9442
58e2af8b 9443static int check_cond_jmp_op(struct bpf_verifier_env *env,
17a52670
AS
9444 struct bpf_insn *insn, int *insn_idx)
9445{
f4d7e40a
AS
9446 struct bpf_verifier_state *this_branch = env->cur_state;
9447 struct bpf_verifier_state *other_branch;
9448 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
fb8d251e 9449 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
17a52670 9450 u8 opcode = BPF_OP(insn->code);
092ed096 9451 bool is_jmp32;
fb8d251e 9452 int pred = -1;
17a52670
AS
9453 int err;
9454
092ed096
JW
9455 /* Only conditional jumps are expected to reach here. */
9456 if (opcode == BPF_JA || opcode > BPF_JSLE) {
9457 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
17a52670
AS
9458 return -EINVAL;
9459 }
9460
9461 if (BPF_SRC(insn->code) == BPF_X) {
9462 if (insn->imm != 0) {
092ed096 9463 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
17a52670
AS
9464 return -EINVAL;
9465 }
9466
9467 /* check src1 operand */
dc503a8a 9468 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17a52670
AS
9469 if (err)
9470 return err;
1be7f75d
AS
9471
9472 if (is_pointer_value(env, insn->src_reg)) {
61bd5218 9473 verbose(env, "R%d pointer comparison prohibited\n",
1be7f75d
AS
9474 insn->src_reg);
9475 return -EACCES;
9476 }
fb8d251e 9477 src_reg = &regs[insn->src_reg];
17a52670
AS
9478 } else {
9479 if (insn->src_reg != BPF_REG_0) {
092ed096 9480 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
17a52670
AS
9481 return -EINVAL;
9482 }
9483 }
9484
9485 /* check src2 operand */
dc503a8a 9486 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17a52670
AS
9487 if (err)
9488 return err;
9489
1a0dc1ac 9490 dst_reg = &regs[insn->dst_reg];
092ed096 9491 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
1a0dc1ac 9492
3f50f132
JF
9493 if (BPF_SRC(insn->code) == BPF_K) {
9494 pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
9495 } else if (src_reg->type == SCALAR_VALUE &&
9496 is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
9497 pred = is_branch_taken(dst_reg,
9498 tnum_subreg(src_reg->var_off).value,
9499 opcode,
9500 is_jmp32);
9501 } else if (src_reg->type == SCALAR_VALUE &&
9502 !is_jmp32 && tnum_is_const(src_reg->var_off)) {
9503 pred = is_branch_taken(dst_reg,
9504 src_reg->var_off.value,
9505 opcode,
9506 is_jmp32);
6d94e741
AS
9507 } else if (reg_is_pkt_pointer_any(dst_reg) &&
9508 reg_is_pkt_pointer_any(src_reg) &&
9509 !is_jmp32) {
9510 pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
3f50f132
JF
9511 }
9512
b5dc0163 9513 if (pred >= 0) {
cac616db
JF
9514 /* If we get here with a dst_reg pointer type it is because
9515 * above is_branch_taken() special cased the 0 comparison.
9516 */
9517 if (!__is_pointer_value(false, dst_reg))
9518 err = mark_chain_precision(env, insn->dst_reg);
6d94e741
AS
9519 if (BPF_SRC(insn->code) == BPF_X && !err &&
9520 !__is_pointer_value(false, src_reg))
b5dc0163
AS
9521 err = mark_chain_precision(env, insn->src_reg);
9522 if (err)
9523 return err;
9524 }
9183671a 9525
fb8d251e 9526 if (pred == 1) {
9183671a
DB
9527 /* Only follow the goto, ignore fall-through. If needed, push
9528 * the fall-through branch for simulation under speculative
9529 * execution.
9530 */
9531 if (!env->bypass_spec_v1 &&
9532 !sanitize_speculative_path(env, insn, *insn_idx + 1,
9533 *insn_idx))
9534 return -EFAULT;
fb8d251e
AS
9535 *insn_idx += insn->off;
9536 return 0;
9537 } else if (pred == 0) {
9183671a
DB
9538 /* Only follow the fall-through branch, since that's where the
9539 * program will go. If needed, push the goto branch for
9540 * simulation under speculative execution.
fb8d251e 9541 */
9183671a
DB
9542 if (!env->bypass_spec_v1 &&
9543 !sanitize_speculative_path(env, insn,
9544 *insn_idx + insn->off + 1,
9545 *insn_idx))
9546 return -EFAULT;
fb8d251e 9547 return 0;
17a52670
AS
9548 }
9549
979d63d5
DB
9550 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
9551 false);
17a52670
AS
9552 if (!other_branch)
9553 return -EFAULT;
f4d7e40a 9554 other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
17a52670 9555
48461135
JB
9556 /* detect if we are comparing against a constant value so we can adjust
9557 * our min/max values for our dst register.
f1174f77
EC
9558 * this is only legit if both are scalars (or pointers to the same
9559 * object, I suppose, but we don't support that right now), because
9560 * otherwise the different base pointers mean the offsets aren't
9561 * comparable.
48461135
JB
9562 */
9563 if (BPF_SRC(insn->code) == BPF_X) {
092ed096 9564 struct bpf_reg_state *src_reg = &regs[insn->src_reg];
092ed096 9565
f1174f77 9566 if (dst_reg->type == SCALAR_VALUE &&
092ed096
JW
9567 src_reg->type == SCALAR_VALUE) {
9568 if (tnum_is_const(src_reg->var_off) ||
3f50f132
JF
9569 (is_jmp32 &&
9570 tnum_is_const(tnum_subreg(src_reg->var_off))))
f4d7e40a 9571 reg_set_min_max(&other_branch_regs[insn->dst_reg],
092ed096 9572 dst_reg,
3f50f132
JF
9573 src_reg->var_off.value,
9574 tnum_subreg(src_reg->var_off).value,
092ed096
JW
9575 opcode, is_jmp32);
9576 else if (tnum_is_const(dst_reg->var_off) ||
3f50f132
JF
9577 (is_jmp32 &&
9578 tnum_is_const(tnum_subreg(dst_reg->var_off))))
f4d7e40a 9579 reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
092ed096 9580 src_reg,
3f50f132
JF
9581 dst_reg->var_off.value,
9582 tnum_subreg(dst_reg->var_off).value,
092ed096
JW
9583 opcode, is_jmp32);
9584 else if (!is_jmp32 &&
9585 (opcode == BPF_JEQ || opcode == BPF_JNE))
f1174f77 9586 /* Comparing for equality, we can combine knowledge */
f4d7e40a
AS
9587 reg_combine_min_max(&other_branch_regs[insn->src_reg],
9588 &other_branch_regs[insn->dst_reg],
092ed096 9589 src_reg, dst_reg, opcode);
e688c3db
AS
9590 if (src_reg->id &&
9591 !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
75748837
AS
9592 find_equal_scalars(this_branch, src_reg);
9593 find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
9594 }
9595
f1174f77
EC
9596 }
9597 } else if (dst_reg->type == SCALAR_VALUE) {
f4d7e40a 9598 reg_set_min_max(&other_branch_regs[insn->dst_reg],
3f50f132
JF
9599 dst_reg, insn->imm, (u32)insn->imm,
9600 opcode, is_jmp32);
48461135
JB
9601 }
9602
e688c3db
AS
9603 if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
9604 !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
75748837
AS
9605 find_equal_scalars(this_branch, dst_reg);
9606 find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
9607 }
9608
092ed096
JW
9609 /* detect if R == 0 where R is returned from bpf_map_lookup_elem().
9610 * NOTE: these optimizations below are related with pointer comparison
9611 * which will never be JMP32.
9612 */
9613 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
1a0dc1ac 9614 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
c25b2ae1 9615 type_may_be_null(dst_reg->type)) {
840b9615 9616 /* Mark all identical registers in each branch as either
57a09bf0
TG
9617 * safe or unknown depending R == 0 or R != 0 conditional.
9618 */
840b9615
JS
9619 mark_ptr_or_null_regs(this_branch, insn->dst_reg,
9620 opcode == BPF_JNE);
9621 mark_ptr_or_null_regs(other_branch, insn->dst_reg,
9622 opcode == BPF_JEQ);
5beca081
DB
9623 } else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
9624 this_branch, other_branch) &&
9625 is_pointer_value(env, insn->dst_reg)) {
61bd5218
JK
9626 verbose(env, "R%d pointer comparison prohibited\n",
9627 insn->dst_reg);
1be7f75d 9628 return -EACCES;
17a52670 9629 }
06ee7115 9630 if (env->log.level & BPF_LOG_LEVEL)
2e576648 9631 print_insn_state(env, this_branch->frame[this_branch->curframe]);
17a52670
AS
9632 return 0;
9633}
9634
17a52670 9635/* verify BPF_LD_IMM64 instruction */
58e2af8b 9636static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
17a52670 9637{
d8eca5bb 9638 struct bpf_insn_aux_data *aux = cur_aux(env);
638f5b90 9639 struct bpf_reg_state *regs = cur_regs(env);
4976b718 9640 struct bpf_reg_state *dst_reg;
d8eca5bb 9641 struct bpf_map *map;
17a52670
AS
9642 int err;
9643
9644 if (BPF_SIZE(insn->code) != BPF_DW) {
61bd5218 9645 verbose(env, "invalid BPF_LD_IMM insn\n");
17a52670
AS
9646 return -EINVAL;
9647 }
9648 if (insn->off != 0) {
61bd5218 9649 verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
17a52670
AS
9650 return -EINVAL;
9651 }
9652
dc503a8a 9653 err = check_reg_arg(env, insn->dst_reg, DST_OP);
17a52670
AS
9654 if (err)
9655 return err;
9656
4976b718 9657 dst_reg = &regs[insn->dst_reg];
6b173873 9658 if (insn->src_reg == 0) {
6b173873
JK
9659 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
9660
4976b718 9661 dst_reg->type = SCALAR_VALUE;
b03c9f9f 9662 __mark_reg_known(&regs[insn->dst_reg], imm);
17a52670 9663 return 0;
6b173873 9664 }
17a52670 9665
d400a6cf
DB
9666 /* All special src_reg cases are listed below. From this point onwards
9667 * we either succeed and assign a corresponding dst_reg->type after
9668 * zeroing the offset, or fail and reject the program.
9669 */
9670 mark_reg_known_zero(env, regs, insn->dst_reg);
4976b718 9671
d400a6cf 9672 if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
4976b718 9673 dst_reg->type = aux->btf_var.reg_type;
34d3a78c 9674 switch (base_type(dst_reg->type)) {
4976b718
HL
9675 case PTR_TO_MEM:
9676 dst_reg->mem_size = aux->btf_var.mem_size;
9677 break;
9678 case PTR_TO_BTF_ID:
22dc4a0f 9679 dst_reg->btf = aux->btf_var.btf;
4976b718
HL
9680 dst_reg->btf_id = aux->btf_var.btf_id;
9681 break;
9682 default:
9683 verbose(env, "bpf verifier is misconfigured\n");
9684 return -EFAULT;
9685 }
9686 return 0;
9687 }
9688
69c087ba
YS
9689 if (insn->src_reg == BPF_PSEUDO_FUNC) {
9690 struct bpf_prog_aux *aux = env->prog->aux;
3990ed4c
MKL
9691 u32 subprogno = find_subprog(env,
9692 env->insn_idx + insn->imm + 1);
69c087ba
YS
9693
9694 if (!aux->func_info) {
9695 verbose(env, "missing btf func_info\n");
9696 return -EINVAL;
9697 }
9698 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
9699 verbose(env, "callback function not static\n");
9700 return -EINVAL;
9701 }
9702
9703 dst_reg->type = PTR_TO_FUNC;
9704 dst_reg->subprogno = subprogno;
9705 return 0;
9706 }
9707
d8eca5bb 9708 map = env->used_maps[aux->map_index];
4976b718 9709 dst_reg->map_ptr = map;
d8eca5bb 9710
387544bf
AS
9711 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
9712 insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
4976b718
HL
9713 dst_reg->type = PTR_TO_MAP_VALUE;
9714 dst_reg->off = aux->map_off;
d8eca5bb 9715 if (map_value_has_spin_lock(map))
4976b718 9716 dst_reg->id = ++env->id_gen;
387544bf
AS
9717 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
9718 insn->src_reg == BPF_PSEUDO_MAP_IDX) {
4976b718 9719 dst_reg->type = CONST_PTR_TO_MAP;
d8eca5bb
DB
9720 } else {
9721 verbose(env, "bpf verifier is misconfigured\n");
9722 return -EINVAL;
9723 }
17a52670 9724
17a52670
AS
9725 return 0;
9726}
9727
96be4325
DB
9728static bool may_access_skb(enum bpf_prog_type type)
9729{
9730 switch (type) {
9731 case BPF_PROG_TYPE_SOCKET_FILTER:
9732 case BPF_PROG_TYPE_SCHED_CLS:
94caee8c 9733 case BPF_PROG_TYPE_SCHED_ACT:
96be4325
DB
9734 return true;
9735 default:
9736 return false;
9737 }
9738}
9739
ddd872bc
AS
9740/* verify safety of LD_ABS|LD_IND instructions:
9741 * - they can only appear in the programs where ctx == skb
9742 * - since they are wrappers of function calls, they scratch R1-R5 registers,
9743 * preserve R6-R9, and store return value into R0
9744 *
9745 * Implicit input:
9746 * ctx == skb == R6 == CTX
9747 *
9748 * Explicit input:
9749 * SRC == any register
9750 * IMM == 32-bit immediate
9751 *
9752 * Output:
9753 * R0 - 8/16/32-bit skb data converted to cpu endianness
9754 */
58e2af8b 9755static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
ddd872bc 9756{
638f5b90 9757 struct bpf_reg_state *regs = cur_regs(env);
6d4f151a 9758 static const int ctx_reg = BPF_REG_6;
ddd872bc 9759 u8 mode = BPF_MODE(insn->code);
ddd872bc
AS
9760 int i, err;
9761
7e40781c 9762 if (!may_access_skb(resolve_prog_type(env->prog))) {
61bd5218 9763 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
ddd872bc
AS
9764 return -EINVAL;
9765 }
9766
e0cea7ce
DB
9767 if (!env->ops->gen_ld_abs) {
9768 verbose(env, "bpf verifier is misconfigured\n");
9769 return -EINVAL;
9770 }
9771
ddd872bc 9772 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
d82bccc6 9773 BPF_SIZE(insn->code) == BPF_DW ||
ddd872bc 9774 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
61bd5218 9775 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
ddd872bc
AS
9776 return -EINVAL;
9777 }
9778
9779 /* check whether implicit source operand (register R6) is readable */
6d4f151a 9780 err = check_reg_arg(env, ctx_reg, SRC_OP);
ddd872bc
AS
9781 if (err)
9782 return err;
9783
fd978bf7
JS
9784 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
9785 * gen_ld_abs() may terminate the program at runtime, leading to
9786 * reference leak.
9787 */
9788 err = check_reference_leak(env);
9789 if (err) {
9790 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
9791 return err;
9792 }
9793
d83525ca
AS
9794 if (env->cur_state->active_spin_lock) {
9795 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
9796 return -EINVAL;
9797 }
9798
6d4f151a 9799 if (regs[ctx_reg].type != PTR_TO_CTX) {
61bd5218
JK
9800 verbose(env,
9801 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
ddd872bc
AS
9802 return -EINVAL;
9803 }
9804
9805 if (mode == BPF_IND) {
9806 /* check explicit source operand */
dc503a8a 9807 err = check_reg_arg(env, insn->src_reg, SRC_OP);
ddd872bc
AS
9808 if (err)
9809 return err;
9810 }
9811
be80a1d3 9812 err = check_ptr_off_reg(env, &regs[ctx_reg], ctx_reg);
6d4f151a
DB
9813 if (err < 0)
9814 return err;
9815
ddd872bc 9816 /* reset caller saved regs to unreadable */
dc503a8a 9817 for (i = 0; i < CALLER_SAVED_REGS; i++) {
61bd5218 9818 mark_reg_not_init(env, regs, caller_saved[i]);
dc503a8a
EC
9819 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
9820 }
ddd872bc
AS
9821
9822 /* mark destination R0 register as readable, since it contains
dc503a8a
EC
9823 * the value fetched from the packet.
9824 * Already marked as written above.
ddd872bc 9825 */
61bd5218 9826 mark_reg_unknown(env, regs, BPF_REG_0);
5327ed3d
JW
9827 /* ld_abs load up to 32-bit skb data. */
9828 regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
ddd872bc
AS
9829 return 0;
9830}
9831
390ee7e2
AS
9832static int check_return_code(struct bpf_verifier_env *env)
9833{
5cf1e914 9834 struct tnum enforce_attach_type_range = tnum_unknown;
27ae7997 9835 const struct bpf_prog *prog = env->prog;
390ee7e2
AS
9836 struct bpf_reg_state *reg;
9837 struct tnum range = tnum_range(0, 1);
7e40781c 9838 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
27ae7997 9839 int err;
bfc6bb74
AS
9840 struct bpf_func_state *frame = env->cur_state->frame[0];
9841 const bool is_subprog = frame->subprogno;
27ae7997 9842
9e4e01df 9843 /* LSM and struct_ops func-ptr's return type could be "void" */
f782e2c3
DB
9844 if (!is_subprog &&
9845 (prog_type == BPF_PROG_TYPE_STRUCT_OPS ||
7e40781c 9846 prog_type == BPF_PROG_TYPE_LSM) &&
27ae7997
MKL
9847 !prog->aux->attach_func_proto->type)
9848 return 0;
9849
8fb33b60 9850 /* eBPF calling convention is such that R0 is used
27ae7997
MKL
9851 * to return the value from eBPF program.
9852 * Make sure that it's readable at this time
9853 * of bpf_exit, which means that program wrote
9854 * something into it earlier
9855 */
9856 err = check_reg_arg(env, BPF_REG_0, SRC_OP);
9857 if (err)
9858 return err;
9859
9860 if (is_pointer_value(env, BPF_REG_0)) {
9861 verbose(env, "R0 leaks addr as return value\n");
9862 return -EACCES;
9863 }
390ee7e2 9864
f782e2c3 9865 reg = cur_regs(env) + BPF_REG_0;
bfc6bb74
AS
9866
9867 if (frame->in_async_callback_fn) {
9868 /* enforce return zero from async callbacks like timer */
9869 if (reg->type != SCALAR_VALUE) {
9870 verbose(env, "In async callback the register R0 is not a known value (%s)\n",
c25b2ae1 9871 reg_type_str(env, reg->type));
bfc6bb74
AS
9872 return -EINVAL;
9873 }
9874
9875 if (!tnum_in(tnum_const(0), reg->var_off)) {
9876 verbose_invalid_scalar(env, reg, &range, "async callback", "R0");
9877 return -EINVAL;
9878 }
9879 return 0;
9880 }
9881
f782e2c3
DB
9882 if (is_subprog) {
9883 if (reg->type != SCALAR_VALUE) {
9884 verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
c25b2ae1 9885 reg_type_str(env, reg->type));
f782e2c3
DB
9886 return -EINVAL;
9887 }
9888 return 0;
9889 }
9890
7e40781c 9891 switch (prog_type) {
983695fa
DB
9892 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
9893 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
1b66d253
DB
9894 env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
9895 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
9896 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
9897 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
9898 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
983695fa 9899 range = tnum_range(1, 1);
77241217
SF
9900 if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
9901 env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
9902 range = tnum_range(0, 3);
ed4ed404 9903 break;
390ee7e2 9904 case BPF_PROG_TYPE_CGROUP_SKB:
5cf1e914 9905 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
9906 range = tnum_range(0, 3);
9907 enforce_attach_type_range = tnum_range(2, 3);
9908 }
ed4ed404 9909 break;
390ee7e2
AS
9910 case BPF_PROG_TYPE_CGROUP_SOCK:
9911 case BPF_PROG_TYPE_SOCK_OPS:
ebc614f6 9912 case BPF_PROG_TYPE_CGROUP_DEVICE:
7b146ceb 9913 case BPF_PROG_TYPE_CGROUP_SYSCTL:
0d01da6a 9914 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
390ee7e2 9915 break;
15ab09bd
AS
9916 case BPF_PROG_TYPE_RAW_TRACEPOINT:
9917 if (!env->prog->aux->attach_btf_id)
9918 return 0;
9919 range = tnum_const(0);
9920 break;
15d83c4d 9921 case BPF_PROG_TYPE_TRACING:
e92888c7
YS
9922 switch (env->prog->expected_attach_type) {
9923 case BPF_TRACE_FENTRY:
9924 case BPF_TRACE_FEXIT:
9925 range = tnum_const(0);
9926 break;
9927 case BPF_TRACE_RAW_TP:
9928 case BPF_MODIFY_RETURN:
15d83c4d 9929 return 0;
2ec0616e
DB
9930 case BPF_TRACE_ITER:
9931 break;
e92888c7
YS
9932 default:
9933 return -ENOTSUPP;
9934 }
15d83c4d 9935 break;
e9ddbb77
JS
9936 case BPF_PROG_TYPE_SK_LOOKUP:
9937 range = tnum_range(SK_DROP, SK_PASS);
9938 break;
e92888c7
YS
9939 case BPF_PROG_TYPE_EXT:
9940 /* freplace program can return anything as its return value
9941 * depends on the to-be-replaced kernel func or bpf program.
9942 */
390ee7e2
AS
9943 default:
9944 return 0;
9945 }
9946
390ee7e2 9947 if (reg->type != SCALAR_VALUE) {
61bd5218 9948 verbose(env, "At program exit the register R0 is not a known value (%s)\n",
c25b2ae1 9949 reg_type_str(env, reg->type));
390ee7e2
AS
9950 return -EINVAL;
9951 }
9952
9953 if (!tnum_in(range, reg->var_off)) {
bc2591d6 9954 verbose_invalid_scalar(env, reg, &range, "program exit", "R0");
390ee7e2
AS
9955 return -EINVAL;
9956 }
5cf1e914 9957
9958 if (!tnum_is_unknown(enforce_attach_type_range) &&
9959 tnum_in(enforce_attach_type_range, reg->var_off))
9960 env->prog->enforce_expected_attach_type = 1;
390ee7e2
AS
9961 return 0;
9962}
9963
475fb78f
AS
9964/* non-recursive DFS pseudo code
9965 * 1 procedure DFS-iterative(G,v):
9966 * 2 label v as discovered
9967 * 3 let S be a stack
9968 * 4 S.push(v)
9969 * 5 while S is not empty
9970 * 6 t <- S.pop()
9971 * 7 if t is what we're looking for:
9972 * 8 return t
9973 * 9 for all edges e in G.adjacentEdges(t) do
9974 * 10 if edge e is already labelled
9975 * 11 continue with the next edge
9976 * 12 w <- G.adjacentVertex(t,e)
9977 * 13 if vertex w is not discovered and not explored
9978 * 14 label e as tree-edge
9979 * 15 label w as discovered
9980 * 16 S.push(w)
9981 * 17 continue at 5
9982 * 18 else if vertex w is discovered
9983 * 19 label e as back-edge
9984 * 20 else
9985 * 21 // vertex w is explored
9986 * 22 label e as forward- or cross-edge
9987 * 23 label t as explored
9988 * 24 S.pop()
9989 *
9990 * convention:
9991 * 0x10 - discovered
9992 * 0x11 - discovered and fall-through edge labelled
9993 * 0x12 - discovered and fall-through and branch edges labelled
9994 * 0x20 - explored
9995 */
9996
9997enum {
9998 DISCOVERED = 0x10,
9999 EXPLORED = 0x20,
10000 FALLTHROUGH = 1,
10001 BRANCH = 2,
10002};
10003
dc2a4ebc
AS
10004static u32 state_htab_size(struct bpf_verifier_env *env)
10005{
10006 return env->prog->len;
10007}
10008
5d839021
AS
10009static struct bpf_verifier_state_list **explored_state(
10010 struct bpf_verifier_env *env,
10011 int idx)
10012{
dc2a4ebc
AS
10013 struct bpf_verifier_state *cur = env->cur_state;
10014 struct bpf_func_state *state = cur->frame[cur->curframe];
10015
10016 return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
5d839021
AS
10017}
10018
10019static void init_explored_state(struct bpf_verifier_env *env, int idx)
10020{
a8f500af 10021 env->insn_aux_data[idx].prune_point = true;
5d839021 10022}
f1bca824 10023
59e2e27d
WAF
10024enum {
10025 DONE_EXPLORING = 0,
10026 KEEP_EXPLORING = 1,
10027};
10028
475fb78f
AS
10029/* t, w, e - match pseudo-code above:
10030 * t - index of current instruction
10031 * w - next instruction
10032 * e - edge
10033 */
2589726d
AS
10034static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
10035 bool loop_ok)
475fb78f 10036{
7df737e9
AS
10037 int *insn_stack = env->cfg.insn_stack;
10038 int *insn_state = env->cfg.insn_state;
10039
475fb78f 10040 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
59e2e27d 10041 return DONE_EXPLORING;
475fb78f
AS
10042
10043 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
59e2e27d 10044 return DONE_EXPLORING;
475fb78f
AS
10045
10046 if (w < 0 || w >= env->prog->len) {
d9762e84 10047 verbose_linfo(env, t, "%d: ", t);
61bd5218 10048 verbose(env, "jump out of range from insn %d to %d\n", t, w);
475fb78f
AS
10049 return -EINVAL;
10050 }
10051
f1bca824
AS
10052 if (e == BRANCH)
10053 /* mark branch target for state pruning */
5d839021 10054 init_explored_state(env, w);
f1bca824 10055
475fb78f
AS
10056 if (insn_state[w] == 0) {
10057 /* tree-edge */
10058 insn_state[t] = DISCOVERED | e;
10059 insn_state[w] = DISCOVERED;
7df737e9 10060 if (env->cfg.cur_stack >= env->prog->len)
475fb78f 10061 return -E2BIG;
7df737e9 10062 insn_stack[env->cfg.cur_stack++] = w;
59e2e27d 10063 return KEEP_EXPLORING;
475fb78f 10064 } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
2c78ee89 10065 if (loop_ok && env->bpf_capable)
59e2e27d 10066 return DONE_EXPLORING;
d9762e84
MKL
10067 verbose_linfo(env, t, "%d: ", t);
10068 verbose_linfo(env, w, "%d: ", w);
61bd5218 10069 verbose(env, "back-edge from insn %d to %d\n", t, w);
475fb78f
AS
10070 return -EINVAL;
10071 } else if (insn_state[w] == EXPLORED) {
10072 /* forward- or cross-edge */
10073 insn_state[t] = DISCOVERED | e;
10074 } else {
61bd5218 10075 verbose(env, "insn state internal bug\n");
475fb78f
AS
10076 return -EFAULT;
10077 }
59e2e27d
WAF
10078 return DONE_EXPLORING;
10079}
10080
efdb22de
YS
10081static int visit_func_call_insn(int t, int insn_cnt,
10082 struct bpf_insn *insns,
10083 struct bpf_verifier_env *env,
10084 bool visit_callee)
10085{
10086 int ret;
10087
10088 ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
10089 if (ret)
10090 return ret;
10091
10092 if (t + 1 < insn_cnt)
10093 init_explored_state(env, t + 1);
10094 if (visit_callee) {
10095 init_explored_state(env, t);
86fc6ee6
AS
10096 ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env,
10097 /* It's ok to allow recursion from CFG point of
10098 * view. __check_func_call() will do the actual
10099 * check.
10100 */
10101 bpf_pseudo_func(insns + t));
efdb22de
YS
10102 }
10103 return ret;
10104}
10105
59e2e27d
WAF
10106/* Visits the instruction at index t and returns one of the following:
10107 * < 0 - an error occurred
10108 * DONE_EXPLORING - the instruction was fully explored
10109 * KEEP_EXPLORING - there is still work to be done before it is fully explored
10110 */
10111static int visit_insn(int t, int insn_cnt, struct bpf_verifier_env *env)
10112{
10113 struct bpf_insn *insns = env->prog->insnsi;
10114 int ret;
10115
69c087ba
YS
10116 if (bpf_pseudo_func(insns + t))
10117 return visit_func_call_insn(t, insn_cnt, insns, env, true);
10118
59e2e27d
WAF
10119 /* All non-branch instructions have a single fall-through edge. */
10120 if (BPF_CLASS(insns[t].code) != BPF_JMP &&
10121 BPF_CLASS(insns[t].code) != BPF_JMP32)
10122 return push_insn(t, t + 1, FALLTHROUGH, env, false);
10123
10124 switch (BPF_OP(insns[t].code)) {
10125 case BPF_EXIT:
10126 return DONE_EXPLORING;
10127
10128 case BPF_CALL:
bfc6bb74
AS
10129 if (insns[t].imm == BPF_FUNC_timer_set_callback)
10130 /* Mark this call insn to trigger is_state_visited() check
10131 * before call itself is processed by __check_func_call().
10132 * Otherwise new async state will be pushed for further
10133 * exploration.
10134 */
10135 init_explored_state(env, t);
efdb22de
YS
10136 return visit_func_call_insn(t, insn_cnt, insns, env,
10137 insns[t].src_reg == BPF_PSEUDO_CALL);
59e2e27d
WAF
10138
10139 case BPF_JA:
10140 if (BPF_SRC(insns[t].code) != BPF_K)
10141 return -EINVAL;
10142
10143 /* unconditional jump with single edge */
10144 ret = push_insn(t, t + insns[t].off + 1, FALLTHROUGH, env,
10145 true);
10146 if (ret)
10147 return ret;
10148
10149 /* unconditional jmp is not a good pruning point,
10150 * but it's marked, since backtracking needs
10151 * to record jmp history in is_state_visited().
10152 */
10153 init_explored_state(env, t + insns[t].off + 1);
10154 /* tell verifier to check for equivalent states
10155 * after every call and jump
10156 */
10157 if (t + 1 < insn_cnt)
10158 init_explored_state(env, t + 1);
10159
10160 return ret;
10161
10162 default:
10163 /* conditional jump with two edges */
10164 init_explored_state(env, t);
10165 ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
10166 if (ret)
10167 return ret;
10168
10169 return push_insn(t, t + insns[t].off + 1, BRANCH, env, true);
10170 }
475fb78f
AS
10171}
10172
10173/* non-recursive depth-first-search to detect loops in BPF program
10174 * loop == back-edge in directed graph
10175 */
58e2af8b 10176static int check_cfg(struct bpf_verifier_env *env)
475fb78f 10177{
475fb78f 10178 int insn_cnt = env->prog->len;
7df737e9 10179 int *insn_stack, *insn_state;
475fb78f 10180 int ret = 0;
59e2e27d 10181 int i;
475fb78f 10182
7df737e9 10183 insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
475fb78f
AS
10184 if (!insn_state)
10185 return -ENOMEM;
10186
7df737e9 10187 insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
475fb78f 10188 if (!insn_stack) {
71dde681 10189 kvfree(insn_state);
475fb78f
AS
10190 return -ENOMEM;
10191 }
10192
10193 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
10194 insn_stack[0] = 0; /* 0 is the first instruction */
7df737e9 10195 env->cfg.cur_stack = 1;
475fb78f 10196
59e2e27d
WAF
10197 while (env->cfg.cur_stack > 0) {
10198 int t = insn_stack[env->cfg.cur_stack - 1];
475fb78f 10199
59e2e27d
WAF
10200 ret = visit_insn(t, insn_cnt, env);
10201 switch (ret) {
10202 case DONE_EXPLORING:
10203 insn_state[t] = EXPLORED;
10204 env->cfg.cur_stack--;
10205 break;
10206 case KEEP_EXPLORING:
10207 break;
10208 default:
10209 if (ret > 0) {
10210 verbose(env, "visit_insn internal bug\n");
10211 ret = -EFAULT;
475fb78f 10212 }
475fb78f 10213 goto err_free;
59e2e27d 10214 }
475fb78f
AS
10215 }
10216
59e2e27d 10217 if (env->cfg.cur_stack < 0) {
61bd5218 10218 verbose(env, "pop stack internal bug\n");
475fb78f
AS
10219 ret = -EFAULT;
10220 goto err_free;
10221 }
475fb78f 10222
475fb78f
AS
10223 for (i = 0; i < insn_cnt; i++) {
10224 if (insn_state[i] != EXPLORED) {
61bd5218 10225 verbose(env, "unreachable insn %d\n", i);
475fb78f
AS
10226 ret = -EINVAL;
10227 goto err_free;
10228 }
10229 }
10230 ret = 0; /* cfg looks good */
10231
10232err_free:
71dde681
AS
10233 kvfree(insn_state);
10234 kvfree(insn_stack);
7df737e9 10235 env->cfg.insn_state = env->cfg.insn_stack = NULL;
475fb78f
AS
10236 return ret;
10237}
10238
09b28d76
AS
10239static int check_abnormal_return(struct bpf_verifier_env *env)
10240{
10241 int i;
10242
10243 for (i = 1; i < env->subprog_cnt; i++) {
10244 if (env->subprog_info[i].has_ld_abs) {
10245 verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
10246 return -EINVAL;
10247 }
10248 if (env->subprog_info[i].has_tail_call) {
10249 verbose(env, "tail_call is not allowed in subprogs without BTF\n");
10250 return -EINVAL;
10251 }
10252 }
10253 return 0;
10254}
10255
838e9690
YS
10256/* The minimum supported BTF func info size */
10257#define MIN_BPF_FUNCINFO_SIZE 8
10258#define MAX_FUNCINFO_REC_SIZE 252
10259
c454a46b
MKL
10260static int check_btf_func(struct bpf_verifier_env *env,
10261 const union bpf_attr *attr,
af2ac3e1 10262 bpfptr_t uattr)
838e9690 10263{
09b28d76 10264 const struct btf_type *type, *func_proto, *ret_type;
d0b2818e 10265 u32 i, nfuncs, urec_size, min_size;
838e9690 10266 u32 krec_size = sizeof(struct bpf_func_info);
c454a46b 10267 struct bpf_func_info *krecord;
8c1b6e69 10268 struct bpf_func_info_aux *info_aux = NULL;
c454a46b
MKL
10269 struct bpf_prog *prog;
10270 const struct btf *btf;
af2ac3e1 10271 bpfptr_t urecord;
d0b2818e 10272 u32 prev_offset = 0;
09b28d76 10273 bool scalar_return;
e7ed83d6 10274 int ret = -ENOMEM;
838e9690
YS
10275
10276 nfuncs = attr->func_info_cnt;
09b28d76
AS
10277 if (!nfuncs) {
10278 if (check_abnormal_return(env))
10279 return -EINVAL;
838e9690 10280 return 0;
09b28d76 10281 }
838e9690
YS
10282
10283 if (nfuncs != env->subprog_cnt) {
10284 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
10285 return -EINVAL;
10286 }
10287
10288 urec_size = attr->func_info_rec_size;
10289 if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
10290 urec_size > MAX_FUNCINFO_REC_SIZE ||
10291 urec_size % sizeof(u32)) {
10292 verbose(env, "invalid func info rec size %u\n", urec_size);
10293 return -EINVAL;
10294 }
10295
c454a46b
MKL
10296 prog = env->prog;
10297 btf = prog->aux->btf;
838e9690 10298
af2ac3e1 10299 urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
838e9690
YS
10300 min_size = min_t(u32, krec_size, urec_size);
10301
ba64e7d8 10302 krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
c454a46b
MKL
10303 if (!krecord)
10304 return -ENOMEM;
8c1b6e69
AS
10305 info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
10306 if (!info_aux)
10307 goto err_free;
ba64e7d8 10308
838e9690
YS
10309 for (i = 0; i < nfuncs; i++) {
10310 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
10311 if (ret) {
10312 if (ret == -E2BIG) {
10313 verbose(env, "nonzero tailing record in func info");
10314 /* set the size kernel expects so loader can zero
10315 * out the rest of the record.
10316 */
af2ac3e1
AS
10317 if (copy_to_bpfptr_offset(uattr,
10318 offsetof(union bpf_attr, func_info_rec_size),
10319 &min_size, sizeof(min_size)))
838e9690
YS
10320 ret = -EFAULT;
10321 }
c454a46b 10322 goto err_free;
838e9690
YS
10323 }
10324
af2ac3e1 10325 if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
838e9690 10326 ret = -EFAULT;
c454a46b 10327 goto err_free;
838e9690
YS
10328 }
10329
d30d42e0 10330 /* check insn_off */
09b28d76 10331 ret = -EINVAL;
838e9690 10332 if (i == 0) {
d30d42e0 10333 if (krecord[i].insn_off) {
838e9690 10334 verbose(env,
d30d42e0
MKL
10335 "nonzero insn_off %u for the first func info record",
10336 krecord[i].insn_off);
c454a46b 10337 goto err_free;
838e9690 10338 }
d30d42e0 10339 } else if (krecord[i].insn_off <= prev_offset) {
838e9690
YS
10340 verbose(env,
10341 "same or smaller insn offset (%u) than previous func info record (%u)",
d30d42e0 10342 krecord[i].insn_off, prev_offset);
c454a46b 10343 goto err_free;
838e9690
YS
10344 }
10345
d30d42e0 10346 if (env->subprog_info[i].start != krecord[i].insn_off) {
838e9690 10347 verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
c454a46b 10348 goto err_free;
838e9690
YS
10349 }
10350
10351 /* check type_id */
ba64e7d8 10352 type = btf_type_by_id(btf, krecord[i].type_id);
51c39bb1 10353 if (!type || !btf_type_is_func(type)) {
838e9690 10354 verbose(env, "invalid type id %d in func info",
ba64e7d8 10355 krecord[i].type_id);
c454a46b 10356 goto err_free;
838e9690 10357 }
51c39bb1 10358 info_aux[i].linkage = BTF_INFO_VLEN(type->info);
09b28d76
AS
10359
10360 func_proto = btf_type_by_id(btf, type->type);
10361 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
10362 /* btf_func_check() already verified it during BTF load */
10363 goto err_free;
10364 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
10365 scalar_return =
10366 btf_type_is_small_int(ret_type) || btf_type_is_enum(ret_type);
10367 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
10368 verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
10369 goto err_free;
10370 }
10371 if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
10372 verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
10373 goto err_free;
10374 }
10375
d30d42e0 10376 prev_offset = krecord[i].insn_off;
af2ac3e1 10377 bpfptr_add(&urecord, urec_size);
838e9690
YS
10378 }
10379
ba64e7d8
YS
10380 prog->aux->func_info = krecord;
10381 prog->aux->func_info_cnt = nfuncs;
8c1b6e69 10382 prog->aux->func_info_aux = info_aux;
838e9690
YS
10383 return 0;
10384
c454a46b 10385err_free:
ba64e7d8 10386 kvfree(krecord);
8c1b6e69 10387 kfree(info_aux);
838e9690
YS
10388 return ret;
10389}
10390
ba64e7d8
YS
10391static void adjust_btf_func(struct bpf_verifier_env *env)
10392{
8c1b6e69 10393 struct bpf_prog_aux *aux = env->prog->aux;
ba64e7d8
YS
10394 int i;
10395
8c1b6e69 10396 if (!aux->func_info)
ba64e7d8
YS
10397 return;
10398
10399 for (i = 0; i < env->subprog_cnt; i++)
8c1b6e69 10400 aux->func_info[i].insn_off = env->subprog_info[i].start;
ba64e7d8
YS
10401}
10402
1b773d00 10403#define MIN_BPF_LINEINFO_SIZE offsetofend(struct bpf_line_info, line_col)
c454a46b
MKL
10404#define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE
10405
10406static int check_btf_line(struct bpf_verifier_env *env,
10407 const union bpf_attr *attr,
af2ac3e1 10408 bpfptr_t uattr)
c454a46b
MKL
10409{
10410 u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
10411 struct bpf_subprog_info *sub;
10412 struct bpf_line_info *linfo;
10413 struct bpf_prog *prog;
10414 const struct btf *btf;
af2ac3e1 10415 bpfptr_t ulinfo;
c454a46b
MKL
10416 int err;
10417
10418 nr_linfo = attr->line_info_cnt;
10419 if (!nr_linfo)
10420 return 0;
0e6491b5
BC
10421 if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
10422 return -EINVAL;
c454a46b
MKL
10423
10424 rec_size = attr->line_info_rec_size;
10425 if (rec_size < MIN_BPF_LINEINFO_SIZE ||
10426 rec_size > MAX_LINEINFO_REC_SIZE ||
10427 rec_size & (sizeof(u32) - 1))
10428 return -EINVAL;
10429
10430 /* Need to zero it in case the userspace may
10431 * pass in a smaller bpf_line_info object.
10432 */
10433 linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
10434 GFP_KERNEL | __GFP_NOWARN);
10435 if (!linfo)
10436 return -ENOMEM;
10437
10438 prog = env->prog;
10439 btf = prog->aux->btf;
10440
10441 s = 0;
10442 sub = env->subprog_info;
af2ac3e1 10443 ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
c454a46b
MKL
10444 expected_size = sizeof(struct bpf_line_info);
10445 ncopy = min_t(u32, expected_size, rec_size);
10446 for (i = 0; i < nr_linfo; i++) {
10447 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
10448 if (err) {
10449 if (err == -E2BIG) {
10450 verbose(env, "nonzero tailing record in line_info");
af2ac3e1
AS
10451 if (copy_to_bpfptr_offset(uattr,
10452 offsetof(union bpf_attr, line_info_rec_size),
10453 &expected_size, sizeof(expected_size)))
c454a46b
MKL
10454 err = -EFAULT;
10455 }
10456 goto err_free;
10457 }
10458
af2ac3e1 10459 if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
c454a46b
MKL
10460 err = -EFAULT;
10461 goto err_free;
10462 }
10463
10464 /*
10465 * Check insn_off to ensure
10466 * 1) strictly increasing AND
10467 * 2) bounded by prog->len
10468 *
10469 * The linfo[0].insn_off == 0 check logically falls into
10470 * the later "missing bpf_line_info for func..." case
10471 * because the first linfo[0].insn_off must be the
10472 * first sub also and the first sub must have
10473 * subprog_info[0].start == 0.
10474 */
10475 if ((i && linfo[i].insn_off <= prev_offset) ||
10476 linfo[i].insn_off >= prog->len) {
10477 verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
10478 i, linfo[i].insn_off, prev_offset,
10479 prog->len);
10480 err = -EINVAL;
10481 goto err_free;
10482 }
10483
fdbaa0be
MKL
10484 if (!prog->insnsi[linfo[i].insn_off].code) {
10485 verbose(env,
10486 "Invalid insn code at line_info[%u].insn_off\n",
10487 i);
10488 err = -EINVAL;
10489 goto err_free;
10490 }
10491
23127b33
MKL
10492 if (!btf_name_by_offset(btf, linfo[i].line_off) ||
10493 !btf_name_by_offset(btf, linfo[i].file_name_off)) {
c454a46b
MKL
10494 verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
10495 err = -EINVAL;
10496 goto err_free;
10497 }
10498
10499 if (s != env->subprog_cnt) {
10500 if (linfo[i].insn_off == sub[s].start) {
10501 sub[s].linfo_idx = i;
10502 s++;
10503 } else if (sub[s].start < linfo[i].insn_off) {
10504 verbose(env, "missing bpf_line_info for func#%u\n", s);
10505 err = -EINVAL;
10506 goto err_free;
10507 }
10508 }
10509
10510 prev_offset = linfo[i].insn_off;
af2ac3e1 10511 bpfptr_add(&ulinfo, rec_size);
c454a46b
MKL
10512 }
10513
10514 if (s != env->subprog_cnt) {
10515 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
10516 env->subprog_cnt - s, s);
10517 err = -EINVAL;
10518 goto err_free;
10519 }
10520
10521 prog->aux->linfo = linfo;
10522 prog->aux->nr_linfo = nr_linfo;
10523
10524 return 0;
10525
10526err_free:
10527 kvfree(linfo);
10528 return err;
10529}
10530
fbd94c7a
AS
10531#define MIN_CORE_RELO_SIZE sizeof(struct bpf_core_relo)
10532#define MAX_CORE_RELO_SIZE MAX_FUNCINFO_REC_SIZE
10533
10534static int check_core_relo(struct bpf_verifier_env *env,
10535 const union bpf_attr *attr,
10536 bpfptr_t uattr)
10537{
10538 u32 i, nr_core_relo, ncopy, expected_size, rec_size;
10539 struct bpf_core_relo core_relo = {};
10540 struct bpf_prog *prog = env->prog;
10541 const struct btf *btf = prog->aux->btf;
10542 struct bpf_core_ctx ctx = {
10543 .log = &env->log,
10544 .btf = btf,
10545 };
10546 bpfptr_t u_core_relo;
10547 int err;
10548
10549 nr_core_relo = attr->core_relo_cnt;
10550 if (!nr_core_relo)
10551 return 0;
10552 if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo))
10553 return -EINVAL;
10554
10555 rec_size = attr->core_relo_rec_size;
10556 if (rec_size < MIN_CORE_RELO_SIZE ||
10557 rec_size > MAX_CORE_RELO_SIZE ||
10558 rec_size % sizeof(u32))
10559 return -EINVAL;
10560
10561 u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel);
10562 expected_size = sizeof(struct bpf_core_relo);
10563 ncopy = min_t(u32, expected_size, rec_size);
10564
10565 /* Unlike func_info and line_info, copy and apply each CO-RE
10566 * relocation record one at a time.
10567 */
10568 for (i = 0; i < nr_core_relo; i++) {
10569 /* future proofing when sizeof(bpf_core_relo) changes */
10570 err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size);
10571 if (err) {
10572 if (err == -E2BIG) {
10573 verbose(env, "nonzero tailing record in core_relo");
10574 if (copy_to_bpfptr_offset(uattr,
10575 offsetof(union bpf_attr, core_relo_rec_size),
10576 &expected_size, sizeof(expected_size)))
10577 err = -EFAULT;
10578 }
10579 break;
10580 }
10581
10582 if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) {
10583 err = -EFAULT;
10584 break;
10585 }
10586
10587 if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) {
10588 verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n",
10589 i, core_relo.insn_off, prog->len);
10590 err = -EINVAL;
10591 break;
10592 }
10593
10594 err = bpf_core_apply(&ctx, &core_relo, i,
10595 &prog->insnsi[core_relo.insn_off / 8]);
10596 if (err)
10597 break;
10598 bpfptr_add(&u_core_relo, rec_size);
10599 }
10600 return err;
10601}
10602
c454a46b
MKL
10603static int check_btf_info(struct bpf_verifier_env *env,
10604 const union bpf_attr *attr,
af2ac3e1 10605 bpfptr_t uattr)
c454a46b
MKL
10606{
10607 struct btf *btf;
10608 int err;
10609
09b28d76
AS
10610 if (!attr->func_info_cnt && !attr->line_info_cnt) {
10611 if (check_abnormal_return(env))
10612 return -EINVAL;
c454a46b 10613 return 0;
09b28d76 10614 }
c454a46b
MKL
10615
10616 btf = btf_get_by_fd(attr->prog_btf_fd);
10617 if (IS_ERR(btf))
10618 return PTR_ERR(btf);
350a5c4d
AS
10619 if (btf_is_kernel(btf)) {
10620 btf_put(btf);
10621 return -EACCES;
10622 }
c454a46b
MKL
10623 env->prog->aux->btf = btf;
10624
10625 err = check_btf_func(env, attr, uattr);
10626 if (err)
10627 return err;
10628
10629 err = check_btf_line(env, attr, uattr);
10630 if (err)
10631 return err;
10632
fbd94c7a
AS
10633 err = check_core_relo(env, attr, uattr);
10634 if (err)
10635 return err;
10636
c454a46b 10637 return 0;
ba64e7d8
YS
10638}
10639
f1174f77
EC
10640/* check %cur's range satisfies %old's */
10641static bool range_within(struct bpf_reg_state *old,
10642 struct bpf_reg_state *cur)
10643{
b03c9f9f
EC
10644 return old->umin_value <= cur->umin_value &&
10645 old->umax_value >= cur->umax_value &&
10646 old->smin_value <= cur->smin_value &&
fd675184
DB
10647 old->smax_value >= cur->smax_value &&
10648 old->u32_min_value <= cur->u32_min_value &&
10649 old->u32_max_value >= cur->u32_max_value &&
10650 old->s32_min_value <= cur->s32_min_value &&
10651 old->s32_max_value >= cur->s32_max_value;
f1174f77
EC
10652}
10653
f1174f77
EC
10654/* If in the old state two registers had the same id, then they need to have
10655 * the same id in the new state as well. But that id could be different from
10656 * the old state, so we need to track the mapping from old to new ids.
10657 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
10658 * regs with old id 5 must also have new id 9 for the new state to be safe. But
10659 * regs with a different old id could still have new id 9, we don't care about
10660 * that.
10661 * So we look through our idmap to see if this old id has been seen before. If
10662 * so, we require the new id to match; otherwise, we add the id pair to the map.
969bf05e 10663 */
c9e73e3d 10664static bool check_ids(u32 old_id, u32 cur_id, struct bpf_id_pair *idmap)
969bf05e 10665{
f1174f77 10666 unsigned int i;
969bf05e 10667
c9e73e3d 10668 for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
f1174f77
EC
10669 if (!idmap[i].old) {
10670 /* Reached an empty slot; haven't seen this id before */
10671 idmap[i].old = old_id;
10672 idmap[i].cur = cur_id;
10673 return true;
10674 }
10675 if (idmap[i].old == old_id)
10676 return idmap[i].cur == cur_id;
10677 }
10678 /* We ran out of idmap slots, which should be impossible */
10679 WARN_ON_ONCE(1);
10680 return false;
10681}
10682
9242b5f5
AS
10683static void clean_func_state(struct bpf_verifier_env *env,
10684 struct bpf_func_state *st)
10685{
10686 enum bpf_reg_liveness live;
10687 int i, j;
10688
10689 for (i = 0; i < BPF_REG_FP; i++) {
10690 live = st->regs[i].live;
10691 /* liveness must not touch this register anymore */
10692 st->regs[i].live |= REG_LIVE_DONE;
10693 if (!(live & REG_LIVE_READ))
10694 /* since the register is unused, clear its state
10695 * to make further comparison simpler
10696 */
f54c7898 10697 __mark_reg_not_init(env, &st->regs[i]);
9242b5f5
AS
10698 }
10699
10700 for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
10701 live = st->stack[i].spilled_ptr.live;
10702 /* liveness must not touch this stack slot anymore */
10703 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
10704 if (!(live & REG_LIVE_READ)) {
f54c7898 10705 __mark_reg_not_init(env, &st->stack[i].spilled_ptr);
9242b5f5
AS
10706 for (j = 0; j < BPF_REG_SIZE; j++)
10707 st->stack[i].slot_type[j] = STACK_INVALID;
10708 }
10709 }
10710}
10711
10712static void clean_verifier_state(struct bpf_verifier_env *env,
10713 struct bpf_verifier_state *st)
10714{
10715 int i;
10716
10717 if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
10718 /* all regs in this state in all frames were already marked */
10719 return;
10720
10721 for (i = 0; i <= st->curframe; i++)
10722 clean_func_state(env, st->frame[i]);
10723}
10724
10725/* the parentage chains form a tree.
10726 * the verifier states are added to state lists at given insn and
10727 * pushed into state stack for future exploration.
10728 * when the verifier reaches bpf_exit insn some of the verifer states
10729 * stored in the state lists have their final liveness state already,
10730 * but a lot of states will get revised from liveness point of view when
10731 * the verifier explores other branches.
10732 * Example:
10733 * 1: r0 = 1
10734 * 2: if r1 == 100 goto pc+1
10735 * 3: r0 = 2
10736 * 4: exit
10737 * when the verifier reaches exit insn the register r0 in the state list of
10738 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
10739 * of insn 2 and goes exploring further. At the insn 4 it will walk the
10740 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
10741 *
10742 * Since the verifier pushes the branch states as it sees them while exploring
10743 * the program the condition of walking the branch instruction for the second
10744 * time means that all states below this branch were already explored and
8fb33b60 10745 * their final liveness marks are already propagated.
9242b5f5
AS
10746 * Hence when the verifier completes the search of state list in is_state_visited()
10747 * we can call this clean_live_states() function to mark all liveness states
10748 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
10749 * will not be used.
10750 * This function also clears the registers and stack for states that !READ
10751 * to simplify state merging.
10752 *
10753 * Important note here that walking the same branch instruction in the callee
10754 * doesn't meant that the states are DONE. The verifier has to compare
10755 * the callsites
10756 */
10757static void clean_live_states(struct bpf_verifier_env *env, int insn,
10758 struct bpf_verifier_state *cur)
10759{
10760 struct bpf_verifier_state_list *sl;
10761 int i;
10762
5d839021 10763 sl = *explored_state(env, insn);
a8f500af 10764 while (sl) {
2589726d
AS
10765 if (sl->state.branches)
10766 goto next;
dc2a4ebc
AS
10767 if (sl->state.insn_idx != insn ||
10768 sl->state.curframe != cur->curframe)
9242b5f5
AS
10769 goto next;
10770 for (i = 0; i <= cur->curframe; i++)
10771 if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
10772 goto next;
10773 clean_verifier_state(env, &sl->state);
10774next:
10775 sl = sl->next;
10776 }
10777}
10778
f1174f77 10779/* Returns true if (rold safe implies rcur safe) */
e042aa53
DB
10780static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
10781 struct bpf_reg_state *rcur, struct bpf_id_pair *idmap)
f1174f77 10782{
f4d7e40a
AS
10783 bool equal;
10784
dc503a8a
EC
10785 if (!(rold->live & REG_LIVE_READ))
10786 /* explored state didn't use this */
10787 return true;
10788
679c782d 10789 equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, parent)) == 0;
f4d7e40a
AS
10790
10791 if (rold->type == PTR_TO_STACK)
10792 /* two stack pointers are equal only if they're pointing to
10793 * the same stack frame, since fp-8 in foo != fp-8 in bar
10794 */
10795 return equal && rold->frameno == rcur->frameno;
10796
10797 if (equal)
969bf05e
AS
10798 return true;
10799
f1174f77
EC
10800 if (rold->type == NOT_INIT)
10801 /* explored state can't have used this */
969bf05e 10802 return true;
f1174f77
EC
10803 if (rcur->type == NOT_INIT)
10804 return false;
c25b2ae1 10805 switch (base_type(rold->type)) {
f1174f77 10806 case SCALAR_VALUE:
e042aa53
DB
10807 if (env->explore_alu_limits)
10808 return false;
f1174f77 10809 if (rcur->type == SCALAR_VALUE) {
b5dc0163
AS
10810 if (!rold->precise && !rcur->precise)
10811 return true;
f1174f77
EC
10812 /* new val must satisfy old val knowledge */
10813 return range_within(rold, rcur) &&
10814 tnum_in(rold->var_off, rcur->var_off);
10815 } else {
179d1c56
JH
10816 /* We're trying to use a pointer in place of a scalar.
10817 * Even if the scalar was unbounded, this could lead to
10818 * pointer leaks because scalars are allowed to leak
10819 * while pointers are not. We could make this safe in
10820 * special cases if root is calling us, but it's
10821 * probably not worth the hassle.
f1174f77 10822 */
179d1c56 10823 return false;
f1174f77 10824 }
69c087ba 10825 case PTR_TO_MAP_KEY:
f1174f77 10826 case PTR_TO_MAP_VALUE:
c25b2ae1
HL
10827 /* a PTR_TO_MAP_VALUE could be safe to use as a
10828 * PTR_TO_MAP_VALUE_OR_NULL into the same map.
10829 * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
10830 * checked, doing so could have affected others with the same
10831 * id, and we can't check for that because we lost the id when
10832 * we converted to a PTR_TO_MAP_VALUE.
10833 */
10834 if (type_may_be_null(rold->type)) {
10835 if (!type_may_be_null(rcur->type))
10836 return false;
10837 if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
10838 return false;
10839 /* Check our ids match any regs they're supposed to */
10840 return check_ids(rold->id, rcur->id, idmap);
10841 }
10842
1b688a19
EC
10843 /* If the new min/max/var_off satisfy the old ones and
10844 * everything else matches, we are OK.
d83525ca
AS
10845 * 'id' is not compared, since it's only used for maps with
10846 * bpf_spin_lock inside map element and in such cases if
10847 * the rest of the prog is valid for one map element then
10848 * it's valid for all map elements regardless of the key
10849 * used in bpf_map_lookup()
1b688a19
EC
10850 */
10851 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
10852 range_within(rold, rcur) &&
10853 tnum_in(rold->var_off, rcur->var_off);
de8f3a83 10854 case PTR_TO_PACKET_META:
f1174f77 10855 case PTR_TO_PACKET:
de8f3a83 10856 if (rcur->type != rold->type)
f1174f77
EC
10857 return false;
10858 /* We must have at least as much range as the old ptr
10859 * did, so that any accesses which were safe before are
10860 * still safe. This is true even if old range < old off,
10861 * since someone could have accessed through (ptr - k), or
10862 * even done ptr -= k in a register, to get a safe access.
10863 */
10864 if (rold->range > rcur->range)
10865 return false;
10866 /* If the offsets don't match, we can't trust our alignment;
10867 * nor can we be sure that we won't fall out of range.
10868 */
10869 if (rold->off != rcur->off)
10870 return false;
10871 /* id relations must be preserved */
10872 if (rold->id && !check_ids(rold->id, rcur->id, idmap))
10873 return false;
10874 /* new val must satisfy old val knowledge */
10875 return range_within(rold, rcur) &&
10876 tnum_in(rold->var_off, rcur->var_off);
10877 case PTR_TO_CTX:
10878 case CONST_PTR_TO_MAP:
f1174f77 10879 case PTR_TO_PACKET_END:
d58e468b 10880 case PTR_TO_FLOW_KEYS:
c64b7983 10881 case PTR_TO_SOCKET:
46f8bc92 10882 case PTR_TO_SOCK_COMMON:
655a51e5 10883 case PTR_TO_TCP_SOCK:
fada7fdc 10884 case PTR_TO_XDP_SOCK:
f1174f77
EC
10885 /* Only valid matches are exact, which memcmp() above
10886 * would have accepted
10887 */
10888 default:
10889 /* Don't know what's going on, just say it's not safe */
10890 return false;
10891 }
969bf05e 10892
f1174f77
EC
10893 /* Shouldn't get here; if we do, say it's not safe */
10894 WARN_ON_ONCE(1);
969bf05e
AS
10895 return false;
10896}
10897
e042aa53
DB
10898static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
10899 struct bpf_func_state *cur, struct bpf_id_pair *idmap)
638f5b90
AS
10900{
10901 int i, spi;
10902
638f5b90
AS
10903 /* walk slots of the explored stack and ignore any additional
10904 * slots in the current stack, since explored(safe) state
10905 * didn't use them
10906 */
10907 for (i = 0; i < old->allocated_stack; i++) {
10908 spi = i / BPF_REG_SIZE;
10909
b233920c
AS
10910 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
10911 i += BPF_REG_SIZE - 1;
cc2b14d5 10912 /* explored state didn't use this */
fd05e57b 10913 continue;
b233920c 10914 }
cc2b14d5 10915
638f5b90
AS
10916 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
10917 continue;
19e2dbb7
AS
10918
10919 /* explored stack has more populated slots than current stack
10920 * and these slots were used
10921 */
10922 if (i >= cur->allocated_stack)
10923 return false;
10924
cc2b14d5
AS
10925 /* if old state was safe with misc data in the stack
10926 * it will be safe with zero-initialized stack.
10927 * The opposite is not true
10928 */
10929 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
10930 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
10931 continue;
638f5b90
AS
10932 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
10933 cur->stack[spi].slot_type[i % BPF_REG_SIZE])
10934 /* Ex: old explored (safe) state has STACK_SPILL in
b8c1a309 10935 * this stack slot, but current has STACK_MISC ->
638f5b90
AS
10936 * this verifier states are not equivalent,
10937 * return false to continue verification of this path
10938 */
10939 return false;
27113c59 10940 if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
638f5b90 10941 continue;
27113c59 10942 if (!is_spilled_reg(&old->stack[spi]))
638f5b90 10943 continue;
e042aa53
DB
10944 if (!regsafe(env, &old->stack[spi].spilled_ptr,
10945 &cur->stack[spi].spilled_ptr, idmap))
638f5b90
AS
10946 /* when explored and current stack slot are both storing
10947 * spilled registers, check that stored pointers types
10948 * are the same as well.
10949 * Ex: explored safe path could have stored
10950 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
10951 * but current path has stored:
10952 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
10953 * such verifier states are not equivalent.
10954 * return false to continue verification of this path
10955 */
10956 return false;
10957 }
10958 return true;
10959}
10960
fd978bf7
JS
10961static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur)
10962{
10963 if (old->acquired_refs != cur->acquired_refs)
10964 return false;
10965 return !memcmp(old->refs, cur->refs,
10966 sizeof(*old->refs) * old->acquired_refs);
10967}
10968
f1bca824
AS
10969/* compare two verifier states
10970 *
10971 * all states stored in state_list are known to be valid, since
10972 * verifier reached 'bpf_exit' instruction through them
10973 *
10974 * this function is called when verifier exploring different branches of
10975 * execution popped from the state stack. If it sees an old state that has
10976 * more strict register state and more strict stack state then this execution
10977 * branch doesn't need to be explored further, since verifier already
10978 * concluded that more strict state leads to valid finish.
10979 *
10980 * Therefore two states are equivalent if register state is more conservative
10981 * and explored stack state is more conservative than the current one.
10982 * Example:
10983 * explored current
10984 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
10985 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
10986 *
10987 * In other words if current stack state (one being explored) has more
10988 * valid slots than old one that already passed validation, it means
10989 * the verifier can stop exploring and conclude that current state is valid too
10990 *
10991 * Similarly with registers. If explored state has register type as invalid
10992 * whereas register type in current state is meaningful, it means that
10993 * the current state will reach 'bpf_exit' instruction safely
10994 */
c9e73e3d 10995static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
f4d7e40a 10996 struct bpf_func_state *cur)
f1bca824
AS
10997{
10998 int i;
10999
c9e73e3d
LB
11000 memset(env->idmap_scratch, 0, sizeof(env->idmap_scratch));
11001 for (i = 0; i < MAX_BPF_REG; i++)
e042aa53
DB
11002 if (!regsafe(env, &old->regs[i], &cur->regs[i],
11003 env->idmap_scratch))
c9e73e3d 11004 return false;
f1bca824 11005
e042aa53 11006 if (!stacksafe(env, old, cur, env->idmap_scratch))
c9e73e3d 11007 return false;
fd978bf7
JS
11008
11009 if (!refsafe(old, cur))
c9e73e3d
LB
11010 return false;
11011
11012 return true;
f1bca824
AS
11013}
11014
f4d7e40a
AS
11015static bool states_equal(struct bpf_verifier_env *env,
11016 struct bpf_verifier_state *old,
11017 struct bpf_verifier_state *cur)
11018{
11019 int i;
11020
11021 if (old->curframe != cur->curframe)
11022 return false;
11023
979d63d5
DB
11024 /* Verification state from speculative execution simulation
11025 * must never prune a non-speculative execution one.
11026 */
11027 if (old->speculative && !cur->speculative)
11028 return false;
11029
d83525ca
AS
11030 if (old->active_spin_lock != cur->active_spin_lock)
11031 return false;
11032
f4d7e40a
AS
11033 /* for states to be equal callsites have to be the same
11034 * and all frame states need to be equivalent
11035 */
11036 for (i = 0; i <= old->curframe; i++) {
11037 if (old->frame[i]->callsite != cur->frame[i]->callsite)
11038 return false;
c9e73e3d 11039 if (!func_states_equal(env, old->frame[i], cur->frame[i]))
f4d7e40a
AS
11040 return false;
11041 }
11042 return true;
11043}
11044
5327ed3d
JW
11045/* Return 0 if no propagation happened. Return negative error code if error
11046 * happened. Otherwise, return the propagated bit.
11047 */
55e7f3b5
JW
11048static int propagate_liveness_reg(struct bpf_verifier_env *env,
11049 struct bpf_reg_state *reg,
11050 struct bpf_reg_state *parent_reg)
11051{
5327ed3d
JW
11052 u8 parent_flag = parent_reg->live & REG_LIVE_READ;
11053 u8 flag = reg->live & REG_LIVE_READ;
55e7f3b5
JW
11054 int err;
11055
5327ed3d
JW
11056 /* When comes here, read flags of PARENT_REG or REG could be any of
11057 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
11058 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
11059 */
11060 if (parent_flag == REG_LIVE_READ64 ||
11061 /* Or if there is no read flag from REG. */
11062 !flag ||
11063 /* Or if the read flag from REG is the same as PARENT_REG. */
11064 parent_flag == flag)
55e7f3b5
JW
11065 return 0;
11066
5327ed3d 11067 err = mark_reg_read(env, reg, parent_reg, flag);
55e7f3b5
JW
11068 if (err)
11069 return err;
11070
5327ed3d 11071 return flag;
55e7f3b5
JW
11072}
11073
8e9cd9ce 11074/* A write screens off any subsequent reads; but write marks come from the
f4d7e40a
AS
11075 * straight-line code between a state and its parent. When we arrive at an
11076 * equivalent state (jump target or such) we didn't arrive by the straight-line
11077 * code, so read marks in the state must propagate to the parent regardless
11078 * of the state's write marks. That's what 'parent == state->parent' comparison
679c782d 11079 * in mark_reg_read() is for.
8e9cd9ce 11080 */
f4d7e40a
AS
11081static int propagate_liveness(struct bpf_verifier_env *env,
11082 const struct bpf_verifier_state *vstate,
11083 struct bpf_verifier_state *vparent)
dc503a8a 11084{
3f8cafa4 11085 struct bpf_reg_state *state_reg, *parent_reg;
f4d7e40a 11086 struct bpf_func_state *state, *parent;
3f8cafa4 11087 int i, frame, err = 0;
dc503a8a 11088
f4d7e40a
AS
11089 if (vparent->curframe != vstate->curframe) {
11090 WARN(1, "propagate_live: parent frame %d current frame %d\n",
11091 vparent->curframe, vstate->curframe);
11092 return -EFAULT;
11093 }
dc503a8a
EC
11094 /* Propagate read liveness of registers... */
11095 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
83d16312 11096 for (frame = 0; frame <= vstate->curframe; frame++) {
3f8cafa4
JW
11097 parent = vparent->frame[frame];
11098 state = vstate->frame[frame];
11099 parent_reg = parent->regs;
11100 state_reg = state->regs;
83d16312
JK
11101 /* We don't need to worry about FP liveness, it's read-only */
11102 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
55e7f3b5
JW
11103 err = propagate_liveness_reg(env, &state_reg[i],
11104 &parent_reg[i]);
5327ed3d 11105 if (err < 0)
3f8cafa4 11106 return err;
5327ed3d
JW
11107 if (err == REG_LIVE_READ64)
11108 mark_insn_zext(env, &parent_reg[i]);
dc503a8a 11109 }
f4d7e40a 11110
1b04aee7 11111 /* Propagate stack slots. */
f4d7e40a
AS
11112 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
11113 i < parent->allocated_stack / BPF_REG_SIZE; i++) {
3f8cafa4
JW
11114 parent_reg = &parent->stack[i].spilled_ptr;
11115 state_reg = &state->stack[i].spilled_ptr;
55e7f3b5
JW
11116 err = propagate_liveness_reg(env, state_reg,
11117 parent_reg);
5327ed3d 11118 if (err < 0)
3f8cafa4 11119 return err;
dc503a8a
EC
11120 }
11121 }
5327ed3d 11122 return 0;
dc503a8a
EC
11123}
11124
a3ce685d
AS
11125/* find precise scalars in the previous equivalent state and
11126 * propagate them into the current state
11127 */
11128static int propagate_precision(struct bpf_verifier_env *env,
11129 const struct bpf_verifier_state *old)
11130{
11131 struct bpf_reg_state *state_reg;
11132 struct bpf_func_state *state;
11133 int i, err = 0;
11134
11135 state = old->frame[old->curframe];
11136 state_reg = state->regs;
11137 for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
11138 if (state_reg->type != SCALAR_VALUE ||
11139 !state_reg->precise)
11140 continue;
11141 if (env->log.level & BPF_LOG_LEVEL2)
11142 verbose(env, "propagating r%d\n", i);
11143 err = mark_chain_precision(env, i);
11144 if (err < 0)
11145 return err;
11146 }
11147
11148 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
27113c59 11149 if (!is_spilled_reg(&state->stack[i]))
a3ce685d
AS
11150 continue;
11151 state_reg = &state->stack[i].spilled_ptr;
11152 if (state_reg->type != SCALAR_VALUE ||
11153 !state_reg->precise)
11154 continue;
11155 if (env->log.level & BPF_LOG_LEVEL2)
11156 verbose(env, "propagating fp%d\n",
11157 (-i - 1) * BPF_REG_SIZE);
11158 err = mark_chain_precision_stack(env, i);
11159 if (err < 0)
11160 return err;
11161 }
11162 return 0;
11163}
11164
2589726d
AS
11165static bool states_maybe_looping(struct bpf_verifier_state *old,
11166 struct bpf_verifier_state *cur)
11167{
11168 struct bpf_func_state *fold, *fcur;
11169 int i, fr = cur->curframe;
11170
11171 if (old->curframe != fr)
11172 return false;
11173
11174 fold = old->frame[fr];
11175 fcur = cur->frame[fr];
11176 for (i = 0; i < MAX_BPF_REG; i++)
11177 if (memcmp(&fold->regs[i], &fcur->regs[i],
11178 offsetof(struct bpf_reg_state, parent)))
11179 return false;
11180 return true;
11181}
11182
11183
58e2af8b 11184static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
f1bca824 11185{
58e2af8b 11186 struct bpf_verifier_state_list *new_sl;
9f4686c4 11187 struct bpf_verifier_state_list *sl, **pprev;
679c782d 11188 struct bpf_verifier_state *cur = env->cur_state, *new;
ceefbc96 11189 int i, j, err, states_cnt = 0;
10d274e8 11190 bool add_new_state = env->test_state_freq ? true : false;
f1bca824 11191
b5dc0163 11192 cur->last_insn_idx = env->prev_insn_idx;
a8f500af 11193 if (!env->insn_aux_data[insn_idx].prune_point)
f1bca824
AS
11194 /* this 'insn_idx' instruction wasn't marked, so we will not
11195 * be doing state search here
11196 */
11197 return 0;
11198
2589726d
AS
11199 /* bpf progs typically have pruning point every 4 instructions
11200 * http://vger.kernel.org/bpfconf2019.html#session-1
11201 * Do not add new state for future pruning if the verifier hasn't seen
11202 * at least 2 jumps and at least 8 instructions.
11203 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
11204 * In tests that amounts to up to 50% reduction into total verifier
11205 * memory consumption and 20% verifier time speedup.
11206 */
11207 if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
11208 env->insn_processed - env->prev_insn_processed >= 8)
11209 add_new_state = true;
11210
a8f500af
AS
11211 pprev = explored_state(env, insn_idx);
11212 sl = *pprev;
11213
9242b5f5
AS
11214 clean_live_states(env, insn_idx, cur);
11215
a8f500af 11216 while (sl) {
dc2a4ebc
AS
11217 states_cnt++;
11218 if (sl->state.insn_idx != insn_idx)
11219 goto next;
bfc6bb74 11220
2589726d 11221 if (sl->state.branches) {
bfc6bb74
AS
11222 struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
11223
11224 if (frame->in_async_callback_fn &&
11225 frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
11226 /* Different async_entry_cnt means that the verifier is
11227 * processing another entry into async callback.
11228 * Seeing the same state is not an indication of infinite
11229 * loop or infinite recursion.
11230 * But finding the same state doesn't mean that it's safe
11231 * to stop processing the current state. The previous state
11232 * hasn't yet reached bpf_exit, since state.branches > 0.
11233 * Checking in_async_callback_fn alone is not enough either.
11234 * Since the verifier still needs to catch infinite loops
11235 * inside async callbacks.
11236 */
11237 } else if (states_maybe_looping(&sl->state, cur) &&
11238 states_equal(env, &sl->state, cur)) {
2589726d
AS
11239 verbose_linfo(env, insn_idx, "; ");
11240 verbose(env, "infinite loop detected at insn %d\n", insn_idx);
11241 return -EINVAL;
11242 }
11243 /* if the verifier is processing a loop, avoid adding new state
11244 * too often, since different loop iterations have distinct
11245 * states and may not help future pruning.
11246 * This threshold shouldn't be too low to make sure that
11247 * a loop with large bound will be rejected quickly.
11248 * The most abusive loop will be:
11249 * r1 += 1
11250 * if r1 < 1000000 goto pc-2
11251 * 1M insn_procssed limit / 100 == 10k peak states.
11252 * This threshold shouldn't be too high either, since states
11253 * at the end of the loop are likely to be useful in pruning.
11254 */
11255 if (env->jmps_processed - env->prev_jmps_processed < 20 &&
11256 env->insn_processed - env->prev_insn_processed < 100)
11257 add_new_state = false;
11258 goto miss;
11259 }
638f5b90 11260 if (states_equal(env, &sl->state, cur)) {
9f4686c4 11261 sl->hit_cnt++;
f1bca824 11262 /* reached equivalent register/stack state,
dc503a8a
EC
11263 * prune the search.
11264 * Registers read by the continuation are read by us.
8e9cd9ce
EC
11265 * If we have any write marks in env->cur_state, they
11266 * will prevent corresponding reads in the continuation
11267 * from reaching our parent (an explored_state). Our
11268 * own state will get the read marks recorded, but
11269 * they'll be immediately forgotten as we're pruning
11270 * this state and will pop a new one.
f1bca824 11271 */
f4d7e40a 11272 err = propagate_liveness(env, &sl->state, cur);
a3ce685d
AS
11273
11274 /* if previous state reached the exit with precision and
11275 * current state is equivalent to it (except precsion marks)
11276 * the precision needs to be propagated back in
11277 * the current state.
11278 */
11279 err = err ? : push_jmp_history(env, cur);
11280 err = err ? : propagate_precision(env, &sl->state);
f4d7e40a
AS
11281 if (err)
11282 return err;
f1bca824 11283 return 1;
dc503a8a 11284 }
2589726d
AS
11285miss:
11286 /* when new state is not going to be added do not increase miss count.
11287 * Otherwise several loop iterations will remove the state
11288 * recorded earlier. The goal of these heuristics is to have
11289 * states from some iterations of the loop (some in the beginning
11290 * and some at the end) to help pruning.
11291 */
11292 if (add_new_state)
11293 sl->miss_cnt++;
9f4686c4
AS
11294 /* heuristic to determine whether this state is beneficial
11295 * to keep checking from state equivalence point of view.
11296 * Higher numbers increase max_states_per_insn and verification time,
11297 * but do not meaningfully decrease insn_processed.
11298 */
11299 if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
11300 /* the state is unlikely to be useful. Remove it to
11301 * speed up verification
11302 */
11303 *pprev = sl->next;
11304 if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
2589726d
AS
11305 u32 br = sl->state.branches;
11306
11307 WARN_ONCE(br,
11308 "BUG live_done but branches_to_explore %d\n",
11309 br);
9f4686c4
AS
11310 free_verifier_state(&sl->state, false);
11311 kfree(sl);
11312 env->peak_states--;
11313 } else {
11314 /* cannot free this state, since parentage chain may
11315 * walk it later. Add it for free_list instead to
11316 * be freed at the end of verification
11317 */
11318 sl->next = env->free_list;
11319 env->free_list = sl;
11320 }
11321 sl = *pprev;
11322 continue;
11323 }
dc2a4ebc 11324next:
9f4686c4
AS
11325 pprev = &sl->next;
11326 sl = *pprev;
f1bca824
AS
11327 }
11328
06ee7115
AS
11329 if (env->max_states_per_insn < states_cnt)
11330 env->max_states_per_insn = states_cnt;
11331
2c78ee89 11332 if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
b5dc0163 11333 return push_jmp_history(env, cur);
ceefbc96 11334
2589726d 11335 if (!add_new_state)
b5dc0163 11336 return push_jmp_history(env, cur);
ceefbc96 11337
2589726d
AS
11338 /* There were no equivalent states, remember the current one.
11339 * Technically the current state is not proven to be safe yet,
f4d7e40a 11340 * but it will either reach outer most bpf_exit (which means it's safe)
2589726d 11341 * or it will be rejected. When there are no loops the verifier won't be
f4d7e40a 11342 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
2589726d
AS
11343 * again on the way to bpf_exit.
11344 * When looping the sl->state.branches will be > 0 and this state
11345 * will not be considered for equivalence until branches == 0.
f1bca824 11346 */
638f5b90 11347 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
f1bca824
AS
11348 if (!new_sl)
11349 return -ENOMEM;
06ee7115
AS
11350 env->total_states++;
11351 env->peak_states++;
2589726d
AS
11352 env->prev_jmps_processed = env->jmps_processed;
11353 env->prev_insn_processed = env->insn_processed;
f1bca824
AS
11354
11355 /* add new state to the head of linked list */
679c782d
EC
11356 new = &new_sl->state;
11357 err = copy_verifier_state(new, cur);
1969db47 11358 if (err) {
679c782d 11359 free_verifier_state(new, false);
1969db47
AS
11360 kfree(new_sl);
11361 return err;
11362 }
dc2a4ebc 11363 new->insn_idx = insn_idx;
2589726d
AS
11364 WARN_ONCE(new->branches != 1,
11365 "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
b5dc0163 11366
2589726d 11367 cur->parent = new;
b5dc0163
AS
11368 cur->first_insn_idx = insn_idx;
11369 clear_jmp_history(cur);
5d839021
AS
11370 new_sl->next = *explored_state(env, insn_idx);
11371 *explored_state(env, insn_idx) = new_sl;
7640ead9
JK
11372 /* connect new state to parentage chain. Current frame needs all
11373 * registers connected. Only r6 - r9 of the callers are alive (pushed
11374 * to the stack implicitly by JITs) so in callers' frames connect just
11375 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
11376 * the state of the call instruction (with WRITTEN set), and r0 comes
11377 * from callee with its full parentage chain, anyway.
11378 */
8e9cd9ce
EC
11379 /* clear write marks in current state: the writes we did are not writes
11380 * our child did, so they don't screen off its reads from us.
11381 * (There are no read marks in current state, because reads always mark
11382 * their parent and current state never has children yet. Only
11383 * explored_states can get read marks.)
11384 */
eea1c227
AS
11385 for (j = 0; j <= cur->curframe; j++) {
11386 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
11387 cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
11388 for (i = 0; i < BPF_REG_FP; i++)
11389 cur->frame[j]->regs[i].live = REG_LIVE_NONE;
11390 }
f4d7e40a
AS
11391
11392 /* all stack frames are accessible from callee, clear them all */
11393 for (j = 0; j <= cur->curframe; j++) {
11394 struct bpf_func_state *frame = cur->frame[j];
679c782d 11395 struct bpf_func_state *newframe = new->frame[j];
f4d7e40a 11396
679c782d 11397 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
cc2b14d5 11398 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
679c782d
EC
11399 frame->stack[i].spilled_ptr.parent =
11400 &newframe->stack[i].spilled_ptr;
11401 }
f4d7e40a 11402 }
f1bca824
AS
11403 return 0;
11404}
11405
c64b7983
JS
11406/* Return true if it's OK to have the same insn return a different type. */
11407static bool reg_type_mismatch_ok(enum bpf_reg_type type)
11408{
c25b2ae1 11409 switch (base_type(type)) {
c64b7983
JS
11410 case PTR_TO_CTX:
11411 case PTR_TO_SOCKET:
46f8bc92 11412 case PTR_TO_SOCK_COMMON:
655a51e5 11413 case PTR_TO_TCP_SOCK:
fada7fdc 11414 case PTR_TO_XDP_SOCK:
2a02759e 11415 case PTR_TO_BTF_ID:
c64b7983
JS
11416 return false;
11417 default:
11418 return true;
11419 }
11420}
11421
11422/* If an instruction was previously used with particular pointer types, then we
11423 * need to be careful to avoid cases such as the below, where it may be ok
11424 * for one branch accessing the pointer, but not ok for the other branch:
11425 *
11426 * R1 = sock_ptr
11427 * goto X;
11428 * ...
11429 * R1 = some_other_valid_ptr;
11430 * goto X;
11431 * ...
11432 * R2 = *(u32 *)(R1 + 0);
11433 */
11434static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
11435{
11436 return src != prev && (!reg_type_mismatch_ok(src) ||
11437 !reg_type_mismatch_ok(prev));
11438}
11439
58e2af8b 11440static int do_check(struct bpf_verifier_env *env)
17a52670 11441{
6f8a57cc 11442 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
51c39bb1 11443 struct bpf_verifier_state *state = env->cur_state;
17a52670 11444 struct bpf_insn *insns = env->prog->insnsi;
638f5b90 11445 struct bpf_reg_state *regs;
06ee7115 11446 int insn_cnt = env->prog->len;
17a52670 11447 bool do_print_state = false;
b5dc0163 11448 int prev_insn_idx = -1;
17a52670 11449
17a52670
AS
11450 for (;;) {
11451 struct bpf_insn *insn;
11452 u8 class;
11453 int err;
11454
b5dc0163 11455 env->prev_insn_idx = prev_insn_idx;
c08435ec 11456 if (env->insn_idx >= insn_cnt) {
61bd5218 11457 verbose(env, "invalid insn idx %d insn_cnt %d\n",
c08435ec 11458 env->insn_idx, insn_cnt);
17a52670
AS
11459 return -EFAULT;
11460 }
11461
c08435ec 11462 insn = &insns[env->insn_idx];
17a52670
AS
11463 class = BPF_CLASS(insn->code);
11464
06ee7115 11465 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
61bd5218
JK
11466 verbose(env,
11467 "BPF program is too large. Processed %d insn\n",
06ee7115 11468 env->insn_processed);
17a52670
AS
11469 return -E2BIG;
11470 }
11471
c08435ec 11472 err = is_state_visited(env, env->insn_idx);
f1bca824
AS
11473 if (err < 0)
11474 return err;
11475 if (err == 1) {
11476 /* found equivalent state, can prune the search */
06ee7115 11477 if (env->log.level & BPF_LOG_LEVEL) {
f1bca824 11478 if (do_print_state)
979d63d5
DB
11479 verbose(env, "\nfrom %d to %d%s: safe\n",
11480 env->prev_insn_idx, env->insn_idx,
11481 env->cur_state->speculative ?
11482 " (speculative execution)" : "");
f1bca824 11483 else
c08435ec 11484 verbose(env, "%d: safe\n", env->insn_idx);
f1bca824
AS
11485 }
11486 goto process_bpf_exit;
11487 }
11488
c3494801
AS
11489 if (signal_pending(current))
11490 return -EAGAIN;
11491
3c2ce60b
DB
11492 if (need_resched())
11493 cond_resched();
11494
2e576648
CL
11495 if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
11496 verbose(env, "\nfrom %d to %d%s:",
11497 env->prev_insn_idx, env->insn_idx,
11498 env->cur_state->speculative ?
11499 " (speculative execution)" : "");
11500 print_verifier_state(env, state->frame[state->curframe], true);
17a52670
AS
11501 do_print_state = false;
11502 }
11503
06ee7115 11504 if (env->log.level & BPF_LOG_LEVEL) {
7105e828 11505 const struct bpf_insn_cbs cbs = {
e6ac2450 11506 .cb_call = disasm_kfunc_name,
7105e828 11507 .cb_print = verbose,
abe08840 11508 .private_data = env,
7105e828
DB
11509 };
11510
2e576648
CL
11511 if (verifier_state_scratched(env))
11512 print_insn_state(env, state->frame[state->curframe]);
11513
c08435ec 11514 verbose_linfo(env, env->insn_idx, "; ");
2e576648 11515 env->prev_log_len = env->log.len_used;
c08435ec 11516 verbose(env, "%d: ", env->insn_idx);
abe08840 11517 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
2e576648
CL
11518 env->prev_insn_print_len = env->log.len_used - env->prev_log_len;
11519 env->prev_log_len = env->log.len_used;
17a52670
AS
11520 }
11521
cae1927c 11522 if (bpf_prog_is_dev_bound(env->prog->aux)) {
c08435ec
DB
11523 err = bpf_prog_offload_verify_insn(env, env->insn_idx,
11524 env->prev_insn_idx);
cae1927c
JK
11525 if (err)
11526 return err;
11527 }
13a27dfc 11528
638f5b90 11529 regs = cur_regs(env);
fe9a5ca7 11530 sanitize_mark_insn_seen(env);
b5dc0163 11531 prev_insn_idx = env->insn_idx;
fd978bf7 11532
17a52670 11533 if (class == BPF_ALU || class == BPF_ALU64) {
1be7f75d 11534 err = check_alu_op(env, insn);
17a52670
AS
11535 if (err)
11536 return err;
11537
11538 } else if (class == BPF_LDX) {
3df126f3 11539 enum bpf_reg_type *prev_src_type, src_reg_type;
9bac3d6d
AS
11540
11541 /* check for reserved fields is already done */
11542
17a52670 11543 /* check src operand */
dc503a8a 11544 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17a52670
AS
11545 if (err)
11546 return err;
11547
dc503a8a 11548 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
17a52670
AS
11549 if (err)
11550 return err;
11551
725f9dcd
AS
11552 src_reg_type = regs[insn->src_reg].type;
11553
17a52670
AS
11554 /* check that memory (src_reg + off) is readable,
11555 * the state of dst_reg will be updated by this func
11556 */
c08435ec
DB
11557 err = check_mem_access(env, env->insn_idx, insn->src_reg,
11558 insn->off, BPF_SIZE(insn->code),
11559 BPF_READ, insn->dst_reg, false);
17a52670
AS
11560 if (err)
11561 return err;
11562
c08435ec 11563 prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type;
3df126f3
JK
11564
11565 if (*prev_src_type == NOT_INIT) {
9bac3d6d
AS
11566 /* saw a valid insn
11567 * dst_reg = *(u32 *)(src_reg + off)
3df126f3 11568 * save type to validate intersecting paths
9bac3d6d 11569 */
3df126f3 11570 *prev_src_type = src_reg_type;
9bac3d6d 11571
c64b7983 11572 } else if (reg_type_mismatch(src_reg_type, *prev_src_type)) {
9bac3d6d
AS
11573 /* ABuser program is trying to use the same insn
11574 * dst_reg = *(u32*) (src_reg + off)
11575 * with different pointer types:
11576 * src_reg == ctx in one branch and
11577 * src_reg == stack|map in some other branch.
11578 * Reject it.
11579 */
61bd5218 11580 verbose(env, "same insn cannot be used with different pointers\n");
9bac3d6d
AS
11581 return -EINVAL;
11582 }
11583
17a52670 11584 } else if (class == BPF_STX) {
3df126f3 11585 enum bpf_reg_type *prev_dst_type, dst_reg_type;
d691f9e8 11586
91c960b0
BJ
11587 if (BPF_MODE(insn->code) == BPF_ATOMIC) {
11588 err = check_atomic(env, env->insn_idx, insn);
17a52670
AS
11589 if (err)
11590 return err;
c08435ec 11591 env->insn_idx++;
17a52670
AS
11592 continue;
11593 }
11594
5ca419f2
BJ
11595 if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
11596 verbose(env, "BPF_STX uses reserved fields\n");
11597 return -EINVAL;
11598 }
11599
17a52670 11600 /* check src1 operand */
dc503a8a 11601 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17a52670
AS
11602 if (err)
11603 return err;
11604 /* check src2 operand */
dc503a8a 11605 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17a52670
AS
11606 if (err)
11607 return err;
11608
d691f9e8
AS
11609 dst_reg_type = regs[insn->dst_reg].type;
11610
17a52670 11611 /* check that memory (dst_reg + off) is writeable */
c08435ec
DB
11612 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
11613 insn->off, BPF_SIZE(insn->code),
11614 BPF_WRITE, insn->src_reg, false);
17a52670
AS
11615 if (err)
11616 return err;
11617
c08435ec 11618 prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type;
3df126f3
JK
11619
11620 if (*prev_dst_type == NOT_INIT) {
11621 *prev_dst_type = dst_reg_type;
c64b7983 11622 } else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) {
61bd5218 11623 verbose(env, "same insn cannot be used with different pointers\n");
d691f9e8
AS
11624 return -EINVAL;
11625 }
11626
17a52670
AS
11627 } else if (class == BPF_ST) {
11628 if (BPF_MODE(insn->code) != BPF_MEM ||
11629 insn->src_reg != BPF_REG_0) {
61bd5218 11630 verbose(env, "BPF_ST uses reserved fields\n");
17a52670
AS
11631 return -EINVAL;
11632 }
11633 /* check src operand */
dc503a8a 11634 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17a52670
AS
11635 if (err)
11636 return err;
11637
f37a8cb8 11638 if (is_ctx_reg(env, insn->dst_reg)) {
9d2be44a 11639 verbose(env, "BPF_ST stores into R%d %s is not allowed\n",
2a159c6f 11640 insn->dst_reg,
c25b2ae1 11641 reg_type_str(env, reg_state(env, insn->dst_reg)->type));
f37a8cb8
DB
11642 return -EACCES;
11643 }
11644
17a52670 11645 /* check that memory (dst_reg + off) is writeable */
c08435ec
DB
11646 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
11647 insn->off, BPF_SIZE(insn->code),
11648 BPF_WRITE, -1, false);
17a52670
AS
11649 if (err)
11650 return err;
11651
092ed096 11652 } else if (class == BPF_JMP || class == BPF_JMP32) {
17a52670
AS
11653 u8 opcode = BPF_OP(insn->code);
11654
2589726d 11655 env->jmps_processed++;
17a52670
AS
11656 if (opcode == BPF_CALL) {
11657 if (BPF_SRC(insn->code) != BPF_K ||
2357672c
KKD
11658 (insn->src_reg != BPF_PSEUDO_KFUNC_CALL
11659 && insn->off != 0) ||
f4d7e40a 11660 (insn->src_reg != BPF_REG_0 &&
e6ac2450
MKL
11661 insn->src_reg != BPF_PSEUDO_CALL &&
11662 insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
092ed096
JW
11663 insn->dst_reg != BPF_REG_0 ||
11664 class == BPF_JMP32) {
61bd5218 11665 verbose(env, "BPF_CALL uses reserved fields\n");
17a52670
AS
11666 return -EINVAL;
11667 }
11668
d83525ca
AS
11669 if (env->cur_state->active_spin_lock &&
11670 (insn->src_reg == BPF_PSEUDO_CALL ||
11671 insn->imm != BPF_FUNC_spin_unlock)) {
11672 verbose(env, "function calls are not allowed while holding a lock\n");
11673 return -EINVAL;
11674 }
f4d7e40a 11675 if (insn->src_reg == BPF_PSEUDO_CALL)
c08435ec 11676 err = check_func_call(env, insn, &env->insn_idx);
e6ac2450 11677 else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL)
5c073f26 11678 err = check_kfunc_call(env, insn, &env->insn_idx);
f4d7e40a 11679 else
69c087ba 11680 err = check_helper_call(env, insn, &env->insn_idx);
17a52670
AS
11681 if (err)
11682 return err;
17a52670
AS
11683 } else if (opcode == BPF_JA) {
11684 if (BPF_SRC(insn->code) != BPF_K ||
11685 insn->imm != 0 ||
11686 insn->src_reg != BPF_REG_0 ||
092ed096
JW
11687 insn->dst_reg != BPF_REG_0 ||
11688 class == BPF_JMP32) {
61bd5218 11689 verbose(env, "BPF_JA uses reserved fields\n");
17a52670
AS
11690 return -EINVAL;
11691 }
11692
c08435ec 11693 env->insn_idx += insn->off + 1;
17a52670
AS
11694 continue;
11695
11696 } else if (opcode == BPF_EXIT) {
11697 if (BPF_SRC(insn->code) != BPF_K ||
11698 insn->imm != 0 ||
11699 insn->src_reg != BPF_REG_0 ||
092ed096
JW
11700 insn->dst_reg != BPF_REG_0 ||
11701 class == BPF_JMP32) {
61bd5218 11702 verbose(env, "BPF_EXIT uses reserved fields\n");
17a52670
AS
11703 return -EINVAL;
11704 }
11705
d83525ca
AS
11706 if (env->cur_state->active_spin_lock) {
11707 verbose(env, "bpf_spin_unlock is missing\n");
11708 return -EINVAL;
11709 }
11710
f4d7e40a
AS
11711 if (state->curframe) {
11712 /* exit from nested function */
c08435ec 11713 err = prepare_func_exit(env, &env->insn_idx);
f4d7e40a
AS
11714 if (err)
11715 return err;
11716 do_print_state = true;
11717 continue;
11718 }
11719
fd978bf7
JS
11720 err = check_reference_leak(env);
11721 if (err)
11722 return err;
11723
390ee7e2
AS
11724 err = check_return_code(env);
11725 if (err)
11726 return err;
f1bca824 11727process_bpf_exit:
0f55f9ed 11728 mark_verifier_state_scratched(env);
2589726d 11729 update_branch_counts(env, env->cur_state);
b5dc0163 11730 err = pop_stack(env, &prev_insn_idx,
6f8a57cc 11731 &env->insn_idx, pop_log);
638f5b90
AS
11732 if (err < 0) {
11733 if (err != -ENOENT)
11734 return err;
17a52670
AS
11735 break;
11736 } else {
11737 do_print_state = true;
11738 continue;
11739 }
11740 } else {
c08435ec 11741 err = check_cond_jmp_op(env, insn, &env->insn_idx);
17a52670
AS
11742 if (err)
11743 return err;
11744 }
11745 } else if (class == BPF_LD) {
11746 u8 mode = BPF_MODE(insn->code);
11747
11748 if (mode == BPF_ABS || mode == BPF_IND) {
ddd872bc
AS
11749 err = check_ld_abs(env, insn);
11750 if (err)
11751 return err;
11752
17a52670
AS
11753 } else if (mode == BPF_IMM) {
11754 err = check_ld_imm(env, insn);
11755 if (err)
11756 return err;
11757
c08435ec 11758 env->insn_idx++;
fe9a5ca7 11759 sanitize_mark_insn_seen(env);
17a52670 11760 } else {
61bd5218 11761 verbose(env, "invalid BPF_LD mode\n");
17a52670
AS
11762 return -EINVAL;
11763 }
11764 } else {
61bd5218 11765 verbose(env, "unknown insn class %d\n", class);
17a52670
AS
11766 return -EINVAL;
11767 }
11768
c08435ec 11769 env->insn_idx++;
17a52670
AS
11770 }
11771
11772 return 0;
11773}
11774
541c3bad
AN
11775static int find_btf_percpu_datasec(struct btf *btf)
11776{
11777 const struct btf_type *t;
11778 const char *tname;
11779 int i, n;
11780
11781 /*
11782 * Both vmlinux and module each have their own ".data..percpu"
11783 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
11784 * types to look at only module's own BTF types.
11785 */
11786 n = btf_nr_types(btf);
11787 if (btf_is_module(btf))
11788 i = btf_nr_types(btf_vmlinux);
11789 else
11790 i = 1;
11791
11792 for(; i < n; i++) {
11793 t = btf_type_by_id(btf, i);
11794 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
11795 continue;
11796
11797 tname = btf_name_by_offset(btf, t->name_off);
11798 if (!strcmp(tname, ".data..percpu"))
11799 return i;
11800 }
11801
11802 return -ENOENT;
11803}
11804
4976b718
HL
11805/* replace pseudo btf_id with kernel symbol address */
11806static int check_pseudo_btf_id(struct bpf_verifier_env *env,
11807 struct bpf_insn *insn,
11808 struct bpf_insn_aux_data *aux)
11809{
eaa6bcb7
HL
11810 const struct btf_var_secinfo *vsi;
11811 const struct btf_type *datasec;
541c3bad 11812 struct btf_mod_pair *btf_mod;
4976b718
HL
11813 const struct btf_type *t;
11814 const char *sym_name;
eaa6bcb7 11815 bool percpu = false;
f16e6313 11816 u32 type, id = insn->imm;
541c3bad 11817 struct btf *btf;
f16e6313 11818 s32 datasec_id;
4976b718 11819 u64 addr;
541c3bad 11820 int i, btf_fd, err;
4976b718 11821
541c3bad
AN
11822 btf_fd = insn[1].imm;
11823 if (btf_fd) {
11824 btf = btf_get_by_fd(btf_fd);
11825 if (IS_ERR(btf)) {
11826 verbose(env, "invalid module BTF object FD specified.\n");
11827 return -EINVAL;
11828 }
11829 } else {
11830 if (!btf_vmlinux) {
11831 verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
11832 return -EINVAL;
11833 }
11834 btf = btf_vmlinux;
11835 btf_get(btf);
4976b718
HL
11836 }
11837
541c3bad 11838 t = btf_type_by_id(btf, id);
4976b718
HL
11839 if (!t) {
11840 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
541c3bad
AN
11841 err = -ENOENT;
11842 goto err_put;
4976b718
HL
11843 }
11844
11845 if (!btf_type_is_var(t)) {
541c3bad
AN
11846 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR.\n", id);
11847 err = -EINVAL;
11848 goto err_put;
4976b718
HL
11849 }
11850
541c3bad 11851 sym_name = btf_name_by_offset(btf, t->name_off);
4976b718
HL
11852 addr = kallsyms_lookup_name(sym_name);
11853 if (!addr) {
11854 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
11855 sym_name);
541c3bad
AN
11856 err = -ENOENT;
11857 goto err_put;
4976b718
HL
11858 }
11859
541c3bad 11860 datasec_id = find_btf_percpu_datasec(btf);
eaa6bcb7 11861 if (datasec_id > 0) {
541c3bad 11862 datasec = btf_type_by_id(btf, datasec_id);
eaa6bcb7
HL
11863 for_each_vsi(i, datasec, vsi) {
11864 if (vsi->type == id) {
11865 percpu = true;
11866 break;
11867 }
11868 }
11869 }
11870
4976b718
HL
11871 insn[0].imm = (u32)addr;
11872 insn[1].imm = addr >> 32;
11873
11874 type = t->type;
541c3bad 11875 t = btf_type_skip_modifiers(btf, type, NULL);
eaa6bcb7 11876 if (percpu) {
5844101a 11877 aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
541c3bad 11878 aux->btf_var.btf = btf;
eaa6bcb7
HL
11879 aux->btf_var.btf_id = type;
11880 } else if (!btf_type_is_struct(t)) {
4976b718
HL
11881 const struct btf_type *ret;
11882 const char *tname;
11883 u32 tsize;
11884
11885 /* resolve the type size of ksym. */
541c3bad 11886 ret = btf_resolve_size(btf, t, &tsize);
4976b718 11887 if (IS_ERR(ret)) {
541c3bad 11888 tname = btf_name_by_offset(btf, t->name_off);
4976b718
HL
11889 verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
11890 tname, PTR_ERR(ret));
541c3bad
AN
11891 err = -EINVAL;
11892 goto err_put;
4976b718 11893 }
34d3a78c 11894 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
4976b718
HL
11895 aux->btf_var.mem_size = tsize;
11896 } else {
11897 aux->btf_var.reg_type = PTR_TO_BTF_ID;
541c3bad 11898 aux->btf_var.btf = btf;
4976b718
HL
11899 aux->btf_var.btf_id = type;
11900 }
541c3bad
AN
11901
11902 /* check whether we recorded this BTF (and maybe module) already */
11903 for (i = 0; i < env->used_btf_cnt; i++) {
11904 if (env->used_btfs[i].btf == btf) {
11905 btf_put(btf);
11906 return 0;
11907 }
11908 }
11909
11910 if (env->used_btf_cnt >= MAX_USED_BTFS) {
11911 err = -E2BIG;
11912 goto err_put;
11913 }
11914
11915 btf_mod = &env->used_btfs[env->used_btf_cnt];
11916 btf_mod->btf = btf;
11917 btf_mod->module = NULL;
11918
11919 /* if we reference variables from kernel module, bump its refcount */
11920 if (btf_is_module(btf)) {
11921 btf_mod->module = btf_try_get_module(btf);
11922 if (!btf_mod->module) {
11923 err = -ENXIO;
11924 goto err_put;
11925 }
11926 }
11927
11928 env->used_btf_cnt++;
11929
4976b718 11930 return 0;
541c3bad
AN
11931err_put:
11932 btf_put(btf);
11933 return err;
4976b718
HL
11934}
11935
56f668df
MKL
11936static int check_map_prealloc(struct bpf_map *map)
11937{
11938 return (map->map_type != BPF_MAP_TYPE_HASH &&
bcc6b1b7
MKL
11939 map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
11940 map->map_type != BPF_MAP_TYPE_HASH_OF_MAPS) ||
56f668df
MKL
11941 !(map->map_flags & BPF_F_NO_PREALLOC);
11942}
11943
d83525ca
AS
11944static bool is_tracing_prog_type(enum bpf_prog_type type)
11945{
11946 switch (type) {
11947 case BPF_PROG_TYPE_KPROBE:
11948 case BPF_PROG_TYPE_TRACEPOINT:
11949 case BPF_PROG_TYPE_PERF_EVENT:
11950 case BPF_PROG_TYPE_RAW_TRACEPOINT:
11951 return true;
11952 default:
11953 return false;
11954 }
11955}
11956
94dacdbd
TG
11957static bool is_preallocated_map(struct bpf_map *map)
11958{
11959 if (!check_map_prealloc(map))
11960 return false;
11961 if (map->inner_map_meta && !check_map_prealloc(map->inner_map_meta))
11962 return false;
11963 return true;
11964}
11965
61bd5218
JK
11966static int check_map_prog_compatibility(struct bpf_verifier_env *env,
11967 struct bpf_map *map,
fdc15d38
AS
11968 struct bpf_prog *prog)
11969
11970{
7e40781c 11971 enum bpf_prog_type prog_type = resolve_prog_type(prog);
94dacdbd
TG
11972 /*
11973 * Validate that trace type programs use preallocated hash maps.
11974 *
11975 * For programs attached to PERF events this is mandatory as the
11976 * perf NMI can hit any arbitrary code sequence.
11977 *
11978 * All other trace types using preallocated hash maps are unsafe as
11979 * well because tracepoint or kprobes can be inside locked regions
11980 * of the memory allocator or at a place where a recursion into the
11981 * memory allocator would see inconsistent state.
11982 *
2ed905c5
TG
11983 * On RT enabled kernels run-time allocation of all trace type
11984 * programs is strictly prohibited due to lock type constraints. On
11985 * !RT kernels it is allowed for backwards compatibility reasons for
11986 * now, but warnings are emitted so developers are made aware of
11987 * the unsafety and can fix their programs before this is enforced.
56f668df 11988 */
7e40781c
UP
11989 if (is_tracing_prog_type(prog_type) && !is_preallocated_map(map)) {
11990 if (prog_type == BPF_PROG_TYPE_PERF_EVENT) {
61bd5218 11991 verbose(env, "perf_event programs can only use preallocated hash map\n");
56f668df
MKL
11992 return -EINVAL;
11993 }
2ed905c5
TG
11994 if (IS_ENABLED(CONFIG_PREEMPT_RT)) {
11995 verbose(env, "trace type programs can only use preallocated hash map\n");
11996 return -EINVAL;
11997 }
94dacdbd
TG
11998 WARN_ONCE(1, "trace type BPF program uses run-time allocation\n");
11999 verbose(env, "trace type programs with run-time allocated hash maps are unsafe. Switch to preallocated hash maps.\n");
fdc15d38 12000 }
a3884572 12001
9e7a4d98
KS
12002 if (map_value_has_spin_lock(map)) {
12003 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
12004 verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
12005 return -EINVAL;
12006 }
12007
12008 if (is_tracing_prog_type(prog_type)) {
12009 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
12010 return -EINVAL;
12011 }
12012
12013 if (prog->aux->sleepable) {
12014 verbose(env, "sleepable progs cannot use bpf_spin_lock yet\n");
12015 return -EINVAL;
12016 }
d83525ca
AS
12017 }
12018
5e0bc308
DB
12019 if (map_value_has_timer(map)) {
12020 if (is_tracing_prog_type(prog_type)) {
12021 verbose(env, "tracing progs cannot use bpf_timer yet\n");
12022 return -EINVAL;
12023 }
12024 }
12025
a3884572 12026 if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) &&
09728266 12027 !bpf_offload_prog_map_match(prog, map)) {
a3884572
JK
12028 verbose(env, "offload device mismatch between prog and map\n");
12029 return -EINVAL;
12030 }
12031
85d33df3
MKL
12032 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
12033 verbose(env, "bpf_struct_ops map cannot be used in prog\n");
12034 return -EINVAL;
12035 }
12036
1e6c62a8
AS
12037 if (prog->aux->sleepable)
12038 switch (map->map_type) {
12039 case BPF_MAP_TYPE_HASH:
12040 case BPF_MAP_TYPE_LRU_HASH:
12041 case BPF_MAP_TYPE_ARRAY:
638e4b82
AS
12042 case BPF_MAP_TYPE_PERCPU_HASH:
12043 case BPF_MAP_TYPE_PERCPU_ARRAY:
12044 case BPF_MAP_TYPE_LRU_PERCPU_HASH:
12045 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
12046 case BPF_MAP_TYPE_HASH_OF_MAPS:
1e6c62a8
AS
12047 if (!is_preallocated_map(map)) {
12048 verbose(env,
638e4b82 12049 "Sleepable programs can only use preallocated maps\n");
1e6c62a8
AS
12050 return -EINVAL;
12051 }
12052 break;
ba90c2cc 12053 case BPF_MAP_TYPE_RINGBUF:
0fe4b381
KS
12054 case BPF_MAP_TYPE_INODE_STORAGE:
12055 case BPF_MAP_TYPE_SK_STORAGE:
12056 case BPF_MAP_TYPE_TASK_STORAGE:
ba90c2cc 12057 break;
1e6c62a8
AS
12058 default:
12059 verbose(env,
ba90c2cc 12060 "Sleepable programs can only use array, hash, and ringbuf maps\n");
1e6c62a8
AS
12061 return -EINVAL;
12062 }
12063
fdc15d38
AS
12064 return 0;
12065}
12066
b741f163
RG
12067static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
12068{
12069 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
12070 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
12071}
12072
4976b718
HL
12073/* find and rewrite pseudo imm in ld_imm64 instructions:
12074 *
12075 * 1. if it accesses map FD, replace it with actual map pointer.
12076 * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
12077 *
12078 * NOTE: btf_vmlinux is required for converting pseudo btf_id.
0246e64d 12079 */
4976b718 12080static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
0246e64d
AS
12081{
12082 struct bpf_insn *insn = env->prog->insnsi;
12083 int insn_cnt = env->prog->len;
fdc15d38 12084 int i, j, err;
0246e64d 12085
f1f7714e 12086 err = bpf_prog_calc_tag(env->prog);
aafe6ae9
DB
12087 if (err)
12088 return err;
12089
0246e64d 12090 for (i = 0; i < insn_cnt; i++, insn++) {
9bac3d6d 12091 if (BPF_CLASS(insn->code) == BPF_LDX &&
d691f9e8 12092 (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
61bd5218 12093 verbose(env, "BPF_LDX uses reserved fields\n");
d691f9e8
AS
12094 return -EINVAL;
12095 }
12096
0246e64d 12097 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
d8eca5bb 12098 struct bpf_insn_aux_data *aux;
0246e64d
AS
12099 struct bpf_map *map;
12100 struct fd f;
d8eca5bb 12101 u64 addr;
387544bf 12102 u32 fd;
0246e64d
AS
12103
12104 if (i == insn_cnt - 1 || insn[1].code != 0 ||
12105 insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
12106 insn[1].off != 0) {
61bd5218 12107 verbose(env, "invalid bpf_ld_imm64 insn\n");
0246e64d
AS
12108 return -EINVAL;
12109 }
12110
d8eca5bb 12111 if (insn[0].src_reg == 0)
0246e64d
AS
12112 /* valid generic load 64-bit imm */
12113 goto next_insn;
12114
4976b718
HL
12115 if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
12116 aux = &env->insn_aux_data[i];
12117 err = check_pseudo_btf_id(env, insn, aux);
12118 if (err)
12119 return err;
12120 goto next_insn;
12121 }
12122
69c087ba
YS
12123 if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
12124 aux = &env->insn_aux_data[i];
12125 aux->ptr_type = PTR_TO_FUNC;
12126 goto next_insn;
12127 }
12128
d8eca5bb
DB
12129 /* In final convert_pseudo_ld_imm64() step, this is
12130 * converted into regular 64-bit imm load insn.
12131 */
387544bf
AS
12132 switch (insn[0].src_reg) {
12133 case BPF_PSEUDO_MAP_VALUE:
12134 case BPF_PSEUDO_MAP_IDX_VALUE:
12135 break;
12136 case BPF_PSEUDO_MAP_FD:
12137 case BPF_PSEUDO_MAP_IDX:
12138 if (insn[1].imm == 0)
12139 break;
12140 fallthrough;
12141 default:
12142 verbose(env, "unrecognized bpf_ld_imm64 insn\n");
0246e64d
AS
12143 return -EINVAL;
12144 }
12145
387544bf
AS
12146 switch (insn[0].src_reg) {
12147 case BPF_PSEUDO_MAP_IDX_VALUE:
12148 case BPF_PSEUDO_MAP_IDX:
12149 if (bpfptr_is_null(env->fd_array)) {
12150 verbose(env, "fd_idx without fd_array is invalid\n");
12151 return -EPROTO;
12152 }
12153 if (copy_from_bpfptr_offset(&fd, env->fd_array,
12154 insn[0].imm * sizeof(fd),
12155 sizeof(fd)))
12156 return -EFAULT;
12157 break;
12158 default:
12159 fd = insn[0].imm;
12160 break;
12161 }
12162
12163 f = fdget(fd);
c2101297 12164 map = __bpf_map_get(f);
0246e64d 12165 if (IS_ERR(map)) {
61bd5218 12166 verbose(env, "fd %d is not pointing to valid bpf_map\n",
20182390 12167 insn[0].imm);
0246e64d
AS
12168 return PTR_ERR(map);
12169 }
12170
61bd5218 12171 err = check_map_prog_compatibility(env, map, env->prog);
fdc15d38
AS
12172 if (err) {
12173 fdput(f);
12174 return err;
12175 }
12176
d8eca5bb 12177 aux = &env->insn_aux_data[i];
387544bf
AS
12178 if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
12179 insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
d8eca5bb
DB
12180 addr = (unsigned long)map;
12181 } else {
12182 u32 off = insn[1].imm;
12183
12184 if (off >= BPF_MAX_VAR_OFF) {
12185 verbose(env, "direct value offset of %u is not allowed\n", off);
12186 fdput(f);
12187 return -EINVAL;
12188 }
12189
12190 if (!map->ops->map_direct_value_addr) {
12191 verbose(env, "no direct value access support for this map type\n");
12192 fdput(f);
12193 return -EINVAL;
12194 }
12195
12196 err = map->ops->map_direct_value_addr(map, &addr, off);
12197 if (err) {
12198 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
12199 map->value_size, off);
12200 fdput(f);
12201 return err;
12202 }
12203
12204 aux->map_off = off;
12205 addr += off;
12206 }
12207
12208 insn[0].imm = (u32)addr;
12209 insn[1].imm = addr >> 32;
0246e64d
AS
12210
12211 /* check whether we recorded this map already */
d8eca5bb 12212 for (j = 0; j < env->used_map_cnt; j++) {
0246e64d 12213 if (env->used_maps[j] == map) {
d8eca5bb 12214 aux->map_index = j;
0246e64d
AS
12215 fdput(f);
12216 goto next_insn;
12217 }
d8eca5bb 12218 }
0246e64d
AS
12219
12220 if (env->used_map_cnt >= MAX_USED_MAPS) {
12221 fdput(f);
12222 return -E2BIG;
12223 }
12224
0246e64d
AS
12225 /* hold the map. If the program is rejected by verifier,
12226 * the map will be released by release_maps() or it
12227 * will be used by the valid program until it's unloaded
ab7f5bf0 12228 * and all maps are released in free_used_maps()
0246e64d 12229 */
1e0bd5a0 12230 bpf_map_inc(map);
d8eca5bb
DB
12231
12232 aux->map_index = env->used_map_cnt;
92117d84
AS
12233 env->used_maps[env->used_map_cnt++] = map;
12234
b741f163 12235 if (bpf_map_is_cgroup_storage(map) &&
e4730423 12236 bpf_cgroup_storage_assign(env->prog->aux, map)) {
b741f163 12237 verbose(env, "only one cgroup storage of each type is allowed\n");
de9cbbaa
RG
12238 fdput(f);
12239 return -EBUSY;
12240 }
12241
0246e64d
AS
12242 fdput(f);
12243next_insn:
12244 insn++;
12245 i++;
5e581dad
DB
12246 continue;
12247 }
12248
12249 /* Basic sanity check before we invest more work here. */
12250 if (!bpf_opcode_in_insntable(insn->code)) {
12251 verbose(env, "unknown opcode %02x\n", insn->code);
12252 return -EINVAL;
0246e64d
AS
12253 }
12254 }
12255
12256 /* now all pseudo BPF_LD_IMM64 instructions load valid
12257 * 'struct bpf_map *' into a register instead of user map_fd.
12258 * These pointers will be used later by verifier to validate map access.
12259 */
12260 return 0;
12261}
12262
12263/* drop refcnt of maps used by the rejected program */
58e2af8b 12264static void release_maps(struct bpf_verifier_env *env)
0246e64d 12265{
a2ea0746
DB
12266 __bpf_free_used_maps(env->prog->aux, env->used_maps,
12267 env->used_map_cnt);
0246e64d
AS
12268}
12269
541c3bad
AN
12270/* drop refcnt of maps used by the rejected program */
12271static void release_btfs(struct bpf_verifier_env *env)
12272{
12273 __bpf_free_used_btfs(env->prog->aux, env->used_btfs,
12274 env->used_btf_cnt);
12275}
12276
0246e64d 12277/* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
58e2af8b 12278static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
0246e64d
AS
12279{
12280 struct bpf_insn *insn = env->prog->insnsi;
12281 int insn_cnt = env->prog->len;
12282 int i;
12283
69c087ba
YS
12284 for (i = 0; i < insn_cnt; i++, insn++) {
12285 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
12286 continue;
12287 if (insn->src_reg == BPF_PSEUDO_FUNC)
12288 continue;
12289 insn->src_reg = 0;
12290 }
0246e64d
AS
12291}
12292
8041902d
AS
12293/* single env->prog->insni[off] instruction was replaced with the range
12294 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying
12295 * [0, off) and [off, end) to new locations, so the patched range stays zero
12296 */
75f0fc7b
HF
12297static void adjust_insn_aux_data(struct bpf_verifier_env *env,
12298 struct bpf_insn_aux_data *new_data,
12299 struct bpf_prog *new_prog, u32 off, u32 cnt)
8041902d 12300{
75f0fc7b 12301 struct bpf_insn_aux_data *old_data = env->insn_aux_data;
b325fbca 12302 struct bpf_insn *insn = new_prog->insnsi;
d203b0fd 12303 u32 old_seen = old_data[off].seen;
b325fbca 12304 u32 prog_len;
c131187d 12305 int i;
8041902d 12306
b325fbca
JW
12307 /* aux info at OFF always needs adjustment, no matter fast path
12308 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
12309 * original insn at old prog.
12310 */
12311 old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
12312
8041902d 12313 if (cnt == 1)
75f0fc7b 12314 return;
b325fbca 12315 prog_len = new_prog->len;
75f0fc7b 12316
8041902d
AS
12317 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
12318 memcpy(new_data + off + cnt - 1, old_data + off,
12319 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
b325fbca 12320 for (i = off; i < off + cnt - 1; i++) {
d203b0fd
DB
12321 /* Expand insni[off]'s seen count to the patched range. */
12322 new_data[i].seen = old_seen;
b325fbca
JW
12323 new_data[i].zext_dst = insn_has_def32(env, insn + i);
12324 }
8041902d
AS
12325 env->insn_aux_data = new_data;
12326 vfree(old_data);
8041902d
AS
12327}
12328
cc8b0b92
AS
12329static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
12330{
12331 int i;
12332
12333 if (len == 1)
12334 return;
4cb3d99c
JW
12335 /* NOTE: fake 'exit' subprog should be updated as well. */
12336 for (i = 0; i <= env->subprog_cnt; i++) {
afd59424 12337 if (env->subprog_info[i].start <= off)
cc8b0b92 12338 continue;
9c8105bd 12339 env->subprog_info[i].start += len - 1;
cc8b0b92
AS
12340 }
12341}
12342
7506d211 12343static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
a748c697
MF
12344{
12345 struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
12346 int i, sz = prog->aux->size_poke_tab;
12347 struct bpf_jit_poke_descriptor *desc;
12348
12349 for (i = 0; i < sz; i++) {
12350 desc = &tab[i];
7506d211
JF
12351 if (desc->insn_idx <= off)
12352 continue;
a748c697
MF
12353 desc->insn_idx += len - 1;
12354 }
12355}
12356
8041902d
AS
12357static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
12358 const struct bpf_insn *patch, u32 len)
12359{
12360 struct bpf_prog *new_prog;
75f0fc7b
HF
12361 struct bpf_insn_aux_data *new_data = NULL;
12362
12363 if (len > 1) {
12364 new_data = vzalloc(array_size(env->prog->len + len - 1,
12365 sizeof(struct bpf_insn_aux_data)));
12366 if (!new_data)
12367 return NULL;
12368 }
8041902d
AS
12369
12370 new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
4f73379e
AS
12371 if (IS_ERR(new_prog)) {
12372 if (PTR_ERR(new_prog) == -ERANGE)
12373 verbose(env,
12374 "insn %d cannot be patched due to 16-bit range\n",
12375 env->insn_aux_data[off].orig_idx);
75f0fc7b 12376 vfree(new_data);
8041902d 12377 return NULL;
4f73379e 12378 }
75f0fc7b 12379 adjust_insn_aux_data(env, new_data, new_prog, off, len);
cc8b0b92 12380 adjust_subprog_starts(env, off, len);
7506d211 12381 adjust_poke_descs(new_prog, off, len);
8041902d
AS
12382 return new_prog;
12383}
12384
52875a04
JK
12385static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
12386 u32 off, u32 cnt)
12387{
12388 int i, j;
12389
12390 /* find first prog starting at or after off (first to remove) */
12391 for (i = 0; i < env->subprog_cnt; i++)
12392 if (env->subprog_info[i].start >= off)
12393 break;
12394 /* find first prog starting at or after off + cnt (first to stay) */
12395 for (j = i; j < env->subprog_cnt; j++)
12396 if (env->subprog_info[j].start >= off + cnt)
12397 break;
12398 /* if j doesn't start exactly at off + cnt, we are just removing
12399 * the front of previous prog
12400 */
12401 if (env->subprog_info[j].start != off + cnt)
12402 j--;
12403
12404 if (j > i) {
12405 struct bpf_prog_aux *aux = env->prog->aux;
12406 int move;
12407
12408 /* move fake 'exit' subprog as well */
12409 move = env->subprog_cnt + 1 - j;
12410
12411 memmove(env->subprog_info + i,
12412 env->subprog_info + j,
12413 sizeof(*env->subprog_info) * move);
12414 env->subprog_cnt -= j - i;
12415
12416 /* remove func_info */
12417 if (aux->func_info) {
12418 move = aux->func_info_cnt - j;
12419
12420 memmove(aux->func_info + i,
12421 aux->func_info + j,
12422 sizeof(*aux->func_info) * move);
12423 aux->func_info_cnt -= j - i;
12424 /* func_info->insn_off is set after all code rewrites,
12425 * in adjust_btf_func() - no need to adjust
12426 */
12427 }
12428 } else {
12429 /* convert i from "first prog to remove" to "first to adjust" */
12430 if (env->subprog_info[i].start == off)
12431 i++;
12432 }
12433
12434 /* update fake 'exit' subprog as well */
12435 for (; i <= env->subprog_cnt; i++)
12436 env->subprog_info[i].start -= cnt;
12437
12438 return 0;
12439}
12440
12441static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
12442 u32 cnt)
12443{
12444 struct bpf_prog *prog = env->prog;
12445 u32 i, l_off, l_cnt, nr_linfo;
12446 struct bpf_line_info *linfo;
12447
12448 nr_linfo = prog->aux->nr_linfo;
12449 if (!nr_linfo)
12450 return 0;
12451
12452 linfo = prog->aux->linfo;
12453
12454 /* find first line info to remove, count lines to be removed */
12455 for (i = 0; i < nr_linfo; i++)
12456 if (linfo[i].insn_off >= off)
12457 break;
12458
12459 l_off = i;
12460 l_cnt = 0;
12461 for (; i < nr_linfo; i++)
12462 if (linfo[i].insn_off < off + cnt)
12463 l_cnt++;
12464 else
12465 break;
12466
12467 /* First live insn doesn't match first live linfo, it needs to "inherit"
12468 * last removed linfo. prog is already modified, so prog->len == off
12469 * means no live instructions after (tail of the program was removed).
12470 */
12471 if (prog->len != off && l_cnt &&
12472 (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
12473 l_cnt--;
12474 linfo[--i].insn_off = off + cnt;
12475 }
12476
12477 /* remove the line info which refer to the removed instructions */
12478 if (l_cnt) {
12479 memmove(linfo + l_off, linfo + i,
12480 sizeof(*linfo) * (nr_linfo - i));
12481
12482 prog->aux->nr_linfo -= l_cnt;
12483 nr_linfo = prog->aux->nr_linfo;
12484 }
12485
12486 /* pull all linfo[i].insn_off >= off + cnt in by cnt */
12487 for (i = l_off; i < nr_linfo; i++)
12488 linfo[i].insn_off -= cnt;
12489
12490 /* fix up all subprogs (incl. 'exit') which start >= off */
12491 for (i = 0; i <= env->subprog_cnt; i++)
12492 if (env->subprog_info[i].linfo_idx > l_off) {
12493 /* program may have started in the removed region but
12494 * may not be fully removed
12495 */
12496 if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
12497 env->subprog_info[i].linfo_idx -= l_cnt;
12498 else
12499 env->subprog_info[i].linfo_idx = l_off;
12500 }
12501
12502 return 0;
12503}
12504
12505static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
12506{
12507 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
12508 unsigned int orig_prog_len = env->prog->len;
12509 int err;
12510
08ca90af
JK
12511 if (bpf_prog_is_dev_bound(env->prog->aux))
12512 bpf_prog_offload_remove_insns(env, off, cnt);
12513
52875a04
JK
12514 err = bpf_remove_insns(env->prog, off, cnt);
12515 if (err)
12516 return err;
12517
12518 err = adjust_subprog_starts_after_remove(env, off, cnt);
12519 if (err)
12520 return err;
12521
12522 err = bpf_adj_linfo_after_remove(env, off, cnt);
12523 if (err)
12524 return err;
12525
12526 memmove(aux_data + off, aux_data + off + cnt,
12527 sizeof(*aux_data) * (orig_prog_len - off - cnt));
12528
12529 return 0;
12530}
12531
2a5418a1
DB
12532/* The verifier does more data flow analysis than llvm and will not
12533 * explore branches that are dead at run time. Malicious programs can
12534 * have dead code too. Therefore replace all dead at-run-time code
12535 * with 'ja -1'.
12536 *
12537 * Just nops are not optimal, e.g. if they would sit at the end of the
12538 * program and through another bug we would manage to jump there, then
12539 * we'd execute beyond program memory otherwise. Returning exception
12540 * code also wouldn't work since we can have subprogs where the dead
12541 * code could be located.
c131187d
AS
12542 */
12543static void sanitize_dead_code(struct bpf_verifier_env *env)
12544{
12545 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
2a5418a1 12546 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
c131187d
AS
12547 struct bpf_insn *insn = env->prog->insnsi;
12548 const int insn_cnt = env->prog->len;
12549 int i;
12550
12551 for (i = 0; i < insn_cnt; i++) {
12552 if (aux_data[i].seen)
12553 continue;
2a5418a1 12554 memcpy(insn + i, &trap, sizeof(trap));
45c709f8 12555 aux_data[i].zext_dst = false;
c131187d
AS
12556 }
12557}
12558
e2ae4ca2
JK
12559static bool insn_is_cond_jump(u8 code)
12560{
12561 u8 op;
12562
092ed096
JW
12563 if (BPF_CLASS(code) == BPF_JMP32)
12564 return true;
12565
e2ae4ca2
JK
12566 if (BPF_CLASS(code) != BPF_JMP)
12567 return false;
12568
12569 op = BPF_OP(code);
12570 return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
12571}
12572
12573static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
12574{
12575 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
12576 struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
12577 struct bpf_insn *insn = env->prog->insnsi;
12578 const int insn_cnt = env->prog->len;
12579 int i;
12580
12581 for (i = 0; i < insn_cnt; i++, insn++) {
12582 if (!insn_is_cond_jump(insn->code))
12583 continue;
12584
12585 if (!aux_data[i + 1].seen)
12586 ja.off = insn->off;
12587 else if (!aux_data[i + 1 + insn->off].seen)
12588 ja.off = 0;
12589 else
12590 continue;
12591
08ca90af
JK
12592 if (bpf_prog_is_dev_bound(env->prog->aux))
12593 bpf_prog_offload_replace_insn(env, i, &ja);
12594
e2ae4ca2
JK
12595 memcpy(insn, &ja, sizeof(ja));
12596 }
12597}
12598
52875a04
JK
12599static int opt_remove_dead_code(struct bpf_verifier_env *env)
12600{
12601 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
12602 int insn_cnt = env->prog->len;
12603 int i, err;
12604
12605 for (i = 0; i < insn_cnt; i++) {
12606 int j;
12607
12608 j = 0;
12609 while (i + j < insn_cnt && !aux_data[i + j].seen)
12610 j++;
12611 if (!j)
12612 continue;
12613
12614 err = verifier_remove_insns(env, i, j);
12615 if (err)
12616 return err;
12617 insn_cnt = env->prog->len;
12618 }
12619
12620 return 0;
12621}
12622
a1b14abc
JK
12623static int opt_remove_nops(struct bpf_verifier_env *env)
12624{
12625 const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
12626 struct bpf_insn *insn = env->prog->insnsi;
12627 int insn_cnt = env->prog->len;
12628 int i, err;
12629
12630 for (i = 0; i < insn_cnt; i++) {
12631 if (memcmp(&insn[i], &ja, sizeof(ja)))
12632 continue;
12633
12634 err = verifier_remove_insns(env, i, 1);
12635 if (err)
12636 return err;
12637 insn_cnt--;
12638 i--;
12639 }
12640
12641 return 0;
12642}
12643
d6c2308c
JW
12644static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
12645 const union bpf_attr *attr)
a4b1d3c1 12646{
d6c2308c 12647 struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
a4b1d3c1 12648 struct bpf_insn_aux_data *aux = env->insn_aux_data;
d6c2308c 12649 int i, patch_len, delta = 0, len = env->prog->len;
a4b1d3c1 12650 struct bpf_insn *insns = env->prog->insnsi;
a4b1d3c1 12651 struct bpf_prog *new_prog;
d6c2308c 12652 bool rnd_hi32;
a4b1d3c1 12653
d6c2308c 12654 rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
a4b1d3c1 12655 zext_patch[1] = BPF_ZEXT_REG(0);
d6c2308c
JW
12656 rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
12657 rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
12658 rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
a4b1d3c1
JW
12659 for (i = 0; i < len; i++) {
12660 int adj_idx = i + delta;
12661 struct bpf_insn insn;
83a28819 12662 int load_reg;
a4b1d3c1 12663
d6c2308c 12664 insn = insns[adj_idx];
83a28819 12665 load_reg = insn_def_regno(&insn);
d6c2308c
JW
12666 if (!aux[adj_idx].zext_dst) {
12667 u8 code, class;
12668 u32 imm_rnd;
12669
12670 if (!rnd_hi32)
12671 continue;
12672
12673 code = insn.code;
12674 class = BPF_CLASS(code);
83a28819 12675 if (load_reg == -1)
d6c2308c
JW
12676 continue;
12677
12678 /* NOTE: arg "reg" (the fourth one) is only used for
83a28819
IL
12679 * BPF_STX + SRC_OP, so it is safe to pass NULL
12680 * here.
d6c2308c 12681 */
83a28819 12682 if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
d6c2308c
JW
12683 if (class == BPF_LD &&
12684 BPF_MODE(code) == BPF_IMM)
12685 i++;
12686 continue;
12687 }
12688
12689 /* ctx load could be transformed into wider load. */
12690 if (class == BPF_LDX &&
12691 aux[adj_idx].ptr_type == PTR_TO_CTX)
12692 continue;
12693
12694 imm_rnd = get_random_int();
12695 rnd_hi32_patch[0] = insn;
12696 rnd_hi32_patch[1].imm = imm_rnd;
83a28819 12697 rnd_hi32_patch[3].dst_reg = load_reg;
d6c2308c
JW
12698 patch = rnd_hi32_patch;
12699 patch_len = 4;
12700 goto apply_patch_buffer;
12701 }
12702
39491867
BJ
12703 /* Add in an zero-extend instruction if a) the JIT has requested
12704 * it or b) it's a CMPXCHG.
12705 *
12706 * The latter is because: BPF_CMPXCHG always loads a value into
12707 * R0, therefore always zero-extends. However some archs'
12708 * equivalent instruction only does this load when the
12709 * comparison is successful. This detail of CMPXCHG is
12710 * orthogonal to the general zero-extension behaviour of the
12711 * CPU, so it's treated independently of bpf_jit_needs_zext.
12712 */
12713 if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
a4b1d3c1
JW
12714 continue;
12715
83a28819
IL
12716 if (WARN_ON(load_reg == -1)) {
12717 verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
12718 return -EFAULT;
b2e37a71
IL
12719 }
12720
a4b1d3c1 12721 zext_patch[0] = insn;
b2e37a71
IL
12722 zext_patch[1].dst_reg = load_reg;
12723 zext_patch[1].src_reg = load_reg;
d6c2308c
JW
12724 patch = zext_patch;
12725 patch_len = 2;
12726apply_patch_buffer:
12727 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
a4b1d3c1
JW
12728 if (!new_prog)
12729 return -ENOMEM;
12730 env->prog = new_prog;
12731 insns = new_prog->insnsi;
12732 aux = env->insn_aux_data;
d6c2308c 12733 delta += patch_len - 1;
a4b1d3c1
JW
12734 }
12735
12736 return 0;
12737}
12738
c64b7983
JS
12739/* convert load instructions that access fields of a context type into a
12740 * sequence of instructions that access fields of the underlying structure:
12741 * struct __sk_buff -> struct sk_buff
12742 * struct bpf_sock_ops -> struct sock
9bac3d6d 12743 */
58e2af8b 12744static int convert_ctx_accesses(struct bpf_verifier_env *env)
9bac3d6d 12745{
00176a34 12746 const struct bpf_verifier_ops *ops = env->ops;
f96da094 12747 int i, cnt, size, ctx_field_size, delta = 0;
3df126f3 12748 const int insn_cnt = env->prog->len;
36bbef52 12749 struct bpf_insn insn_buf[16], *insn;
46f53a65 12750 u32 target_size, size_default, off;
9bac3d6d 12751 struct bpf_prog *new_prog;
d691f9e8 12752 enum bpf_access_type type;
f96da094 12753 bool is_narrower_load;
9bac3d6d 12754
b09928b9
DB
12755 if (ops->gen_prologue || env->seen_direct_write) {
12756 if (!ops->gen_prologue) {
12757 verbose(env, "bpf verifier is misconfigured\n");
12758 return -EINVAL;
12759 }
36bbef52
DB
12760 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
12761 env->prog);
12762 if (cnt >= ARRAY_SIZE(insn_buf)) {
61bd5218 12763 verbose(env, "bpf verifier is misconfigured\n");
36bbef52
DB
12764 return -EINVAL;
12765 } else if (cnt) {
8041902d 12766 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
36bbef52
DB
12767 if (!new_prog)
12768 return -ENOMEM;
8041902d 12769
36bbef52 12770 env->prog = new_prog;
3df126f3 12771 delta += cnt - 1;
36bbef52
DB
12772 }
12773 }
12774
c64b7983 12775 if (bpf_prog_is_dev_bound(env->prog->aux))
9bac3d6d
AS
12776 return 0;
12777
3df126f3 12778 insn = env->prog->insnsi + delta;
36bbef52 12779
9bac3d6d 12780 for (i = 0; i < insn_cnt; i++, insn++) {
c64b7983 12781 bpf_convert_ctx_access_t convert_ctx_access;
2039f26f 12782 bool ctx_access;
c64b7983 12783
62c7989b
DB
12784 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
12785 insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
12786 insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
2039f26f 12787 insn->code == (BPF_LDX | BPF_MEM | BPF_DW)) {
d691f9e8 12788 type = BPF_READ;
2039f26f
DB
12789 ctx_access = true;
12790 } else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
12791 insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
12792 insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
12793 insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
12794 insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
12795 insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
12796 insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
12797 insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
d691f9e8 12798 type = BPF_WRITE;
2039f26f
DB
12799 ctx_access = BPF_CLASS(insn->code) == BPF_STX;
12800 } else {
9bac3d6d 12801 continue;
2039f26f 12802 }
9bac3d6d 12803
af86ca4e 12804 if (type == BPF_WRITE &&
2039f26f 12805 env->insn_aux_data[i + delta].sanitize_stack_spill) {
af86ca4e 12806 struct bpf_insn patch[] = {
af86ca4e 12807 *insn,
2039f26f 12808 BPF_ST_NOSPEC(),
af86ca4e
AS
12809 };
12810
12811 cnt = ARRAY_SIZE(patch);
12812 new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
12813 if (!new_prog)
12814 return -ENOMEM;
12815
12816 delta += cnt - 1;
12817 env->prog = new_prog;
12818 insn = new_prog->insnsi + i + delta;
12819 continue;
12820 }
12821
2039f26f
DB
12822 if (!ctx_access)
12823 continue;
12824
c64b7983
JS
12825 switch (env->insn_aux_data[i + delta].ptr_type) {
12826 case PTR_TO_CTX:
12827 if (!ops->convert_ctx_access)
12828 continue;
12829 convert_ctx_access = ops->convert_ctx_access;
12830 break;
12831 case PTR_TO_SOCKET:
46f8bc92 12832 case PTR_TO_SOCK_COMMON:
c64b7983
JS
12833 convert_ctx_access = bpf_sock_convert_ctx_access;
12834 break;
655a51e5
MKL
12835 case PTR_TO_TCP_SOCK:
12836 convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
12837 break;
fada7fdc
JL
12838 case PTR_TO_XDP_SOCK:
12839 convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
12840 break;
2a02759e 12841 case PTR_TO_BTF_ID:
27ae7997
MKL
12842 if (type == BPF_READ) {
12843 insn->code = BPF_LDX | BPF_PROBE_MEM |
12844 BPF_SIZE((insn)->code);
12845 env->prog->aux->num_exentries++;
7e40781c 12846 } else if (resolve_prog_type(env->prog) != BPF_PROG_TYPE_STRUCT_OPS) {
2a02759e
AS
12847 verbose(env, "Writes through BTF pointers are not allowed\n");
12848 return -EINVAL;
12849 }
2a02759e 12850 continue;
c64b7983 12851 default:
9bac3d6d 12852 continue;
c64b7983 12853 }
9bac3d6d 12854
31fd8581 12855 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
f96da094 12856 size = BPF_LDST_BYTES(insn);
31fd8581
YS
12857
12858 /* If the read access is a narrower load of the field,
12859 * convert to a 4/8-byte load, to minimum program type specific
12860 * convert_ctx_access changes. If conversion is successful,
12861 * we will apply proper mask to the result.
12862 */
f96da094 12863 is_narrower_load = size < ctx_field_size;
46f53a65
AI
12864 size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
12865 off = insn->off;
31fd8581 12866 if (is_narrower_load) {
f96da094
DB
12867 u8 size_code;
12868
12869 if (type == BPF_WRITE) {
61bd5218 12870 verbose(env, "bpf verifier narrow ctx access misconfigured\n");
f96da094
DB
12871 return -EINVAL;
12872 }
31fd8581 12873
f96da094 12874 size_code = BPF_H;
31fd8581
YS
12875 if (ctx_field_size == 4)
12876 size_code = BPF_W;
12877 else if (ctx_field_size == 8)
12878 size_code = BPF_DW;
f96da094 12879
bc23105c 12880 insn->off = off & ~(size_default - 1);
31fd8581
YS
12881 insn->code = BPF_LDX | BPF_MEM | size_code;
12882 }
f96da094
DB
12883
12884 target_size = 0;
c64b7983
JS
12885 cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
12886 &target_size);
f96da094
DB
12887 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
12888 (ctx_field_size && !target_size)) {
61bd5218 12889 verbose(env, "bpf verifier is misconfigured\n");
9bac3d6d
AS
12890 return -EINVAL;
12891 }
f96da094
DB
12892
12893 if (is_narrower_load && size < target_size) {
d895a0f1
IL
12894 u8 shift = bpf_ctx_narrow_access_offset(
12895 off, size, size_default) * 8;
d7af7e49
AI
12896 if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) {
12897 verbose(env, "bpf verifier narrow ctx load misconfigured\n");
12898 return -EINVAL;
12899 }
46f53a65
AI
12900 if (ctx_field_size <= 4) {
12901 if (shift)
12902 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
12903 insn->dst_reg,
12904 shift);
31fd8581 12905 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
f96da094 12906 (1 << size * 8) - 1);
46f53a65
AI
12907 } else {
12908 if (shift)
12909 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
12910 insn->dst_reg,
12911 shift);
31fd8581 12912 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
e2f7fc0a 12913 (1ULL << size * 8) - 1);
46f53a65 12914 }
31fd8581 12915 }
9bac3d6d 12916
8041902d 12917 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
9bac3d6d
AS
12918 if (!new_prog)
12919 return -ENOMEM;
12920
3df126f3 12921 delta += cnt - 1;
9bac3d6d
AS
12922
12923 /* keep walking new program and skip insns we just inserted */
12924 env->prog = new_prog;
3df126f3 12925 insn = new_prog->insnsi + i + delta;
9bac3d6d
AS
12926 }
12927
12928 return 0;
12929}
12930
1c2a088a
AS
12931static int jit_subprogs(struct bpf_verifier_env *env)
12932{
12933 struct bpf_prog *prog = env->prog, **func, *tmp;
12934 int i, j, subprog_start, subprog_end = 0, len, subprog;
a748c697 12935 struct bpf_map *map_ptr;
7105e828 12936 struct bpf_insn *insn;
1c2a088a 12937 void *old_bpf_func;
c4c0bdc0 12938 int err, num_exentries;
1c2a088a 12939
f910cefa 12940 if (env->subprog_cnt <= 1)
1c2a088a
AS
12941 return 0;
12942
7105e828 12943 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
3990ed4c 12944 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
69c087ba 12945 continue;
69c087ba 12946
c7a89784
DB
12947 /* Upon error here we cannot fall back to interpreter but
12948 * need a hard reject of the program. Thus -EFAULT is
12949 * propagated in any case.
12950 */
1c2a088a
AS
12951 subprog = find_subprog(env, i + insn->imm + 1);
12952 if (subprog < 0) {
12953 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
12954 i + insn->imm + 1);
12955 return -EFAULT;
12956 }
12957 /* temporarily remember subprog id inside insn instead of
12958 * aux_data, since next loop will split up all insns into funcs
12959 */
f910cefa 12960 insn->off = subprog;
1c2a088a
AS
12961 /* remember original imm in case JIT fails and fallback
12962 * to interpreter will be needed
12963 */
12964 env->insn_aux_data[i].call_imm = insn->imm;
12965 /* point imm to __bpf_call_base+1 from JITs point of view */
12966 insn->imm = 1;
3990ed4c
MKL
12967 if (bpf_pseudo_func(insn))
12968 /* jit (e.g. x86_64) may emit fewer instructions
12969 * if it learns a u32 imm is the same as a u64 imm.
12970 * Force a non zero here.
12971 */
12972 insn[1].imm = 1;
1c2a088a
AS
12973 }
12974
c454a46b
MKL
12975 err = bpf_prog_alloc_jited_linfo(prog);
12976 if (err)
12977 goto out_undo_insn;
12978
12979 err = -ENOMEM;
6396bb22 12980 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
1c2a088a 12981 if (!func)
c7a89784 12982 goto out_undo_insn;
1c2a088a 12983
f910cefa 12984 for (i = 0; i < env->subprog_cnt; i++) {
1c2a088a 12985 subprog_start = subprog_end;
4cb3d99c 12986 subprog_end = env->subprog_info[i + 1].start;
1c2a088a
AS
12987
12988 len = subprog_end - subprog_start;
fb7dd8bc 12989 /* bpf_prog_run() doesn't call subprogs directly,
492ecee8
AS
12990 * hence main prog stats include the runtime of subprogs.
12991 * subprogs don't have IDs and not reachable via prog_get_next_id
700d4796 12992 * func[i]->stats will never be accessed and stays NULL
492ecee8
AS
12993 */
12994 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
1c2a088a
AS
12995 if (!func[i])
12996 goto out_free;
12997 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
12998 len * sizeof(struct bpf_insn));
4f74d809 12999 func[i]->type = prog->type;
1c2a088a 13000 func[i]->len = len;
4f74d809
DB
13001 if (bpf_prog_calc_tag(func[i]))
13002 goto out_free;
1c2a088a 13003 func[i]->is_func = 1;
ba64e7d8 13004 func[i]->aux->func_idx = i;
f263a814 13005 /* Below members will be freed only at prog->aux */
ba64e7d8
YS
13006 func[i]->aux->btf = prog->aux->btf;
13007 func[i]->aux->func_info = prog->aux->func_info;
f263a814
JF
13008 func[i]->aux->poke_tab = prog->aux->poke_tab;
13009 func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
ba64e7d8 13010
a748c697 13011 for (j = 0; j < prog->aux->size_poke_tab; j++) {
f263a814 13012 struct bpf_jit_poke_descriptor *poke;
a748c697 13013
f263a814
JF
13014 poke = &prog->aux->poke_tab[j];
13015 if (poke->insn_idx < subprog_end &&
13016 poke->insn_idx >= subprog_start)
13017 poke->aux = func[i]->aux;
a748c697
MF
13018 }
13019
1c2a088a
AS
13020 /* Use bpf_prog_F_tag to indicate functions in stack traces.
13021 * Long term would need debug info to populate names
13022 */
13023 func[i]->aux->name[0] = 'F';
9c8105bd 13024 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
1c2a088a 13025 func[i]->jit_requested = 1;
e6ac2450 13026 func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
2357672c 13027 func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
c454a46b
MKL
13028 func[i]->aux->linfo = prog->aux->linfo;
13029 func[i]->aux->nr_linfo = prog->aux->nr_linfo;
13030 func[i]->aux->jited_linfo = prog->aux->jited_linfo;
13031 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
c4c0bdc0
YS
13032 num_exentries = 0;
13033 insn = func[i]->insnsi;
13034 for (j = 0; j < func[i]->len; j++, insn++) {
13035 if (BPF_CLASS(insn->code) == BPF_LDX &&
13036 BPF_MODE(insn->code) == BPF_PROBE_MEM)
13037 num_exentries++;
13038 }
13039 func[i]->aux->num_exentries = num_exentries;
ebf7d1f5 13040 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
1c2a088a
AS
13041 func[i] = bpf_int_jit_compile(func[i]);
13042 if (!func[i]->jited) {
13043 err = -ENOTSUPP;
13044 goto out_free;
13045 }
13046 cond_resched();
13047 }
a748c697 13048
1c2a088a
AS
13049 /* at this point all bpf functions were successfully JITed
13050 * now populate all bpf_calls with correct addresses and
13051 * run last pass of JIT
13052 */
f910cefa 13053 for (i = 0; i < env->subprog_cnt; i++) {
1c2a088a
AS
13054 insn = func[i]->insnsi;
13055 for (j = 0; j < func[i]->len; j++, insn++) {
69c087ba 13056 if (bpf_pseudo_func(insn)) {
3990ed4c 13057 subprog = insn->off;
69c087ba
YS
13058 insn[0].imm = (u32)(long)func[subprog]->bpf_func;
13059 insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
13060 continue;
13061 }
23a2d70c 13062 if (!bpf_pseudo_call(insn))
1c2a088a
AS
13063 continue;
13064 subprog = insn->off;
3d717fad 13065 insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
1c2a088a 13066 }
2162fed4
SD
13067
13068 /* we use the aux data to keep a list of the start addresses
13069 * of the JITed images for each function in the program
13070 *
13071 * for some architectures, such as powerpc64, the imm field
13072 * might not be large enough to hold the offset of the start
13073 * address of the callee's JITed image from __bpf_call_base
13074 *
13075 * in such cases, we can lookup the start address of a callee
13076 * by using its subprog id, available from the off field of
13077 * the call instruction, as an index for this list
13078 */
13079 func[i]->aux->func = func;
13080 func[i]->aux->func_cnt = env->subprog_cnt;
1c2a088a 13081 }
f910cefa 13082 for (i = 0; i < env->subprog_cnt; i++) {
1c2a088a
AS
13083 old_bpf_func = func[i]->bpf_func;
13084 tmp = bpf_int_jit_compile(func[i]);
13085 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
13086 verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
c7a89784 13087 err = -ENOTSUPP;
1c2a088a
AS
13088 goto out_free;
13089 }
13090 cond_resched();
13091 }
13092
13093 /* finally lock prog and jit images for all functions and
13094 * populate kallsysm
13095 */
f910cefa 13096 for (i = 0; i < env->subprog_cnt; i++) {
1c2a088a
AS
13097 bpf_prog_lock_ro(func[i]);
13098 bpf_prog_kallsyms_add(func[i]);
13099 }
7105e828
DB
13100
13101 /* Last step: make now unused interpreter insns from main
13102 * prog consistent for later dump requests, so they can
13103 * later look the same as if they were interpreted only.
13104 */
13105 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
69c087ba
YS
13106 if (bpf_pseudo_func(insn)) {
13107 insn[0].imm = env->insn_aux_data[i].call_imm;
3990ed4c
MKL
13108 insn[1].imm = insn->off;
13109 insn->off = 0;
69c087ba
YS
13110 continue;
13111 }
23a2d70c 13112 if (!bpf_pseudo_call(insn))
7105e828
DB
13113 continue;
13114 insn->off = env->insn_aux_data[i].call_imm;
13115 subprog = find_subprog(env, i + insn->off + 1);
dbecd738 13116 insn->imm = subprog;
7105e828
DB
13117 }
13118
1c2a088a
AS
13119 prog->jited = 1;
13120 prog->bpf_func = func[0]->bpf_func;
d00c6473 13121 prog->jited_len = func[0]->jited_len;
1c2a088a 13122 prog->aux->func = func;
f910cefa 13123 prog->aux->func_cnt = env->subprog_cnt;
e16301fb 13124 bpf_prog_jit_attempt_done(prog);
1c2a088a
AS
13125 return 0;
13126out_free:
f263a814
JF
13127 /* We failed JIT'ing, so at this point we need to unregister poke
13128 * descriptors from subprogs, so that kernel is not attempting to
13129 * patch it anymore as we're freeing the subprog JIT memory.
13130 */
13131 for (i = 0; i < prog->aux->size_poke_tab; i++) {
13132 map_ptr = prog->aux->poke_tab[i].tail_call.map;
13133 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
13134 }
13135 /* At this point we're guaranteed that poke descriptors are not
13136 * live anymore. We can just unlink its descriptor table as it's
13137 * released with the main prog.
13138 */
a748c697
MF
13139 for (i = 0; i < env->subprog_cnt; i++) {
13140 if (!func[i])
13141 continue;
f263a814 13142 func[i]->aux->poke_tab = NULL;
a748c697
MF
13143 bpf_jit_free(func[i]);
13144 }
1c2a088a 13145 kfree(func);
c7a89784 13146out_undo_insn:
1c2a088a
AS
13147 /* cleanup main prog to be interpreted */
13148 prog->jit_requested = 0;
13149 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
23a2d70c 13150 if (!bpf_pseudo_call(insn))
1c2a088a
AS
13151 continue;
13152 insn->off = 0;
13153 insn->imm = env->insn_aux_data[i].call_imm;
13154 }
e16301fb 13155 bpf_prog_jit_attempt_done(prog);
1c2a088a
AS
13156 return err;
13157}
13158
1ea47e01
AS
13159static int fixup_call_args(struct bpf_verifier_env *env)
13160{
19d28fbd 13161#ifndef CONFIG_BPF_JIT_ALWAYS_ON
1ea47e01
AS
13162 struct bpf_prog *prog = env->prog;
13163 struct bpf_insn *insn = prog->insnsi;
e6ac2450 13164 bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
1ea47e01 13165 int i, depth;
19d28fbd 13166#endif
e4052d06 13167 int err = 0;
1ea47e01 13168
e4052d06
QM
13169 if (env->prog->jit_requested &&
13170 !bpf_prog_is_dev_bound(env->prog->aux)) {
19d28fbd
DM
13171 err = jit_subprogs(env);
13172 if (err == 0)
1c2a088a 13173 return 0;
c7a89784
DB
13174 if (err == -EFAULT)
13175 return err;
19d28fbd
DM
13176 }
13177#ifndef CONFIG_BPF_JIT_ALWAYS_ON
e6ac2450
MKL
13178 if (has_kfunc_call) {
13179 verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
13180 return -EINVAL;
13181 }
e411901c
MF
13182 if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
13183 /* When JIT fails the progs with bpf2bpf calls and tail_calls
13184 * have to be rejected, since interpreter doesn't support them yet.
13185 */
13186 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
13187 return -EINVAL;
13188 }
1ea47e01 13189 for (i = 0; i < prog->len; i++, insn++) {
69c087ba
YS
13190 if (bpf_pseudo_func(insn)) {
13191 /* When JIT fails the progs with callback calls
13192 * have to be rejected, since interpreter doesn't support them yet.
13193 */
13194 verbose(env, "callbacks are not allowed in non-JITed programs\n");
13195 return -EINVAL;
13196 }
13197
23a2d70c 13198 if (!bpf_pseudo_call(insn))
1ea47e01
AS
13199 continue;
13200 depth = get_callee_stack_depth(env, insn, i);
13201 if (depth < 0)
13202 return depth;
13203 bpf_patch_call_args(insn, depth);
13204 }
19d28fbd
DM
13205 err = 0;
13206#endif
13207 return err;
1ea47e01
AS
13208}
13209
e6ac2450
MKL
13210static int fixup_kfunc_call(struct bpf_verifier_env *env,
13211 struct bpf_insn *insn)
13212{
13213 const struct bpf_kfunc_desc *desc;
13214
a5d82727
KKD
13215 if (!insn->imm) {
13216 verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
13217 return -EINVAL;
13218 }
13219
e6ac2450
MKL
13220 /* insn->imm has the btf func_id. Replace it with
13221 * an address (relative to __bpf_base_call).
13222 */
2357672c 13223 desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
e6ac2450
MKL
13224 if (!desc) {
13225 verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
13226 insn->imm);
13227 return -EFAULT;
13228 }
13229
13230 insn->imm = desc->imm;
13231
13232 return 0;
13233}
13234
e6ac5933
BJ
13235/* Do various post-verification rewrites in a single program pass.
13236 * These rewrites simplify JIT and interpreter implementations.
e245c5c6 13237 */
e6ac5933 13238static int do_misc_fixups(struct bpf_verifier_env *env)
e245c5c6 13239{
79741b3b 13240 struct bpf_prog *prog = env->prog;
f92c1e18 13241 enum bpf_attach_type eatype = prog->expected_attach_type;
d2e4c1e6 13242 bool expect_blinding = bpf_jit_blinding_enabled(prog);
9b99edca 13243 enum bpf_prog_type prog_type = resolve_prog_type(prog);
79741b3b 13244 struct bpf_insn *insn = prog->insnsi;
e245c5c6 13245 const struct bpf_func_proto *fn;
79741b3b 13246 const int insn_cnt = prog->len;
09772d92 13247 const struct bpf_map_ops *ops;
c93552c4 13248 struct bpf_insn_aux_data *aux;
81ed18ab
AS
13249 struct bpf_insn insn_buf[16];
13250 struct bpf_prog *new_prog;
13251 struct bpf_map *map_ptr;
d2e4c1e6 13252 int i, ret, cnt, delta = 0;
e245c5c6 13253
79741b3b 13254 for (i = 0; i < insn_cnt; i++, insn++) {
e6ac5933 13255 /* Make divide-by-zero exceptions impossible. */
f6b1b3bf
DB
13256 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
13257 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
13258 insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
68fda450 13259 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
f6b1b3bf 13260 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
e88b2c6e
DB
13261 bool isdiv = BPF_OP(insn->code) == BPF_DIV;
13262 struct bpf_insn *patchlet;
13263 struct bpf_insn chk_and_div[] = {
9b00f1b7 13264 /* [R,W]x div 0 -> 0 */
e88b2c6e
DB
13265 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
13266 BPF_JNE | BPF_K, insn->src_reg,
13267 0, 2, 0),
f6b1b3bf
DB
13268 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
13269 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
13270 *insn,
13271 };
e88b2c6e 13272 struct bpf_insn chk_and_mod[] = {
9b00f1b7 13273 /* [R,W]x mod 0 -> [R,W]x */
e88b2c6e
DB
13274 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
13275 BPF_JEQ | BPF_K, insn->src_reg,
9b00f1b7 13276 0, 1 + (is64 ? 0 : 1), 0),
f6b1b3bf 13277 *insn,
9b00f1b7
DB
13278 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
13279 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
f6b1b3bf 13280 };
f6b1b3bf 13281
e88b2c6e
DB
13282 patchlet = isdiv ? chk_and_div : chk_and_mod;
13283 cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
9b00f1b7 13284 ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
f6b1b3bf
DB
13285
13286 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
68fda450
AS
13287 if (!new_prog)
13288 return -ENOMEM;
13289
13290 delta += cnt - 1;
13291 env->prog = prog = new_prog;
13292 insn = new_prog->insnsi + i + delta;
13293 continue;
13294 }
13295
e6ac5933 13296 /* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
e0cea7ce
DB
13297 if (BPF_CLASS(insn->code) == BPF_LD &&
13298 (BPF_MODE(insn->code) == BPF_ABS ||
13299 BPF_MODE(insn->code) == BPF_IND)) {
13300 cnt = env->ops->gen_ld_abs(insn, insn_buf);
13301 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
13302 verbose(env, "bpf verifier is misconfigured\n");
13303 return -EINVAL;
13304 }
13305
13306 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
13307 if (!new_prog)
13308 return -ENOMEM;
13309
13310 delta += cnt - 1;
13311 env->prog = prog = new_prog;
13312 insn = new_prog->insnsi + i + delta;
13313 continue;
13314 }
13315
e6ac5933 13316 /* Rewrite pointer arithmetic to mitigate speculation attacks. */
979d63d5
DB
13317 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
13318 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
13319 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
13320 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
979d63d5 13321 struct bpf_insn *patch = &insn_buf[0];
801c6058 13322 bool issrc, isneg, isimm;
979d63d5
DB
13323 u32 off_reg;
13324
13325 aux = &env->insn_aux_data[i + delta];
3612af78
DB
13326 if (!aux->alu_state ||
13327 aux->alu_state == BPF_ALU_NON_POINTER)
979d63d5
DB
13328 continue;
13329
13330 isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
13331 issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
13332 BPF_ALU_SANITIZE_SRC;
801c6058 13333 isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
979d63d5
DB
13334
13335 off_reg = issrc ? insn->src_reg : insn->dst_reg;
801c6058
DB
13336 if (isimm) {
13337 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
13338 } else {
13339 if (isneg)
13340 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
13341 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
13342 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
13343 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
13344 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
13345 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
13346 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
13347 }
b9b34ddb
DB
13348 if (!issrc)
13349 *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
13350 insn->src_reg = BPF_REG_AX;
979d63d5
DB
13351 if (isneg)
13352 insn->code = insn->code == code_add ?
13353 code_sub : code_add;
13354 *patch++ = *insn;
801c6058 13355 if (issrc && isneg && !isimm)
979d63d5
DB
13356 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
13357 cnt = patch - insn_buf;
13358
13359 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
13360 if (!new_prog)
13361 return -ENOMEM;
13362
13363 delta += cnt - 1;
13364 env->prog = prog = new_prog;
13365 insn = new_prog->insnsi + i + delta;
13366 continue;
13367 }
13368
79741b3b
AS
13369 if (insn->code != (BPF_JMP | BPF_CALL))
13370 continue;
cc8b0b92
AS
13371 if (insn->src_reg == BPF_PSEUDO_CALL)
13372 continue;
e6ac2450
MKL
13373 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
13374 ret = fixup_kfunc_call(env, insn);
13375 if (ret)
13376 return ret;
13377 continue;
13378 }
e245c5c6 13379
79741b3b
AS
13380 if (insn->imm == BPF_FUNC_get_route_realm)
13381 prog->dst_needed = 1;
13382 if (insn->imm == BPF_FUNC_get_prandom_u32)
13383 bpf_user_rnd_init_once();
9802d865
JB
13384 if (insn->imm == BPF_FUNC_override_return)
13385 prog->kprobe_override = 1;
79741b3b 13386 if (insn->imm == BPF_FUNC_tail_call) {
7b9f6da1
DM
13387 /* If we tail call into other programs, we
13388 * cannot make any assumptions since they can
13389 * be replaced dynamically during runtime in
13390 * the program array.
13391 */
13392 prog->cb_access = 1;
e411901c
MF
13393 if (!allow_tail_call_in_subprogs(env))
13394 prog->aux->stack_depth = MAX_BPF_STACK;
13395 prog->aux->max_pkt_offset = MAX_PACKET_OFF;
7b9f6da1 13396
79741b3b 13397 /* mark bpf_tail_call as different opcode to avoid
8fb33b60 13398 * conditional branch in the interpreter for every normal
79741b3b
AS
13399 * call and to prevent accidental JITing by JIT compiler
13400 * that doesn't support bpf_tail_call yet
e245c5c6 13401 */
79741b3b 13402 insn->imm = 0;
71189fa9 13403 insn->code = BPF_JMP | BPF_TAIL_CALL;
b2157399 13404
c93552c4 13405 aux = &env->insn_aux_data[i + delta];
2c78ee89 13406 if (env->bpf_capable && !expect_blinding &&
cc52d914 13407 prog->jit_requested &&
d2e4c1e6
DB
13408 !bpf_map_key_poisoned(aux) &&
13409 !bpf_map_ptr_poisoned(aux) &&
13410 !bpf_map_ptr_unpriv(aux)) {
13411 struct bpf_jit_poke_descriptor desc = {
13412 .reason = BPF_POKE_REASON_TAIL_CALL,
13413 .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
13414 .tail_call.key = bpf_map_key_immediate(aux),
a748c697 13415 .insn_idx = i + delta,
d2e4c1e6
DB
13416 };
13417
13418 ret = bpf_jit_add_poke_descriptor(prog, &desc);
13419 if (ret < 0) {
13420 verbose(env, "adding tail call poke descriptor failed\n");
13421 return ret;
13422 }
13423
13424 insn->imm = ret + 1;
13425 continue;
13426 }
13427
c93552c4
DB
13428 if (!bpf_map_ptr_unpriv(aux))
13429 continue;
13430
b2157399
AS
13431 /* instead of changing every JIT dealing with tail_call
13432 * emit two extra insns:
13433 * if (index >= max_entries) goto out;
13434 * index &= array->index_mask;
13435 * to avoid out-of-bounds cpu speculation
13436 */
c93552c4 13437 if (bpf_map_ptr_poisoned(aux)) {
40950343 13438 verbose(env, "tail_call abusing map_ptr\n");
b2157399
AS
13439 return -EINVAL;
13440 }
c93552c4 13441
d2e4c1e6 13442 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
b2157399
AS
13443 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
13444 map_ptr->max_entries, 2);
13445 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
13446 container_of(map_ptr,
13447 struct bpf_array,
13448 map)->index_mask);
13449 insn_buf[2] = *insn;
13450 cnt = 3;
13451 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
13452 if (!new_prog)
13453 return -ENOMEM;
13454
13455 delta += cnt - 1;
13456 env->prog = prog = new_prog;
13457 insn = new_prog->insnsi + i + delta;
79741b3b
AS
13458 continue;
13459 }
e245c5c6 13460
b00628b1
AS
13461 if (insn->imm == BPF_FUNC_timer_set_callback) {
13462 /* The verifier will process callback_fn as many times as necessary
13463 * with different maps and the register states prepared by
13464 * set_timer_callback_state will be accurate.
13465 *
13466 * The following use case is valid:
13467 * map1 is shared by prog1, prog2, prog3.
13468 * prog1 calls bpf_timer_init for some map1 elements
13469 * prog2 calls bpf_timer_set_callback for some map1 elements.
13470 * Those that were not bpf_timer_init-ed will return -EINVAL.
13471 * prog3 calls bpf_timer_start for some map1 elements.
13472 * Those that were not both bpf_timer_init-ed and
13473 * bpf_timer_set_callback-ed will return -EINVAL.
13474 */
13475 struct bpf_insn ld_addrs[2] = {
13476 BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
13477 };
13478
13479 insn_buf[0] = ld_addrs[0];
13480 insn_buf[1] = ld_addrs[1];
13481 insn_buf[2] = *insn;
13482 cnt = 3;
13483
13484 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
13485 if (!new_prog)
13486 return -ENOMEM;
13487
13488 delta += cnt - 1;
13489 env->prog = prog = new_prog;
13490 insn = new_prog->insnsi + i + delta;
13491 goto patch_call_imm;
13492 }
13493
89c63074 13494 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
09772d92
DB
13495 * and other inlining handlers are currently limited to 64 bit
13496 * only.
89c63074 13497 */
60b58afc 13498 if (prog->jit_requested && BITS_PER_LONG == 64 &&
09772d92
DB
13499 (insn->imm == BPF_FUNC_map_lookup_elem ||
13500 insn->imm == BPF_FUNC_map_update_elem ||
84430d42
DB
13501 insn->imm == BPF_FUNC_map_delete_elem ||
13502 insn->imm == BPF_FUNC_map_push_elem ||
13503 insn->imm == BPF_FUNC_map_pop_elem ||
e6a4750f 13504 insn->imm == BPF_FUNC_map_peek_elem ||
0640c77c
AI
13505 insn->imm == BPF_FUNC_redirect_map ||
13506 insn->imm == BPF_FUNC_for_each_map_elem)) {
c93552c4
DB
13507 aux = &env->insn_aux_data[i + delta];
13508 if (bpf_map_ptr_poisoned(aux))
13509 goto patch_call_imm;
13510
d2e4c1e6 13511 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
09772d92
DB
13512 ops = map_ptr->ops;
13513 if (insn->imm == BPF_FUNC_map_lookup_elem &&
13514 ops->map_gen_lookup) {
13515 cnt = ops->map_gen_lookup(map_ptr, insn_buf);
4a8f87e6
DB
13516 if (cnt == -EOPNOTSUPP)
13517 goto patch_map_ops_generic;
13518 if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
09772d92
DB
13519 verbose(env, "bpf verifier is misconfigured\n");
13520 return -EINVAL;
13521 }
81ed18ab 13522
09772d92
DB
13523 new_prog = bpf_patch_insn_data(env, i + delta,
13524 insn_buf, cnt);
13525 if (!new_prog)
13526 return -ENOMEM;
81ed18ab 13527
09772d92
DB
13528 delta += cnt - 1;
13529 env->prog = prog = new_prog;
13530 insn = new_prog->insnsi + i + delta;
13531 continue;
13532 }
81ed18ab 13533
09772d92
DB
13534 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
13535 (void *(*)(struct bpf_map *map, void *key))NULL));
13536 BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
13537 (int (*)(struct bpf_map *map, void *key))NULL));
13538 BUILD_BUG_ON(!__same_type(ops->map_update_elem,
13539 (int (*)(struct bpf_map *map, void *key, void *value,
13540 u64 flags))NULL));
84430d42
DB
13541 BUILD_BUG_ON(!__same_type(ops->map_push_elem,
13542 (int (*)(struct bpf_map *map, void *value,
13543 u64 flags))NULL));
13544 BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
13545 (int (*)(struct bpf_map *map, void *value))NULL));
13546 BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
13547 (int (*)(struct bpf_map *map, void *value))NULL));
e6a4750f
BT
13548 BUILD_BUG_ON(!__same_type(ops->map_redirect,
13549 (int (*)(struct bpf_map *map, u32 ifindex, u64 flags))NULL));
0640c77c
AI
13550 BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
13551 (int (*)(struct bpf_map *map,
13552 bpf_callback_t callback_fn,
13553 void *callback_ctx,
13554 u64 flags))NULL));
e6a4750f 13555
4a8f87e6 13556patch_map_ops_generic:
09772d92
DB
13557 switch (insn->imm) {
13558 case BPF_FUNC_map_lookup_elem:
3d717fad 13559 insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
09772d92
DB
13560 continue;
13561 case BPF_FUNC_map_update_elem:
3d717fad 13562 insn->imm = BPF_CALL_IMM(ops->map_update_elem);
09772d92
DB
13563 continue;
13564 case BPF_FUNC_map_delete_elem:
3d717fad 13565 insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
09772d92 13566 continue;
84430d42 13567 case BPF_FUNC_map_push_elem:
3d717fad 13568 insn->imm = BPF_CALL_IMM(ops->map_push_elem);
84430d42
DB
13569 continue;
13570 case BPF_FUNC_map_pop_elem:
3d717fad 13571 insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
84430d42
DB
13572 continue;
13573 case BPF_FUNC_map_peek_elem:
3d717fad 13574 insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
84430d42 13575 continue;
e6a4750f 13576 case BPF_FUNC_redirect_map:
3d717fad 13577 insn->imm = BPF_CALL_IMM(ops->map_redirect);
e6a4750f 13578 continue;
0640c77c
AI
13579 case BPF_FUNC_for_each_map_elem:
13580 insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
e6a4750f 13581 continue;
09772d92 13582 }
81ed18ab 13583
09772d92 13584 goto patch_call_imm;
81ed18ab
AS
13585 }
13586
e6ac5933 13587 /* Implement bpf_jiffies64 inline. */
5576b991
MKL
13588 if (prog->jit_requested && BITS_PER_LONG == 64 &&
13589 insn->imm == BPF_FUNC_jiffies64) {
13590 struct bpf_insn ld_jiffies_addr[2] = {
13591 BPF_LD_IMM64(BPF_REG_0,
13592 (unsigned long)&jiffies),
13593 };
13594
13595 insn_buf[0] = ld_jiffies_addr[0];
13596 insn_buf[1] = ld_jiffies_addr[1];
13597 insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
13598 BPF_REG_0, 0);
13599 cnt = 3;
13600
13601 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
13602 cnt);
13603 if (!new_prog)
13604 return -ENOMEM;
13605
13606 delta += cnt - 1;
13607 env->prog = prog = new_prog;
13608 insn = new_prog->insnsi + i + delta;
13609 continue;
13610 }
13611
f92c1e18
JO
13612 /* Implement bpf_get_func_arg inline. */
13613 if (prog_type == BPF_PROG_TYPE_TRACING &&
13614 insn->imm == BPF_FUNC_get_func_arg) {
13615 /* Load nr_args from ctx - 8 */
13616 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
13617 insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
13618 insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3);
13619 insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
13620 insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
13621 insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
13622 insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0);
13623 insn_buf[7] = BPF_JMP_A(1);
13624 insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
13625 cnt = 9;
13626
13627 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
13628 if (!new_prog)
13629 return -ENOMEM;
13630
13631 delta += cnt - 1;
13632 env->prog = prog = new_prog;
13633 insn = new_prog->insnsi + i + delta;
13634 continue;
13635 }
13636
13637 /* Implement bpf_get_func_ret inline. */
13638 if (prog_type == BPF_PROG_TYPE_TRACING &&
13639 insn->imm == BPF_FUNC_get_func_ret) {
13640 if (eatype == BPF_TRACE_FEXIT ||
13641 eatype == BPF_MODIFY_RETURN) {
13642 /* Load nr_args from ctx - 8 */
13643 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
13644 insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
13645 insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1);
13646 insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
13647 insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0);
13648 insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0);
13649 cnt = 6;
13650 } else {
13651 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP);
13652 cnt = 1;
13653 }
13654
13655 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
13656 if (!new_prog)
13657 return -ENOMEM;
13658
13659 delta += cnt - 1;
13660 env->prog = prog = new_prog;
13661 insn = new_prog->insnsi + i + delta;
13662 continue;
13663 }
13664
13665 /* Implement get_func_arg_cnt inline. */
13666 if (prog_type == BPF_PROG_TYPE_TRACING &&
13667 insn->imm == BPF_FUNC_get_func_arg_cnt) {
13668 /* Load nr_args from ctx - 8 */
13669 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
13670
13671 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
13672 if (!new_prog)
13673 return -ENOMEM;
13674
13675 env->prog = prog = new_prog;
13676 insn = new_prog->insnsi + i + delta;
13677 continue;
13678 }
13679
9b99edca
JO
13680 /* Implement bpf_get_func_ip inline. */
13681 if (prog_type == BPF_PROG_TYPE_TRACING &&
13682 insn->imm == BPF_FUNC_get_func_ip) {
f92c1e18
JO
13683 /* Load IP address from ctx - 16 */
13684 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16);
9b99edca
JO
13685
13686 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
13687 if (!new_prog)
13688 return -ENOMEM;
13689
13690 env->prog = prog = new_prog;
13691 insn = new_prog->insnsi + i + delta;
13692 continue;
13693 }
13694
81ed18ab 13695patch_call_imm:
5e43f899 13696 fn = env->ops->get_func_proto(insn->imm, env->prog);
79741b3b
AS
13697 /* all functions that have prototype and verifier allowed
13698 * programs to call them, must be real in-kernel functions
13699 */
13700 if (!fn->func) {
61bd5218
JK
13701 verbose(env,
13702 "kernel subsystem misconfigured func %s#%d\n",
79741b3b
AS
13703 func_id_name(insn->imm), insn->imm);
13704 return -EFAULT;
e245c5c6 13705 }
79741b3b 13706 insn->imm = fn->func - __bpf_call_base;
e245c5c6 13707 }
e245c5c6 13708
d2e4c1e6
DB
13709 /* Since poke tab is now finalized, publish aux to tracker. */
13710 for (i = 0; i < prog->aux->size_poke_tab; i++) {
13711 map_ptr = prog->aux->poke_tab[i].tail_call.map;
13712 if (!map_ptr->ops->map_poke_track ||
13713 !map_ptr->ops->map_poke_untrack ||
13714 !map_ptr->ops->map_poke_run) {
13715 verbose(env, "bpf verifier is misconfigured\n");
13716 return -EINVAL;
13717 }
13718
13719 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
13720 if (ret < 0) {
13721 verbose(env, "tracking tail call prog failed\n");
13722 return ret;
13723 }
13724 }
13725
e6ac2450
MKL
13726 sort_kfunc_descs_by_imm(env->prog);
13727
79741b3b
AS
13728 return 0;
13729}
e245c5c6 13730
58e2af8b 13731static void free_states(struct bpf_verifier_env *env)
f1bca824 13732{
58e2af8b 13733 struct bpf_verifier_state_list *sl, *sln;
f1bca824
AS
13734 int i;
13735
9f4686c4
AS
13736 sl = env->free_list;
13737 while (sl) {
13738 sln = sl->next;
13739 free_verifier_state(&sl->state, false);
13740 kfree(sl);
13741 sl = sln;
13742 }
51c39bb1 13743 env->free_list = NULL;
9f4686c4 13744
f1bca824
AS
13745 if (!env->explored_states)
13746 return;
13747
dc2a4ebc 13748 for (i = 0; i < state_htab_size(env); i++) {
f1bca824
AS
13749 sl = env->explored_states[i];
13750
a8f500af
AS
13751 while (sl) {
13752 sln = sl->next;
13753 free_verifier_state(&sl->state, false);
13754 kfree(sl);
13755 sl = sln;
13756 }
51c39bb1 13757 env->explored_states[i] = NULL;
f1bca824 13758 }
51c39bb1 13759}
f1bca824 13760
51c39bb1
AS
13761static int do_check_common(struct bpf_verifier_env *env, int subprog)
13762{
6f8a57cc 13763 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
51c39bb1
AS
13764 struct bpf_verifier_state *state;
13765 struct bpf_reg_state *regs;
13766 int ret, i;
13767
13768 env->prev_linfo = NULL;
13769 env->pass_cnt++;
13770
13771 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
13772 if (!state)
13773 return -ENOMEM;
13774 state->curframe = 0;
13775 state->speculative = false;
13776 state->branches = 1;
13777 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
13778 if (!state->frame[0]) {
13779 kfree(state);
13780 return -ENOMEM;
13781 }
13782 env->cur_state = state;
13783 init_func_state(env, state->frame[0],
13784 BPF_MAIN_FUNC /* callsite */,
13785 0 /* frameno */,
13786 subprog);
13787
13788 regs = state->frame[state->curframe]->regs;
be8704ff 13789 if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
51c39bb1
AS
13790 ret = btf_prepare_func_args(env, subprog, regs);
13791 if (ret)
13792 goto out;
13793 for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
13794 if (regs[i].type == PTR_TO_CTX)
13795 mark_reg_known_zero(env, regs, i);
13796 else if (regs[i].type == SCALAR_VALUE)
13797 mark_reg_unknown(env, regs, i);
cf9f2f8d 13798 else if (base_type(regs[i].type) == PTR_TO_MEM) {
e5069b9c
DB
13799 const u32 mem_size = regs[i].mem_size;
13800
13801 mark_reg_known_zero(env, regs, i);
13802 regs[i].mem_size = mem_size;
13803 regs[i].id = ++env->id_gen;
13804 }
51c39bb1
AS
13805 }
13806 } else {
13807 /* 1st arg to a function */
13808 regs[BPF_REG_1].type = PTR_TO_CTX;
13809 mark_reg_known_zero(env, regs, BPF_REG_1);
34747c41 13810 ret = btf_check_subprog_arg_match(env, subprog, regs);
51c39bb1
AS
13811 if (ret == -EFAULT)
13812 /* unlikely verifier bug. abort.
13813 * ret == 0 and ret < 0 are sadly acceptable for
13814 * main() function due to backward compatibility.
13815 * Like socket filter program may be written as:
13816 * int bpf_prog(struct pt_regs *ctx)
13817 * and never dereference that ctx in the program.
13818 * 'struct pt_regs' is a type mismatch for socket
13819 * filter that should be using 'struct __sk_buff'.
13820 */
13821 goto out;
13822 }
13823
13824 ret = do_check(env);
13825out:
f59bbfc2
AS
13826 /* check for NULL is necessary, since cur_state can be freed inside
13827 * do_check() under memory pressure.
13828 */
13829 if (env->cur_state) {
13830 free_verifier_state(env->cur_state, true);
13831 env->cur_state = NULL;
13832 }
6f8a57cc
AN
13833 while (!pop_stack(env, NULL, NULL, false));
13834 if (!ret && pop_log)
13835 bpf_vlog_reset(&env->log, 0);
51c39bb1 13836 free_states(env);
51c39bb1
AS
13837 return ret;
13838}
13839
13840/* Verify all global functions in a BPF program one by one based on their BTF.
13841 * All global functions must pass verification. Otherwise the whole program is rejected.
13842 * Consider:
13843 * int bar(int);
13844 * int foo(int f)
13845 * {
13846 * return bar(f);
13847 * }
13848 * int bar(int b)
13849 * {
13850 * ...
13851 * }
13852 * foo() will be verified first for R1=any_scalar_value. During verification it
13853 * will be assumed that bar() already verified successfully and call to bar()
13854 * from foo() will be checked for type match only. Later bar() will be verified
13855 * independently to check that it's safe for R1=any_scalar_value.
13856 */
13857static int do_check_subprogs(struct bpf_verifier_env *env)
13858{
13859 struct bpf_prog_aux *aux = env->prog->aux;
13860 int i, ret;
13861
13862 if (!aux->func_info)
13863 return 0;
13864
13865 for (i = 1; i < env->subprog_cnt; i++) {
13866 if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
13867 continue;
13868 env->insn_idx = env->subprog_info[i].start;
13869 WARN_ON_ONCE(env->insn_idx == 0);
13870 ret = do_check_common(env, i);
13871 if (ret) {
13872 return ret;
13873 } else if (env->log.level & BPF_LOG_LEVEL) {
13874 verbose(env,
13875 "Func#%d is safe for any args that match its prototype\n",
13876 i);
13877 }
13878 }
13879 return 0;
13880}
13881
13882static int do_check_main(struct bpf_verifier_env *env)
13883{
13884 int ret;
13885
13886 env->insn_idx = 0;
13887 ret = do_check_common(env, 0);
13888 if (!ret)
13889 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
13890 return ret;
13891}
13892
13893
06ee7115
AS
13894static void print_verification_stats(struct bpf_verifier_env *env)
13895{
13896 int i;
13897
13898 if (env->log.level & BPF_LOG_STATS) {
13899 verbose(env, "verification time %lld usec\n",
13900 div_u64(env->verification_time, 1000));
13901 verbose(env, "stack depth ");
13902 for (i = 0; i < env->subprog_cnt; i++) {
13903 u32 depth = env->subprog_info[i].stack_depth;
13904
13905 verbose(env, "%d", depth);
13906 if (i + 1 < env->subprog_cnt)
13907 verbose(env, "+");
13908 }
13909 verbose(env, "\n");
13910 }
13911 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
13912 "total_states %d peak_states %d mark_read %d\n",
13913 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
13914 env->max_states_per_insn, env->total_states,
13915 env->peak_states, env->longest_mark_read_walk);
f1bca824
AS
13916}
13917
27ae7997
MKL
13918static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
13919{
13920 const struct btf_type *t, *func_proto;
13921 const struct bpf_struct_ops *st_ops;
13922 const struct btf_member *member;
13923 struct bpf_prog *prog = env->prog;
13924 u32 btf_id, member_idx;
13925 const char *mname;
13926
12aa8a94
THJ
13927 if (!prog->gpl_compatible) {
13928 verbose(env, "struct ops programs must have a GPL compatible license\n");
13929 return -EINVAL;
13930 }
13931
27ae7997
MKL
13932 btf_id = prog->aux->attach_btf_id;
13933 st_ops = bpf_struct_ops_find(btf_id);
13934 if (!st_ops) {
13935 verbose(env, "attach_btf_id %u is not a supported struct\n",
13936 btf_id);
13937 return -ENOTSUPP;
13938 }
13939
13940 t = st_ops->type;
13941 member_idx = prog->expected_attach_type;
13942 if (member_idx >= btf_type_vlen(t)) {
13943 verbose(env, "attach to invalid member idx %u of struct %s\n",
13944 member_idx, st_ops->name);
13945 return -EINVAL;
13946 }
13947
13948 member = &btf_type_member(t)[member_idx];
13949 mname = btf_name_by_offset(btf_vmlinux, member->name_off);
13950 func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
13951 NULL);
13952 if (!func_proto) {
13953 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
13954 mname, member_idx, st_ops->name);
13955 return -EINVAL;
13956 }
13957
13958 if (st_ops->check_member) {
13959 int err = st_ops->check_member(t, member);
13960
13961 if (err) {
13962 verbose(env, "attach to unsupported member %s of struct %s\n",
13963 mname, st_ops->name);
13964 return err;
13965 }
13966 }
13967
13968 prog->aux->attach_func_proto = func_proto;
13969 prog->aux->attach_func_name = mname;
13970 env->ops = st_ops->verifier_ops;
13971
13972 return 0;
13973}
6ba43b76
KS
13974#define SECURITY_PREFIX "security_"
13975
f7b12b6f 13976static int check_attach_modify_return(unsigned long addr, const char *func_name)
6ba43b76 13977{
69191754 13978 if (within_error_injection_list(addr) ||
f7b12b6f 13979 !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
6ba43b76 13980 return 0;
6ba43b76 13981
6ba43b76
KS
13982 return -EINVAL;
13983}
27ae7997 13984
1e6c62a8
AS
13985/* list of non-sleepable functions that are otherwise on
13986 * ALLOW_ERROR_INJECTION list
13987 */
13988BTF_SET_START(btf_non_sleepable_error_inject)
13989/* Three functions below can be called from sleepable and non-sleepable context.
13990 * Assume non-sleepable from bpf safety point of view.
13991 */
9dd3d069 13992BTF_ID(func, __filemap_add_folio)
1e6c62a8
AS
13993BTF_ID(func, should_fail_alloc_page)
13994BTF_ID(func, should_failslab)
13995BTF_SET_END(btf_non_sleepable_error_inject)
13996
13997static int check_non_sleepable_error_inject(u32 btf_id)
13998{
13999 return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
14000}
14001
f7b12b6f
THJ
14002int bpf_check_attach_target(struct bpf_verifier_log *log,
14003 const struct bpf_prog *prog,
14004 const struct bpf_prog *tgt_prog,
14005 u32 btf_id,
14006 struct bpf_attach_target_info *tgt_info)
38207291 14007{
be8704ff 14008 bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
f1b9509c 14009 const char prefix[] = "btf_trace_";
5b92a28a 14010 int ret = 0, subprog = -1, i;
38207291 14011 const struct btf_type *t;
5b92a28a 14012 bool conservative = true;
38207291 14013 const char *tname;
5b92a28a 14014 struct btf *btf;
f7b12b6f 14015 long addr = 0;
38207291 14016
f1b9509c 14017 if (!btf_id) {
efc68158 14018 bpf_log(log, "Tracing programs must provide btf_id\n");
f1b9509c
AS
14019 return -EINVAL;
14020 }
22dc4a0f 14021 btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
5b92a28a 14022 if (!btf) {
efc68158 14023 bpf_log(log,
5b92a28a
AS
14024 "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
14025 return -EINVAL;
14026 }
14027 t = btf_type_by_id(btf, btf_id);
f1b9509c 14028 if (!t) {
efc68158 14029 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
f1b9509c
AS
14030 return -EINVAL;
14031 }
5b92a28a 14032 tname = btf_name_by_offset(btf, t->name_off);
f1b9509c 14033 if (!tname) {
efc68158 14034 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
f1b9509c
AS
14035 return -EINVAL;
14036 }
5b92a28a
AS
14037 if (tgt_prog) {
14038 struct bpf_prog_aux *aux = tgt_prog->aux;
14039
14040 for (i = 0; i < aux->func_info_cnt; i++)
14041 if (aux->func_info[i].type_id == btf_id) {
14042 subprog = i;
14043 break;
14044 }
14045 if (subprog == -1) {
efc68158 14046 bpf_log(log, "Subprog %s doesn't exist\n", tname);
5b92a28a
AS
14047 return -EINVAL;
14048 }
14049 conservative = aux->func_info_aux[subprog].unreliable;
be8704ff
AS
14050 if (prog_extension) {
14051 if (conservative) {
efc68158 14052 bpf_log(log,
be8704ff
AS
14053 "Cannot replace static functions\n");
14054 return -EINVAL;
14055 }
14056 if (!prog->jit_requested) {
efc68158 14057 bpf_log(log,
be8704ff
AS
14058 "Extension programs should be JITed\n");
14059 return -EINVAL;
14060 }
be8704ff
AS
14061 }
14062 if (!tgt_prog->jited) {
efc68158 14063 bpf_log(log, "Can attach to only JITed progs\n");
be8704ff
AS
14064 return -EINVAL;
14065 }
14066 if (tgt_prog->type == prog->type) {
14067 /* Cannot fentry/fexit another fentry/fexit program.
14068 * Cannot attach program extension to another extension.
14069 * It's ok to attach fentry/fexit to extension program.
14070 */
efc68158 14071 bpf_log(log, "Cannot recursively attach\n");
be8704ff
AS
14072 return -EINVAL;
14073 }
14074 if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
14075 prog_extension &&
14076 (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
14077 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
14078 /* Program extensions can extend all program types
14079 * except fentry/fexit. The reason is the following.
14080 * The fentry/fexit programs are used for performance
14081 * analysis, stats and can be attached to any program
14082 * type except themselves. When extension program is
14083 * replacing XDP function it is necessary to allow
14084 * performance analysis of all functions. Both original
14085 * XDP program and its program extension. Hence
14086 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
14087 * allowed. If extending of fentry/fexit was allowed it
14088 * would be possible to create long call chain
14089 * fentry->extension->fentry->extension beyond
14090 * reasonable stack size. Hence extending fentry is not
14091 * allowed.
14092 */
efc68158 14093 bpf_log(log, "Cannot extend fentry/fexit\n");
be8704ff
AS
14094 return -EINVAL;
14095 }
5b92a28a 14096 } else {
be8704ff 14097 if (prog_extension) {
efc68158 14098 bpf_log(log, "Cannot replace kernel functions\n");
be8704ff
AS
14099 return -EINVAL;
14100 }
5b92a28a 14101 }
f1b9509c
AS
14102
14103 switch (prog->expected_attach_type) {
14104 case BPF_TRACE_RAW_TP:
5b92a28a 14105 if (tgt_prog) {
efc68158 14106 bpf_log(log,
5b92a28a
AS
14107 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
14108 return -EINVAL;
14109 }
38207291 14110 if (!btf_type_is_typedef(t)) {
efc68158 14111 bpf_log(log, "attach_btf_id %u is not a typedef\n",
38207291
MKL
14112 btf_id);
14113 return -EINVAL;
14114 }
f1b9509c 14115 if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
efc68158 14116 bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
38207291
MKL
14117 btf_id, tname);
14118 return -EINVAL;
14119 }
14120 tname += sizeof(prefix) - 1;
5b92a28a 14121 t = btf_type_by_id(btf, t->type);
38207291
MKL
14122 if (!btf_type_is_ptr(t))
14123 /* should never happen in valid vmlinux build */
14124 return -EINVAL;
5b92a28a 14125 t = btf_type_by_id(btf, t->type);
38207291
MKL
14126 if (!btf_type_is_func_proto(t))
14127 /* should never happen in valid vmlinux build */
14128 return -EINVAL;
14129
f7b12b6f 14130 break;
15d83c4d
YS
14131 case BPF_TRACE_ITER:
14132 if (!btf_type_is_func(t)) {
efc68158 14133 bpf_log(log, "attach_btf_id %u is not a function\n",
15d83c4d
YS
14134 btf_id);
14135 return -EINVAL;
14136 }
14137 t = btf_type_by_id(btf, t->type);
14138 if (!btf_type_is_func_proto(t))
14139 return -EINVAL;
f7b12b6f
THJ
14140 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
14141 if (ret)
14142 return ret;
14143 break;
be8704ff
AS
14144 default:
14145 if (!prog_extension)
14146 return -EINVAL;
df561f66 14147 fallthrough;
ae240823 14148 case BPF_MODIFY_RETURN:
9e4e01df 14149 case BPF_LSM_MAC:
fec56f58
AS
14150 case BPF_TRACE_FENTRY:
14151 case BPF_TRACE_FEXIT:
14152 if (!btf_type_is_func(t)) {
efc68158 14153 bpf_log(log, "attach_btf_id %u is not a function\n",
fec56f58
AS
14154 btf_id);
14155 return -EINVAL;
14156 }
be8704ff 14157 if (prog_extension &&
efc68158 14158 btf_check_type_match(log, prog, btf, t))
be8704ff 14159 return -EINVAL;
5b92a28a 14160 t = btf_type_by_id(btf, t->type);
fec56f58
AS
14161 if (!btf_type_is_func_proto(t))
14162 return -EINVAL;
f7b12b6f 14163
4a1e7c0c
THJ
14164 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
14165 (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
14166 prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
14167 return -EINVAL;
14168
f7b12b6f 14169 if (tgt_prog && conservative)
5b92a28a 14170 t = NULL;
f7b12b6f
THJ
14171
14172 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
fec56f58 14173 if (ret < 0)
f7b12b6f
THJ
14174 return ret;
14175
5b92a28a 14176 if (tgt_prog) {
e9eeec58
YS
14177 if (subprog == 0)
14178 addr = (long) tgt_prog->bpf_func;
14179 else
14180 addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
5b92a28a
AS
14181 } else {
14182 addr = kallsyms_lookup_name(tname);
14183 if (!addr) {
efc68158 14184 bpf_log(log,
5b92a28a
AS
14185 "The address of function %s cannot be found\n",
14186 tname);
f7b12b6f 14187 return -ENOENT;
5b92a28a 14188 }
fec56f58 14189 }
18644cec 14190
1e6c62a8
AS
14191 if (prog->aux->sleepable) {
14192 ret = -EINVAL;
14193 switch (prog->type) {
14194 case BPF_PROG_TYPE_TRACING:
14195 /* fentry/fexit/fmod_ret progs can be sleepable only if they are
14196 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
14197 */
14198 if (!check_non_sleepable_error_inject(btf_id) &&
14199 within_error_injection_list(addr))
14200 ret = 0;
14201 break;
14202 case BPF_PROG_TYPE_LSM:
14203 /* LSM progs check that they are attached to bpf_lsm_*() funcs.
14204 * Only some of them are sleepable.
14205 */
423f1610 14206 if (bpf_lsm_is_sleepable_hook(btf_id))
1e6c62a8
AS
14207 ret = 0;
14208 break;
14209 default:
14210 break;
14211 }
f7b12b6f
THJ
14212 if (ret) {
14213 bpf_log(log, "%s is not sleepable\n", tname);
14214 return ret;
14215 }
1e6c62a8 14216 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
1af9270e 14217 if (tgt_prog) {
efc68158 14218 bpf_log(log, "can't modify return codes of BPF programs\n");
f7b12b6f
THJ
14219 return -EINVAL;
14220 }
14221 ret = check_attach_modify_return(addr, tname);
14222 if (ret) {
14223 bpf_log(log, "%s() is not modifiable\n", tname);
14224 return ret;
1af9270e 14225 }
18644cec 14226 }
f7b12b6f
THJ
14227
14228 break;
14229 }
14230 tgt_info->tgt_addr = addr;
14231 tgt_info->tgt_name = tname;
14232 tgt_info->tgt_type = t;
14233 return 0;
14234}
14235
35e3815f
JO
14236BTF_SET_START(btf_id_deny)
14237BTF_ID_UNUSED
14238#ifdef CONFIG_SMP
14239BTF_ID(func, migrate_disable)
14240BTF_ID(func, migrate_enable)
14241#endif
14242#if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
14243BTF_ID(func, rcu_read_unlock_strict)
14244#endif
14245BTF_SET_END(btf_id_deny)
14246
f7b12b6f
THJ
14247static int check_attach_btf_id(struct bpf_verifier_env *env)
14248{
14249 struct bpf_prog *prog = env->prog;
3aac1ead 14250 struct bpf_prog *tgt_prog = prog->aux->dst_prog;
f7b12b6f
THJ
14251 struct bpf_attach_target_info tgt_info = {};
14252 u32 btf_id = prog->aux->attach_btf_id;
14253 struct bpf_trampoline *tr;
14254 int ret;
14255 u64 key;
14256
79a7f8bd
AS
14257 if (prog->type == BPF_PROG_TYPE_SYSCALL) {
14258 if (prog->aux->sleepable)
14259 /* attach_btf_id checked to be zero already */
14260 return 0;
14261 verbose(env, "Syscall programs can only be sleepable\n");
14262 return -EINVAL;
14263 }
14264
f7b12b6f
THJ
14265 if (prog->aux->sleepable && prog->type != BPF_PROG_TYPE_TRACING &&
14266 prog->type != BPF_PROG_TYPE_LSM) {
14267 verbose(env, "Only fentry/fexit/fmod_ret and lsm programs can be sleepable\n");
14268 return -EINVAL;
14269 }
14270
14271 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
14272 return check_struct_ops_btf_id(env);
14273
14274 if (prog->type != BPF_PROG_TYPE_TRACING &&
14275 prog->type != BPF_PROG_TYPE_LSM &&
14276 prog->type != BPF_PROG_TYPE_EXT)
14277 return 0;
14278
14279 ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
14280 if (ret)
fec56f58 14281 return ret;
f7b12b6f
THJ
14282
14283 if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
3aac1ead
THJ
14284 /* to make freplace equivalent to their targets, they need to
14285 * inherit env->ops and expected_attach_type for the rest of the
14286 * verification
14287 */
f7b12b6f
THJ
14288 env->ops = bpf_verifier_ops[tgt_prog->type];
14289 prog->expected_attach_type = tgt_prog->expected_attach_type;
14290 }
14291
14292 /* store info about the attachment target that will be used later */
14293 prog->aux->attach_func_proto = tgt_info.tgt_type;
14294 prog->aux->attach_func_name = tgt_info.tgt_name;
14295
4a1e7c0c
THJ
14296 if (tgt_prog) {
14297 prog->aux->saved_dst_prog_type = tgt_prog->type;
14298 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
14299 }
14300
f7b12b6f
THJ
14301 if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
14302 prog->aux->attach_btf_trace = true;
14303 return 0;
14304 } else if (prog->expected_attach_type == BPF_TRACE_ITER) {
14305 if (!bpf_iter_prog_supported(prog))
14306 return -EINVAL;
14307 return 0;
14308 }
14309
14310 if (prog->type == BPF_PROG_TYPE_LSM) {
14311 ret = bpf_lsm_verify_prog(&env->log, prog);
14312 if (ret < 0)
14313 return ret;
35e3815f
JO
14314 } else if (prog->type == BPF_PROG_TYPE_TRACING &&
14315 btf_id_set_contains(&btf_id_deny, btf_id)) {
14316 return -EINVAL;
38207291 14317 }
f7b12b6f 14318
22dc4a0f 14319 key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
f7b12b6f
THJ
14320 tr = bpf_trampoline_get(key, &tgt_info);
14321 if (!tr)
14322 return -ENOMEM;
14323
3aac1ead 14324 prog->aux->dst_trampoline = tr;
f7b12b6f 14325 return 0;
38207291
MKL
14326}
14327
76654e67
AM
14328struct btf *bpf_get_btf_vmlinux(void)
14329{
14330 if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
14331 mutex_lock(&bpf_verifier_lock);
14332 if (!btf_vmlinux)
14333 btf_vmlinux = btf_parse_vmlinux();
14334 mutex_unlock(&bpf_verifier_lock);
14335 }
14336 return btf_vmlinux;
14337}
14338
af2ac3e1 14339int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr)
51580e79 14340{
06ee7115 14341 u64 start_time = ktime_get_ns();
58e2af8b 14342 struct bpf_verifier_env *env;
b9193c1b 14343 struct bpf_verifier_log *log;
9e4c24e7 14344 int i, len, ret = -EINVAL;
e2ae4ca2 14345 bool is_priv;
51580e79 14346
eba0c929
AB
14347 /* no program is valid */
14348 if (ARRAY_SIZE(bpf_verifier_ops) == 0)
14349 return -EINVAL;
14350
58e2af8b 14351 /* 'struct bpf_verifier_env' can be global, but since it's not small,
cbd35700
AS
14352 * allocate/free it every time bpf_check() is called
14353 */
58e2af8b 14354 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
cbd35700
AS
14355 if (!env)
14356 return -ENOMEM;
61bd5218 14357 log = &env->log;
cbd35700 14358
9e4c24e7 14359 len = (*prog)->len;
fad953ce 14360 env->insn_aux_data =
9e4c24e7 14361 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
3df126f3
JK
14362 ret = -ENOMEM;
14363 if (!env->insn_aux_data)
14364 goto err_free_env;
9e4c24e7
JK
14365 for (i = 0; i < len; i++)
14366 env->insn_aux_data[i].orig_idx = i;
9bac3d6d 14367 env->prog = *prog;
00176a34 14368 env->ops = bpf_verifier_ops[env->prog->type];
387544bf 14369 env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
2c78ee89 14370 is_priv = bpf_capable();
0246e64d 14371
76654e67 14372 bpf_get_btf_vmlinux();
8580ac94 14373
cbd35700 14374 /* grab the mutex to protect few globals used by verifier */
45a73c17
AS
14375 if (!is_priv)
14376 mutex_lock(&bpf_verifier_lock);
cbd35700
AS
14377
14378 if (attr->log_level || attr->log_buf || attr->log_size) {
14379 /* user requested verbose verifier output
14380 * and supplied buffer to store the verification trace
14381 */
e7bf8249
JK
14382 log->level = attr->log_level;
14383 log->ubuf = (char __user *) (unsigned long) attr->log_buf;
14384 log->len_total = attr->log_size;
cbd35700 14385
e7bf8249 14386 /* log attributes have to be sane */
866de407
HT
14387 if (!bpf_verifier_log_attr_valid(log)) {
14388 ret = -EINVAL;
3df126f3 14389 goto err_unlock;
866de407 14390 }
cbd35700 14391 }
1ad2f583 14392
0f55f9ed
CL
14393 mark_verifier_state_clean(env);
14394
8580ac94
AS
14395 if (IS_ERR(btf_vmlinux)) {
14396 /* Either gcc or pahole or kernel are broken. */
14397 verbose(env, "in-kernel BTF is malformed\n");
14398 ret = PTR_ERR(btf_vmlinux);
38207291 14399 goto skip_full_check;
8580ac94
AS
14400 }
14401
1ad2f583
DB
14402 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
14403 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
e07b98d9 14404 env->strict_alignment = true;
e9ee9efc
DM
14405 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
14406 env->strict_alignment = false;
cbd35700 14407
2c78ee89 14408 env->allow_ptr_leaks = bpf_allow_ptr_leaks();
01f810ac 14409 env->allow_uninit_stack = bpf_allow_uninit_stack();
41c48f3a 14410 env->allow_ptr_to_map_access = bpf_allow_ptr_to_map_access();
2c78ee89
AS
14411 env->bypass_spec_v1 = bpf_bypass_spec_v1();
14412 env->bypass_spec_v4 = bpf_bypass_spec_v4();
14413 env->bpf_capable = bpf_capable();
e2ae4ca2 14414
10d274e8
AS
14415 if (is_priv)
14416 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
14417
dc2a4ebc 14418 env->explored_states = kvcalloc(state_htab_size(env),
58e2af8b 14419 sizeof(struct bpf_verifier_state_list *),
f1bca824
AS
14420 GFP_USER);
14421 ret = -ENOMEM;
14422 if (!env->explored_states)
14423 goto skip_full_check;
14424
e6ac2450
MKL
14425 ret = add_subprog_and_kfunc(env);
14426 if (ret < 0)
14427 goto skip_full_check;
14428
d9762e84 14429 ret = check_subprogs(env);
475fb78f
AS
14430 if (ret < 0)
14431 goto skip_full_check;
14432
c454a46b 14433 ret = check_btf_info(env, attr, uattr);
838e9690
YS
14434 if (ret < 0)
14435 goto skip_full_check;
14436
be8704ff
AS
14437 ret = check_attach_btf_id(env);
14438 if (ret)
14439 goto skip_full_check;
14440
4976b718
HL
14441 ret = resolve_pseudo_ldimm64(env);
14442 if (ret < 0)
14443 goto skip_full_check;
14444
ceb11679
YZ
14445 if (bpf_prog_is_dev_bound(env->prog->aux)) {
14446 ret = bpf_prog_offload_verifier_prep(env->prog);
14447 if (ret)
14448 goto skip_full_check;
14449 }
14450
d9762e84
MKL
14451 ret = check_cfg(env);
14452 if (ret < 0)
14453 goto skip_full_check;
14454
51c39bb1
AS
14455 ret = do_check_subprogs(env);
14456 ret = ret ?: do_check_main(env);
cbd35700 14457
c941ce9c
QM
14458 if (ret == 0 && bpf_prog_is_dev_bound(env->prog->aux))
14459 ret = bpf_prog_offload_finalize(env);
14460
0246e64d 14461skip_full_check:
51c39bb1 14462 kvfree(env->explored_states);
0246e64d 14463
c131187d 14464 if (ret == 0)
9b38c405 14465 ret = check_max_stack_depth(env);
c131187d 14466
9b38c405 14467 /* instruction rewrites happen after this point */
e2ae4ca2
JK
14468 if (is_priv) {
14469 if (ret == 0)
14470 opt_hard_wire_dead_code_branches(env);
52875a04
JK
14471 if (ret == 0)
14472 ret = opt_remove_dead_code(env);
a1b14abc
JK
14473 if (ret == 0)
14474 ret = opt_remove_nops(env);
52875a04
JK
14475 } else {
14476 if (ret == 0)
14477 sanitize_dead_code(env);
e2ae4ca2
JK
14478 }
14479
9bac3d6d
AS
14480 if (ret == 0)
14481 /* program is valid, convert *(u32*)(ctx + off) accesses */
14482 ret = convert_ctx_accesses(env);
14483
e245c5c6 14484 if (ret == 0)
e6ac5933 14485 ret = do_misc_fixups(env);
e245c5c6 14486
a4b1d3c1
JW
14487 /* do 32-bit optimization after insn patching has done so those patched
14488 * insns could be handled correctly.
14489 */
d6c2308c
JW
14490 if (ret == 0 && !bpf_prog_is_dev_bound(env->prog->aux)) {
14491 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
14492 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
14493 : false;
a4b1d3c1
JW
14494 }
14495
1ea47e01
AS
14496 if (ret == 0)
14497 ret = fixup_call_args(env);
14498
06ee7115
AS
14499 env->verification_time = ktime_get_ns() - start_time;
14500 print_verification_stats(env);
aba64c7d 14501 env->prog->aux->verified_insns = env->insn_processed;
06ee7115 14502
a2a7d570 14503 if (log->level && bpf_verifier_log_full(log))
cbd35700 14504 ret = -ENOSPC;
a2a7d570 14505 if (log->level && !log->ubuf) {
cbd35700 14506 ret = -EFAULT;
a2a7d570 14507 goto err_release_maps;
cbd35700
AS
14508 }
14509
541c3bad
AN
14510 if (ret)
14511 goto err_release_maps;
14512
14513 if (env->used_map_cnt) {
0246e64d 14514 /* if program passed verifier, update used_maps in bpf_prog_info */
9bac3d6d
AS
14515 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
14516 sizeof(env->used_maps[0]),
14517 GFP_KERNEL);
0246e64d 14518
9bac3d6d 14519 if (!env->prog->aux->used_maps) {
0246e64d 14520 ret = -ENOMEM;
a2a7d570 14521 goto err_release_maps;
0246e64d
AS
14522 }
14523
9bac3d6d 14524 memcpy(env->prog->aux->used_maps, env->used_maps,
0246e64d 14525 sizeof(env->used_maps[0]) * env->used_map_cnt);
9bac3d6d 14526 env->prog->aux->used_map_cnt = env->used_map_cnt;
541c3bad
AN
14527 }
14528 if (env->used_btf_cnt) {
14529 /* if program passed verifier, update used_btfs in bpf_prog_aux */
14530 env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
14531 sizeof(env->used_btfs[0]),
14532 GFP_KERNEL);
14533 if (!env->prog->aux->used_btfs) {
14534 ret = -ENOMEM;
14535 goto err_release_maps;
14536 }
0246e64d 14537
541c3bad
AN
14538 memcpy(env->prog->aux->used_btfs, env->used_btfs,
14539 sizeof(env->used_btfs[0]) * env->used_btf_cnt);
14540 env->prog->aux->used_btf_cnt = env->used_btf_cnt;
14541 }
14542 if (env->used_map_cnt || env->used_btf_cnt) {
0246e64d
AS
14543 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
14544 * bpf_ld_imm64 instructions
14545 */
14546 convert_pseudo_ld_imm64(env);
14547 }
cbd35700 14548
541c3bad 14549 adjust_btf_func(env);
ba64e7d8 14550
a2a7d570 14551err_release_maps:
9bac3d6d 14552 if (!env->prog->aux->used_maps)
0246e64d 14553 /* if we didn't copy map pointers into bpf_prog_info, release
ab7f5bf0 14554 * them now. Otherwise free_used_maps() will release them.
0246e64d
AS
14555 */
14556 release_maps(env);
541c3bad
AN
14557 if (!env->prog->aux->used_btfs)
14558 release_btfs(env);
03f87c0b
THJ
14559
14560 /* extension progs temporarily inherit the attach_type of their targets
14561 for verification purposes, so set it back to zero before returning
14562 */
14563 if (env->prog->type == BPF_PROG_TYPE_EXT)
14564 env->prog->expected_attach_type = 0;
14565
9bac3d6d 14566 *prog = env->prog;
3df126f3 14567err_unlock:
45a73c17
AS
14568 if (!is_priv)
14569 mutex_unlock(&bpf_verifier_lock);
3df126f3
JK
14570 vfree(env->insn_aux_data);
14571err_free_env:
14572 kfree(env);
51580e79
AS
14573 return ret;
14574}