bpf: verifier: Improve function state reallocation
[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>
51580e79
AS
7#include <linux/kernel.h>
8#include <linux/types.h>
9#include <linux/slab.h>
10#include <linux/bpf.h>
838e9690 11#include <linux/btf.h>
58e2af8b 12#include <linux/bpf_verifier.h>
51580e79
AS
13#include <linux/filter.h>
14#include <net/netlink.h>
15#include <linux/file.h>
16#include <linux/vmalloc.h>
ebb676da 17#include <linux/stringify.h>
cc8b0b92
AS
18#include <linux/bsearch.h>
19#include <linux/sort.h>
c195651e 20#include <linux/perf_event.h>
d9762e84 21#include <linux/ctype.h>
6ba43b76 22#include <linux/error-injection.h>
9e4e01df 23#include <linux/bpf_lsm.h>
1e6c62a8 24#include <linux/btf_ids.h>
51580e79 25
f4ac7e0b
JK
26#include "disasm.h"
27
00176a34 28static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
91cc1a99 29#define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
00176a34
JK
30 [_id] = & _name ## _verifier_ops,
31#define BPF_MAP_TYPE(_id, _ops)
f2e10bff 32#define BPF_LINK_TYPE(_id, _name)
00176a34
JK
33#include <linux/bpf_types.h>
34#undef BPF_PROG_TYPE
35#undef BPF_MAP_TYPE
f2e10bff 36#undef BPF_LINK_TYPE
00176a34
JK
37};
38
51580e79
AS
39/* bpf_check() is a static code analyzer that walks eBPF program
40 * instruction by instruction and updates register/stack state.
41 * All paths of conditional branches are analyzed until 'bpf_exit' insn.
42 *
43 * The first pass is depth-first-search to check that the program is a DAG.
44 * It rejects the following programs:
45 * - larger than BPF_MAXINSNS insns
46 * - if loop is present (detected via back-edge)
47 * - unreachable insns exist (shouldn't be a forest. program = one function)
48 * - out of bounds or malformed jumps
49 * The second pass is all possible path descent from the 1st insn.
50 * Since it's analyzing all pathes through the program, the length of the
eba38a96 51 * analysis is limited to 64k insn, which may be hit even if total number of
51580e79
AS
52 * insn is less then 4K, but there are too many branches that change stack/regs.
53 * Number of 'branches to be analyzed' is limited to 1k
54 *
55 * On entry to each instruction, each register has a type, and the instruction
56 * changes the types of the registers depending on instruction semantics.
57 * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
58 * copied to R1.
59 *
60 * All registers are 64-bit.
61 * R0 - return register
62 * R1-R5 argument passing registers
63 * R6-R9 callee saved registers
64 * R10 - frame pointer read-only
65 *
66 * At the start of BPF program the register R1 contains a pointer to bpf_context
67 * and has type PTR_TO_CTX.
68 *
69 * Verifier tracks arithmetic operations on pointers in case:
70 * BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
71 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
72 * 1st insn copies R10 (which has FRAME_PTR) type into R1
73 * and 2nd arithmetic instruction is pattern matched to recognize
74 * that it wants to construct a pointer to some element within stack.
75 * So after 2nd insn, the register R1 has type PTR_TO_STACK
76 * (and -20 constant is saved for further stack bounds checking).
77 * Meaning that this reg is a pointer to stack plus known immediate constant.
78 *
f1174f77 79 * Most of the time the registers have SCALAR_VALUE type, which
51580e79 80 * means the register has some value, but it's not a valid pointer.
f1174f77 81 * (like pointer plus pointer becomes SCALAR_VALUE type)
51580e79
AS
82 *
83 * When verifier sees load or store instructions the type of base register
c64b7983
JS
84 * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are
85 * four pointer types recognized by check_mem_access() function.
51580e79
AS
86 *
87 * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
88 * and the range of [ptr, ptr + map's value_size) is accessible.
89 *
90 * registers used to pass values to function calls are checked against
91 * function argument constraints.
92 *
93 * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
94 * It means that the register type passed to this function must be
95 * PTR_TO_STACK and it will be used inside the function as
96 * 'pointer to map element key'
97 *
98 * For example the argument constraints for bpf_map_lookup_elem():
99 * .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
100 * .arg1_type = ARG_CONST_MAP_PTR,
101 * .arg2_type = ARG_PTR_TO_MAP_KEY,
102 *
103 * ret_type says that this function returns 'pointer to map elem value or null'
104 * function expects 1st argument to be a const pointer to 'struct bpf_map' and
105 * 2nd argument should be a pointer to stack, which will be used inside
106 * the helper function as a pointer to map element key.
107 *
108 * On the kernel side the helper function looks like:
109 * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
110 * {
111 * struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
112 * void *key = (void *) (unsigned long) r2;
113 * void *value;
114 *
115 * here kernel can access 'key' and 'map' pointers safely, knowing that
116 * [key, key + map->key_size) bytes are valid and were initialized on
117 * the stack of eBPF program.
118 * }
119 *
120 * Corresponding eBPF program may look like:
121 * BPF_MOV64_REG(BPF_REG_2, BPF_REG_10), // after this insn R2 type is FRAME_PTR
122 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
123 * BPF_LD_MAP_FD(BPF_REG_1, map_fd), // after this insn R1 type is CONST_PTR_TO_MAP
124 * BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
125 * here verifier looks at prototype of map_lookup_elem() and sees:
126 * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
127 * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
128 *
129 * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
130 * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
131 * and were initialized prior to this call.
132 * If it's ok, then verifier allows this BPF_CALL insn and looks at
133 * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
134 * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
135 * returns ether pointer to map value or NULL.
136 *
137 * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
138 * insn, the register holding that pointer in the true branch changes state to
139 * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
140 * branch. See check_cond_jmp_op().
141 *
142 * After the call R0 is set to return type of the function and registers R1-R5
143 * are set to NOT_INIT to indicate that they are no longer readable.
fd978bf7
JS
144 *
145 * The following reference types represent a potential reference to a kernel
146 * resource which, after first being allocated, must be checked and freed by
147 * the BPF program:
148 * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET
149 *
150 * When the verifier sees a helper call return a reference type, it allocates a
151 * pointer id for the reference and stores it in the current function state.
152 * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into
153 * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type
154 * passes through a NULL-check conditional. For the branch wherein the state is
155 * changed to CONST_IMM, the verifier releases the reference.
6acc9b43
JS
156 *
157 * For each helper function that allocates a reference, such as
158 * bpf_sk_lookup_tcp(), there is a corresponding release function, such as
159 * bpf_sk_release(). When a reference type passes into the release function,
160 * the verifier also releases the reference. If any unchecked or unreleased
161 * reference remains at the end of the program, the verifier rejects it.
51580e79
AS
162 */
163
17a52670 164/* verifier_state + insn_idx are pushed to stack when branch is encountered */
58e2af8b 165struct bpf_verifier_stack_elem {
17a52670
AS
166 /* verifer state is 'st'
167 * before processing instruction 'insn_idx'
168 * and after processing instruction 'prev_insn_idx'
169 */
58e2af8b 170 struct bpf_verifier_state st;
17a52670
AS
171 int insn_idx;
172 int prev_insn_idx;
58e2af8b 173 struct bpf_verifier_stack_elem *next;
6f8a57cc
AN
174 /* length of verifier log at the time this state was pushed on stack */
175 u32 log_pos;
cbd35700
AS
176};
177
b285fcb7 178#define BPF_COMPLEXITY_LIMIT_JMP_SEQ 8192
ceefbc96 179#define BPF_COMPLEXITY_LIMIT_STATES 64
07016151 180
d2e4c1e6
DB
181#define BPF_MAP_KEY_POISON (1ULL << 63)
182#define BPF_MAP_KEY_SEEN (1ULL << 62)
183
c93552c4
DB
184#define BPF_MAP_PTR_UNPRIV 1UL
185#define BPF_MAP_PTR_POISON ((void *)((0xeB9FUL << 1) + \
186 POISON_POINTER_DELTA))
187#define BPF_MAP_PTR(X) ((struct bpf_map *)((X) & ~BPF_MAP_PTR_UNPRIV))
188
189static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux)
190{
d2e4c1e6 191 return BPF_MAP_PTR(aux->map_ptr_state) == BPF_MAP_PTR_POISON;
c93552c4
DB
192}
193
194static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux)
195{
d2e4c1e6 196 return aux->map_ptr_state & BPF_MAP_PTR_UNPRIV;
c93552c4
DB
197}
198
199static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
200 const struct bpf_map *map, bool unpriv)
201{
202 BUILD_BUG_ON((unsigned long)BPF_MAP_PTR_POISON & BPF_MAP_PTR_UNPRIV);
203 unpriv |= bpf_map_ptr_unpriv(aux);
d2e4c1e6
DB
204 aux->map_ptr_state = (unsigned long)map |
205 (unpriv ? BPF_MAP_PTR_UNPRIV : 0UL);
206}
207
208static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux)
209{
210 return aux->map_key_state & BPF_MAP_KEY_POISON;
211}
212
213static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux)
214{
215 return !(aux->map_key_state & BPF_MAP_KEY_SEEN);
216}
217
218static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux)
219{
220 return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON);
221}
222
223static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state)
224{
225 bool poisoned = bpf_map_key_poisoned(aux);
226
227 aux->map_key_state = state | BPF_MAP_KEY_SEEN |
228 (poisoned ? BPF_MAP_KEY_POISON : 0ULL);
c93552c4 229}
fad73a1a 230
23a2d70c
YS
231static bool bpf_pseudo_call(const struct bpf_insn *insn)
232{
233 return insn->code == (BPF_JMP | BPF_CALL) &&
234 insn->src_reg == BPF_PSEUDO_CALL;
235}
236
e6ac2450
MKL
237static bool bpf_pseudo_kfunc_call(const struct bpf_insn *insn)
238{
239 return insn->code == (BPF_JMP | BPF_CALL) &&
240 insn->src_reg == BPF_PSEUDO_KFUNC_CALL;
241}
242
69c087ba
YS
243static bool bpf_pseudo_func(const struct bpf_insn *insn)
244{
245 return insn->code == (BPF_LD | BPF_IMM | BPF_DW) &&
246 insn->src_reg == BPF_PSEUDO_FUNC;
247}
248
33ff9823
DB
249struct bpf_call_arg_meta {
250 struct bpf_map *map_ptr;
435faee1 251 bool raw_mode;
36bbef52 252 bool pkt_access;
435faee1
DB
253 int regno;
254 int access_size;
457f4436 255 int mem_size;
10060503 256 u64 msize_max_value;
1b986589 257 int ref_obj_id;
d83525ca 258 int func_id;
22dc4a0f 259 struct btf *btf;
eaa6bcb7 260 u32 btf_id;
22dc4a0f 261 struct btf *ret_btf;
eaa6bcb7 262 u32 ret_btf_id;
69c087ba 263 u32 subprogno;
33ff9823
DB
264};
265
8580ac94
AS
266struct btf *btf_vmlinux;
267
cbd35700
AS
268static DEFINE_MUTEX(bpf_verifier_lock);
269
d9762e84
MKL
270static const struct bpf_line_info *
271find_linfo(const struct bpf_verifier_env *env, u32 insn_off)
272{
273 const struct bpf_line_info *linfo;
274 const struct bpf_prog *prog;
275 u32 i, nr_linfo;
276
277 prog = env->prog;
278 nr_linfo = prog->aux->nr_linfo;
279
280 if (!nr_linfo || insn_off >= prog->len)
281 return NULL;
282
283 linfo = prog->aux->linfo;
284 for (i = 1; i < nr_linfo; i++)
285 if (insn_off < linfo[i].insn_off)
286 break;
287
288 return &linfo[i - 1];
289}
290
77d2e05a
MKL
291void bpf_verifier_vlog(struct bpf_verifier_log *log, const char *fmt,
292 va_list args)
cbd35700 293{
a2a7d570 294 unsigned int n;
cbd35700 295
a2a7d570 296 n = vscnprintf(log->kbuf, BPF_VERIFIER_TMP_LOG_SIZE, fmt, args);
a2a7d570
JK
297
298 WARN_ONCE(n >= BPF_VERIFIER_TMP_LOG_SIZE - 1,
299 "verifier log line truncated - local buffer too short\n");
300
301 n = min(log->len_total - log->len_used - 1, n);
302 log->kbuf[n] = '\0';
303
8580ac94
AS
304 if (log->level == BPF_LOG_KERNEL) {
305 pr_err("BPF:%s\n", log->kbuf);
306 return;
307 }
a2a7d570
JK
308 if (!copy_to_user(log->ubuf + log->len_used, log->kbuf, n + 1))
309 log->len_used += n;
310 else
311 log->ubuf = NULL;
cbd35700 312}
abe08840 313
6f8a57cc
AN
314static void bpf_vlog_reset(struct bpf_verifier_log *log, u32 new_pos)
315{
316 char zero = 0;
317
318 if (!bpf_verifier_log_needed(log))
319 return;
320
321 log->len_used = new_pos;
322 if (put_user(zero, log->ubuf + new_pos))
323 log->ubuf = NULL;
324}
325
abe08840
JO
326/* log_level controls verbosity level of eBPF verifier.
327 * bpf_verifier_log_write() is used to dump the verification trace to the log,
328 * so the user can figure out what's wrong with the program
430e68d1 329 */
abe08840
JO
330__printf(2, 3) void bpf_verifier_log_write(struct bpf_verifier_env *env,
331 const char *fmt, ...)
332{
333 va_list args;
334
77d2e05a
MKL
335 if (!bpf_verifier_log_needed(&env->log))
336 return;
337
abe08840 338 va_start(args, fmt);
77d2e05a 339 bpf_verifier_vlog(&env->log, fmt, args);
abe08840
JO
340 va_end(args);
341}
342EXPORT_SYMBOL_GPL(bpf_verifier_log_write);
343
344__printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
345{
77d2e05a 346 struct bpf_verifier_env *env = private_data;
abe08840
JO
347 va_list args;
348
77d2e05a
MKL
349 if (!bpf_verifier_log_needed(&env->log))
350 return;
351
abe08840 352 va_start(args, fmt);
77d2e05a 353 bpf_verifier_vlog(&env->log, fmt, args);
abe08840
JO
354 va_end(args);
355}
cbd35700 356
9e15db66
AS
357__printf(2, 3) void bpf_log(struct bpf_verifier_log *log,
358 const char *fmt, ...)
359{
360 va_list args;
361
362 if (!bpf_verifier_log_needed(log))
363 return;
364
365 va_start(args, fmt);
366 bpf_verifier_vlog(log, fmt, args);
367 va_end(args);
368}
369
d9762e84
MKL
370static const char *ltrim(const char *s)
371{
372 while (isspace(*s))
373 s++;
374
375 return s;
376}
377
378__printf(3, 4) static void verbose_linfo(struct bpf_verifier_env *env,
379 u32 insn_off,
380 const char *prefix_fmt, ...)
381{
382 const struct bpf_line_info *linfo;
383
384 if (!bpf_verifier_log_needed(&env->log))
385 return;
386
387 linfo = find_linfo(env, insn_off);
388 if (!linfo || linfo == env->prev_linfo)
389 return;
390
391 if (prefix_fmt) {
392 va_list args;
393
394 va_start(args, prefix_fmt);
395 bpf_verifier_vlog(&env->log, prefix_fmt, args);
396 va_end(args);
397 }
398
399 verbose(env, "%s\n",
400 ltrim(btf_name_by_offset(env->prog->aux->btf,
401 linfo->line_off)));
402
403 env->prev_linfo = linfo;
404}
405
bc2591d6
YS
406static void verbose_invalid_scalar(struct bpf_verifier_env *env,
407 struct bpf_reg_state *reg,
408 struct tnum *range, const char *ctx,
409 const char *reg_name)
410{
411 char tn_buf[48];
412
413 verbose(env, "At %s the register %s ", ctx, reg_name);
414 if (!tnum_is_unknown(reg->var_off)) {
415 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
416 verbose(env, "has value %s", tn_buf);
417 } else {
418 verbose(env, "has unknown scalar value");
419 }
420 tnum_strn(tn_buf, sizeof(tn_buf), *range);
421 verbose(env, " should have been in %s\n", tn_buf);
422}
423
de8f3a83
DB
424static bool type_is_pkt_pointer(enum bpf_reg_type type)
425{
426 return type == PTR_TO_PACKET ||
427 type == PTR_TO_PACKET_META;
428}
429
46f8bc92
MKL
430static bool type_is_sk_pointer(enum bpf_reg_type type)
431{
432 return type == PTR_TO_SOCKET ||
655a51e5 433 type == PTR_TO_SOCK_COMMON ||
fada7fdc
JL
434 type == PTR_TO_TCP_SOCK ||
435 type == PTR_TO_XDP_SOCK;
46f8bc92
MKL
436}
437
cac616db
JF
438static bool reg_type_not_null(enum bpf_reg_type type)
439{
440 return type == PTR_TO_SOCKET ||
441 type == PTR_TO_TCP_SOCK ||
442 type == PTR_TO_MAP_VALUE ||
69c087ba 443 type == PTR_TO_MAP_KEY ||
01c66c48 444 type == PTR_TO_SOCK_COMMON;
cac616db
JF
445}
446
840b9615
JS
447static bool reg_type_may_be_null(enum bpf_reg_type type)
448{
fd978bf7 449 return type == PTR_TO_MAP_VALUE_OR_NULL ||
46f8bc92 450 type == PTR_TO_SOCKET_OR_NULL ||
655a51e5 451 type == PTR_TO_SOCK_COMMON_OR_NULL ||
b121b341 452 type == PTR_TO_TCP_SOCK_OR_NULL ||
457f4436 453 type == PTR_TO_BTF_ID_OR_NULL ||
afbf21dc
YS
454 type == PTR_TO_MEM_OR_NULL ||
455 type == PTR_TO_RDONLY_BUF_OR_NULL ||
456 type == PTR_TO_RDWR_BUF_OR_NULL;
fd978bf7
JS
457}
458
d83525ca
AS
459static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
460{
461 return reg->type == PTR_TO_MAP_VALUE &&
462 map_value_has_spin_lock(reg->map_ptr);
463}
464
cba368c1
MKL
465static bool reg_type_may_be_refcounted_or_null(enum bpf_reg_type type)
466{
467 return type == PTR_TO_SOCKET ||
468 type == PTR_TO_SOCKET_OR_NULL ||
469 type == PTR_TO_TCP_SOCK ||
457f4436
AN
470 type == PTR_TO_TCP_SOCK_OR_NULL ||
471 type == PTR_TO_MEM ||
472 type == PTR_TO_MEM_OR_NULL;
cba368c1
MKL
473}
474
1b986589 475static bool arg_type_may_be_refcounted(enum bpf_arg_type type)
fd978bf7 476{
1b986589 477 return type == ARG_PTR_TO_SOCK_COMMON;
fd978bf7
JS
478}
479
fd1b0d60
LB
480static bool arg_type_may_be_null(enum bpf_arg_type type)
481{
482 return type == ARG_PTR_TO_MAP_VALUE_OR_NULL ||
483 type == ARG_PTR_TO_MEM_OR_NULL ||
484 type == ARG_PTR_TO_CTX_OR_NULL ||
485 type == ARG_PTR_TO_SOCKET_OR_NULL ||
69c087ba
YS
486 type == ARG_PTR_TO_ALLOC_MEM_OR_NULL ||
487 type == ARG_PTR_TO_STACK_OR_NULL;
fd1b0d60
LB
488}
489
fd978bf7
JS
490/* Determine whether the function releases some resources allocated by another
491 * function call. The first reference type argument will be assumed to be
492 * released by release_reference().
493 */
494static bool is_release_function(enum bpf_func_id func_id)
495{
457f4436
AN
496 return func_id == BPF_FUNC_sk_release ||
497 func_id == BPF_FUNC_ringbuf_submit ||
498 func_id == BPF_FUNC_ringbuf_discard;
840b9615
JS
499}
500
64d85290 501static bool may_be_acquire_function(enum bpf_func_id func_id)
46f8bc92
MKL
502{
503 return func_id == BPF_FUNC_sk_lookup_tcp ||
edbf8c01 504 func_id == BPF_FUNC_sk_lookup_udp ||
64d85290 505 func_id == BPF_FUNC_skc_lookup_tcp ||
457f4436
AN
506 func_id == BPF_FUNC_map_lookup_elem ||
507 func_id == BPF_FUNC_ringbuf_reserve;
64d85290
JS
508}
509
510static bool is_acquire_function(enum bpf_func_id func_id,
511 const struct bpf_map *map)
512{
513 enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
514
515 if (func_id == BPF_FUNC_sk_lookup_tcp ||
516 func_id == BPF_FUNC_sk_lookup_udp ||
457f4436
AN
517 func_id == BPF_FUNC_skc_lookup_tcp ||
518 func_id == BPF_FUNC_ringbuf_reserve)
64d85290
JS
519 return true;
520
521 if (func_id == BPF_FUNC_map_lookup_elem &&
522 (map_type == BPF_MAP_TYPE_SOCKMAP ||
523 map_type == BPF_MAP_TYPE_SOCKHASH))
524 return true;
525
526 return false;
46f8bc92
MKL
527}
528
1b986589
MKL
529static bool is_ptr_cast_function(enum bpf_func_id func_id)
530{
531 return func_id == BPF_FUNC_tcp_sock ||
1df8f55a
MKL
532 func_id == BPF_FUNC_sk_fullsock ||
533 func_id == BPF_FUNC_skc_to_tcp_sock ||
534 func_id == BPF_FUNC_skc_to_tcp6_sock ||
535 func_id == BPF_FUNC_skc_to_udp6_sock ||
536 func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
537 func_id == BPF_FUNC_skc_to_tcp_request_sock;
1b986589
MKL
538}
539
39491867
BJ
540static bool is_cmpxchg_insn(const struct bpf_insn *insn)
541{
542 return BPF_CLASS(insn->code) == BPF_STX &&
543 BPF_MODE(insn->code) == BPF_ATOMIC &&
544 insn->imm == BPF_CMPXCHG;
545}
546
17a52670
AS
547/* string representation of 'enum bpf_reg_type' */
548static const char * const reg_type_str[] = {
549 [NOT_INIT] = "?",
f1174f77 550 [SCALAR_VALUE] = "inv",
17a52670
AS
551 [PTR_TO_CTX] = "ctx",
552 [CONST_PTR_TO_MAP] = "map_ptr",
553 [PTR_TO_MAP_VALUE] = "map_value",
554 [PTR_TO_MAP_VALUE_OR_NULL] = "map_value_or_null",
17a52670 555 [PTR_TO_STACK] = "fp",
969bf05e 556 [PTR_TO_PACKET] = "pkt",
de8f3a83 557 [PTR_TO_PACKET_META] = "pkt_meta",
969bf05e 558 [PTR_TO_PACKET_END] = "pkt_end",
d58e468b 559 [PTR_TO_FLOW_KEYS] = "flow_keys",
c64b7983
JS
560 [PTR_TO_SOCKET] = "sock",
561 [PTR_TO_SOCKET_OR_NULL] = "sock_or_null",
46f8bc92
MKL
562 [PTR_TO_SOCK_COMMON] = "sock_common",
563 [PTR_TO_SOCK_COMMON_OR_NULL] = "sock_common_or_null",
655a51e5
MKL
564 [PTR_TO_TCP_SOCK] = "tcp_sock",
565 [PTR_TO_TCP_SOCK_OR_NULL] = "tcp_sock_or_null",
9df1c28b 566 [PTR_TO_TP_BUFFER] = "tp_buffer",
fada7fdc 567 [PTR_TO_XDP_SOCK] = "xdp_sock",
9e15db66 568 [PTR_TO_BTF_ID] = "ptr_",
b121b341 569 [PTR_TO_BTF_ID_OR_NULL] = "ptr_or_null_",
eaa6bcb7 570 [PTR_TO_PERCPU_BTF_ID] = "percpu_ptr_",
457f4436
AN
571 [PTR_TO_MEM] = "mem",
572 [PTR_TO_MEM_OR_NULL] = "mem_or_null",
afbf21dc
YS
573 [PTR_TO_RDONLY_BUF] = "rdonly_buf",
574 [PTR_TO_RDONLY_BUF_OR_NULL] = "rdonly_buf_or_null",
575 [PTR_TO_RDWR_BUF] = "rdwr_buf",
576 [PTR_TO_RDWR_BUF_OR_NULL] = "rdwr_buf_or_null",
69c087ba
YS
577 [PTR_TO_FUNC] = "func",
578 [PTR_TO_MAP_KEY] = "map_key",
17a52670
AS
579};
580
8efea21d
EC
581static char slot_type_char[] = {
582 [STACK_INVALID] = '?',
583 [STACK_SPILL] = 'r',
584 [STACK_MISC] = 'm',
585 [STACK_ZERO] = '0',
586};
587
4e92024a
AS
588static void print_liveness(struct bpf_verifier_env *env,
589 enum bpf_reg_liveness live)
590{
9242b5f5 591 if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE))
4e92024a
AS
592 verbose(env, "_");
593 if (live & REG_LIVE_READ)
594 verbose(env, "r");
595 if (live & REG_LIVE_WRITTEN)
596 verbose(env, "w");
9242b5f5
AS
597 if (live & REG_LIVE_DONE)
598 verbose(env, "D");
4e92024a
AS
599}
600
f4d7e40a
AS
601static struct bpf_func_state *func(struct bpf_verifier_env *env,
602 const struct bpf_reg_state *reg)
603{
604 struct bpf_verifier_state *cur = env->cur_state;
605
606 return cur->frame[reg->frameno];
607}
608
22dc4a0f 609static const char *kernel_type_name(const struct btf* btf, u32 id)
9e15db66 610{
22dc4a0f 611 return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off);
9e15db66
AS
612}
613
61bd5218 614static void print_verifier_state(struct bpf_verifier_env *env,
f4d7e40a 615 const struct bpf_func_state *state)
17a52670 616{
f4d7e40a 617 const struct bpf_reg_state *reg;
17a52670
AS
618 enum bpf_reg_type t;
619 int i;
620
f4d7e40a
AS
621 if (state->frameno)
622 verbose(env, " frame%d:", state->frameno);
17a52670 623 for (i = 0; i < MAX_BPF_REG; i++) {
1a0dc1ac
AS
624 reg = &state->regs[i];
625 t = reg->type;
17a52670
AS
626 if (t == NOT_INIT)
627 continue;
4e92024a
AS
628 verbose(env, " R%d", i);
629 print_liveness(env, reg->live);
630 verbose(env, "=%s", reg_type_str[t]);
b5dc0163
AS
631 if (t == SCALAR_VALUE && reg->precise)
632 verbose(env, "P");
f1174f77
EC
633 if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
634 tnum_is_const(reg->var_off)) {
635 /* reg->off should be 0 for SCALAR_VALUE */
61bd5218 636 verbose(env, "%lld", reg->var_off.value + reg->off);
f1174f77 637 } else {
eaa6bcb7
HL
638 if (t == PTR_TO_BTF_ID ||
639 t == PTR_TO_BTF_ID_OR_NULL ||
640 t == PTR_TO_PERCPU_BTF_ID)
22dc4a0f 641 verbose(env, "%s", kernel_type_name(reg->btf, reg->btf_id));
cba368c1
MKL
642 verbose(env, "(id=%d", reg->id);
643 if (reg_type_may_be_refcounted_or_null(t))
644 verbose(env, ",ref_obj_id=%d", reg->ref_obj_id);
f1174f77 645 if (t != SCALAR_VALUE)
61bd5218 646 verbose(env, ",off=%d", reg->off);
de8f3a83 647 if (type_is_pkt_pointer(t))
61bd5218 648 verbose(env, ",r=%d", reg->range);
f1174f77 649 else if (t == CONST_PTR_TO_MAP ||
69c087ba 650 t == PTR_TO_MAP_KEY ||
f1174f77
EC
651 t == PTR_TO_MAP_VALUE ||
652 t == PTR_TO_MAP_VALUE_OR_NULL)
61bd5218 653 verbose(env, ",ks=%d,vs=%d",
f1174f77
EC
654 reg->map_ptr->key_size,
655 reg->map_ptr->value_size);
7d1238f2
EC
656 if (tnum_is_const(reg->var_off)) {
657 /* Typically an immediate SCALAR_VALUE, but
658 * could be a pointer whose offset is too big
659 * for reg->off
660 */
61bd5218 661 verbose(env, ",imm=%llx", reg->var_off.value);
7d1238f2
EC
662 } else {
663 if (reg->smin_value != reg->umin_value &&
664 reg->smin_value != S64_MIN)
61bd5218 665 verbose(env, ",smin_value=%lld",
7d1238f2
EC
666 (long long)reg->smin_value);
667 if (reg->smax_value != reg->umax_value &&
668 reg->smax_value != S64_MAX)
61bd5218 669 verbose(env, ",smax_value=%lld",
7d1238f2
EC
670 (long long)reg->smax_value);
671 if (reg->umin_value != 0)
61bd5218 672 verbose(env, ",umin_value=%llu",
7d1238f2
EC
673 (unsigned long long)reg->umin_value);
674 if (reg->umax_value != U64_MAX)
61bd5218 675 verbose(env, ",umax_value=%llu",
7d1238f2
EC
676 (unsigned long long)reg->umax_value);
677 if (!tnum_is_unknown(reg->var_off)) {
678 char tn_buf[48];
f1174f77 679
7d1238f2 680 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
61bd5218 681 verbose(env, ",var_off=%s", tn_buf);
7d1238f2 682 }
3f50f132
JF
683 if (reg->s32_min_value != reg->smin_value &&
684 reg->s32_min_value != S32_MIN)
685 verbose(env, ",s32_min_value=%d",
686 (int)(reg->s32_min_value));
687 if (reg->s32_max_value != reg->smax_value &&
688 reg->s32_max_value != S32_MAX)
689 verbose(env, ",s32_max_value=%d",
690 (int)(reg->s32_max_value));
691 if (reg->u32_min_value != reg->umin_value &&
692 reg->u32_min_value != U32_MIN)
693 verbose(env, ",u32_min_value=%d",
694 (int)(reg->u32_min_value));
695 if (reg->u32_max_value != reg->umax_value &&
696 reg->u32_max_value != U32_MAX)
697 verbose(env, ",u32_max_value=%d",
698 (int)(reg->u32_max_value));
f1174f77 699 }
61bd5218 700 verbose(env, ")");
f1174f77 701 }
17a52670 702 }
638f5b90 703 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
8efea21d
EC
704 char types_buf[BPF_REG_SIZE + 1];
705 bool valid = false;
706 int j;
707
708 for (j = 0; j < BPF_REG_SIZE; j++) {
709 if (state->stack[i].slot_type[j] != STACK_INVALID)
710 valid = true;
711 types_buf[j] = slot_type_char[
712 state->stack[i].slot_type[j]];
713 }
714 types_buf[BPF_REG_SIZE] = 0;
715 if (!valid)
716 continue;
717 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
718 print_liveness(env, state->stack[i].spilled_ptr.live);
b5dc0163
AS
719 if (state->stack[i].slot_type[0] == STACK_SPILL) {
720 reg = &state->stack[i].spilled_ptr;
721 t = reg->type;
722 verbose(env, "=%s", reg_type_str[t]);
723 if (t == SCALAR_VALUE && reg->precise)
724 verbose(env, "P");
725 if (t == SCALAR_VALUE && tnum_is_const(reg->var_off))
726 verbose(env, "%lld", reg->var_off.value + reg->off);
727 } else {
8efea21d 728 verbose(env, "=%s", types_buf);
b5dc0163 729 }
17a52670 730 }
fd978bf7
JS
731 if (state->acquired_refs && state->refs[0].id) {
732 verbose(env, " refs=%d", state->refs[0].id);
733 for (i = 1; i < state->acquired_refs; i++)
734 if (state->refs[i].id)
735 verbose(env, ",%d", state->refs[i].id);
736 }
61bd5218 737 verbose(env, "\n");
17a52670
AS
738}
739
c69431aa
LB
740/* copy array src of length n * size bytes to dst. dst is reallocated if it's too
741 * small to hold src. This is different from krealloc since we don't want to preserve
742 * the contents of dst.
743 *
744 * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could
745 * not be allocated.
638f5b90 746 */
c69431aa 747static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags)
638f5b90 748{
c69431aa
LB
749 size_t bytes;
750
751 if (ZERO_OR_NULL_PTR(src))
752 goto out;
753
754 if (unlikely(check_mul_overflow(n, size, &bytes)))
755 return NULL;
756
757 if (ksize(dst) < bytes) {
758 kfree(dst);
759 dst = kmalloc_track_caller(bytes, flags);
760 if (!dst)
761 return NULL;
762 }
763
764 memcpy(dst, src, bytes);
765out:
766 return dst ? dst : ZERO_SIZE_PTR;
767}
768
769/* resize an array from old_n items to new_n items. the array is reallocated if it's too
770 * small to hold new_n items. new items are zeroed out if the array grows.
771 *
772 * Contrary to krealloc_array, does not free arr if new_n is zero.
773 */
774static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size)
775{
776 if (!new_n || old_n == new_n)
777 goto out;
778
779 arr = krealloc_array(arr, new_n, size, GFP_KERNEL);
780 if (!arr)
781 return NULL;
782
783 if (new_n > old_n)
784 memset(arr + old_n * size, 0, (new_n - old_n) * size);
785
786out:
787 return arr ? arr : ZERO_SIZE_PTR;
788}
789
790static int copy_reference_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
791{
792 dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs,
793 sizeof(struct bpf_reference_state), GFP_KERNEL);
794 if (!dst->refs)
795 return -ENOMEM;
796
797 dst->acquired_refs = src->acquired_refs;
798 return 0;
799}
800
801static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
802{
803 size_t n = src->allocated_stack / BPF_REG_SIZE;
804
805 dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state),
806 GFP_KERNEL);
807 if (!dst->stack)
808 return -ENOMEM;
809
810 dst->allocated_stack = src->allocated_stack;
811 return 0;
812}
813
814static int resize_reference_state(struct bpf_func_state *state, size_t n)
815{
816 state->refs = realloc_array(state->refs, state->acquired_refs, n,
817 sizeof(struct bpf_reference_state));
818 if (!state->refs)
819 return -ENOMEM;
820
821 state->acquired_refs = n;
822 return 0;
823}
824
825static int grow_stack_state(struct bpf_func_state *state, int size)
826{
827 size_t old_n = state->allocated_stack / BPF_REG_SIZE, n = size / BPF_REG_SIZE;
828
829 if (old_n >= n)
830 return 0;
831
832 state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state));
833 if (!state->stack)
834 return -ENOMEM;
835
836 state->allocated_stack = size;
837 return 0;
fd978bf7
JS
838}
839
840/* Acquire a pointer id from the env and update the state->refs to include
841 * this new pointer reference.
842 * On success, returns a valid pointer id to associate with the register
843 * On failure, returns a negative errno.
638f5b90 844 */
fd978bf7 845static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
638f5b90 846{
fd978bf7
JS
847 struct bpf_func_state *state = cur_func(env);
848 int new_ofs = state->acquired_refs;
849 int id, err;
850
c69431aa 851 err = resize_reference_state(state, state->acquired_refs + 1);
fd978bf7
JS
852 if (err)
853 return err;
854 id = ++env->id_gen;
855 state->refs[new_ofs].id = id;
856 state->refs[new_ofs].insn_idx = insn_idx;
638f5b90 857
fd978bf7
JS
858 return id;
859}
860
861/* release function corresponding to acquire_reference_state(). Idempotent. */
46f8bc92 862static int release_reference_state(struct bpf_func_state *state, int ptr_id)
fd978bf7
JS
863{
864 int i, last_idx;
865
fd978bf7
JS
866 last_idx = state->acquired_refs - 1;
867 for (i = 0; i < state->acquired_refs; i++) {
868 if (state->refs[i].id == ptr_id) {
869 if (last_idx && i != last_idx)
870 memcpy(&state->refs[i], &state->refs[last_idx],
871 sizeof(*state->refs));
872 memset(&state->refs[last_idx], 0, sizeof(*state->refs));
873 state->acquired_refs--;
638f5b90 874 return 0;
638f5b90 875 }
638f5b90 876 }
46f8bc92 877 return -EINVAL;
fd978bf7
JS
878}
879
f4d7e40a
AS
880static void free_func_state(struct bpf_func_state *state)
881{
5896351e
AS
882 if (!state)
883 return;
fd978bf7 884 kfree(state->refs);
f4d7e40a
AS
885 kfree(state->stack);
886 kfree(state);
887}
888
b5dc0163
AS
889static void clear_jmp_history(struct bpf_verifier_state *state)
890{
891 kfree(state->jmp_history);
892 state->jmp_history = NULL;
893 state->jmp_history_cnt = 0;
894}
895
1969db47
AS
896static void free_verifier_state(struct bpf_verifier_state *state,
897 bool free_self)
638f5b90 898{
f4d7e40a
AS
899 int i;
900
901 for (i = 0; i <= state->curframe; i++) {
902 free_func_state(state->frame[i]);
903 state->frame[i] = NULL;
904 }
b5dc0163 905 clear_jmp_history(state);
1969db47
AS
906 if (free_self)
907 kfree(state);
638f5b90
AS
908}
909
910/* copy verifier state from src to dst growing dst stack space
911 * when necessary to accommodate larger src stack
912 */
f4d7e40a
AS
913static int copy_func_state(struct bpf_func_state *dst,
914 const struct bpf_func_state *src)
638f5b90
AS
915{
916 int err;
917
fd978bf7
JS
918 memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
919 err = copy_reference_state(dst, src);
638f5b90
AS
920 if (err)
921 return err;
638f5b90
AS
922 return copy_stack_state(dst, src);
923}
924
f4d7e40a
AS
925static int copy_verifier_state(struct bpf_verifier_state *dst_state,
926 const struct bpf_verifier_state *src)
927{
928 struct bpf_func_state *dst;
b5dc0163 929 u32 jmp_sz = sizeof(struct bpf_idx_pair) * src->jmp_history_cnt;
f4d7e40a
AS
930 int i, err;
931
b5dc0163
AS
932 if (dst_state->jmp_history_cnt < src->jmp_history_cnt) {
933 kfree(dst_state->jmp_history);
934 dst_state->jmp_history = kmalloc(jmp_sz, GFP_USER);
935 if (!dst_state->jmp_history)
936 return -ENOMEM;
937 }
938 memcpy(dst_state->jmp_history, src->jmp_history, jmp_sz);
939 dst_state->jmp_history_cnt = src->jmp_history_cnt;
940
f4d7e40a
AS
941 /* if dst has more stack frames then src frame, free them */
942 for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
943 free_func_state(dst_state->frame[i]);
944 dst_state->frame[i] = NULL;
945 }
979d63d5 946 dst_state->speculative = src->speculative;
f4d7e40a 947 dst_state->curframe = src->curframe;
d83525ca 948 dst_state->active_spin_lock = src->active_spin_lock;
2589726d
AS
949 dst_state->branches = src->branches;
950 dst_state->parent = src->parent;
b5dc0163
AS
951 dst_state->first_insn_idx = src->first_insn_idx;
952 dst_state->last_insn_idx = src->last_insn_idx;
f4d7e40a
AS
953 for (i = 0; i <= src->curframe; i++) {
954 dst = dst_state->frame[i];
955 if (!dst) {
956 dst = kzalloc(sizeof(*dst), GFP_KERNEL);
957 if (!dst)
958 return -ENOMEM;
959 dst_state->frame[i] = dst;
960 }
961 err = copy_func_state(dst, src->frame[i]);
962 if (err)
963 return err;
964 }
965 return 0;
966}
967
2589726d
AS
968static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
969{
970 while (st) {
971 u32 br = --st->branches;
972
973 /* WARN_ON(br > 1) technically makes sense here,
974 * but see comment in push_stack(), hence:
975 */
976 WARN_ONCE((int)br < 0,
977 "BUG update_branch_counts:branches_to_explore=%d\n",
978 br);
979 if (br)
980 break;
981 st = st->parent;
982 }
983}
984
638f5b90 985static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
6f8a57cc 986 int *insn_idx, bool pop_log)
638f5b90
AS
987{
988 struct bpf_verifier_state *cur = env->cur_state;
989 struct bpf_verifier_stack_elem *elem, *head = env->head;
990 int err;
17a52670
AS
991
992 if (env->head == NULL)
638f5b90 993 return -ENOENT;
17a52670 994
638f5b90
AS
995 if (cur) {
996 err = copy_verifier_state(cur, &head->st);
997 if (err)
998 return err;
999 }
6f8a57cc
AN
1000 if (pop_log)
1001 bpf_vlog_reset(&env->log, head->log_pos);
638f5b90
AS
1002 if (insn_idx)
1003 *insn_idx = head->insn_idx;
17a52670 1004 if (prev_insn_idx)
638f5b90
AS
1005 *prev_insn_idx = head->prev_insn_idx;
1006 elem = head->next;
1969db47 1007 free_verifier_state(&head->st, false);
638f5b90 1008 kfree(head);
17a52670
AS
1009 env->head = elem;
1010 env->stack_size--;
638f5b90 1011 return 0;
17a52670
AS
1012}
1013
58e2af8b 1014static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
979d63d5
DB
1015 int insn_idx, int prev_insn_idx,
1016 bool speculative)
17a52670 1017{
638f5b90 1018 struct bpf_verifier_state *cur = env->cur_state;
58e2af8b 1019 struct bpf_verifier_stack_elem *elem;
638f5b90 1020 int err;
17a52670 1021
638f5b90 1022 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
17a52670
AS
1023 if (!elem)
1024 goto err;
1025
17a52670
AS
1026 elem->insn_idx = insn_idx;
1027 elem->prev_insn_idx = prev_insn_idx;
1028 elem->next = env->head;
6f8a57cc 1029 elem->log_pos = env->log.len_used;
17a52670
AS
1030 env->head = elem;
1031 env->stack_size++;
1969db47
AS
1032 err = copy_verifier_state(&elem->st, cur);
1033 if (err)
1034 goto err;
979d63d5 1035 elem->st.speculative |= speculative;
b285fcb7
AS
1036 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1037 verbose(env, "The sequence of %d jumps is too complex.\n",
1038 env->stack_size);
17a52670
AS
1039 goto err;
1040 }
2589726d
AS
1041 if (elem->st.parent) {
1042 ++elem->st.parent->branches;
1043 /* WARN_ON(branches > 2) technically makes sense here,
1044 * but
1045 * 1. speculative states will bump 'branches' for non-branch
1046 * instructions
1047 * 2. is_state_visited() heuristics may decide not to create
1048 * a new state for a sequence of branches and all such current
1049 * and cloned states will be pointing to a single parent state
1050 * which might have large 'branches' count.
1051 */
1052 }
17a52670
AS
1053 return &elem->st;
1054err:
5896351e
AS
1055 free_verifier_state(env->cur_state, true);
1056 env->cur_state = NULL;
17a52670 1057 /* pop all elements and return */
6f8a57cc 1058 while (!pop_stack(env, NULL, NULL, false));
17a52670
AS
1059 return NULL;
1060}
1061
1062#define CALLER_SAVED_REGS 6
1063static const int caller_saved[CALLER_SAVED_REGS] = {
1064 BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
1065};
1066
f54c7898
DB
1067static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1068 struct bpf_reg_state *reg);
f1174f77 1069
e688c3db
AS
1070/* This helper doesn't clear reg->id */
1071static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
b03c9f9f 1072{
b03c9f9f
EC
1073 reg->var_off = tnum_const(imm);
1074 reg->smin_value = (s64)imm;
1075 reg->smax_value = (s64)imm;
1076 reg->umin_value = imm;
1077 reg->umax_value = imm;
3f50f132
JF
1078
1079 reg->s32_min_value = (s32)imm;
1080 reg->s32_max_value = (s32)imm;
1081 reg->u32_min_value = (u32)imm;
1082 reg->u32_max_value = (u32)imm;
1083}
1084
e688c3db
AS
1085/* Mark the unknown part of a register (variable offset or scalar value) as
1086 * known to have the value @imm.
1087 */
1088static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1089{
1090 /* Clear id, off, and union(map_ptr, range) */
1091 memset(((u8 *)reg) + sizeof(reg->type), 0,
1092 offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
1093 ___mark_reg_known(reg, imm);
1094}
1095
3f50f132
JF
1096static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1097{
1098 reg->var_off = tnum_const_subreg(reg->var_off, imm);
1099 reg->s32_min_value = (s32)imm;
1100 reg->s32_max_value = (s32)imm;
1101 reg->u32_min_value = (u32)imm;
1102 reg->u32_max_value = (u32)imm;
b03c9f9f
EC
1103}
1104
f1174f77
EC
1105/* Mark the 'variable offset' part of a register as zero. This should be
1106 * used only on registers holding a pointer type.
1107 */
1108static void __mark_reg_known_zero(struct bpf_reg_state *reg)
a9789ef9 1109{
b03c9f9f 1110 __mark_reg_known(reg, 0);
f1174f77 1111}
a9789ef9 1112
cc2b14d5
AS
1113static void __mark_reg_const_zero(struct bpf_reg_state *reg)
1114{
1115 __mark_reg_known(reg, 0);
cc2b14d5
AS
1116 reg->type = SCALAR_VALUE;
1117}
1118
61bd5218
JK
1119static void mark_reg_known_zero(struct bpf_verifier_env *env,
1120 struct bpf_reg_state *regs, u32 regno)
f1174f77
EC
1121{
1122 if (WARN_ON(regno >= MAX_BPF_REG)) {
61bd5218 1123 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
f1174f77
EC
1124 /* Something bad happened, let's kill all regs */
1125 for (regno = 0; regno < MAX_BPF_REG; regno++)
f54c7898 1126 __mark_reg_not_init(env, regs + regno);
f1174f77
EC
1127 return;
1128 }
1129 __mark_reg_known_zero(regs + regno);
1130}
1131
4ddb7416
DB
1132static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
1133{
1134 switch (reg->type) {
1135 case PTR_TO_MAP_VALUE_OR_NULL: {
1136 const struct bpf_map *map = reg->map_ptr;
1137
1138 if (map->inner_map_meta) {
1139 reg->type = CONST_PTR_TO_MAP;
1140 reg->map_ptr = map->inner_map_meta;
1141 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
1142 reg->type = PTR_TO_XDP_SOCK;
1143 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
1144 map->map_type == BPF_MAP_TYPE_SOCKHASH) {
1145 reg->type = PTR_TO_SOCKET;
1146 } else {
1147 reg->type = PTR_TO_MAP_VALUE;
1148 }
1149 break;
1150 }
1151 case PTR_TO_SOCKET_OR_NULL:
1152 reg->type = PTR_TO_SOCKET;
1153 break;
1154 case PTR_TO_SOCK_COMMON_OR_NULL:
1155 reg->type = PTR_TO_SOCK_COMMON;
1156 break;
1157 case PTR_TO_TCP_SOCK_OR_NULL:
1158 reg->type = PTR_TO_TCP_SOCK;
1159 break;
1160 case PTR_TO_BTF_ID_OR_NULL:
1161 reg->type = PTR_TO_BTF_ID;
1162 break;
1163 case PTR_TO_MEM_OR_NULL:
1164 reg->type = PTR_TO_MEM;
1165 break;
1166 case PTR_TO_RDONLY_BUF_OR_NULL:
1167 reg->type = PTR_TO_RDONLY_BUF;
1168 break;
1169 case PTR_TO_RDWR_BUF_OR_NULL:
1170 reg->type = PTR_TO_RDWR_BUF;
1171 break;
1172 default:
33ccec5f 1173 WARN_ONCE(1, "unknown nullable register type");
4ddb7416
DB
1174 }
1175}
1176
de8f3a83
DB
1177static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1178{
1179 return type_is_pkt_pointer(reg->type);
1180}
1181
1182static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
1183{
1184 return reg_is_pkt_pointer(reg) ||
1185 reg->type == PTR_TO_PACKET_END;
1186}
1187
1188/* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
1189static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
1190 enum bpf_reg_type which)
1191{
1192 /* The register can already have a range from prior markings.
1193 * This is fine as long as it hasn't been advanced from its
1194 * origin.
1195 */
1196 return reg->type == which &&
1197 reg->id == 0 &&
1198 reg->off == 0 &&
1199 tnum_equals_const(reg->var_off, 0);
1200}
1201
3f50f132
JF
1202/* Reset the min/max bounds of a register */
1203static void __mark_reg_unbounded(struct bpf_reg_state *reg)
1204{
1205 reg->smin_value = S64_MIN;
1206 reg->smax_value = S64_MAX;
1207 reg->umin_value = 0;
1208 reg->umax_value = U64_MAX;
1209
1210 reg->s32_min_value = S32_MIN;
1211 reg->s32_max_value = S32_MAX;
1212 reg->u32_min_value = 0;
1213 reg->u32_max_value = U32_MAX;
1214}
1215
1216static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
1217{
1218 reg->smin_value = S64_MIN;
1219 reg->smax_value = S64_MAX;
1220 reg->umin_value = 0;
1221 reg->umax_value = U64_MAX;
1222}
1223
1224static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
1225{
1226 reg->s32_min_value = S32_MIN;
1227 reg->s32_max_value = S32_MAX;
1228 reg->u32_min_value = 0;
1229 reg->u32_max_value = U32_MAX;
1230}
1231
1232static void __update_reg32_bounds(struct bpf_reg_state *reg)
1233{
1234 struct tnum var32_off = tnum_subreg(reg->var_off);
1235
1236 /* min signed is max(sign bit) | min(other bits) */
1237 reg->s32_min_value = max_t(s32, reg->s32_min_value,
1238 var32_off.value | (var32_off.mask & S32_MIN));
1239 /* max signed is min(sign bit) | max(other bits) */
1240 reg->s32_max_value = min_t(s32, reg->s32_max_value,
1241 var32_off.value | (var32_off.mask & S32_MAX));
1242 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
1243 reg->u32_max_value = min(reg->u32_max_value,
1244 (u32)(var32_off.value | var32_off.mask));
1245}
1246
1247static void __update_reg64_bounds(struct bpf_reg_state *reg)
b03c9f9f
EC
1248{
1249 /* min signed is max(sign bit) | min(other bits) */
1250 reg->smin_value = max_t(s64, reg->smin_value,
1251 reg->var_off.value | (reg->var_off.mask & S64_MIN));
1252 /* max signed is min(sign bit) | max(other bits) */
1253 reg->smax_value = min_t(s64, reg->smax_value,
1254 reg->var_off.value | (reg->var_off.mask & S64_MAX));
1255 reg->umin_value = max(reg->umin_value, reg->var_off.value);
1256 reg->umax_value = min(reg->umax_value,
1257 reg->var_off.value | reg->var_off.mask);
1258}
1259
3f50f132
JF
1260static void __update_reg_bounds(struct bpf_reg_state *reg)
1261{
1262 __update_reg32_bounds(reg);
1263 __update_reg64_bounds(reg);
1264}
1265
b03c9f9f 1266/* Uses signed min/max values to inform unsigned, and vice-versa */
3f50f132
JF
1267static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
1268{
1269 /* Learn sign from signed bounds.
1270 * If we cannot cross the sign boundary, then signed and unsigned bounds
1271 * are the same, so combine. This works even in the negative case, e.g.
1272 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1273 */
1274 if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) {
1275 reg->s32_min_value = reg->u32_min_value =
1276 max_t(u32, reg->s32_min_value, reg->u32_min_value);
1277 reg->s32_max_value = reg->u32_max_value =
1278 min_t(u32, reg->s32_max_value, reg->u32_max_value);
1279 return;
1280 }
1281 /* Learn sign from unsigned bounds. Signed bounds cross the sign
1282 * boundary, so we must be careful.
1283 */
1284 if ((s32)reg->u32_max_value >= 0) {
1285 /* Positive. We can't learn anything from the smin, but smax
1286 * is positive, hence safe.
1287 */
1288 reg->s32_min_value = reg->u32_min_value;
1289 reg->s32_max_value = reg->u32_max_value =
1290 min_t(u32, reg->s32_max_value, reg->u32_max_value);
1291 } else if ((s32)reg->u32_min_value < 0) {
1292 /* Negative. We can't learn anything from the smax, but smin
1293 * is negative, hence safe.
1294 */
1295 reg->s32_min_value = reg->u32_min_value =
1296 max_t(u32, reg->s32_min_value, reg->u32_min_value);
1297 reg->s32_max_value = reg->u32_max_value;
1298 }
1299}
1300
1301static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
b03c9f9f
EC
1302{
1303 /* Learn sign from signed bounds.
1304 * If we cannot cross the sign boundary, then signed and unsigned bounds
1305 * are the same, so combine. This works even in the negative case, e.g.
1306 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1307 */
1308 if (reg->smin_value >= 0 || reg->smax_value < 0) {
1309 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1310 reg->umin_value);
1311 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1312 reg->umax_value);
1313 return;
1314 }
1315 /* Learn sign from unsigned bounds. Signed bounds cross the sign
1316 * boundary, so we must be careful.
1317 */
1318 if ((s64)reg->umax_value >= 0) {
1319 /* Positive. We can't learn anything from the smin, but smax
1320 * is positive, hence safe.
1321 */
1322 reg->smin_value = reg->umin_value;
1323 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1324 reg->umax_value);
1325 } else if ((s64)reg->umin_value < 0) {
1326 /* Negative. We can't learn anything from the smax, but smin
1327 * is negative, hence safe.
1328 */
1329 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1330 reg->umin_value);
1331 reg->smax_value = reg->umax_value;
1332 }
1333}
1334
3f50f132
JF
1335static void __reg_deduce_bounds(struct bpf_reg_state *reg)
1336{
1337 __reg32_deduce_bounds(reg);
1338 __reg64_deduce_bounds(reg);
1339}
1340
b03c9f9f
EC
1341/* Attempts to improve var_off based on unsigned min/max information */
1342static void __reg_bound_offset(struct bpf_reg_state *reg)
1343{
3f50f132
JF
1344 struct tnum var64_off = tnum_intersect(reg->var_off,
1345 tnum_range(reg->umin_value,
1346 reg->umax_value));
1347 struct tnum var32_off = tnum_intersect(tnum_subreg(reg->var_off),
1348 tnum_range(reg->u32_min_value,
1349 reg->u32_max_value));
1350
1351 reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
b03c9f9f
EC
1352}
1353
3f50f132 1354static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
b03c9f9f 1355{
3f50f132
JF
1356 reg->umin_value = reg->u32_min_value;
1357 reg->umax_value = reg->u32_max_value;
1358 /* Attempt to pull 32-bit signed bounds into 64-bit bounds
1359 * but must be positive otherwise set to worse case bounds
1360 * and refine later from tnum.
1361 */
3a71dc36 1362 if (reg->s32_min_value >= 0 && reg->s32_max_value >= 0)
3f50f132
JF
1363 reg->smax_value = reg->s32_max_value;
1364 else
1365 reg->smax_value = U32_MAX;
3a71dc36
JF
1366 if (reg->s32_min_value >= 0)
1367 reg->smin_value = reg->s32_min_value;
1368 else
1369 reg->smin_value = 0;
3f50f132
JF
1370}
1371
1372static void __reg_combine_32_into_64(struct bpf_reg_state *reg)
1373{
1374 /* special case when 64-bit register has upper 32-bit register
1375 * zeroed. Typically happens after zext or <<32, >>32 sequence
1376 * allowing us to use 32-bit bounds directly,
1377 */
1378 if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) {
1379 __reg_assign_32_into_64(reg);
1380 } else {
1381 /* Otherwise the best we can do is push lower 32bit known and
1382 * unknown bits into register (var_off set from jmp logic)
1383 * then learn as much as possible from the 64-bit tnum
1384 * known and unknown bits. The previous smin/smax bounds are
1385 * invalid here because of jmp32 compare so mark them unknown
1386 * so they do not impact tnum bounds calculation.
1387 */
1388 __mark_reg64_unbounded(reg);
1389 __update_reg_bounds(reg);
1390 }
1391
1392 /* Intersecting with the old var_off might have improved our bounds
1393 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1394 * then new var_off is (0; 0x7f...fc) which improves our umax.
1395 */
1396 __reg_deduce_bounds(reg);
1397 __reg_bound_offset(reg);
1398 __update_reg_bounds(reg);
1399}
1400
1401static bool __reg64_bound_s32(s64 a)
1402{
b0270958 1403 return a > S32_MIN && a < S32_MAX;
3f50f132
JF
1404}
1405
1406static bool __reg64_bound_u32(u64 a)
1407{
10bf4e83 1408 return a > U32_MIN && a < U32_MAX;
3f50f132
JF
1409}
1410
1411static void __reg_combine_64_into_32(struct bpf_reg_state *reg)
1412{
1413 __mark_reg32_unbounded(reg);
1414
b0270958 1415 if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) {
3f50f132 1416 reg->s32_min_value = (s32)reg->smin_value;
3f50f132 1417 reg->s32_max_value = (s32)reg->smax_value;
b0270958 1418 }
10bf4e83 1419 if (__reg64_bound_u32(reg->umin_value) && __reg64_bound_u32(reg->umax_value)) {
3f50f132 1420 reg->u32_min_value = (u32)reg->umin_value;
3f50f132 1421 reg->u32_max_value = (u32)reg->umax_value;
10bf4e83 1422 }
3f50f132
JF
1423
1424 /* Intersecting with the old var_off might have improved our bounds
1425 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1426 * then new var_off is (0; 0x7f...fc) which improves our umax.
1427 */
1428 __reg_deduce_bounds(reg);
1429 __reg_bound_offset(reg);
1430 __update_reg_bounds(reg);
b03c9f9f
EC
1431}
1432
f1174f77 1433/* Mark a register as having a completely unknown (scalar) value. */
f54c7898
DB
1434static void __mark_reg_unknown(const struct bpf_verifier_env *env,
1435 struct bpf_reg_state *reg)
f1174f77 1436{
a9c676bc
AS
1437 /*
1438 * Clear type, id, off, and union(map_ptr, range) and
1439 * padding between 'type' and union
1440 */
1441 memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
f1174f77 1442 reg->type = SCALAR_VALUE;
f1174f77 1443 reg->var_off = tnum_unknown;
f4d7e40a 1444 reg->frameno = 0;
2c78ee89 1445 reg->precise = env->subprog_cnt > 1 || !env->bpf_capable;
b03c9f9f 1446 __mark_reg_unbounded(reg);
f1174f77
EC
1447}
1448
61bd5218
JK
1449static void mark_reg_unknown(struct bpf_verifier_env *env,
1450 struct bpf_reg_state *regs, u32 regno)
f1174f77
EC
1451{
1452 if (WARN_ON(regno >= MAX_BPF_REG)) {
61bd5218 1453 verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
19ceb417
AS
1454 /* Something bad happened, let's kill all regs except FP */
1455 for (regno = 0; regno < BPF_REG_FP; regno++)
f54c7898 1456 __mark_reg_not_init(env, regs + regno);
f1174f77
EC
1457 return;
1458 }
f54c7898 1459 __mark_reg_unknown(env, regs + regno);
f1174f77
EC
1460}
1461
f54c7898
DB
1462static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1463 struct bpf_reg_state *reg)
f1174f77 1464{
f54c7898 1465 __mark_reg_unknown(env, reg);
f1174f77
EC
1466 reg->type = NOT_INIT;
1467}
1468
61bd5218
JK
1469static void mark_reg_not_init(struct bpf_verifier_env *env,
1470 struct bpf_reg_state *regs, u32 regno)
f1174f77
EC
1471{
1472 if (WARN_ON(regno >= MAX_BPF_REG)) {
61bd5218 1473 verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
19ceb417
AS
1474 /* Something bad happened, let's kill all regs except FP */
1475 for (regno = 0; regno < BPF_REG_FP; regno++)
f54c7898 1476 __mark_reg_not_init(env, regs + regno);
f1174f77
EC
1477 return;
1478 }
f54c7898 1479 __mark_reg_not_init(env, regs + regno);
a9789ef9
DB
1480}
1481
41c48f3a
AI
1482static void mark_btf_ld_reg(struct bpf_verifier_env *env,
1483 struct bpf_reg_state *regs, u32 regno,
22dc4a0f
AN
1484 enum bpf_reg_type reg_type,
1485 struct btf *btf, u32 btf_id)
41c48f3a
AI
1486{
1487 if (reg_type == SCALAR_VALUE) {
1488 mark_reg_unknown(env, regs, regno);
1489 return;
1490 }
1491 mark_reg_known_zero(env, regs, regno);
1492 regs[regno].type = PTR_TO_BTF_ID;
22dc4a0f 1493 regs[regno].btf = btf;
41c48f3a
AI
1494 regs[regno].btf_id = btf_id;
1495}
1496
5327ed3d 1497#define DEF_NOT_SUBREG (0)
61bd5218 1498static void init_reg_state(struct bpf_verifier_env *env,
f4d7e40a 1499 struct bpf_func_state *state)
17a52670 1500{
f4d7e40a 1501 struct bpf_reg_state *regs = state->regs;
17a52670
AS
1502 int i;
1503
dc503a8a 1504 for (i = 0; i < MAX_BPF_REG; i++) {
61bd5218 1505 mark_reg_not_init(env, regs, i);
dc503a8a 1506 regs[i].live = REG_LIVE_NONE;
679c782d 1507 regs[i].parent = NULL;
5327ed3d 1508 regs[i].subreg_def = DEF_NOT_SUBREG;
dc503a8a 1509 }
17a52670
AS
1510
1511 /* frame pointer */
f1174f77 1512 regs[BPF_REG_FP].type = PTR_TO_STACK;
61bd5218 1513 mark_reg_known_zero(env, regs, BPF_REG_FP);
f4d7e40a 1514 regs[BPF_REG_FP].frameno = state->frameno;
6760bf2d
DB
1515}
1516
f4d7e40a
AS
1517#define BPF_MAIN_FUNC (-1)
1518static void init_func_state(struct bpf_verifier_env *env,
1519 struct bpf_func_state *state,
1520 int callsite, int frameno, int subprogno)
1521{
1522 state->callsite = callsite;
1523 state->frameno = frameno;
1524 state->subprogno = subprogno;
1525 init_reg_state(env, state);
1526}
1527
17a52670
AS
1528enum reg_arg_type {
1529 SRC_OP, /* register is used as source operand */
1530 DST_OP, /* register is used as destination operand */
1531 DST_OP_NO_MARK /* same as above, check only, don't mark */
1532};
1533
cc8b0b92
AS
1534static int cmp_subprogs(const void *a, const void *b)
1535{
9c8105bd
JW
1536 return ((struct bpf_subprog_info *)a)->start -
1537 ((struct bpf_subprog_info *)b)->start;
cc8b0b92
AS
1538}
1539
1540static int find_subprog(struct bpf_verifier_env *env, int off)
1541{
9c8105bd 1542 struct bpf_subprog_info *p;
cc8b0b92 1543
9c8105bd
JW
1544 p = bsearch(&off, env->subprog_info, env->subprog_cnt,
1545 sizeof(env->subprog_info[0]), cmp_subprogs);
cc8b0b92
AS
1546 if (!p)
1547 return -ENOENT;
9c8105bd 1548 return p - env->subprog_info;
cc8b0b92
AS
1549
1550}
1551
1552static int add_subprog(struct bpf_verifier_env *env, int off)
1553{
1554 int insn_cnt = env->prog->len;
1555 int ret;
1556
1557 if (off >= insn_cnt || off < 0) {
1558 verbose(env, "call to invalid destination\n");
1559 return -EINVAL;
1560 }
1561 ret = find_subprog(env, off);
1562 if (ret >= 0)
282a0f46 1563 return ret;
4cb3d99c 1564 if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
cc8b0b92
AS
1565 verbose(env, "too many subprograms\n");
1566 return -E2BIG;
1567 }
e6ac2450 1568 /* determine subprog starts. The end is one before the next starts */
9c8105bd
JW
1569 env->subprog_info[env->subprog_cnt++].start = off;
1570 sort(env->subprog_info, env->subprog_cnt,
1571 sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
282a0f46 1572 return env->subprog_cnt - 1;
cc8b0b92
AS
1573}
1574
e6ac2450
MKL
1575struct bpf_kfunc_desc {
1576 struct btf_func_model func_model;
1577 u32 func_id;
1578 s32 imm;
1579};
1580
1581#define MAX_KFUNC_DESCS 256
1582struct bpf_kfunc_desc_tab {
1583 struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS];
1584 u32 nr_descs;
1585};
1586
1587static int kfunc_desc_cmp_by_id(const void *a, const void *b)
1588{
1589 const struct bpf_kfunc_desc *d0 = a;
1590 const struct bpf_kfunc_desc *d1 = b;
1591
1592 /* func_id is not greater than BTF_MAX_TYPE */
1593 return d0->func_id - d1->func_id;
1594}
1595
1596static const struct bpf_kfunc_desc *
1597find_kfunc_desc(const struct bpf_prog *prog, u32 func_id)
1598{
1599 struct bpf_kfunc_desc desc = {
1600 .func_id = func_id,
1601 };
1602 struct bpf_kfunc_desc_tab *tab;
1603
1604 tab = prog->aux->kfunc_tab;
1605 return bsearch(&desc, tab->descs, tab->nr_descs,
1606 sizeof(tab->descs[0]), kfunc_desc_cmp_by_id);
1607}
1608
1609static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id)
1610{
1611 const struct btf_type *func, *func_proto;
1612 struct bpf_kfunc_desc_tab *tab;
1613 struct bpf_prog_aux *prog_aux;
1614 struct bpf_kfunc_desc *desc;
1615 const char *func_name;
1616 unsigned long addr;
1617 int err;
1618
1619 prog_aux = env->prog->aux;
1620 tab = prog_aux->kfunc_tab;
1621 if (!tab) {
1622 if (!btf_vmlinux) {
1623 verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
1624 return -ENOTSUPP;
1625 }
1626
1627 if (!env->prog->jit_requested) {
1628 verbose(env, "JIT is required for calling kernel function\n");
1629 return -ENOTSUPP;
1630 }
1631
1632 if (!bpf_jit_supports_kfunc_call()) {
1633 verbose(env, "JIT does not support calling kernel function\n");
1634 return -ENOTSUPP;
1635 }
1636
1637 if (!env->prog->gpl_compatible) {
1638 verbose(env, "cannot call kernel function from non-GPL compatible program\n");
1639 return -EINVAL;
1640 }
1641
1642 tab = kzalloc(sizeof(*tab), GFP_KERNEL);
1643 if (!tab)
1644 return -ENOMEM;
1645 prog_aux->kfunc_tab = tab;
1646 }
1647
1648 if (find_kfunc_desc(env->prog, func_id))
1649 return 0;
1650
1651 if (tab->nr_descs == MAX_KFUNC_DESCS) {
1652 verbose(env, "too many different kernel function calls\n");
1653 return -E2BIG;
1654 }
1655
1656 func = btf_type_by_id(btf_vmlinux, func_id);
1657 if (!func || !btf_type_is_func(func)) {
1658 verbose(env, "kernel btf_id %u is not a function\n",
1659 func_id);
1660 return -EINVAL;
1661 }
1662 func_proto = btf_type_by_id(btf_vmlinux, func->type);
1663 if (!func_proto || !btf_type_is_func_proto(func_proto)) {
1664 verbose(env, "kernel function btf_id %u does not have a valid func_proto\n",
1665 func_id);
1666 return -EINVAL;
1667 }
1668
1669 func_name = btf_name_by_offset(btf_vmlinux, func->name_off);
1670 addr = kallsyms_lookup_name(func_name);
1671 if (!addr) {
1672 verbose(env, "cannot find address for kernel function %s\n",
1673 func_name);
1674 return -EINVAL;
1675 }
1676
1677 desc = &tab->descs[tab->nr_descs++];
1678 desc->func_id = func_id;
1679 desc->imm = BPF_CAST_CALL(addr) - __bpf_call_base;
1680 err = btf_distill_func_proto(&env->log, btf_vmlinux,
1681 func_proto, func_name,
1682 &desc->func_model);
1683 if (!err)
1684 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
1685 kfunc_desc_cmp_by_id, NULL);
1686 return err;
1687}
1688
1689static int kfunc_desc_cmp_by_imm(const void *a, const void *b)
1690{
1691 const struct bpf_kfunc_desc *d0 = a;
1692 const struct bpf_kfunc_desc *d1 = b;
1693
1694 if (d0->imm > d1->imm)
1695 return 1;
1696 else if (d0->imm < d1->imm)
1697 return -1;
1698 return 0;
1699}
1700
1701static void sort_kfunc_descs_by_imm(struct bpf_prog *prog)
1702{
1703 struct bpf_kfunc_desc_tab *tab;
1704
1705 tab = prog->aux->kfunc_tab;
1706 if (!tab)
1707 return;
1708
1709 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
1710 kfunc_desc_cmp_by_imm, NULL);
1711}
1712
1713bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
1714{
1715 return !!prog->aux->kfunc_tab;
1716}
1717
1718const struct btf_func_model *
1719bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
1720 const struct bpf_insn *insn)
1721{
1722 const struct bpf_kfunc_desc desc = {
1723 .imm = insn->imm,
1724 };
1725 const struct bpf_kfunc_desc *res;
1726 struct bpf_kfunc_desc_tab *tab;
1727
1728 tab = prog->aux->kfunc_tab;
1729 res = bsearch(&desc, tab->descs, tab->nr_descs,
1730 sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm);
1731
1732 return res ? &res->func_model : NULL;
1733}
1734
1735static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
cc8b0b92 1736{
9c8105bd 1737 struct bpf_subprog_info *subprog = env->subprog_info;
cc8b0b92 1738 struct bpf_insn *insn = env->prog->insnsi;
e6ac2450 1739 int i, ret, insn_cnt = env->prog->len;
cc8b0b92 1740
f910cefa
JW
1741 /* Add entry function. */
1742 ret = add_subprog(env, 0);
e6ac2450 1743 if (ret)
f910cefa
JW
1744 return ret;
1745
e6ac2450
MKL
1746 for (i = 0; i < insn_cnt; i++, insn++) {
1747 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
1748 !bpf_pseudo_kfunc_call(insn))
cc8b0b92 1749 continue;
e6ac2450 1750
2c78ee89 1751 if (!env->bpf_capable) {
e6ac2450 1752 verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
cc8b0b92
AS
1753 return -EPERM;
1754 }
e6ac2450
MKL
1755
1756 if (bpf_pseudo_func(insn)) {
1757 ret = add_subprog(env, i + insn->imm + 1);
1758 if (ret >= 0)
1759 /* remember subprog */
1760 insn[1].imm = ret;
1761 } else if (bpf_pseudo_call(insn)) {
1762 ret = add_subprog(env, i + insn->imm + 1);
1763 } else {
1764 ret = add_kfunc_call(env, insn->imm);
1765 }
1766
cc8b0b92
AS
1767 if (ret < 0)
1768 return ret;
1769 }
1770
4cb3d99c
JW
1771 /* Add a fake 'exit' subprog which could simplify subprog iteration
1772 * logic. 'subprog_cnt' should not be increased.
1773 */
1774 subprog[env->subprog_cnt].start = insn_cnt;
1775
06ee7115 1776 if (env->log.level & BPF_LOG_LEVEL2)
cc8b0b92 1777 for (i = 0; i < env->subprog_cnt; i++)
9c8105bd 1778 verbose(env, "func#%d @%d\n", i, subprog[i].start);
cc8b0b92 1779
e6ac2450
MKL
1780 return 0;
1781}
1782
1783static int check_subprogs(struct bpf_verifier_env *env)
1784{
1785 int i, subprog_start, subprog_end, off, cur_subprog = 0;
1786 struct bpf_subprog_info *subprog = env->subprog_info;
1787 struct bpf_insn *insn = env->prog->insnsi;
1788 int insn_cnt = env->prog->len;
1789
cc8b0b92 1790 /* now check that all jumps are within the same subprog */
4cb3d99c
JW
1791 subprog_start = subprog[cur_subprog].start;
1792 subprog_end = subprog[cur_subprog + 1].start;
cc8b0b92
AS
1793 for (i = 0; i < insn_cnt; i++) {
1794 u8 code = insn[i].code;
1795
7f6e4312
MF
1796 if (code == (BPF_JMP | BPF_CALL) &&
1797 insn[i].imm == BPF_FUNC_tail_call &&
1798 insn[i].src_reg != BPF_PSEUDO_CALL)
1799 subprog[cur_subprog].has_tail_call = true;
09b28d76
AS
1800 if (BPF_CLASS(code) == BPF_LD &&
1801 (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
1802 subprog[cur_subprog].has_ld_abs = true;
092ed096 1803 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
cc8b0b92
AS
1804 goto next;
1805 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
1806 goto next;
1807 off = i + insn[i].off + 1;
1808 if (off < subprog_start || off >= subprog_end) {
1809 verbose(env, "jump out of range from insn %d to %d\n", i, off);
1810 return -EINVAL;
1811 }
1812next:
1813 if (i == subprog_end - 1) {
1814 /* to avoid fall-through from one subprog into another
1815 * the last insn of the subprog should be either exit
1816 * or unconditional jump back
1817 */
1818 if (code != (BPF_JMP | BPF_EXIT) &&
1819 code != (BPF_JMP | BPF_JA)) {
1820 verbose(env, "last insn is not an exit or jmp\n");
1821 return -EINVAL;
1822 }
1823 subprog_start = subprog_end;
4cb3d99c
JW
1824 cur_subprog++;
1825 if (cur_subprog < env->subprog_cnt)
9c8105bd 1826 subprog_end = subprog[cur_subprog + 1].start;
cc8b0b92
AS
1827 }
1828 }
1829 return 0;
1830}
1831
679c782d
EC
1832/* Parentage chain of this register (or stack slot) should take care of all
1833 * issues like callee-saved registers, stack slot allocation time, etc.
1834 */
f4d7e40a 1835static int mark_reg_read(struct bpf_verifier_env *env,
679c782d 1836 const struct bpf_reg_state *state,
5327ed3d 1837 struct bpf_reg_state *parent, u8 flag)
f4d7e40a
AS
1838{
1839 bool writes = parent == state->parent; /* Observe write marks */
06ee7115 1840 int cnt = 0;
dc503a8a
EC
1841
1842 while (parent) {
1843 /* if read wasn't screened by an earlier write ... */
679c782d 1844 if (writes && state->live & REG_LIVE_WRITTEN)
dc503a8a 1845 break;
9242b5f5
AS
1846 if (parent->live & REG_LIVE_DONE) {
1847 verbose(env, "verifier BUG type %s var_off %lld off %d\n",
1848 reg_type_str[parent->type],
1849 parent->var_off.value, parent->off);
1850 return -EFAULT;
1851 }
5327ed3d
JW
1852 /* The first condition is more likely to be true than the
1853 * second, checked it first.
1854 */
1855 if ((parent->live & REG_LIVE_READ) == flag ||
1856 parent->live & REG_LIVE_READ64)
25af32da
AS
1857 /* The parentage chain never changes and
1858 * this parent was already marked as LIVE_READ.
1859 * There is no need to keep walking the chain again and
1860 * keep re-marking all parents as LIVE_READ.
1861 * This case happens when the same register is read
1862 * multiple times without writes into it in-between.
5327ed3d
JW
1863 * Also, if parent has the stronger REG_LIVE_READ64 set,
1864 * then no need to set the weak REG_LIVE_READ32.
25af32da
AS
1865 */
1866 break;
dc503a8a 1867 /* ... then we depend on parent's value */
5327ed3d
JW
1868 parent->live |= flag;
1869 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
1870 if (flag == REG_LIVE_READ64)
1871 parent->live &= ~REG_LIVE_READ32;
dc503a8a
EC
1872 state = parent;
1873 parent = state->parent;
f4d7e40a 1874 writes = true;
06ee7115 1875 cnt++;
dc503a8a 1876 }
06ee7115
AS
1877
1878 if (env->longest_mark_read_walk < cnt)
1879 env->longest_mark_read_walk = cnt;
f4d7e40a 1880 return 0;
dc503a8a
EC
1881}
1882
5327ed3d
JW
1883/* This function is supposed to be used by the following 32-bit optimization
1884 * code only. It returns TRUE if the source or destination register operates
1885 * on 64-bit, otherwise return FALSE.
1886 */
1887static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
1888 u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
1889{
1890 u8 code, class, op;
1891
1892 code = insn->code;
1893 class = BPF_CLASS(code);
1894 op = BPF_OP(code);
1895 if (class == BPF_JMP) {
1896 /* BPF_EXIT for "main" will reach here. Return TRUE
1897 * conservatively.
1898 */
1899 if (op == BPF_EXIT)
1900 return true;
1901 if (op == BPF_CALL) {
1902 /* BPF to BPF call will reach here because of marking
1903 * caller saved clobber with DST_OP_NO_MARK for which we
1904 * don't care the register def because they are anyway
1905 * marked as NOT_INIT already.
1906 */
1907 if (insn->src_reg == BPF_PSEUDO_CALL)
1908 return false;
1909 /* Helper call will reach here because of arg type
1910 * check, conservatively return TRUE.
1911 */
1912 if (t == SRC_OP)
1913 return true;
1914
1915 return false;
1916 }
1917 }
1918
1919 if (class == BPF_ALU64 || class == BPF_JMP ||
1920 /* BPF_END always use BPF_ALU class. */
1921 (class == BPF_ALU && op == BPF_END && insn->imm == 64))
1922 return true;
1923
1924 if (class == BPF_ALU || class == BPF_JMP32)
1925 return false;
1926
1927 if (class == BPF_LDX) {
1928 if (t != SRC_OP)
1929 return BPF_SIZE(code) == BPF_DW;
1930 /* LDX source must be ptr. */
1931 return true;
1932 }
1933
1934 if (class == BPF_STX) {
83a28819
IL
1935 /* BPF_STX (including atomic variants) has multiple source
1936 * operands, one of which is a ptr. Check whether the caller is
1937 * asking about it.
1938 */
1939 if (t == SRC_OP && reg->type != SCALAR_VALUE)
5327ed3d
JW
1940 return true;
1941 return BPF_SIZE(code) == BPF_DW;
1942 }
1943
1944 if (class == BPF_LD) {
1945 u8 mode = BPF_MODE(code);
1946
1947 /* LD_IMM64 */
1948 if (mode == BPF_IMM)
1949 return true;
1950
1951 /* Both LD_IND and LD_ABS return 32-bit data. */
1952 if (t != SRC_OP)
1953 return false;
1954
1955 /* Implicit ctx ptr. */
1956 if (regno == BPF_REG_6)
1957 return true;
1958
1959 /* Explicit source could be any width. */
1960 return true;
1961 }
1962
1963 if (class == BPF_ST)
1964 /* The only source register for BPF_ST is a ptr. */
1965 return true;
1966
1967 /* Conservatively return true at default. */
1968 return true;
1969}
1970
83a28819
IL
1971/* Return the regno defined by the insn, or -1. */
1972static int insn_def_regno(const struct bpf_insn *insn)
b325fbca 1973{
83a28819
IL
1974 switch (BPF_CLASS(insn->code)) {
1975 case BPF_JMP:
1976 case BPF_JMP32:
1977 case BPF_ST:
1978 return -1;
1979 case BPF_STX:
1980 if (BPF_MODE(insn->code) == BPF_ATOMIC &&
1981 (insn->imm & BPF_FETCH)) {
1982 if (insn->imm == BPF_CMPXCHG)
1983 return BPF_REG_0;
1984 else
1985 return insn->src_reg;
1986 } else {
1987 return -1;
1988 }
1989 default:
1990 return insn->dst_reg;
1991 }
b325fbca
JW
1992}
1993
1994/* Return TRUE if INSN has defined any 32-bit value explicitly. */
1995static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
1996{
83a28819
IL
1997 int dst_reg = insn_def_regno(insn);
1998
1999 if (dst_reg == -1)
b325fbca
JW
2000 return false;
2001
83a28819 2002 return !is_reg64(env, insn, dst_reg, NULL, DST_OP);
b325fbca
JW
2003}
2004
5327ed3d
JW
2005static void mark_insn_zext(struct bpf_verifier_env *env,
2006 struct bpf_reg_state *reg)
2007{
2008 s32 def_idx = reg->subreg_def;
2009
2010 if (def_idx == DEF_NOT_SUBREG)
2011 return;
2012
2013 env->insn_aux_data[def_idx - 1].zext_dst = true;
2014 /* The dst will be zero extended, so won't be sub-register anymore. */
2015 reg->subreg_def = DEF_NOT_SUBREG;
2016}
2017
dc503a8a 2018static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
17a52670
AS
2019 enum reg_arg_type t)
2020{
f4d7e40a
AS
2021 struct bpf_verifier_state *vstate = env->cur_state;
2022 struct bpf_func_state *state = vstate->frame[vstate->curframe];
5327ed3d 2023 struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
c342dc10 2024 struct bpf_reg_state *reg, *regs = state->regs;
5327ed3d 2025 bool rw64;
dc503a8a 2026
17a52670 2027 if (regno >= MAX_BPF_REG) {
61bd5218 2028 verbose(env, "R%d is invalid\n", regno);
17a52670
AS
2029 return -EINVAL;
2030 }
2031
c342dc10 2032 reg = &regs[regno];
5327ed3d 2033 rw64 = is_reg64(env, insn, regno, reg, t);
17a52670
AS
2034 if (t == SRC_OP) {
2035 /* check whether register used as source operand can be read */
c342dc10 2036 if (reg->type == NOT_INIT) {
61bd5218 2037 verbose(env, "R%d !read_ok\n", regno);
17a52670
AS
2038 return -EACCES;
2039 }
679c782d 2040 /* We don't need to worry about FP liveness because it's read-only */
c342dc10
JW
2041 if (regno == BPF_REG_FP)
2042 return 0;
2043
5327ed3d
JW
2044 if (rw64)
2045 mark_insn_zext(env, reg);
2046
2047 return mark_reg_read(env, reg, reg->parent,
2048 rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
17a52670
AS
2049 } else {
2050 /* check whether register used as dest operand can be written to */
2051 if (regno == BPF_REG_FP) {
61bd5218 2052 verbose(env, "frame pointer is read only\n");
17a52670
AS
2053 return -EACCES;
2054 }
c342dc10 2055 reg->live |= REG_LIVE_WRITTEN;
5327ed3d 2056 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
17a52670 2057 if (t == DST_OP)
61bd5218 2058 mark_reg_unknown(env, regs, regno);
17a52670
AS
2059 }
2060 return 0;
2061}
2062
b5dc0163
AS
2063/* for any branch, call, exit record the history of jmps in the given state */
2064static int push_jmp_history(struct bpf_verifier_env *env,
2065 struct bpf_verifier_state *cur)
2066{
2067 u32 cnt = cur->jmp_history_cnt;
2068 struct bpf_idx_pair *p;
2069
2070 cnt++;
2071 p = krealloc(cur->jmp_history, cnt * sizeof(*p), GFP_USER);
2072 if (!p)
2073 return -ENOMEM;
2074 p[cnt - 1].idx = env->insn_idx;
2075 p[cnt - 1].prev_idx = env->prev_insn_idx;
2076 cur->jmp_history = p;
2077 cur->jmp_history_cnt = cnt;
2078 return 0;
2079}
2080
2081/* Backtrack one insn at a time. If idx is not at the top of recorded
2082 * history then previous instruction came from straight line execution.
2083 */
2084static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
2085 u32 *history)
2086{
2087 u32 cnt = *history;
2088
2089 if (cnt && st->jmp_history[cnt - 1].idx == i) {
2090 i = st->jmp_history[cnt - 1].prev_idx;
2091 (*history)--;
2092 } else {
2093 i--;
2094 }
2095 return i;
2096}
2097
e6ac2450
MKL
2098static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
2099{
2100 const struct btf_type *func;
2101
2102 if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
2103 return NULL;
2104
2105 func = btf_type_by_id(btf_vmlinux, insn->imm);
2106 return btf_name_by_offset(btf_vmlinux, func->name_off);
2107}
2108
b5dc0163
AS
2109/* For given verifier state backtrack_insn() is called from the last insn to
2110 * the first insn. Its purpose is to compute a bitmask of registers and
2111 * stack slots that needs precision in the parent verifier state.
2112 */
2113static int backtrack_insn(struct bpf_verifier_env *env, int idx,
2114 u32 *reg_mask, u64 *stack_mask)
2115{
2116 const struct bpf_insn_cbs cbs = {
e6ac2450 2117 .cb_call = disasm_kfunc_name,
b5dc0163
AS
2118 .cb_print = verbose,
2119 .private_data = env,
2120 };
2121 struct bpf_insn *insn = env->prog->insnsi + idx;
2122 u8 class = BPF_CLASS(insn->code);
2123 u8 opcode = BPF_OP(insn->code);
2124 u8 mode = BPF_MODE(insn->code);
2125 u32 dreg = 1u << insn->dst_reg;
2126 u32 sreg = 1u << insn->src_reg;
2127 u32 spi;
2128
2129 if (insn->code == 0)
2130 return 0;
2131 if (env->log.level & BPF_LOG_LEVEL) {
2132 verbose(env, "regs=%x stack=%llx before ", *reg_mask, *stack_mask);
2133 verbose(env, "%d: ", idx);
2134 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
2135 }
2136
2137 if (class == BPF_ALU || class == BPF_ALU64) {
2138 if (!(*reg_mask & dreg))
2139 return 0;
2140 if (opcode == BPF_MOV) {
2141 if (BPF_SRC(insn->code) == BPF_X) {
2142 /* dreg = sreg
2143 * dreg needs precision after this insn
2144 * sreg needs precision before this insn
2145 */
2146 *reg_mask &= ~dreg;
2147 *reg_mask |= sreg;
2148 } else {
2149 /* dreg = K
2150 * dreg needs precision after this insn.
2151 * Corresponding register is already marked
2152 * as precise=true in this verifier state.
2153 * No further markings in parent are necessary
2154 */
2155 *reg_mask &= ~dreg;
2156 }
2157 } else {
2158 if (BPF_SRC(insn->code) == BPF_X) {
2159 /* dreg += sreg
2160 * both dreg and sreg need precision
2161 * before this insn
2162 */
2163 *reg_mask |= sreg;
2164 } /* else dreg += K
2165 * dreg still needs precision before this insn
2166 */
2167 }
2168 } else if (class == BPF_LDX) {
2169 if (!(*reg_mask & dreg))
2170 return 0;
2171 *reg_mask &= ~dreg;
2172
2173 /* scalars can only be spilled into stack w/o losing precision.
2174 * Load from any other memory can be zero extended.
2175 * The desire to keep that precision is already indicated
2176 * by 'precise' mark in corresponding register of this state.
2177 * No further tracking necessary.
2178 */
2179 if (insn->src_reg != BPF_REG_FP)
2180 return 0;
2181 if (BPF_SIZE(insn->code) != BPF_DW)
2182 return 0;
2183
2184 /* dreg = *(u64 *)[fp - off] was a fill from the stack.
2185 * that [fp - off] slot contains scalar that needs to be
2186 * tracked with precision
2187 */
2188 spi = (-insn->off - 1) / BPF_REG_SIZE;
2189 if (spi >= 64) {
2190 verbose(env, "BUG spi %d\n", spi);
2191 WARN_ONCE(1, "verifier backtracking bug");
2192 return -EFAULT;
2193 }
2194 *stack_mask |= 1ull << spi;
b3b50f05 2195 } else if (class == BPF_STX || class == BPF_ST) {
b5dc0163 2196 if (*reg_mask & dreg)
b3b50f05 2197 /* stx & st shouldn't be using _scalar_ dst_reg
b5dc0163
AS
2198 * to access memory. It means backtracking
2199 * encountered a case of pointer subtraction.
2200 */
2201 return -ENOTSUPP;
2202 /* scalars can only be spilled into stack */
2203 if (insn->dst_reg != BPF_REG_FP)
2204 return 0;
2205 if (BPF_SIZE(insn->code) != BPF_DW)
2206 return 0;
2207 spi = (-insn->off - 1) / BPF_REG_SIZE;
2208 if (spi >= 64) {
2209 verbose(env, "BUG spi %d\n", spi);
2210 WARN_ONCE(1, "verifier backtracking bug");
2211 return -EFAULT;
2212 }
2213 if (!(*stack_mask & (1ull << spi)))
2214 return 0;
2215 *stack_mask &= ~(1ull << spi);
b3b50f05
AN
2216 if (class == BPF_STX)
2217 *reg_mask |= sreg;
b5dc0163
AS
2218 } else if (class == BPF_JMP || class == BPF_JMP32) {
2219 if (opcode == BPF_CALL) {
2220 if (insn->src_reg == BPF_PSEUDO_CALL)
2221 return -ENOTSUPP;
2222 /* regular helper call sets R0 */
2223 *reg_mask &= ~1;
2224 if (*reg_mask & 0x3f) {
2225 /* if backtracing was looking for registers R1-R5
2226 * they should have been found already.
2227 */
2228 verbose(env, "BUG regs %x\n", *reg_mask);
2229 WARN_ONCE(1, "verifier backtracking bug");
2230 return -EFAULT;
2231 }
2232 } else if (opcode == BPF_EXIT) {
2233 return -ENOTSUPP;
2234 }
2235 } else if (class == BPF_LD) {
2236 if (!(*reg_mask & dreg))
2237 return 0;
2238 *reg_mask &= ~dreg;
2239 /* It's ld_imm64 or ld_abs or ld_ind.
2240 * For ld_imm64 no further tracking of precision
2241 * into parent is necessary
2242 */
2243 if (mode == BPF_IND || mode == BPF_ABS)
2244 /* to be analyzed */
2245 return -ENOTSUPP;
b5dc0163
AS
2246 }
2247 return 0;
2248}
2249
2250/* the scalar precision tracking algorithm:
2251 * . at the start all registers have precise=false.
2252 * . scalar ranges are tracked as normal through alu and jmp insns.
2253 * . once precise value of the scalar register is used in:
2254 * . ptr + scalar alu
2255 * . if (scalar cond K|scalar)
2256 * . helper_call(.., scalar, ...) where ARG_CONST is expected
2257 * backtrack through the verifier states and mark all registers and
2258 * stack slots with spilled constants that these scalar regisers
2259 * should be precise.
2260 * . during state pruning two registers (or spilled stack slots)
2261 * are equivalent if both are not precise.
2262 *
2263 * Note the verifier cannot simply walk register parentage chain,
2264 * since many different registers and stack slots could have been
2265 * used to compute single precise scalar.
2266 *
2267 * The approach of starting with precise=true for all registers and then
2268 * backtrack to mark a register as not precise when the verifier detects
2269 * that program doesn't care about specific value (e.g., when helper
2270 * takes register as ARG_ANYTHING parameter) is not safe.
2271 *
2272 * It's ok to walk single parentage chain of the verifier states.
2273 * It's possible that this backtracking will go all the way till 1st insn.
2274 * All other branches will be explored for needing precision later.
2275 *
2276 * The backtracking needs to deal with cases like:
2277 * 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)
2278 * r9 -= r8
2279 * r5 = r9
2280 * if r5 > 0x79f goto pc+7
2281 * R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
2282 * r5 += 1
2283 * ...
2284 * call bpf_perf_event_output#25
2285 * where .arg5_type = ARG_CONST_SIZE_OR_ZERO
2286 *
2287 * and this case:
2288 * r6 = 1
2289 * call foo // uses callee's r6 inside to compute r0
2290 * r0 += r6
2291 * if r0 == 0 goto
2292 *
2293 * to track above reg_mask/stack_mask needs to be independent for each frame.
2294 *
2295 * Also if parent's curframe > frame where backtracking started,
2296 * the verifier need to mark registers in both frames, otherwise callees
2297 * may incorrectly prune callers. This is similar to
2298 * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
2299 *
2300 * For now backtracking falls back into conservative marking.
2301 */
2302static void mark_all_scalars_precise(struct bpf_verifier_env *env,
2303 struct bpf_verifier_state *st)
2304{
2305 struct bpf_func_state *func;
2306 struct bpf_reg_state *reg;
2307 int i, j;
2308
2309 /* big hammer: mark all scalars precise in this path.
2310 * pop_stack may still get !precise scalars.
2311 */
2312 for (; st; st = st->parent)
2313 for (i = 0; i <= st->curframe; i++) {
2314 func = st->frame[i];
2315 for (j = 0; j < BPF_REG_FP; j++) {
2316 reg = &func->regs[j];
2317 if (reg->type != SCALAR_VALUE)
2318 continue;
2319 reg->precise = true;
2320 }
2321 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
2322 if (func->stack[j].slot_type[0] != STACK_SPILL)
2323 continue;
2324 reg = &func->stack[j].spilled_ptr;
2325 if (reg->type != SCALAR_VALUE)
2326 continue;
2327 reg->precise = true;
2328 }
2329 }
2330}
2331
a3ce685d
AS
2332static int __mark_chain_precision(struct bpf_verifier_env *env, int regno,
2333 int spi)
b5dc0163
AS
2334{
2335 struct bpf_verifier_state *st = env->cur_state;
2336 int first_idx = st->first_insn_idx;
2337 int last_idx = env->insn_idx;
2338 struct bpf_func_state *func;
2339 struct bpf_reg_state *reg;
a3ce685d
AS
2340 u32 reg_mask = regno >= 0 ? 1u << regno : 0;
2341 u64 stack_mask = spi >= 0 ? 1ull << spi : 0;
b5dc0163 2342 bool skip_first = true;
a3ce685d 2343 bool new_marks = false;
b5dc0163
AS
2344 int i, err;
2345
2c78ee89 2346 if (!env->bpf_capable)
b5dc0163
AS
2347 return 0;
2348
2349 func = st->frame[st->curframe];
a3ce685d
AS
2350 if (regno >= 0) {
2351 reg = &func->regs[regno];
2352 if (reg->type != SCALAR_VALUE) {
2353 WARN_ONCE(1, "backtracing misuse");
2354 return -EFAULT;
2355 }
2356 if (!reg->precise)
2357 new_marks = true;
2358 else
2359 reg_mask = 0;
2360 reg->precise = true;
b5dc0163 2361 }
b5dc0163 2362
a3ce685d
AS
2363 while (spi >= 0) {
2364 if (func->stack[spi].slot_type[0] != STACK_SPILL) {
2365 stack_mask = 0;
2366 break;
2367 }
2368 reg = &func->stack[spi].spilled_ptr;
2369 if (reg->type != SCALAR_VALUE) {
2370 stack_mask = 0;
2371 break;
2372 }
2373 if (!reg->precise)
2374 new_marks = true;
2375 else
2376 stack_mask = 0;
2377 reg->precise = true;
2378 break;
2379 }
2380
2381 if (!new_marks)
2382 return 0;
2383 if (!reg_mask && !stack_mask)
2384 return 0;
b5dc0163
AS
2385 for (;;) {
2386 DECLARE_BITMAP(mask, 64);
b5dc0163
AS
2387 u32 history = st->jmp_history_cnt;
2388
2389 if (env->log.level & BPF_LOG_LEVEL)
2390 verbose(env, "last_idx %d first_idx %d\n", last_idx, first_idx);
2391 for (i = last_idx;;) {
2392 if (skip_first) {
2393 err = 0;
2394 skip_first = false;
2395 } else {
2396 err = backtrack_insn(env, i, &reg_mask, &stack_mask);
2397 }
2398 if (err == -ENOTSUPP) {
2399 mark_all_scalars_precise(env, st);
2400 return 0;
2401 } else if (err) {
2402 return err;
2403 }
2404 if (!reg_mask && !stack_mask)
2405 /* Found assignment(s) into tracked register in this state.
2406 * Since this state is already marked, just return.
2407 * Nothing to be tracked further in the parent state.
2408 */
2409 return 0;
2410 if (i == first_idx)
2411 break;
2412 i = get_prev_insn_idx(st, i, &history);
2413 if (i >= env->prog->len) {
2414 /* This can happen if backtracking reached insn 0
2415 * and there are still reg_mask or stack_mask
2416 * to backtrack.
2417 * It means the backtracking missed the spot where
2418 * particular register was initialized with a constant.
2419 */
2420 verbose(env, "BUG backtracking idx %d\n", i);
2421 WARN_ONCE(1, "verifier backtracking bug");
2422 return -EFAULT;
2423 }
2424 }
2425 st = st->parent;
2426 if (!st)
2427 break;
2428
a3ce685d 2429 new_marks = false;
b5dc0163
AS
2430 func = st->frame[st->curframe];
2431 bitmap_from_u64(mask, reg_mask);
2432 for_each_set_bit(i, mask, 32) {
2433 reg = &func->regs[i];
a3ce685d
AS
2434 if (reg->type != SCALAR_VALUE) {
2435 reg_mask &= ~(1u << i);
b5dc0163 2436 continue;
a3ce685d 2437 }
b5dc0163
AS
2438 if (!reg->precise)
2439 new_marks = true;
2440 reg->precise = true;
2441 }
2442
2443 bitmap_from_u64(mask, stack_mask);
2444 for_each_set_bit(i, mask, 64) {
2445 if (i >= func->allocated_stack / BPF_REG_SIZE) {
2339cd6c
AS
2446 /* the sequence of instructions:
2447 * 2: (bf) r3 = r10
2448 * 3: (7b) *(u64 *)(r3 -8) = r0
2449 * 4: (79) r4 = *(u64 *)(r10 -8)
2450 * doesn't contain jmps. It's backtracked
2451 * as a single block.
2452 * During backtracking insn 3 is not recognized as
2453 * stack access, so at the end of backtracking
2454 * stack slot fp-8 is still marked in stack_mask.
2455 * However the parent state may not have accessed
2456 * fp-8 and it's "unallocated" stack space.
2457 * In such case fallback to conservative.
b5dc0163 2458 */
2339cd6c
AS
2459 mark_all_scalars_precise(env, st);
2460 return 0;
b5dc0163
AS
2461 }
2462
a3ce685d
AS
2463 if (func->stack[i].slot_type[0] != STACK_SPILL) {
2464 stack_mask &= ~(1ull << i);
b5dc0163 2465 continue;
a3ce685d 2466 }
b5dc0163 2467 reg = &func->stack[i].spilled_ptr;
a3ce685d
AS
2468 if (reg->type != SCALAR_VALUE) {
2469 stack_mask &= ~(1ull << i);
b5dc0163 2470 continue;
a3ce685d 2471 }
b5dc0163
AS
2472 if (!reg->precise)
2473 new_marks = true;
2474 reg->precise = true;
2475 }
2476 if (env->log.level & BPF_LOG_LEVEL) {
2477 print_verifier_state(env, func);
2478 verbose(env, "parent %s regs=%x stack=%llx marks\n",
2479 new_marks ? "didn't have" : "already had",
2480 reg_mask, stack_mask);
2481 }
2482
a3ce685d
AS
2483 if (!reg_mask && !stack_mask)
2484 break;
b5dc0163
AS
2485 if (!new_marks)
2486 break;
2487
2488 last_idx = st->last_insn_idx;
2489 first_idx = st->first_insn_idx;
2490 }
2491 return 0;
2492}
2493
a3ce685d
AS
2494static int mark_chain_precision(struct bpf_verifier_env *env, int regno)
2495{
2496 return __mark_chain_precision(env, regno, -1);
2497}
2498
2499static int mark_chain_precision_stack(struct bpf_verifier_env *env, int spi)
2500{
2501 return __mark_chain_precision(env, -1, spi);
2502}
b5dc0163 2503
1be7f75d
AS
2504static bool is_spillable_regtype(enum bpf_reg_type type)
2505{
2506 switch (type) {
2507 case PTR_TO_MAP_VALUE:
2508 case PTR_TO_MAP_VALUE_OR_NULL:
2509 case PTR_TO_STACK:
2510 case PTR_TO_CTX:
969bf05e 2511 case PTR_TO_PACKET:
de8f3a83 2512 case PTR_TO_PACKET_META:
969bf05e 2513 case PTR_TO_PACKET_END:
d58e468b 2514 case PTR_TO_FLOW_KEYS:
1be7f75d 2515 case CONST_PTR_TO_MAP:
c64b7983
JS
2516 case PTR_TO_SOCKET:
2517 case PTR_TO_SOCKET_OR_NULL:
46f8bc92
MKL
2518 case PTR_TO_SOCK_COMMON:
2519 case PTR_TO_SOCK_COMMON_OR_NULL:
655a51e5
MKL
2520 case PTR_TO_TCP_SOCK:
2521 case PTR_TO_TCP_SOCK_OR_NULL:
fada7fdc 2522 case PTR_TO_XDP_SOCK:
65726b5b 2523 case PTR_TO_BTF_ID:
b121b341 2524 case PTR_TO_BTF_ID_OR_NULL:
afbf21dc
YS
2525 case PTR_TO_RDONLY_BUF:
2526 case PTR_TO_RDONLY_BUF_OR_NULL:
2527 case PTR_TO_RDWR_BUF:
2528 case PTR_TO_RDWR_BUF_OR_NULL:
eaa6bcb7 2529 case PTR_TO_PERCPU_BTF_ID:
744ea4e3
GR
2530 case PTR_TO_MEM:
2531 case PTR_TO_MEM_OR_NULL:
69c087ba
YS
2532 case PTR_TO_FUNC:
2533 case PTR_TO_MAP_KEY:
1be7f75d
AS
2534 return true;
2535 default:
2536 return false;
2537 }
2538}
2539
cc2b14d5
AS
2540/* Does this register contain a constant zero? */
2541static bool register_is_null(struct bpf_reg_state *reg)
2542{
2543 return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
2544}
2545
f7cf25b2
AS
2546static bool register_is_const(struct bpf_reg_state *reg)
2547{
2548 return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
2549}
2550
5689d49b
YS
2551static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
2552{
2553 return tnum_is_unknown(reg->var_off) &&
2554 reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
2555 reg->umin_value == 0 && reg->umax_value == U64_MAX &&
2556 reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
2557 reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
2558}
2559
2560static bool register_is_bounded(struct bpf_reg_state *reg)
2561{
2562 return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
2563}
2564
6e7e63cb
JH
2565static bool __is_pointer_value(bool allow_ptr_leaks,
2566 const struct bpf_reg_state *reg)
2567{
2568 if (allow_ptr_leaks)
2569 return false;
2570
2571 return reg->type != SCALAR_VALUE;
2572}
2573
f7cf25b2
AS
2574static void save_register_state(struct bpf_func_state *state,
2575 int spi, struct bpf_reg_state *reg)
2576{
2577 int i;
2578
2579 state->stack[spi].spilled_ptr = *reg;
2580 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
2581
2582 for (i = 0; i < BPF_REG_SIZE; i++)
2583 state->stack[spi].slot_type[i] = STACK_SPILL;
2584}
2585
01f810ac 2586/* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
17a52670
AS
2587 * stack boundary and alignment are checked in check_mem_access()
2588 */
01f810ac
AM
2589static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
2590 /* stack frame we're writing to */
2591 struct bpf_func_state *state,
2592 int off, int size, int value_regno,
2593 int insn_idx)
17a52670 2594{
f4d7e40a 2595 struct bpf_func_state *cur; /* state of the current function */
638f5b90 2596 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
b5dc0163 2597 u32 dst_reg = env->prog->insnsi[insn_idx].dst_reg;
f7cf25b2 2598 struct bpf_reg_state *reg = NULL;
638f5b90 2599
c69431aa 2600 err = grow_stack_state(state, round_up(slot + 1, BPF_REG_SIZE));
638f5b90
AS
2601 if (err)
2602 return err;
9c399760
AS
2603 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
2604 * so it's aligned access and [off, off + size) are within stack limits
2605 */
638f5b90
AS
2606 if (!env->allow_ptr_leaks &&
2607 state->stack[spi].slot_type[0] == STACK_SPILL &&
2608 size != BPF_REG_SIZE) {
2609 verbose(env, "attempt to corrupt spilled pointer on stack\n");
2610 return -EACCES;
2611 }
17a52670 2612
f4d7e40a 2613 cur = env->cur_state->frame[env->cur_state->curframe];
f7cf25b2
AS
2614 if (value_regno >= 0)
2615 reg = &cur->regs[value_regno];
17a52670 2616
5689d49b 2617 if (reg && size == BPF_REG_SIZE && register_is_bounded(reg) &&
2c78ee89 2618 !register_is_null(reg) && env->bpf_capable) {
b5dc0163
AS
2619 if (dst_reg != BPF_REG_FP) {
2620 /* The backtracking logic can only recognize explicit
2621 * stack slot address like [fp - 8]. Other spill of
2622 * scalar via different register has to be conervative.
2623 * Backtrack from here and mark all registers as precise
2624 * that contributed into 'reg' being a constant.
2625 */
2626 err = mark_chain_precision(env, value_regno);
2627 if (err)
2628 return err;
2629 }
f7cf25b2
AS
2630 save_register_state(state, spi, reg);
2631 } else if (reg && is_spillable_regtype(reg->type)) {
17a52670 2632 /* register containing pointer is being spilled into stack */
9c399760 2633 if (size != BPF_REG_SIZE) {
f7cf25b2 2634 verbose_linfo(env, insn_idx, "; ");
61bd5218 2635 verbose(env, "invalid size of register spill\n");
17a52670
AS
2636 return -EACCES;
2637 }
2638
f7cf25b2 2639 if (state != cur && reg->type == PTR_TO_STACK) {
f4d7e40a
AS
2640 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
2641 return -EINVAL;
2642 }
2643
2c78ee89 2644 if (!env->bypass_spec_v4) {
f7cf25b2 2645 bool sanitize = false;
17a52670 2646
f7cf25b2
AS
2647 if (state->stack[spi].slot_type[0] == STACK_SPILL &&
2648 register_is_const(&state->stack[spi].spilled_ptr))
2649 sanitize = true;
2650 for (i = 0; i < BPF_REG_SIZE; i++)
2651 if (state->stack[spi].slot_type[i] == STACK_MISC) {
2652 sanitize = true;
2653 break;
2654 }
2655 if (sanitize) {
af86ca4e
AS
2656 int *poff = &env->insn_aux_data[insn_idx].sanitize_stack_off;
2657 int soff = (-spi - 1) * BPF_REG_SIZE;
2658
2659 /* detected reuse of integer stack slot with a pointer
2660 * which means either llvm is reusing stack slot or
2661 * an attacker is trying to exploit CVE-2018-3639
2662 * (speculative store bypass)
2663 * Have to sanitize that slot with preemptive
2664 * store of zero.
2665 */
2666 if (*poff && *poff != soff) {
2667 /* disallow programs where single insn stores
2668 * into two different stack slots, since verifier
2669 * cannot sanitize them
2670 */
2671 verbose(env,
2672 "insn %d cannot access two stack slots fp%d and fp%d",
2673 insn_idx, *poff, soff);
2674 return -EINVAL;
2675 }
2676 *poff = soff;
2677 }
af86ca4e 2678 }
f7cf25b2 2679 save_register_state(state, spi, reg);
9c399760 2680 } else {
cc2b14d5
AS
2681 u8 type = STACK_MISC;
2682
679c782d
EC
2683 /* regular write of data into stack destroys any spilled ptr */
2684 state->stack[spi].spilled_ptr.type = NOT_INIT;
0bae2d4d
JW
2685 /* Mark slots as STACK_MISC if they belonged to spilled ptr. */
2686 if (state->stack[spi].slot_type[0] == STACK_SPILL)
2687 for (i = 0; i < BPF_REG_SIZE; i++)
2688 state->stack[spi].slot_type[i] = STACK_MISC;
9c399760 2689
cc2b14d5
AS
2690 /* only mark the slot as written if all 8 bytes were written
2691 * otherwise read propagation may incorrectly stop too soon
2692 * when stack slots are partially written.
2693 * This heuristic means that read propagation will be
2694 * conservative, since it will add reg_live_read marks
2695 * to stack slots all the way to first state when programs
2696 * writes+reads less than 8 bytes
2697 */
2698 if (size == BPF_REG_SIZE)
2699 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
2700
2701 /* when we zero initialize stack slots mark them as such */
b5dc0163
AS
2702 if (reg && register_is_null(reg)) {
2703 /* backtracking doesn't work for STACK_ZERO yet. */
2704 err = mark_chain_precision(env, value_regno);
2705 if (err)
2706 return err;
cc2b14d5 2707 type = STACK_ZERO;
b5dc0163 2708 }
cc2b14d5 2709
0bae2d4d 2710 /* Mark slots affected by this stack write. */
9c399760 2711 for (i = 0; i < size; i++)
638f5b90 2712 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
cc2b14d5 2713 type;
17a52670
AS
2714 }
2715 return 0;
2716}
2717
01f810ac
AM
2718/* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
2719 * known to contain a variable offset.
2720 * This function checks whether the write is permitted and conservatively
2721 * tracks the effects of the write, considering that each stack slot in the
2722 * dynamic range is potentially written to.
2723 *
2724 * 'off' includes 'regno->off'.
2725 * 'value_regno' can be -1, meaning that an unknown value is being written to
2726 * the stack.
2727 *
2728 * Spilled pointers in range are not marked as written because we don't know
2729 * what's going to be actually written. This means that read propagation for
2730 * future reads cannot be terminated by this write.
2731 *
2732 * For privileged programs, uninitialized stack slots are considered
2733 * initialized by this write (even though we don't know exactly what offsets
2734 * are going to be written to). The idea is that we don't want the verifier to
2735 * reject future reads that access slots written to through variable offsets.
2736 */
2737static int check_stack_write_var_off(struct bpf_verifier_env *env,
2738 /* func where register points to */
2739 struct bpf_func_state *state,
2740 int ptr_regno, int off, int size,
2741 int value_regno, int insn_idx)
2742{
2743 struct bpf_func_state *cur; /* state of the current function */
2744 int min_off, max_off;
2745 int i, err;
2746 struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
2747 bool writing_zero = false;
2748 /* set if the fact that we're writing a zero is used to let any
2749 * stack slots remain STACK_ZERO
2750 */
2751 bool zero_used = false;
2752
2753 cur = env->cur_state->frame[env->cur_state->curframe];
2754 ptr_reg = &cur->regs[ptr_regno];
2755 min_off = ptr_reg->smin_value + off;
2756 max_off = ptr_reg->smax_value + off + size;
2757 if (value_regno >= 0)
2758 value_reg = &cur->regs[value_regno];
2759 if (value_reg && register_is_null(value_reg))
2760 writing_zero = true;
2761
c69431aa 2762 err = grow_stack_state(state, round_up(-min_off, BPF_REG_SIZE));
01f810ac
AM
2763 if (err)
2764 return err;
2765
2766
2767 /* Variable offset writes destroy any spilled pointers in range. */
2768 for (i = min_off; i < max_off; i++) {
2769 u8 new_type, *stype;
2770 int slot, spi;
2771
2772 slot = -i - 1;
2773 spi = slot / BPF_REG_SIZE;
2774 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
2775
2776 if (!env->allow_ptr_leaks
2777 && *stype != NOT_INIT
2778 && *stype != SCALAR_VALUE) {
2779 /* Reject the write if there's are spilled pointers in
2780 * range. If we didn't reject here, the ptr status
2781 * would be erased below (even though not all slots are
2782 * actually overwritten), possibly opening the door to
2783 * leaks.
2784 */
2785 verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
2786 insn_idx, i);
2787 return -EINVAL;
2788 }
2789
2790 /* Erase all spilled pointers. */
2791 state->stack[spi].spilled_ptr.type = NOT_INIT;
2792
2793 /* Update the slot type. */
2794 new_type = STACK_MISC;
2795 if (writing_zero && *stype == STACK_ZERO) {
2796 new_type = STACK_ZERO;
2797 zero_used = true;
2798 }
2799 /* If the slot is STACK_INVALID, we check whether it's OK to
2800 * pretend that it will be initialized by this write. The slot
2801 * might not actually be written to, and so if we mark it as
2802 * initialized future reads might leak uninitialized memory.
2803 * For privileged programs, we will accept such reads to slots
2804 * that may or may not be written because, if we're reject
2805 * them, the error would be too confusing.
2806 */
2807 if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
2808 verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
2809 insn_idx, i);
2810 return -EINVAL;
2811 }
2812 *stype = new_type;
2813 }
2814 if (zero_used) {
2815 /* backtracking doesn't work for STACK_ZERO yet. */
2816 err = mark_chain_precision(env, value_regno);
2817 if (err)
2818 return err;
2819 }
2820 return 0;
2821}
2822
2823/* When register 'dst_regno' is assigned some values from stack[min_off,
2824 * max_off), we set the register's type according to the types of the
2825 * respective stack slots. If all the stack values are known to be zeros, then
2826 * so is the destination reg. Otherwise, the register is considered to be
2827 * SCALAR. This function does not deal with register filling; the caller must
2828 * ensure that all spilled registers in the stack range have been marked as
2829 * read.
2830 */
2831static void mark_reg_stack_read(struct bpf_verifier_env *env,
2832 /* func where src register points to */
2833 struct bpf_func_state *ptr_state,
2834 int min_off, int max_off, int dst_regno)
2835{
2836 struct bpf_verifier_state *vstate = env->cur_state;
2837 struct bpf_func_state *state = vstate->frame[vstate->curframe];
2838 int i, slot, spi;
2839 u8 *stype;
2840 int zeros = 0;
2841
2842 for (i = min_off; i < max_off; i++) {
2843 slot = -i - 1;
2844 spi = slot / BPF_REG_SIZE;
2845 stype = ptr_state->stack[spi].slot_type;
2846 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
2847 break;
2848 zeros++;
2849 }
2850 if (zeros == max_off - min_off) {
2851 /* any access_size read into register is zero extended,
2852 * so the whole register == const_zero
2853 */
2854 __mark_reg_const_zero(&state->regs[dst_regno]);
2855 /* backtracking doesn't support STACK_ZERO yet,
2856 * so mark it precise here, so that later
2857 * backtracking can stop here.
2858 * Backtracking may not need this if this register
2859 * doesn't participate in pointer adjustment.
2860 * Forward propagation of precise flag is not
2861 * necessary either. This mark is only to stop
2862 * backtracking. Any register that contributed
2863 * to const 0 was marked precise before spill.
2864 */
2865 state->regs[dst_regno].precise = true;
2866 } else {
2867 /* have read misc data from the stack */
2868 mark_reg_unknown(env, state->regs, dst_regno);
2869 }
2870 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
2871}
2872
2873/* Read the stack at 'off' and put the results into the register indicated by
2874 * 'dst_regno'. It handles reg filling if the addressed stack slot is a
2875 * spilled reg.
2876 *
2877 * 'dst_regno' can be -1, meaning that the read value is not going to a
2878 * register.
2879 *
2880 * The access is assumed to be within the current stack bounds.
2881 */
2882static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
2883 /* func where src register points to */
2884 struct bpf_func_state *reg_state,
2885 int off, int size, int dst_regno)
17a52670 2886{
f4d7e40a
AS
2887 struct bpf_verifier_state *vstate = env->cur_state;
2888 struct bpf_func_state *state = vstate->frame[vstate->curframe];
638f5b90 2889 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
f7cf25b2 2890 struct bpf_reg_state *reg;
638f5b90 2891 u8 *stype;
17a52670 2892
f4d7e40a 2893 stype = reg_state->stack[spi].slot_type;
f7cf25b2 2894 reg = &reg_state->stack[spi].spilled_ptr;
17a52670 2895
638f5b90 2896 if (stype[0] == STACK_SPILL) {
9c399760 2897 if (size != BPF_REG_SIZE) {
f7cf25b2
AS
2898 if (reg->type != SCALAR_VALUE) {
2899 verbose_linfo(env, env->insn_idx, "; ");
2900 verbose(env, "invalid size of register fill\n");
2901 return -EACCES;
2902 }
01f810ac
AM
2903 if (dst_regno >= 0) {
2904 mark_reg_unknown(env, state->regs, dst_regno);
2905 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
f7cf25b2
AS
2906 }
2907 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
2908 return 0;
17a52670 2909 }
9c399760 2910 for (i = 1; i < BPF_REG_SIZE; i++) {
638f5b90 2911 if (stype[(slot - i) % BPF_REG_SIZE] != STACK_SPILL) {
61bd5218 2912 verbose(env, "corrupted spill memory\n");
17a52670
AS
2913 return -EACCES;
2914 }
2915 }
2916
01f810ac 2917 if (dst_regno >= 0) {
17a52670 2918 /* restore register state from stack */
01f810ac 2919 state->regs[dst_regno] = *reg;
2f18f62e
AS
2920 /* mark reg as written since spilled pointer state likely
2921 * has its liveness marks cleared by is_state_visited()
2922 * which resets stack/reg liveness for state transitions
2923 */
01f810ac 2924 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
6e7e63cb 2925 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
01f810ac 2926 /* If dst_regno==-1, the caller is asking us whether
6e7e63cb
JH
2927 * it is acceptable to use this value as a SCALAR_VALUE
2928 * (e.g. for XADD).
2929 * We must not allow unprivileged callers to do that
2930 * with spilled pointers.
2931 */
2932 verbose(env, "leaking pointer from stack off %d\n",
2933 off);
2934 return -EACCES;
dc503a8a 2935 }
f7cf25b2 2936 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
17a52670 2937 } else {
01f810ac 2938 u8 type;
cc2b14d5 2939
17a52670 2940 for (i = 0; i < size; i++) {
01f810ac
AM
2941 type = stype[(slot - i) % BPF_REG_SIZE];
2942 if (type == STACK_MISC)
cc2b14d5 2943 continue;
01f810ac 2944 if (type == STACK_ZERO)
cc2b14d5 2945 continue;
cc2b14d5
AS
2946 verbose(env, "invalid read from stack off %d+%d size %d\n",
2947 off, i, size);
2948 return -EACCES;
2949 }
f7cf25b2 2950 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
01f810ac
AM
2951 if (dst_regno >= 0)
2952 mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
17a52670 2953 }
f7cf25b2 2954 return 0;
17a52670
AS
2955}
2956
01f810ac
AM
2957enum stack_access_src {
2958 ACCESS_DIRECT = 1, /* the access is performed by an instruction */
2959 ACCESS_HELPER = 2, /* the access is performed by a helper */
2960};
2961
2962static int check_stack_range_initialized(struct bpf_verifier_env *env,
2963 int regno, int off, int access_size,
2964 bool zero_size_allowed,
2965 enum stack_access_src type,
2966 struct bpf_call_arg_meta *meta);
2967
2968static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
2969{
2970 return cur_regs(env) + regno;
2971}
2972
2973/* Read the stack at 'ptr_regno + off' and put the result into the register
2974 * 'dst_regno'.
2975 * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
2976 * but not its variable offset.
2977 * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
2978 *
2979 * As opposed to check_stack_read_fixed_off, this function doesn't deal with
2980 * filling registers (i.e. reads of spilled register cannot be detected when
2981 * the offset is not fixed). We conservatively mark 'dst_regno' as containing
2982 * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
2983 * offset; for a fixed offset check_stack_read_fixed_off should be used
2984 * instead.
2985 */
2986static int check_stack_read_var_off(struct bpf_verifier_env *env,
2987 int ptr_regno, int off, int size, int dst_regno)
e4298d25 2988{
01f810ac
AM
2989 /* The state of the source register. */
2990 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
2991 struct bpf_func_state *ptr_state = func(env, reg);
2992 int err;
2993 int min_off, max_off;
2994
2995 /* Note that we pass a NULL meta, so raw access will not be permitted.
e4298d25 2996 */
01f810ac
AM
2997 err = check_stack_range_initialized(env, ptr_regno, off, size,
2998 false, ACCESS_DIRECT, NULL);
2999 if (err)
3000 return err;
3001
3002 min_off = reg->smin_value + off;
3003 max_off = reg->smax_value + off;
3004 mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
3005 return 0;
3006}
3007
3008/* check_stack_read dispatches to check_stack_read_fixed_off or
3009 * check_stack_read_var_off.
3010 *
3011 * The caller must ensure that the offset falls within the allocated stack
3012 * bounds.
3013 *
3014 * 'dst_regno' is a register which will receive the value from the stack. It
3015 * can be -1, meaning that the read value is not going to a register.
3016 */
3017static int check_stack_read(struct bpf_verifier_env *env,
3018 int ptr_regno, int off, int size,
3019 int dst_regno)
3020{
3021 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3022 struct bpf_func_state *state = func(env, reg);
3023 int err;
3024 /* Some accesses are only permitted with a static offset. */
3025 bool var_off = !tnum_is_const(reg->var_off);
3026
3027 /* The offset is required to be static when reads don't go to a
3028 * register, in order to not leak pointers (see
3029 * check_stack_read_fixed_off).
3030 */
3031 if (dst_regno < 0 && var_off) {
e4298d25
DB
3032 char tn_buf[48];
3033
3034 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
01f810ac 3035 verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
e4298d25
DB
3036 tn_buf, off, size);
3037 return -EACCES;
3038 }
01f810ac
AM
3039 /* Variable offset is prohibited for unprivileged mode for simplicity
3040 * since it requires corresponding support in Spectre masking for stack
3041 * ALU. See also retrieve_ptr_limit().
3042 */
3043 if (!env->bypass_spec_v1 && var_off) {
3044 char tn_buf[48];
e4298d25 3045
01f810ac
AM
3046 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3047 verbose(env, "R%d variable offset stack access prohibited for !root, var_off=%s\n",
3048 ptr_regno, tn_buf);
e4298d25
DB
3049 return -EACCES;
3050 }
3051
01f810ac
AM
3052 if (!var_off) {
3053 off += reg->var_off.value;
3054 err = check_stack_read_fixed_off(env, state, off, size,
3055 dst_regno);
3056 } else {
3057 /* Variable offset stack reads need more conservative handling
3058 * than fixed offset ones. Note that dst_regno >= 0 on this
3059 * branch.
3060 */
3061 err = check_stack_read_var_off(env, ptr_regno, off, size,
3062 dst_regno);
3063 }
3064 return err;
3065}
3066
3067
3068/* check_stack_write dispatches to check_stack_write_fixed_off or
3069 * check_stack_write_var_off.
3070 *
3071 * 'ptr_regno' is the register used as a pointer into the stack.
3072 * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
3073 * 'value_regno' is the register whose value we're writing to the stack. It can
3074 * be -1, meaning that we're not writing from a register.
3075 *
3076 * The caller must ensure that the offset falls within the maximum stack size.
3077 */
3078static int check_stack_write(struct bpf_verifier_env *env,
3079 int ptr_regno, int off, int size,
3080 int value_regno, int insn_idx)
3081{
3082 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3083 struct bpf_func_state *state = func(env, reg);
3084 int err;
3085
3086 if (tnum_is_const(reg->var_off)) {
3087 off += reg->var_off.value;
3088 err = check_stack_write_fixed_off(env, state, off, size,
3089 value_regno, insn_idx);
3090 } else {
3091 /* Variable offset stack reads need more conservative handling
3092 * than fixed offset ones.
3093 */
3094 err = check_stack_write_var_off(env, state,
3095 ptr_regno, off, size,
3096 value_regno, insn_idx);
3097 }
3098 return err;
e4298d25
DB
3099}
3100
591fe988
DB
3101static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
3102 int off, int size, enum bpf_access_type type)
3103{
3104 struct bpf_reg_state *regs = cur_regs(env);
3105 struct bpf_map *map = regs[regno].map_ptr;
3106 u32 cap = bpf_map_flags_to_cap(map);
3107
3108 if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
3109 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
3110 map->value_size, off, size);
3111 return -EACCES;
3112 }
3113
3114 if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
3115 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
3116 map->value_size, off, size);
3117 return -EACCES;
3118 }
3119
3120 return 0;
3121}
3122
457f4436
AN
3123/* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
3124static int __check_mem_access(struct bpf_verifier_env *env, int regno,
3125 int off, int size, u32 mem_size,
3126 bool zero_size_allowed)
17a52670 3127{
457f4436
AN
3128 bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
3129 struct bpf_reg_state *reg;
3130
3131 if (off >= 0 && size_ok && (u64)off + size <= mem_size)
3132 return 0;
17a52670 3133
457f4436
AN
3134 reg = &cur_regs(env)[regno];
3135 switch (reg->type) {
69c087ba
YS
3136 case PTR_TO_MAP_KEY:
3137 verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
3138 mem_size, off, size);
3139 break;
457f4436 3140 case PTR_TO_MAP_VALUE:
61bd5218 3141 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
457f4436
AN
3142 mem_size, off, size);
3143 break;
3144 case PTR_TO_PACKET:
3145 case PTR_TO_PACKET_META:
3146 case PTR_TO_PACKET_END:
3147 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
3148 off, size, regno, reg->id, off, mem_size);
3149 break;
3150 case PTR_TO_MEM:
3151 default:
3152 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
3153 mem_size, off, size);
17a52670 3154 }
457f4436
AN
3155
3156 return -EACCES;
17a52670
AS
3157}
3158
457f4436
AN
3159/* check read/write into a memory region with possible variable offset */
3160static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
3161 int off, int size, u32 mem_size,
3162 bool zero_size_allowed)
dbcfe5f7 3163{
f4d7e40a
AS
3164 struct bpf_verifier_state *vstate = env->cur_state;
3165 struct bpf_func_state *state = vstate->frame[vstate->curframe];
dbcfe5f7
GB
3166 struct bpf_reg_state *reg = &state->regs[regno];
3167 int err;
3168
457f4436 3169 /* We may have adjusted the register pointing to memory region, so we
f1174f77
EC
3170 * need to try adding each of min_value and max_value to off
3171 * to make sure our theoretical access will be safe.
dbcfe5f7 3172 */
06ee7115 3173 if (env->log.level & BPF_LOG_LEVEL)
61bd5218 3174 print_verifier_state(env, state);
b7137c4e 3175
dbcfe5f7
GB
3176 /* The minimum value is only important with signed
3177 * comparisons where we can't assume the floor of a
3178 * value is 0. If we are using signed variables for our
3179 * index'es we need to make sure that whatever we use
3180 * will have a set floor within our range.
3181 */
b7137c4e
DB
3182 if (reg->smin_value < 0 &&
3183 (reg->smin_value == S64_MIN ||
3184 (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
3185 reg->smin_value + off < 0)) {
61bd5218 3186 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
dbcfe5f7
GB
3187 regno);
3188 return -EACCES;
3189 }
457f4436
AN
3190 err = __check_mem_access(env, regno, reg->smin_value + off, size,
3191 mem_size, zero_size_allowed);
dbcfe5f7 3192 if (err) {
457f4436 3193 verbose(env, "R%d min value is outside of the allowed memory range\n",
61bd5218 3194 regno);
dbcfe5f7
GB
3195 return err;
3196 }
3197
b03c9f9f
EC
3198 /* If we haven't set a max value then we need to bail since we can't be
3199 * sure we won't do bad things.
3200 * If reg->umax_value + off could overflow, treat that as unbounded too.
dbcfe5f7 3201 */
b03c9f9f 3202 if (reg->umax_value >= BPF_MAX_VAR_OFF) {
457f4436 3203 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
dbcfe5f7
GB
3204 regno);
3205 return -EACCES;
3206 }
457f4436
AN
3207 err = __check_mem_access(env, regno, reg->umax_value + off, size,
3208 mem_size, zero_size_allowed);
3209 if (err) {
3210 verbose(env, "R%d max value is outside of the allowed memory range\n",
61bd5218 3211 regno);
457f4436
AN
3212 return err;
3213 }
3214
3215 return 0;
3216}
d83525ca 3217
457f4436
AN
3218/* check read/write into a map element with possible variable offset */
3219static int check_map_access(struct bpf_verifier_env *env, u32 regno,
3220 int off, int size, bool zero_size_allowed)
3221{
3222 struct bpf_verifier_state *vstate = env->cur_state;
3223 struct bpf_func_state *state = vstate->frame[vstate->curframe];
3224 struct bpf_reg_state *reg = &state->regs[regno];
3225 struct bpf_map *map = reg->map_ptr;
3226 int err;
3227
3228 err = check_mem_region_access(env, regno, off, size, map->value_size,
3229 zero_size_allowed);
3230 if (err)
3231 return err;
3232
3233 if (map_value_has_spin_lock(map)) {
3234 u32 lock = map->spin_lock_off;
d83525ca
AS
3235
3236 /* if any part of struct bpf_spin_lock can be touched by
3237 * load/store reject this program.
3238 * To check that [x1, x2) overlaps with [y1, y2)
3239 * it is sufficient to check x1 < y2 && y1 < x2.
3240 */
3241 if (reg->smin_value + off < lock + sizeof(struct bpf_spin_lock) &&
3242 lock < reg->umax_value + off + size) {
3243 verbose(env, "bpf_spin_lock cannot be accessed directly by load/store\n");
3244 return -EACCES;
3245 }
3246 }
f1174f77 3247 return err;
dbcfe5f7
GB
3248}
3249
969bf05e
AS
3250#define MAX_PACKET_OFF 0xffff
3251
7e40781c
UP
3252static enum bpf_prog_type resolve_prog_type(struct bpf_prog *prog)
3253{
3aac1ead 3254 return prog->aux->dst_prog ? prog->aux->dst_prog->type : prog->type;
7e40781c
UP
3255}
3256
58e2af8b 3257static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
3a0af8fd
TG
3258 const struct bpf_call_arg_meta *meta,
3259 enum bpf_access_type t)
4acf6c0b 3260{
7e40781c
UP
3261 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
3262
3263 switch (prog_type) {
5d66fa7d 3264 /* Program types only with direct read access go here! */
3a0af8fd
TG
3265 case BPF_PROG_TYPE_LWT_IN:
3266 case BPF_PROG_TYPE_LWT_OUT:
004d4b27 3267 case BPF_PROG_TYPE_LWT_SEG6LOCAL:
2dbb9b9e 3268 case BPF_PROG_TYPE_SK_REUSEPORT:
5d66fa7d 3269 case BPF_PROG_TYPE_FLOW_DISSECTOR:
d5563d36 3270 case BPF_PROG_TYPE_CGROUP_SKB:
3a0af8fd
TG
3271 if (t == BPF_WRITE)
3272 return false;
8731745e 3273 fallthrough;
5d66fa7d
DB
3274
3275 /* Program types with direct read + write access go here! */
36bbef52
DB
3276 case BPF_PROG_TYPE_SCHED_CLS:
3277 case BPF_PROG_TYPE_SCHED_ACT:
4acf6c0b 3278 case BPF_PROG_TYPE_XDP:
3a0af8fd 3279 case BPF_PROG_TYPE_LWT_XMIT:
8a31db56 3280 case BPF_PROG_TYPE_SK_SKB:
4f738adb 3281 case BPF_PROG_TYPE_SK_MSG:
36bbef52
DB
3282 if (meta)
3283 return meta->pkt_access;
3284
3285 env->seen_direct_write = true;
4acf6c0b 3286 return true;
0d01da6a
SF
3287
3288 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
3289 if (t == BPF_WRITE)
3290 env->seen_direct_write = true;
3291
3292 return true;
3293
4acf6c0b
BB
3294 default:
3295 return false;
3296 }
3297}
3298
f1174f77 3299static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
9fd29c08 3300 int size, bool zero_size_allowed)
f1174f77 3301{
638f5b90 3302 struct bpf_reg_state *regs = cur_regs(env);
f1174f77
EC
3303 struct bpf_reg_state *reg = &regs[regno];
3304 int err;
3305
3306 /* We may have added a variable offset to the packet pointer; but any
3307 * reg->range we have comes after that. We are only checking the fixed
3308 * offset.
3309 */
3310
3311 /* We don't allow negative numbers, because we aren't tracking enough
3312 * detail to prove they're safe.
3313 */
b03c9f9f 3314 if (reg->smin_value < 0) {
61bd5218 3315 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
f1174f77
EC
3316 regno);
3317 return -EACCES;
3318 }
6d94e741
AS
3319
3320 err = reg->range < 0 ? -EINVAL :
3321 __check_mem_access(env, regno, off, size, reg->range,
457f4436 3322 zero_size_allowed);
f1174f77 3323 if (err) {
61bd5218 3324 verbose(env, "R%d offset is outside of the packet\n", regno);
f1174f77
EC
3325 return err;
3326 }
e647815a 3327
457f4436 3328 /* __check_mem_access has made sure "off + size - 1" is within u16.
e647815a
JW
3329 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
3330 * otherwise find_good_pkt_pointers would have refused to set range info
457f4436 3331 * that __check_mem_access would have rejected this pkt access.
e647815a
JW
3332 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
3333 */
3334 env->prog->aux->max_pkt_offset =
3335 max_t(u32, env->prog->aux->max_pkt_offset,
3336 off + reg->umax_value + size - 1);
3337
f1174f77
EC
3338 return err;
3339}
3340
3341/* check access to 'struct bpf_context' fields. Supports fixed offsets only */
31fd8581 3342static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
9e15db66 3343 enum bpf_access_type t, enum bpf_reg_type *reg_type,
22dc4a0f 3344 struct btf **btf, u32 *btf_id)
17a52670 3345{
f96da094
DB
3346 struct bpf_insn_access_aux info = {
3347 .reg_type = *reg_type,
9e15db66 3348 .log = &env->log,
f96da094 3349 };
31fd8581 3350
4f9218aa 3351 if (env->ops->is_valid_access &&
5e43f899 3352 env->ops->is_valid_access(off, size, t, env->prog, &info)) {
f96da094
DB
3353 /* A non zero info.ctx_field_size indicates that this field is a
3354 * candidate for later verifier transformation to load the whole
3355 * field and then apply a mask when accessed with a narrower
3356 * access than actual ctx access size. A zero info.ctx_field_size
3357 * will only allow for whole field access and rejects any other
3358 * type of narrower access.
31fd8581 3359 */
23994631 3360 *reg_type = info.reg_type;
31fd8581 3361
22dc4a0f
AN
3362 if (*reg_type == PTR_TO_BTF_ID || *reg_type == PTR_TO_BTF_ID_OR_NULL) {
3363 *btf = info.btf;
9e15db66 3364 *btf_id = info.btf_id;
22dc4a0f 3365 } else {
9e15db66 3366 env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
22dc4a0f 3367 }
32bbe007
AS
3368 /* remember the offset of last byte accessed in ctx */
3369 if (env->prog->aux->max_ctx_offset < off + size)
3370 env->prog->aux->max_ctx_offset = off + size;
17a52670 3371 return 0;
32bbe007 3372 }
17a52670 3373
61bd5218 3374 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
17a52670
AS
3375 return -EACCES;
3376}
3377
d58e468b
PP
3378static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
3379 int size)
3380{
3381 if (size < 0 || off < 0 ||
3382 (u64)off + size > sizeof(struct bpf_flow_keys)) {
3383 verbose(env, "invalid access to flow keys off=%d size=%d\n",
3384 off, size);
3385 return -EACCES;
3386 }
3387 return 0;
3388}
3389
5f456649
MKL
3390static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
3391 u32 regno, int off, int size,
3392 enum bpf_access_type t)
c64b7983
JS
3393{
3394 struct bpf_reg_state *regs = cur_regs(env);
3395 struct bpf_reg_state *reg = &regs[regno];
5f456649 3396 struct bpf_insn_access_aux info = {};
46f8bc92 3397 bool valid;
c64b7983
JS
3398
3399 if (reg->smin_value < 0) {
3400 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3401 regno);
3402 return -EACCES;
3403 }
3404
46f8bc92
MKL
3405 switch (reg->type) {
3406 case PTR_TO_SOCK_COMMON:
3407 valid = bpf_sock_common_is_valid_access(off, size, t, &info);
3408 break;
3409 case PTR_TO_SOCKET:
3410 valid = bpf_sock_is_valid_access(off, size, t, &info);
3411 break;
655a51e5
MKL
3412 case PTR_TO_TCP_SOCK:
3413 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
3414 break;
fada7fdc
JL
3415 case PTR_TO_XDP_SOCK:
3416 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
3417 break;
46f8bc92
MKL
3418 default:
3419 valid = false;
c64b7983
JS
3420 }
3421
5f456649 3422
46f8bc92
MKL
3423 if (valid) {
3424 env->insn_aux_data[insn_idx].ctx_field_size =
3425 info.ctx_field_size;
3426 return 0;
3427 }
3428
3429 verbose(env, "R%d invalid %s access off=%d size=%d\n",
3430 regno, reg_type_str[reg->type], off, size);
3431
3432 return -EACCES;
c64b7983
JS
3433}
3434
4cabc5b1
DB
3435static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
3436{
2a159c6f 3437 return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
4cabc5b1
DB
3438}
3439
f37a8cb8
DB
3440static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
3441{
2a159c6f 3442 const struct bpf_reg_state *reg = reg_state(env, regno);
f37a8cb8 3443
46f8bc92
MKL
3444 return reg->type == PTR_TO_CTX;
3445}
3446
3447static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
3448{
3449 const struct bpf_reg_state *reg = reg_state(env, regno);
3450
3451 return type_is_sk_pointer(reg->type);
f37a8cb8
DB
3452}
3453
ca369602
DB
3454static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
3455{
2a159c6f 3456 const struct bpf_reg_state *reg = reg_state(env, regno);
ca369602
DB
3457
3458 return type_is_pkt_pointer(reg->type);
3459}
3460
4b5defde
DB
3461static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
3462{
3463 const struct bpf_reg_state *reg = reg_state(env, regno);
3464
3465 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
3466 return reg->type == PTR_TO_FLOW_KEYS;
3467}
3468
61bd5218
JK
3469static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
3470 const struct bpf_reg_state *reg,
d1174416 3471 int off, int size, bool strict)
969bf05e 3472{
f1174f77 3473 struct tnum reg_off;
e07b98d9 3474 int ip_align;
d1174416
DM
3475
3476 /* Byte size accesses are always allowed. */
3477 if (!strict || size == 1)
3478 return 0;
3479
e4eda884
DM
3480 /* For platforms that do not have a Kconfig enabling
3481 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
3482 * NET_IP_ALIGN is universally set to '2'. And on platforms
3483 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
3484 * to this code only in strict mode where we want to emulate
3485 * the NET_IP_ALIGN==2 checking. Therefore use an
3486 * unconditional IP align value of '2'.
e07b98d9 3487 */
e4eda884 3488 ip_align = 2;
f1174f77
EC
3489
3490 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
3491 if (!tnum_is_aligned(reg_off, size)) {
3492 char tn_buf[48];
3493
3494 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
61bd5218
JK
3495 verbose(env,
3496 "misaligned packet access off %d+%s+%d+%d size %d\n",
f1174f77 3497 ip_align, tn_buf, reg->off, off, size);
969bf05e
AS
3498 return -EACCES;
3499 }
79adffcd 3500
969bf05e
AS
3501 return 0;
3502}
3503
61bd5218
JK
3504static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
3505 const struct bpf_reg_state *reg,
f1174f77
EC
3506 const char *pointer_desc,
3507 int off, int size, bool strict)
79adffcd 3508{
f1174f77
EC
3509 struct tnum reg_off;
3510
3511 /* Byte size accesses are always allowed. */
3512 if (!strict || size == 1)
3513 return 0;
3514
3515 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
3516 if (!tnum_is_aligned(reg_off, size)) {
3517 char tn_buf[48];
3518
3519 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
61bd5218 3520 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
f1174f77 3521 pointer_desc, tn_buf, reg->off, off, size);
79adffcd
DB
3522 return -EACCES;
3523 }
3524
969bf05e
AS
3525 return 0;
3526}
3527
e07b98d9 3528static int check_ptr_alignment(struct bpf_verifier_env *env,
ca369602
DB
3529 const struct bpf_reg_state *reg, int off,
3530 int size, bool strict_alignment_once)
79adffcd 3531{
ca369602 3532 bool strict = env->strict_alignment || strict_alignment_once;
f1174f77 3533 const char *pointer_desc = "";
d1174416 3534
79adffcd
DB
3535 switch (reg->type) {
3536 case PTR_TO_PACKET:
de8f3a83
DB
3537 case PTR_TO_PACKET_META:
3538 /* Special case, because of NET_IP_ALIGN. Given metadata sits
3539 * right in front, treat it the very same way.
3540 */
61bd5218 3541 return check_pkt_ptr_alignment(env, reg, off, size, strict);
d58e468b
PP
3542 case PTR_TO_FLOW_KEYS:
3543 pointer_desc = "flow keys ";
3544 break;
69c087ba
YS
3545 case PTR_TO_MAP_KEY:
3546 pointer_desc = "key ";
3547 break;
f1174f77
EC
3548 case PTR_TO_MAP_VALUE:
3549 pointer_desc = "value ";
3550 break;
3551 case PTR_TO_CTX:
3552 pointer_desc = "context ";
3553 break;
3554 case PTR_TO_STACK:
3555 pointer_desc = "stack ";
01f810ac
AM
3556 /* The stack spill tracking logic in check_stack_write_fixed_off()
3557 * and check_stack_read_fixed_off() relies on stack accesses being
a5ec6ae1
JH
3558 * aligned.
3559 */
3560 strict = true;
f1174f77 3561 break;
c64b7983
JS
3562 case PTR_TO_SOCKET:
3563 pointer_desc = "sock ";
3564 break;
46f8bc92
MKL
3565 case PTR_TO_SOCK_COMMON:
3566 pointer_desc = "sock_common ";
3567 break;
655a51e5
MKL
3568 case PTR_TO_TCP_SOCK:
3569 pointer_desc = "tcp_sock ";
3570 break;
fada7fdc
JL
3571 case PTR_TO_XDP_SOCK:
3572 pointer_desc = "xdp_sock ";
3573 break;
79adffcd 3574 default:
f1174f77 3575 break;
79adffcd 3576 }
61bd5218
JK
3577 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
3578 strict);
79adffcd
DB
3579}
3580
f4d7e40a
AS
3581static int update_stack_depth(struct bpf_verifier_env *env,
3582 const struct bpf_func_state *func,
3583 int off)
3584{
9c8105bd 3585 u16 stack = env->subprog_info[func->subprogno].stack_depth;
f4d7e40a
AS
3586
3587 if (stack >= -off)
3588 return 0;
3589
3590 /* update known max for given subprogram */
9c8105bd 3591 env->subprog_info[func->subprogno].stack_depth = -off;
70a87ffe
AS
3592 return 0;
3593}
f4d7e40a 3594
70a87ffe
AS
3595/* starting from main bpf function walk all instructions of the function
3596 * and recursively walk all callees that given function can call.
3597 * Ignore jump and exit insns.
3598 * Since recursion is prevented by check_cfg() this algorithm
3599 * only needs a local stack of MAX_CALL_FRAMES to remember callsites
3600 */
3601static int check_max_stack_depth(struct bpf_verifier_env *env)
3602{
9c8105bd
JW
3603 int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
3604 struct bpf_subprog_info *subprog = env->subprog_info;
70a87ffe 3605 struct bpf_insn *insn = env->prog->insnsi;
ebf7d1f5 3606 bool tail_call_reachable = false;
70a87ffe
AS
3607 int ret_insn[MAX_CALL_FRAMES];
3608 int ret_prog[MAX_CALL_FRAMES];
ebf7d1f5 3609 int j;
f4d7e40a 3610
70a87ffe 3611process_func:
7f6e4312
MF
3612 /* protect against potential stack overflow that might happen when
3613 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
3614 * depth for such case down to 256 so that the worst case scenario
3615 * would result in 8k stack size (32 which is tailcall limit * 256 =
3616 * 8k).
3617 *
3618 * To get the idea what might happen, see an example:
3619 * func1 -> sub rsp, 128
3620 * subfunc1 -> sub rsp, 256
3621 * tailcall1 -> add rsp, 256
3622 * func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
3623 * subfunc2 -> sub rsp, 64
3624 * subfunc22 -> sub rsp, 128
3625 * tailcall2 -> add rsp, 128
3626 * func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
3627 *
3628 * tailcall will unwind the current stack frame but it will not get rid
3629 * of caller's stack as shown on the example above.
3630 */
3631 if (idx && subprog[idx].has_tail_call && depth >= 256) {
3632 verbose(env,
3633 "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
3634 depth);
3635 return -EACCES;
3636 }
70a87ffe
AS
3637 /* round up to 32-bytes, since this is granularity
3638 * of interpreter stack size
3639 */
9c8105bd 3640 depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
70a87ffe 3641 if (depth > MAX_BPF_STACK) {
f4d7e40a 3642 verbose(env, "combined stack size of %d calls is %d. Too large\n",
70a87ffe 3643 frame + 1, depth);
f4d7e40a
AS
3644 return -EACCES;
3645 }
70a87ffe 3646continue_func:
4cb3d99c 3647 subprog_end = subprog[idx + 1].start;
70a87ffe 3648 for (; i < subprog_end; i++) {
69c087ba 3649 if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
70a87ffe
AS
3650 continue;
3651 /* remember insn and function to return to */
3652 ret_insn[frame] = i + 1;
9c8105bd 3653 ret_prog[frame] = idx;
70a87ffe
AS
3654
3655 /* find the callee */
3656 i = i + insn[i].imm + 1;
9c8105bd
JW
3657 idx = find_subprog(env, i);
3658 if (idx < 0) {
70a87ffe
AS
3659 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
3660 i);
3661 return -EFAULT;
3662 }
ebf7d1f5
MF
3663
3664 if (subprog[idx].has_tail_call)
3665 tail_call_reachable = true;
3666
70a87ffe
AS
3667 frame++;
3668 if (frame >= MAX_CALL_FRAMES) {
927cb781
PC
3669 verbose(env, "the call stack of %d frames is too deep !\n",
3670 frame);
3671 return -E2BIG;
70a87ffe
AS
3672 }
3673 goto process_func;
3674 }
ebf7d1f5
MF
3675 /* if tail call got detected across bpf2bpf calls then mark each of the
3676 * currently present subprog frames as tail call reachable subprogs;
3677 * this info will be utilized by JIT so that we will be preserving the
3678 * tail call counter throughout bpf2bpf calls combined with tailcalls
3679 */
3680 if (tail_call_reachable)
3681 for (j = 0; j < frame; j++)
3682 subprog[ret_prog[j]].tail_call_reachable = true;
3683
70a87ffe
AS
3684 /* end of for() loop means the last insn of the 'subprog'
3685 * was reached. Doesn't matter whether it was JA or EXIT
3686 */
3687 if (frame == 0)
3688 return 0;
9c8105bd 3689 depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
70a87ffe
AS
3690 frame--;
3691 i = ret_insn[frame];
9c8105bd 3692 idx = ret_prog[frame];
70a87ffe 3693 goto continue_func;
f4d7e40a
AS
3694}
3695
19d28fbd 3696#ifndef CONFIG_BPF_JIT_ALWAYS_ON
1ea47e01
AS
3697static int get_callee_stack_depth(struct bpf_verifier_env *env,
3698 const struct bpf_insn *insn, int idx)
3699{
3700 int start = idx + insn->imm + 1, subprog;
3701
3702 subprog = find_subprog(env, start);
3703 if (subprog < 0) {
3704 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
3705 start);
3706 return -EFAULT;
3707 }
9c8105bd 3708 return env->subprog_info[subprog].stack_depth;
1ea47e01 3709}
19d28fbd 3710#endif
1ea47e01 3711
51c39bb1
AS
3712int check_ctx_reg(struct bpf_verifier_env *env,
3713 const struct bpf_reg_state *reg, int regno)
58990d1f
DB
3714{
3715 /* Access to ctx or passing it to a helper is only allowed in
3716 * its original, unmodified form.
3717 */
3718
3719 if (reg->off) {
3720 verbose(env, "dereference of modified ctx ptr R%d off=%d disallowed\n",
3721 regno, reg->off);
3722 return -EACCES;
3723 }
3724
3725 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3726 char tn_buf[48];
3727
3728 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3729 verbose(env, "variable ctx access var_off=%s disallowed\n", tn_buf);
3730 return -EACCES;
3731 }
3732
3733 return 0;
3734}
3735
afbf21dc
YS
3736static int __check_buffer_access(struct bpf_verifier_env *env,
3737 const char *buf_info,
3738 const struct bpf_reg_state *reg,
3739 int regno, int off, int size)
9df1c28b
MM
3740{
3741 if (off < 0) {
3742 verbose(env,
4fc00b79 3743 "R%d invalid %s buffer access: off=%d, size=%d\n",
afbf21dc 3744 regno, buf_info, off, size);
9df1c28b
MM
3745 return -EACCES;
3746 }
3747 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3748 char tn_buf[48];
3749
3750 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3751 verbose(env,
4fc00b79 3752 "R%d invalid variable buffer offset: off=%d, var_off=%s\n",
9df1c28b
MM
3753 regno, off, tn_buf);
3754 return -EACCES;
3755 }
afbf21dc
YS
3756
3757 return 0;
3758}
3759
3760static int check_tp_buffer_access(struct bpf_verifier_env *env,
3761 const struct bpf_reg_state *reg,
3762 int regno, int off, int size)
3763{
3764 int err;
3765
3766 err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
3767 if (err)
3768 return err;
3769
9df1c28b
MM
3770 if (off + size > env->prog->aux->max_tp_access)
3771 env->prog->aux->max_tp_access = off + size;
3772
3773 return 0;
3774}
3775
afbf21dc
YS
3776static int check_buffer_access(struct bpf_verifier_env *env,
3777 const struct bpf_reg_state *reg,
3778 int regno, int off, int size,
3779 bool zero_size_allowed,
3780 const char *buf_info,
3781 u32 *max_access)
3782{
3783 int err;
3784
3785 err = __check_buffer_access(env, buf_info, reg, regno, off, size);
3786 if (err)
3787 return err;
3788
3789 if (off + size > *max_access)
3790 *max_access = off + size;
3791
3792 return 0;
3793}
3794
3f50f132
JF
3795/* BPF architecture zero extends alu32 ops into 64-bit registesr */
3796static void zext_32_to_64(struct bpf_reg_state *reg)
3797{
3798 reg->var_off = tnum_subreg(reg->var_off);
3799 __reg_assign_32_into_64(reg);
3800}
9df1c28b 3801
0c17d1d2
JH
3802/* truncate register to smaller size (in bytes)
3803 * must be called with size < BPF_REG_SIZE
3804 */
3805static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
3806{
3807 u64 mask;
3808
3809 /* clear high bits in bit representation */
3810 reg->var_off = tnum_cast(reg->var_off, size);
3811
3812 /* fix arithmetic bounds */
3813 mask = ((u64)1 << (size * 8)) - 1;
3814 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
3815 reg->umin_value &= mask;
3816 reg->umax_value &= mask;
3817 } else {
3818 reg->umin_value = 0;
3819 reg->umax_value = mask;
3820 }
3821 reg->smin_value = reg->umin_value;
3822 reg->smax_value = reg->umax_value;
3f50f132
JF
3823
3824 /* If size is smaller than 32bit register the 32bit register
3825 * values are also truncated so we push 64-bit bounds into
3826 * 32-bit bounds. Above were truncated < 32-bits already.
3827 */
3828 if (size >= 4)
3829 return;
3830 __reg_combine_64_into_32(reg);
0c17d1d2
JH
3831}
3832
a23740ec
AN
3833static bool bpf_map_is_rdonly(const struct bpf_map *map)
3834{
3835 return (map->map_flags & BPF_F_RDONLY_PROG) && map->frozen;
3836}
3837
3838static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val)
3839{
3840 void *ptr;
3841 u64 addr;
3842 int err;
3843
3844 err = map->ops->map_direct_value_addr(map, &addr, off);
3845 if (err)
3846 return err;
2dedd7d2 3847 ptr = (void *)(long)addr + off;
a23740ec
AN
3848
3849 switch (size) {
3850 case sizeof(u8):
3851 *val = (u64)*(u8 *)ptr;
3852 break;
3853 case sizeof(u16):
3854 *val = (u64)*(u16 *)ptr;
3855 break;
3856 case sizeof(u32):
3857 *val = (u64)*(u32 *)ptr;
3858 break;
3859 case sizeof(u64):
3860 *val = *(u64 *)ptr;
3861 break;
3862 default:
3863 return -EINVAL;
3864 }
3865 return 0;
3866}
3867
9e15db66
AS
3868static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
3869 struct bpf_reg_state *regs,
3870 int regno, int off, int size,
3871 enum bpf_access_type atype,
3872 int value_regno)
3873{
3874 struct bpf_reg_state *reg = regs + regno;
22dc4a0f
AN
3875 const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
3876 const char *tname = btf_name_by_offset(reg->btf, t->name_off);
9e15db66
AS
3877 u32 btf_id;
3878 int ret;
3879
9e15db66
AS
3880 if (off < 0) {
3881 verbose(env,
3882 "R%d is ptr_%s invalid negative access: off=%d\n",
3883 regno, tname, off);
3884 return -EACCES;
3885 }
3886 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3887 char tn_buf[48];
3888
3889 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3890 verbose(env,
3891 "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
3892 regno, tname, off, tn_buf);
3893 return -EACCES;
3894 }
3895
27ae7997 3896 if (env->ops->btf_struct_access) {
22dc4a0f
AN
3897 ret = env->ops->btf_struct_access(&env->log, reg->btf, t,
3898 off, size, atype, &btf_id);
27ae7997
MKL
3899 } else {
3900 if (atype != BPF_READ) {
3901 verbose(env, "only read is supported\n");
3902 return -EACCES;
3903 }
3904
22dc4a0f
AN
3905 ret = btf_struct_access(&env->log, reg->btf, t, off, size,
3906 atype, &btf_id);
27ae7997
MKL
3907 }
3908
9e15db66
AS
3909 if (ret < 0)
3910 return ret;
3911
41c48f3a 3912 if (atype == BPF_READ && value_regno >= 0)
22dc4a0f 3913 mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id);
41c48f3a
AI
3914
3915 return 0;
3916}
3917
3918static int check_ptr_to_map_access(struct bpf_verifier_env *env,
3919 struct bpf_reg_state *regs,
3920 int regno, int off, int size,
3921 enum bpf_access_type atype,
3922 int value_regno)
3923{
3924 struct bpf_reg_state *reg = regs + regno;
3925 struct bpf_map *map = reg->map_ptr;
3926 const struct btf_type *t;
3927 const char *tname;
3928 u32 btf_id;
3929 int ret;
3930
3931 if (!btf_vmlinux) {
3932 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
3933 return -ENOTSUPP;
3934 }
3935
3936 if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
3937 verbose(env, "map_ptr access not supported for map type %d\n",
3938 map->map_type);
3939 return -ENOTSUPP;
3940 }
3941
3942 t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
3943 tname = btf_name_by_offset(btf_vmlinux, t->name_off);
3944
3945 if (!env->allow_ptr_to_map_access) {
3946 verbose(env,
3947 "%s access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
3948 tname);
3949 return -EPERM;
9e15db66 3950 }
27ae7997 3951
41c48f3a
AI
3952 if (off < 0) {
3953 verbose(env, "R%d is %s invalid negative access: off=%d\n",
3954 regno, tname, off);
3955 return -EACCES;
3956 }
3957
3958 if (atype != BPF_READ) {
3959 verbose(env, "only read from %s is supported\n", tname);
3960 return -EACCES;
3961 }
3962
22dc4a0f 3963 ret = btf_struct_access(&env->log, btf_vmlinux, t, off, size, atype, &btf_id);
41c48f3a
AI
3964 if (ret < 0)
3965 return ret;
3966
3967 if (value_regno >= 0)
22dc4a0f 3968 mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id);
41c48f3a 3969
9e15db66
AS
3970 return 0;
3971}
3972
01f810ac
AM
3973/* Check that the stack access at the given offset is within bounds. The
3974 * maximum valid offset is -1.
3975 *
3976 * The minimum valid offset is -MAX_BPF_STACK for writes, and
3977 * -state->allocated_stack for reads.
3978 */
3979static int check_stack_slot_within_bounds(int off,
3980 struct bpf_func_state *state,
3981 enum bpf_access_type t)
3982{
3983 int min_valid_off;
3984
3985 if (t == BPF_WRITE)
3986 min_valid_off = -MAX_BPF_STACK;
3987 else
3988 min_valid_off = -state->allocated_stack;
3989
3990 if (off < min_valid_off || off > -1)
3991 return -EACCES;
3992 return 0;
3993}
3994
3995/* Check that the stack access at 'regno + off' falls within the maximum stack
3996 * bounds.
3997 *
3998 * 'off' includes `regno->offset`, but not its dynamic part (if any).
3999 */
4000static int check_stack_access_within_bounds(
4001 struct bpf_verifier_env *env,
4002 int regno, int off, int access_size,
4003 enum stack_access_src src, enum bpf_access_type type)
4004{
4005 struct bpf_reg_state *regs = cur_regs(env);
4006 struct bpf_reg_state *reg = regs + regno;
4007 struct bpf_func_state *state = func(env, reg);
4008 int min_off, max_off;
4009 int err;
4010 char *err_extra;
4011
4012 if (src == ACCESS_HELPER)
4013 /* We don't know if helpers are reading or writing (or both). */
4014 err_extra = " indirect access to";
4015 else if (type == BPF_READ)
4016 err_extra = " read from";
4017 else
4018 err_extra = " write to";
4019
4020 if (tnum_is_const(reg->var_off)) {
4021 min_off = reg->var_off.value + off;
4022 if (access_size > 0)
4023 max_off = min_off + access_size - 1;
4024 else
4025 max_off = min_off;
4026 } else {
4027 if (reg->smax_value >= BPF_MAX_VAR_OFF ||
4028 reg->smin_value <= -BPF_MAX_VAR_OFF) {
4029 verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
4030 err_extra, regno);
4031 return -EACCES;
4032 }
4033 min_off = reg->smin_value + off;
4034 if (access_size > 0)
4035 max_off = reg->smax_value + off + access_size - 1;
4036 else
4037 max_off = min_off;
4038 }
4039
4040 err = check_stack_slot_within_bounds(min_off, state, type);
4041 if (!err)
4042 err = check_stack_slot_within_bounds(max_off, state, type);
4043
4044 if (err) {
4045 if (tnum_is_const(reg->var_off)) {
4046 verbose(env, "invalid%s stack R%d off=%d size=%d\n",
4047 err_extra, regno, off, access_size);
4048 } else {
4049 char tn_buf[48];
4050
4051 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4052 verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
4053 err_extra, regno, tn_buf, access_size);
4054 }
4055 }
4056 return err;
4057}
41c48f3a 4058
17a52670
AS
4059/* check whether memory at (regno + off) is accessible for t = (read | write)
4060 * if t==write, value_regno is a register which value is stored into memory
4061 * if t==read, value_regno is a register which will receive the value from memory
4062 * if t==write && value_regno==-1, some unknown value is stored into memory
4063 * if t==read && value_regno==-1, don't care what we read from memory
4064 */
ca369602
DB
4065static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
4066 int off, int bpf_size, enum bpf_access_type t,
4067 int value_regno, bool strict_alignment_once)
17a52670 4068{
638f5b90
AS
4069 struct bpf_reg_state *regs = cur_regs(env);
4070 struct bpf_reg_state *reg = regs + regno;
f4d7e40a 4071 struct bpf_func_state *state;
17a52670
AS
4072 int size, err = 0;
4073
4074 size = bpf_size_to_bytes(bpf_size);
4075 if (size < 0)
4076 return size;
4077
f1174f77 4078 /* alignment checks will add in reg->off themselves */
ca369602 4079 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
969bf05e
AS
4080 if (err)
4081 return err;
17a52670 4082
f1174f77
EC
4083 /* for access checks, reg->off is just part of off */
4084 off += reg->off;
4085
69c087ba
YS
4086 if (reg->type == PTR_TO_MAP_KEY) {
4087 if (t == BPF_WRITE) {
4088 verbose(env, "write to change key R%d not allowed\n", regno);
4089 return -EACCES;
4090 }
4091
4092 err = check_mem_region_access(env, regno, off, size,
4093 reg->map_ptr->key_size, false);
4094 if (err)
4095 return err;
4096 if (value_regno >= 0)
4097 mark_reg_unknown(env, regs, value_regno);
4098 } else if (reg->type == PTR_TO_MAP_VALUE) {
1be7f75d
AS
4099 if (t == BPF_WRITE && value_regno >= 0 &&
4100 is_pointer_value(env, value_regno)) {
61bd5218 4101 verbose(env, "R%d leaks addr into map\n", value_regno);
1be7f75d
AS
4102 return -EACCES;
4103 }
591fe988
DB
4104 err = check_map_access_type(env, regno, off, size, t);
4105 if (err)
4106 return err;
9fd29c08 4107 err = check_map_access(env, regno, off, size, false);
a23740ec
AN
4108 if (!err && t == BPF_READ && value_regno >= 0) {
4109 struct bpf_map *map = reg->map_ptr;
4110
4111 /* if map is read-only, track its contents as scalars */
4112 if (tnum_is_const(reg->var_off) &&
4113 bpf_map_is_rdonly(map) &&
4114 map->ops->map_direct_value_addr) {
4115 int map_off = off + reg->var_off.value;
4116 u64 val = 0;
4117
4118 err = bpf_map_direct_read(map, map_off, size,
4119 &val);
4120 if (err)
4121 return err;
4122
4123 regs[value_regno].type = SCALAR_VALUE;
4124 __mark_reg_known(&regs[value_regno], val);
4125 } else {
4126 mark_reg_unknown(env, regs, value_regno);
4127 }
4128 }
457f4436
AN
4129 } else if (reg->type == PTR_TO_MEM) {
4130 if (t == BPF_WRITE && value_regno >= 0 &&
4131 is_pointer_value(env, value_regno)) {
4132 verbose(env, "R%d leaks addr into mem\n", value_regno);
4133 return -EACCES;
4134 }
4135 err = check_mem_region_access(env, regno, off, size,
4136 reg->mem_size, false);
4137 if (!err && t == BPF_READ && value_regno >= 0)
4138 mark_reg_unknown(env, regs, value_regno);
1a0dc1ac 4139 } else if (reg->type == PTR_TO_CTX) {
f1174f77 4140 enum bpf_reg_type reg_type = SCALAR_VALUE;
22dc4a0f 4141 struct btf *btf = NULL;
9e15db66 4142 u32 btf_id = 0;
19de99f7 4143
1be7f75d
AS
4144 if (t == BPF_WRITE && value_regno >= 0 &&
4145 is_pointer_value(env, value_regno)) {
61bd5218 4146 verbose(env, "R%d leaks addr into ctx\n", value_regno);
1be7f75d
AS
4147 return -EACCES;
4148 }
f1174f77 4149
58990d1f
DB
4150 err = check_ctx_reg(env, reg, regno);
4151 if (err < 0)
4152 return err;
4153
22dc4a0f 4154 err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf, &btf_id);
9e15db66
AS
4155 if (err)
4156 verbose_linfo(env, insn_idx, "; ");
969bf05e 4157 if (!err && t == BPF_READ && value_regno >= 0) {
f1174f77 4158 /* ctx access returns either a scalar, or a
de8f3a83
DB
4159 * PTR_TO_PACKET[_META,_END]. In the latter
4160 * case, we know the offset is zero.
f1174f77 4161 */
46f8bc92 4162 if (reg_type == SCALAR_VALUE) {
638f5b90 4163 mark_reg_unknown(env, regs, value_regno);
46f8bc92 4164 } else {
638f5b90 4165 mark_reg_known_zero(env, regs,
61bd5218 4166 value_regno);
46f8bc92
MKL
4167 if (reg_type_may_be_null(reg_type))
4168 regs[value_regno].id = ++env->id_gen;
5327ed3d
JW
4169 /* A load of ctx field could have different
4170 * actual load size with the one encoded in the
4171 * insn. When the dst is PTR, it is for sure not
4172 * a sub-register.
4173 */
4174 regs[value_regno].subreg_def = DEF_NOT_SUBREG;
b121b341 4175 if (reg_type == PTR_TO_BTF_ID ||
22dc4a0f
AN
4176 reg_type == PTR_TO_BTF_ID_OR_NULL) {
4177 regs[value_regno].btf = btf;
9e15db66 4178 regs[value_regno].btf_id = btf_id;
22dc4a0f 4179 }
46f8bc92 4180 }
638f5b90 4181 regs[value_regno].type = reg_type;
969bf05e 4182 }
17a52670 4183
f1174f77 4184 } else if (reg->type == PTR_TO_STACK) {
01f810ac
AM
4185 /* Basic bounds checks. */
4186 err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
e4298d25
DB
4187 if (err)
4188 return err;
8726679a 4189
f4d7e40a
AS
4190 state = func(env, reg);
4191 err = update_stack_depth(env, state, off);
4192 if (err)
4193 return err;
8726679a 4194
01f810ac
AM
4195 if (t == BPF_READ)
4196 err = check_stack_read(env, regno, off, size,
61bd5218 4197 value_regno);
01f810ac
AM
4198 else
4199 err = check_stack_write(env, regno, off, size,
4200 value_regno, insn_idx);
de8f3a83 4201 } else if (reg_is_pkt_pointer(reg)) {
3a0af8fd 4202 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
61bd5218 4203 verbose(env, "cannot write into packet\n");
969bf05e
AS
4204 return -EACCES;
4205 }
4acf6c0b
BB
4206 if (t == BPF_WRITE && value_regno >= 0 &&
4207 is_pointer_value(env, value_regno)) {
61bd5218
JK
4208 verbose(env, "R%d leaks addr into packet\n",
4209 value_regno);
4acf6c0b
BB
4210 return -EACCES;
4211 }
9fd29c08 4212 err = check_packet_access(env, regno, off, size, false);
969bf05e 4213 if (!err && t == BPF_READ && value_regno >= 0)
638f5b90 4214 mark_reg_unknown(env, regs, value_regno);
d58e468b
PP
4215 } else if (reg->type == PTR_TO_FLOW_KEYS) {
4216 if (t == BPF_WRITE && value_regno >= 0 &&
4217 is_pointer_value(env, value_regno)) {
4218 verbose(env, "R%d leaks addr into flow keys\n",
4219 value_regno);
4220 return -EACCES;
4221 }
4222
4223 err = check_flow_keys_access(env, off, size);
4224 if (!err && t == BPF_READ && value_regno >= 0)
4225 mark_reg_unknown(env, regs, value_regno);
46f8bc92 4226 } else if (type_is_sk_pointer(reg->type)) {
c64b7983 4227 if (t == BPF_WRITE) {
46f8bc92
MKL
4228 verbose(env, "R%d cannot write into %s\n",
4229 regno, reg_type_str[reg->type]);
c64b7983
JS
4230 return -EACCES;
4231 }
5f456649 4232 err = check_sock_access(env, insn_idx, regno, off, size, t);
c64b7983
JS
4233 if (!err && value_regno >= 0)
4234 mark_reg_unknown(env, regs, value_regno);
9df1c28b
MM
4235 } else if (reg->type == PTR_TO_TP_BUFFER) {
4236 err = check_tp_buffer_access(env, reg, regno, off, size);
4237 if (!err && t == BPF_READ && value_regno >= 0)
4238 mark_reg_unknown(env, regs, value_regno);
9e15db66
AS
4239 } else if (reg->type == PTR_TO_BTF_ID) {
4240 err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
4241 value_regno);
41c48f3a
AI
4242 } else if (reg->type == CONST_PTR_TO_MAP) {
4243 err = check_ptr_to_map_access(env, regs, regno, off, size, t,
4244 value_regno);
afbf21dc
YS
4245 } else if (reg->type == PTR_TO_RDONLY_BUF) {
4246 if (t == BPF_WRITE) {
4247 verbose(env, "R%d cannot write into %s\n",
4248 regno, reg_type_str[reg->type]);
4249 return -EACCES;
4250 }
f6dfbe31
CIK
4251 err = check_buffer_access(env, reg, regno, off, size, false,
4252 "rdonly",
afbf21dc
YS
4253 &env->prog->aux->max_rdonly_access);
4254 if (!err && value_regno >= 0)
4255 mark_reg_unknown(env, regs, value_regno);
4256 } else if (reg->type == PTR_TO_RDWR_BUF) {
f6dfbe31
CIK
4257 err = check_buffer_access(env, reg, regno, off, size, false,
4258 "rdwr",
afbf21dc
YS
4259 &env->prog->aux->max_rdwr_access);
4260 if (!err && t == BPF_READ && value_regno >= 0)
4261 mark_reg_unknown(env, regs, value_regno);
17a52670 4262 } else {
61bd5218
JK
4263 verbose(env, "R%d invalid mem access '%s'\n", regno,
4264 reg_type_str[reg->type]);
17a52670
AS
4265 return -EACCES;
4266 }
969bf05e 4267
f1174f77 4268 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
638f5b90 4269 regs[value_regno].type == SCALAR_VALUE) {
f1174f77 4270 /* b/h/w load zero-extends, mark upper bits as known 0 */
0c17d1d2 4271 coerce_reg_to_size(&regs[value_regno], size);
969bf05e 4272 }
17a52670
AS
4273 return err;
4274}
4275
91c960b0 4276static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
17a52670 4277{
5ffa2550 4278 int load_reg;
17a52670
AS
4279 int err;
4280
5ca419f2
BJ
4281 switch (insn->imm) {
4282 case BPF_ADD:
4283 case BPF_ADD | BPF_FETCH:
981f94c3
BJ
4284 case BPF_AND:
4285 case BPF_AND | BPF_FETCH:
4286 case BPF_OR:
4287 case BPF_OR | BPF_FETCH:
4288 case BPF_XOR:
4289 case BPF_XOR | BPF_FETCH:
5ffa2550
BJ
4290 case BPF_XCHG:
4291 case BPF_CMPXCHG:
5ca419f2
BJ
4292 break;
4293 default:
91c960b0
BJ
4294 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
4295 return -EINVAL;
4296 }
4297
4298 if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
4299 verbose(env, "invalid atomic operand size\n");
17a52670
AS
4300 return -EINVAL;
4301 }
4302
4303 /* check src1 operand */
dc503a8a 4304 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17a52670
AS
4305 if (err)
4306 return err;
4307
4308 /* check src2 operand */
dc503a8a 4309 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17a52670
AS
4310 if (err)
4311 return err;
4312
5ffa2550
BJ
4313 if (insn->imm == BPF_CMPXCHG) {
4314 /* Check comparison of R0 with memory location */
4315 err = check_reg_arg(env, BPF_REG_0, SRC_OP);
4316 if (err)
4317 return err;
4318 }
4319
6bdf6abc 4320 if (is_pointer_value(env, insn->src_reg)) {
61bd5218 4321 verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
6bdf6abc
DB
4322 return -EACCES;
4323 }
4324
ca369602 4325 if (is_ctx_reg(env, insn->dst_reg) ||
4b5defde 4326 is_pkt_reg(env, insn->dst_reg) ||
46f8bc92
MKL
4327 is_flow_key_reg(env, insn->dst_reg) ||
4328 is_sk_reg(env, insn->dst_reg)) {
91c960b0 4329 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
2a159c6f
DB
4330 insn->dst_reg,
4331 reg_type_str[reg_state(env, insn->dst_reg)->type]);
f37a8cb8
DB
4332 return -EACCES;
4333 }
4334
37086bfd
BJ
4335 if (insn->imm & BPF_FETCH) {
4336 if (insn->imm == BPF_CMPXCHG)
4337 load_reg = BPF_REG_0;
4338 else
4339 load_reg = insn->src_reg;
4340
4341 /* check and record load of old value */
4342 err = check_reg_arg(env, load_reg, DST_OP);
4343 if (err)
4344 return err;
4345 } else {
4346 /* This instruction accesses a memory location but doesn't
4347 * actually load it into a register.
4348 */
4349 load_reg = -1;
4350 }
4351
91c960b0 4352 /* check whether we can read the memory */
31fd8581 4353 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
37086bfd 4354 BPF_SIZE(insn->code), BPF_READ, load_reg, true);
17a52670
AS
4355 if (err)
4356 return err;
4357
91c960b0 4358 /* check whether we can write into the same memory */
5ca419f2
BJ
4359 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
4360 BPF_SIZE(insn->code), BPF_WRITE, -1, true);
4361 if (err)
4362 return err;
4363
5ca419f2 4364 return 0;
17a52670
AS
4365}
4366
01f810ac
AM
4367/* When register 'regno' is used to read the stack (either directly or through
4368 * a helper function) make sure that it's within stack boundary and, depending
4369 * on the access type, that all elements of the stack are initialized.
4370 *
4371 * 'off' includes 'regno->off', but not its dynamic part (if any).
4372 *
4373 * All registers that have been spilled on the stack in the slots within the
4374 * read offsets are marked as read.
4375 */
4376static int check_stack_range_initialized(
4377 struct bpf_verifier_env *env, int regno, int off,
4378 int access_size, bool zero_size_allowed,
4379 enum stack_access_src type, struct bpf_call_arg_meta *meta)
2011fccf
AI
4380{
4381 struct bpf_reg_state *reg = reg_state(env, regno);
01f810ac
AM
4382 struct bpf_func_state *state = func(env, reg);
4383 int err, min_off, max_off, i, j, slot, spi;
4384 char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
4385 enum bpf_access_type bounds_check_type;
4386 /* Some accesses can write anything into the stack, others are
4387 * read-only.
4388 */
4389 bool clobber = false;
2011fccf 4390
01f810ac
AM
4391 if (access_size == 0 && !zero_size_allowed) {
4392 verbose(env, "invalid zero-sized read\n");
2011fccf
AI
4393 return -EACCES;
4394 }
2011fccf 4395
01f810ac
AM
4396 if (type == ACCESS_HELPER) {
4397 /* The bounds checks for writes are more permissive than for
4398 * reads. However, if raw_mode is not set, we'll do extra
4399 * checks below.
4400 */
4401 bounds_check_type = BPF_WRITE;
4402 clobber = true;
4403 } else {
4404 bounds_check_type = BPF_READ;
4405 }
4406 err = check_stack_access_within_bounds(env, regno, off, access_size,
4407 type, bounds_check_type);
4408 if (err)
4409 return err;
4410
17a52670 4411
2011fccf 4412 if (tnum_is_const(reg->var_off)) {
01f810ac 4413 min_off = max_off = reg->var_off.value + off;
2011fccf 4414 } else {
088ec26d
AI
4415 /* Variable offset is prohibited for unprivileged mode for
4416 * simplicity since it requires corresponding support in
4417 * Spectre masking for stack ALU.
4418 * See also retrieve_ptr_limit().
4419 */
2c78ee89 4420 if (!env->bypass_spec_v1) {
088ec26d 4421 char tn_buf[48];
f1174f77 4422
088ec26d 4423 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
01f810ac
AM
4424 verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
4425 regno, err_extra, tn_buf);
088ec26d
AI
4426 return -EACCES;
4427 }
f2bcd05e
AI
4428 /* Only initialized buffer on stack is allowed to be accessed
4429 * with variable offset. With uninitialized buffer it's hard to
4430 * guarantee that whole memory is marked as initialized on
4431 * helper return since specific bounds are unknown what may
4432 * cause uninitialized stack leaking.
4433 */
4434 if (meta && meta->raw_mode)
4435 meta = NULL;
4436
01f810ac
AM
4437 min_off = reg->smin_value + off;
4438 max_off = reg->smax_value + off;
17a52670
AS
4439 }
4440
435faee1
DB
4441 if (meta && meta->raw_mode) {
4442 meta->access_size = access_size;
4443 meta->regno = regno;
4444 return 0;
4445 }
4446
2011fccf 4447 for (i = min_off; i < max_off + access_size; i++) {
cc2b14d5
AS
4448 u8 *stype;
4449
2011fccf 4450 slot = -i - 1;
638f5b90 4451 spi = slot / BPF_REG_SIZE;
cc2b14d5
AS
4452 if (state->allocated_stack <= slot)
4453 goto err;
4454 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
4455 if (*stype == STACK_MISC)
4456 goto mark;
4457 if (*stype == STACK_ZERO) {
01f810ac
AM
4458 if (clobber) {
4459 /* helper can write anything into the stack */
4460 *stype = STACK_MISC;
4461 }
cc2b14d5 4462 goto mark;
17a52670 4463 }
1d68f22b
YS
4464
4465 if (state->stack[spi].slot_type[0] == STACK_SPILL &&
4466 state->stack[spi].spilled_ptr.type == PTR_TO_BTF_ID)
4467 goto mark;
4468
f7cf25b2 4469 if (state->stack[spi].slot_type[0] == STACK_SPILL &&
cd17d38f
YS
4470 (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
4471 env->allow_ptr_leaks)) {
01f810ac
AM
4472 if (clobber) {
4473 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
4474 for (j = 0; j < BPF_REG_SIZE; j++)
4475 state->stack[spi].slot_type[j] = STACK_MISC;
4476 }
f7cf25b2
AS
4477 goto mark;
4478 }
4479
cc2b14d5 4480err:
2011fccf 4481 if (tnum_is_const(reg->var_off)) {
01f810ac
AM
4482 verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
4483 err_extra, regno, min_off, i - min_off, access_size);
2011fccf
AI
4484 } else {
4485 char tn_buf[48];
4486
4487 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
01f810ac
AM
4488 verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
4489 err_extra, regno, tn_buf, i - min_off, access_size);
2011fccf 4490 }
cc2b14d5
AS
4491 return -EACCES;
4492mark:
4493 /* reading any byte out of 8-byte 'spill_slot' will cause
4494 * the whole slot to be marked as 'read'
4495 */
679c782d 4496 mark_reg_read(env, &state->stack[spi].spilled_ptr,
5327ed3d
JW
4497 state->stack[spi].spilled_ptr.parent,
4498 REG_LIVE_READ64);
17a52670 4499 }
2011fccf 4500 return update_stack_depth(env, state, min_off);
17a52670
AS
4501}
4502
06c1c049
GB
4503static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
4504 int access_size, bool zero_size_allowed,
4505 struct bpf_call_arg_meta *meta)
4506{
638f5b90 4507 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
06c1c049 4508
f1174f77 4509 switch (reg->type) {
06c1c049 4510 case PTR_TO_PACKET:
de8f3a83 4511 case PTR_TO_PACKET_META:
9fd29c08
YS
4512 return check_packet_access(env, regno, reg->off, access_size,
4513 zero_size_allowed);
69c087ba
YS
4514 case PTR_TO_MAP_KEY:
4515 return check_mem_region_access(env, regno, reg->off, access_size,
4516 reg->map_ptr->key_size, false);
06c1c049 4517 case PTR_TO_MAP_VALUE:
591fe988
DB
4518 if (check_map_access_type(env, regno, reg->off, access_size,
4519 meta && meta->raw_mode ? BPF_WRITE :
4520 BPF_READ))
4521 return -EACCES;
9fd29c08
YS
4522 return check_map_access(env, regno, reg->off, access_size,
4523 zero_size_allowed);
457f4436
AN
4524 case PTR_TO_MEM:
4525 return check_mem_region_access(env, regno, reg->off,
4526 access_size, reg->mem_size,
4527 zero_size_allowed);
afbf21dc
YS
4528 case PTR_TO_RDONLY_BUF:
4529 if (meta && meta->raw_mode)
4530 return -EACCES;
4531 return check_buffer_access(env, reg, regno, reg->off,
4532 access_size, zero_size_allowed,
4533 "rdonly",
4534 &env->prog->aux->max_rdonly_access);
4535 case PTR_TO_RDWR_BUF:
4536 return check_buffer_access(env, reg, regno, reg->off,
4537 access_size, zero_size_allowed,
4538 "rdwr",
4539 &env->prog->aux->max_rdwr_access);
0d004c02 4540 case PTR_TO_STACK:
01f810ac
AM
4541 return check_stack_range_initialized(
4542 env,
4543 regno, reg->off, access_size,
4544 zero_size_allowed, ACCESS_HELPER, meta);
0d004c02
LB
4545 default: /* scalar_value or invalid ptr */
4546 /* Allow zero-byte read from NULL, regardless of pointer type */
4547 if (zero_size_allowed && access_size == 0 &&
4548 register_is_null(reg))
4549 return 0;
4550
4551 verbose(env, "R%d type=%s expected=%s\n", regno,
4552 reg_type_str[reg->type],
4553 reg_type_str[PTR_TO_STACK]);
4554 return -EACCES;
06c1c049
GB
4555 }
4556}
4557
e5069b9c
DB
4558int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
4559 u32 regno, u32 mem_size)
4560{
4561 if (register_is_null(reg))
4562 return 0;
4563
4564 if (reg_type_may_be_null(reg->type)) {
4565 /* Assuming that the register contains a value check if the memory
4566 * access is safe. Temporarily save and restore the register's state as
4567 * the conversion shouldn't be visible to a caller.
4568 */
4569 const struct bpf_reg_state saved_reg = *reg;
4570 int rv;
4571
4572 mark_ptr_not_null_reg(reg);
4573 rv = check_helper_mem_access(env, regno, mem_size, true, NULL);
4574 *reg = saved_reg;
4575 return rv;
4576 }
4577
4578 return check_helper_mem_access(env, regno, mem_size, true, NULL);
4579}
4580
d83525ca
AS
4581/* Implementation details:
4582 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL
4583 * Two bpf_map_lookups (even with the same key) will have different reg->id.
4584 * For traditional PTR_TO_MAP_VALUE the verifier clears reg->id after
4585 * value_or_null->value transition, since the verifier only cares about
4586 * the range of access to valid map value pointer and doesn't care about actual
4587 * address of the map element.
4588 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
4589 * reg->id > 0 after value_or_null->value transition. By doing so
4590 * two bpf_map_lookups will be considered two different pointers that
4591 * point to different bpf_spin_locks.
4592 * The verifier allows taking only one bpf_spin_lock at a time to avoid
4593 * dead-locks.
4594 * Since only one bpf_spin_lock is allowed the checks are simpler than
4595 * reg_is_refcounted() logic. The verifier needs to remember only
4596 * one spin_lock instead of array of acquired_refs.
4597 * cur_state->active_spin_lock remembers which map value element got locked
4598 * and clears it after bpf_spin_unlock.
4599 */
4600static int process_spin_lock(struct bpf_verifier_env *env, int regno,
4601 bool is_lock)
4602{
4603 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4604 struct bpf_verifier_state *cur = env->cur_state;
4605 bool is_const = tnum_is_const(reg->var_off);
4606 struct bpf_map *map = reg->map_ptr;
4607 u64 val = reg->var_off.value;
4608
d83525ca
AS
4609 if (!is_const) {
4610 verbose(env,
4611 "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
4612 regno);
4613 return -EINVAL;
4614 }
4615 if (!map->btf) {
4616 verbose(env,
4617 "map '%s' has to have BTF in order to use bpf_spin_lock\n",
4618 map->name);
4619 return -EINVAL;
4620 }
4621 if (!map_value_has_spin_lock(map)) {
4622 if (map->spin_lock_off == -E2BIG)
4623 verbose(env,
4624 "map '%s' has more than one 'struct bpf_spin_lock'\n",
4625 map->name);
4626 else if (map->spin_lock_off == -ENOENT)
4627 verbose(env,
4628 "map '%s' doesn't have 'struct bpf_spin_lock'\n",
4629 map->name);
4630 else
4631 verbose(env,
4632 "map '%s' is not a struct type or bpf_spin_lock is mangled\n",
4633 map->name);
4634 return -EINVAL;
4635 }
4636 if (map->spin_lock_off != val + reg->off) {
4637 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock'\n",
4638 val + reg->off);
4639 return -EINVAL;
4640 }
4641 if (is_lock) {
4642 if (cur->active_spin_lock) {
4643 verbose(env,
4644 "Locking two bpf_spin_locks are not allowed\n");
4645 return -EINVAL;
4646 }
4647 cur->active_spin_lock = reg->id;
4648 } else {
4649 if (!cur->active_spin_lock) {
4650 verbose(env, "bpf_spin_unlock without taking a lock\n");
4651 return -EINVAL;
4652 }
4653 if (cur->active_spin_lock != reg->id) {
4654 verbose(env, "bpf_spin_unlock of different lock\n");
4655 return -EINVAL;
4656 }
4657 cur->active_spin_lock = 0;
4658 }
4659 return 0;
4660}
4661
90133415
DB
4662static bool arg_type_is_mem_ptr(enum bpf_arg_type type)
4663{
4664 return type == ARG_PTR_TO_MEM ||
4665 type == ARG_PTR_TO_MEM_OR_NULL ||
4666 type == ARG_PTR_TO_UNINIT_MEM;
4667}
4668
4669static bool arg_type_is_mem_size(enum bpf_arg_type type)
4670{
4671 return type == ARG_CONST_SIZE ||
4672 type == ARG_CONST_SIZE_OR_ZERO;
4673}
4674
457f4436
AN
4675static bool arg_type_is_alloc_size(enum bpf_arg_type type)
4676{
4677 return type == ARG_CONST_ALLOC_SIZE_OR_ZERO;
4678}
4679
57c3bb72
AI
4680static bool arg_type_is_int_ptr(enum bpf_arg_type type)
4681{
4682 return type == ARG_PTR_TO_INT ||
4683 type == ARG_PTR_TO_LONG;
4684}
4685
4686static int int_ptr_type_to_size(enum bpf_arg_type type)
4687{
4688 if (type == ARG_PTR_TO_INT)
4689 return sizeof(u32);
4690 else if (type == ARG_PTR_TO_LONG)
4691 return sizeof(u64);
4692
4693 return -EINVAL;
4694}
4695
912f442c
LB
4696static int resolve_map_arg_type(struct bpf_verifier_env *env,
4697 const struct bpf_call_arg_meta *meta,
4698 enum bpf_arg_type *arg_type)
4699{
4700 if (!meta->map_ptr) {
4701 /* kernel subsystem misconfigured verifier */
4702 verbose(env, "invalid map_ptr to access map->type\n");
4703 return -EACCES;
4704 }
4705
4706 switch (meta->map_ptr->map_type) {
4707 case BPF_MAP_TYPE_SOCKMAP:
4708 case BPF_MAP_TYPE_SOCKHASH:
4709 if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
6550f2dd 4710 *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
912f442c
LB
4711 } else {
4712 verbose(env, "invalid arg_type for sockmap/sockhash\n");
4713 return -EINVAL;
4714 }
4715 break;
4716
4717 default:
4718 break;
4719 }
4720 return 0;
4721}
4722
f79e7ea5
LB
4723struct bpf_reg_types {
4724 const enum bpf_reg_type types[10];
1df8f55a 4725 u32 *btf_id;
f79e7ea5
LB
4726};
4727
4728static const struct bpf_reg_types map_key_value_types = {
4729 .types = {
4730 PTR_TO_STACK,
4731 PTR_TO_PACKET,
4732 PTR_TO_PACKET_META,
69c087ba 4733 PTR_TO_MAP_KEY,
f79e7ea5
LB
4734 PTR_TO_MAP_VALUE,
4735 },
4736};
4737
4738static const struct bpf_reg_types sock_types = {
4739 .types = {
4740 PTR_TO_SOCK_COMMON,
4741 PTR_TO_SOCKET,
4742 PTR_TO_TCP_SOCK,
4743 PTR_TO_XDP_SOCK,
4744 },
4745};
4746
49a2a4d4 4747#ifdef CONFIG_NET
1df8f55a
MKL
4748static const struct bpf_reg_types btf_id_sock_common_types = {
4749 .types = {
4750 PTR_TO_SOCK_COMMON,
4751 PTR_TO_SOCKET,
4752 PTR_TO_TCP_SOCK,
4753 PTR_TO_XDP_SOCK,
4754 PTR_TO_BTF_ID,
4755 },
4756 .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
4757};
49a2a4d4 4758#endif
1df8f55a 4759
f79e7ea5
LB
4760static const struct bpf_reg_types mem_types = {
4761 .types = {
4762 PTR_TO_STACK,
4763 PTR_TO_PACKET,
4764 PTR_TO_PACKET_META,
69c087ba 4765 PTR_TO_MAP_KEY,
f79e7ea5
LB
4766 PTR_TO_MAP_VALUE,
4767 PTR_TO_MEM,
4768 PTR_TO_RDONLY_BUF,
4769 PTR_TO_RDWR_BUF,
4770 },
4771};
4772
4773static const struct bpf_reg_types int_ptr_types = {
4774 .types = {
4775 PTR_TO_STACK,
4776 PTR_TO_PACKET,
4777 PTR_TO_PACKET_META,
69c087ba 4778 PTR_TO_MAP_KEY,
f79e7ea5
LB
4779 PTR_TO_MAP_VALUE,
4780 },
4781};
4782
4783static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
4784static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
4785static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
4786static const struct bpf_reg_types alloc_mem_types = { .types = { PTR_TO_MEM } };
4787static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
4788static const struct bpf_reg_types btf_ptr_types = { .types = { PTR_TO_BTF_ID } };
4789static const struct bpf_reg_types spin_lock_types = { .types = { PTR_TO_MAP_VALUE } };
eaa6bcb7 4790static const struct bpf_reg_types percpu_btf_ptr_types = { .types = { PTR_TO_PERCPU_BTF_ID } };
69c087ba
YS
4791static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
4792static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
fff13c4b 4793static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
f79e7ea5 4794
0789e13b 4795static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
f79e7ea5
LB
4796 [ARG_PTR_TO_MAP_KEY] = &map_key_value_types,
4797 [ARG_PTR_TO_MAP_VALUE] = &map_key_value_types,
4798 [ARG_PTR_TO_UNINIT_MAP_VALUE] = &map_key_value_types,
4799 [ARG_PTR_TO_MAP_VALUE_OR_NULL] = &map_key_value_types,
4800 [ARG_CONST_SIZE] = &scalar_types,
4801 [ARG_CONST_SIZE_OR_ZERO] = &scalar_types,
4802 [ARG_CONST_ALLOC_SIZE_OR_ZERO] = &scalar_types,
4803 [ARG_CONST_MAP_PTR] = &const_map_ptr_types,
4804 [ARG_PTR_TO_CTX] = &context_types,
4805 [ARG_PTR_TO_CTX_OR_NULL] = &context_types,
4806 [ARG_PTR_TO_SOCK_COMMON] = &sock_types,
49a2a4d4 4807#ifdef CONFIG_NET
1df8f55a 4808 [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types,
49a2a4d4 4809#endif
f79e7ea5
LB
4810 [ARG_PTR_TO_SOCKET] = &fullsock_types,
4811 [ARG_PTR_TO_SOCKET_OR_NULL] = &fullsock_types,
4812 [ARG_PTR_TO_BTF_ID] = &btf_ptr_types,
4813 [ARG_PTR_TO_SPIN_LOCK] = &spin_lock_types,
4814 [ARG_PTR_TO_MEM] = &mem_types,
4815 [ARG_PTR_TO_MEM_OR_NULL] = &mem_types,
4816 [ARG_PTR_TO_UNINIT_MEM] = &mem_types,
4817 [ARG_PTR_TO_ALLOC_MEM] = &alloc_mem_types,
4818 [ARG_PTR_TO_ALLOC_MEM_OR_NULL] = &alloc_mem_types,
4819 [ARG_PTR_TO_INT] = &int_ptr_types,
4820 [ARG_PTR_TO_LONG] = &int_ptr_types,
eaa6bcb7 4821 [ARG_PTR_TO_PERCPU_BTF_ID] = &percpu_btf_ptr_types,
69c087ba
YS
4822 [ARG_PTR_TO_FUNC] = &func_ptr_types,
4823 [ARG_PTR_TO_STACK_OR_NULL] = &stack_ptr_types,
fff13c4b 4824 [ARG_PTR_TO_CONST_STR] = &const_str_ptr_types,
f79e7ea5
LB
4825};
4826
4827static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
a968d5e2
MKL
4828 enum bpf_arg_type arg_type,
4829 const u32 *arg_btf_id)
f79e7ea5
LB
4830{
4831 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4832 enum bpf_reg_type expected, type = reg->type;
a968d5e2 4833 const struct bpf_reg_types *compatible;
f79e7ea5
LB
4834 int i, j;
4835
a968d5e2
MKL
4836 compatible = compatible_reg_types[arg_type];
4837 if (!compatible) {
4838 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
4839 return -EFAULT;
4840 }
4841
f79e7ea5
LB
4842 for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
4843 expected = compatible->types[i];
4844 if (expected == NOT_INIT)
4845 break;
4846
4847 if (type == expected)
a968d5e2 4848 goto found;
f79e7ea5
LB
4849 }
4850
4851 verbose(env, "R%d type=%s expected=", regno, reg_type_str[type]);
4852 for (j = 0; j + 1 < i; j++)
4853 verbose(env, "%s, ", reg_type_str[compatible->types[j]]);
4854 verbose(env, "%s\n", reg_type_str[compatible->types[j]]);
4855 return -EACCES;
a968d5e2
MKL
4856
4857found:
4858 if (type == PTR_TO_BTF_ID) {
1df8f55a
MKL
4859 if (!arg_btf_id) {
4860 if (!compatible->btf_id) {
4861 verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
4862 return -EFAULT;
4863 }
4864 arg_btf_id = compatible->btf_id;
4865 }
4866
22dc4a0f
AN
4867 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
4868 btf_vmlinux, *arg_btf_id)) {
a968d5e2 4869 verbose(env, "R%d is of type %s but %s is expected\n",
22dc4a0f
AN
4870 regno, kernel_type_name(reg->btf, reg->btf_id),
4871 kernel_type_name(btf_vmlinux, *arg_btf_id));
a968d5e2
MKL
4872 return -EACCES;
4873 }
4874
4875 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4876 verbose(env, "R%d is a pointer to in-kernel struct with non-zero offset\n",
4877 regno);
4878 return -EACCES;
4879 }
4880 }
4881
4882 return 0;
f79e7ea5
LB
4883}
4884
af7ec138
YS
4885static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
4886 struct bpf_call_arg_meta *meta,
4887 const struct bpf_func_proto *fn)
17a52670 4888{
af7ec138 4889 u32 regno = BPF_REG_1 + arg;
638f5b90 4890 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
af7ec138 4891 enum bpf_arg_type arg_type = fn->arg_type[arg];
f79e7ea5 4892 enum bpf_reg_type type = reg->type;
17a52670
AS
4893 int err = 0;
4894
80f1d68c 4895 if (arg_type == ARG_DONTCARE)
17a52670
AS
4896 return 0;
4897
dc503a8a
EC
4898 err = check_reg_arg(env, regno, SRC_OP);
4899 if (err)
4900 return err;
17a52670 4901
1be7f75d
AS
4902 if (arg_type == ARG_ANYTHING) {
4903 if (is_pointer_value(env, regno)) {
61bd5218
JK
4904 verbose(env, "R%d leaks addr into helper function\n",
4905 regno);
1be7f75d
AS
4906 return -EACCES;
4907 }
80f1d68c 4908 return 0;
1be7f75d 4909 }
80f1d68c 4910
de8f3a83 4911 if (type_is_pkt_pointer(type) &&
3a0af8fd 4912 !may_access_direct_pkt_data(env, meta, BPF_READ)) {
61bd5218 4913 verbose(env, "helper access to the packet is not allowed\n");
6841de8b
AS
4914 return -EACCES;
4915 }
4916
912f442c
LB
4917 if (arg_type == ARG_PTR_TO_MAP_VALUE ||
4918 arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE ||
4919 arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL) {
4920 err = resolve_map_arg_type(env, meta, &arg_type);
4921 if (err)
4922 return err;
4923 }
4924
fd1b0d60
LB
4925 if (register_is_null(reg) && arg_type_may_be_null(arg_type))
4926 /* A NULL register has a SCALAR_VALUE type, so skip
4927 * type checking.
4928 */
4929 goto skip_type_check;
4930
a968d5e2 4931 err = check_reg_type(env, regno, arg_type, fn->arg_btf_id[arg]);
f79e7ea5
LB
4932 if (err)
4933 return err;
4934
a968d5e2 4935 if (type == PTR_TO_CTX) {
feec7040
LB
4936 err = check_ctx_reg(env, reg, regno);
4937 if (err < 0)
4938 return err;
d7b9454a
LB
4939 }
4940
fd1b0d60 4941skip_type_check:
02f7c958 4942 if (reg->ref_obj_id) {
457f4436
AN
4943 if (meta->ref_obj_id) {
4944 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
4945 regno, reg->ref_obj_id,
4946 meta->ref_obj_id);
4947 return -EFAULT;
4948 }
4949 meta->ref_obj_id = reg->ref_obj_id;
17a52670
AS
4950 }
4951
17a52670
AS
4952 if (arg_type == ARG_CONST_MAP_PTR) {
4953 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
33ff9823 4954 meta->map_ptr = reg->map_ptr;
17a52670
AS
4955 } else if (arg_type == ARG_PTR_TO_MAP_KEY) {
4956 /* bpf_map_xxx(..., map_ptr, ..., key) call:
4957 * check that [key, key + map->key_size) are within
4958 * stack limits and initialized
4959 */
33ff9823 4960 if (!meta->map_ptr) {
17a52670
AS
4961 /* in function declaration map_ptr must come before
4962 * map_key, so that it's verified and known before
4963 * we have to check map_key here. Otherwise it means
4964 * that kernel subsystem misconfigured verifier
4965 */
61bd5218 4966 verbose(env, "invalid map_ptr to access map->key\n");
17a52670
AS
4967 return -EACCES;
4968 }
d71962f3
PC
4969 err = check_helper_mem_access(env, regno,
4970 meta->map_ptr->key_size, false,
4971 NULL);
2ea864c5 4972 } else if (arg_type == ARG_PTR_TO_MAP_VALUE ||
6ac99e8f
MKL
4973 (arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL &&
4974 !register_is_null(reg)) ||
2ea864c5 4975 arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE) {
17a52670
AS
4976 /* bpf_map_xxx(..., map_ptr, ..., value) call:
4977 * check [value, value + map->value_size) validity
4978 */
33ff9823 4979 if (!meta->map_ptr) {
17a52670 4980 /* kernel subsystem misconfigured verifier */
61bd5218 4981 verbose(env, "invalid map_ptr to access map->value\n");
17a52670
AS
4982 return -EACCES;
4983 }
2ea864c5 4984 meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE);
d71962f3
PC
4985 err = check_helper_mem_access(env, regno,
4986 meta->map_ptr->value_size, false,
2ea864c5 4987 meta);
eaa6bcb7
HL
4988 } else if (arg_type == ARG_PTR_TO_PERCPU_BTF_ID) {
4989 if (!reg->btf_id) {
4990 verbose(env, "Helper has invalid btf_id in R%d\n", regno);
4991 return -EACCES;
4992 }
22dc4a0f 4993 meta->ret_btf = reg->btf;
eaa6bcb7 4994 meta->ret_btf_id = reg->btf_id;
c18f0b6a
LB
4995 } else if (arg_type == ARG_PTR_TO_SPIN_LOCK) {
4996 if (meta->func_id == BPF_FUNC_spin_lock) {
4997 if (process_spin_lock(env, regno, true))
4998 return -EACCES;
4999 } else if (meta->func_id == BPF_FUNC_spin_unlock) {
5000 if (process_spin_lock(env, regno, false))
5001 return -EACCES;
5002 } else {
5003 verbose(env, "verifier internal error\n");
5004 return -EFAULT;
5005 }
69c087ba
YS
5006 } else if (arg_type == ARG_PTR_TO_FUNC) {
5007 meta->subprogno = reg->subprogno;
a2bbe7cc
LB
5008 } else if (arg_type_is_mem_ptr(arg_type)) {
5009 /* The access to this pointer is only checked when we hit the
5010 * next is_mem_size argument below.
5011 */
5012 meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MEM);
90133415 5013 } else if (arg_type_is_mem_size(arg_type)) {
39f19ebb 5014 bool zero_size_allowed = (arg_type == ARG_CONST_SIZE_OR_ZERO);
17a52670 5015
10060503
JF
5016 /* This is used to refine r0 return value bounds for helpers
5017 * that enforce this value as an upper bound on return values.
5018 * See do_refine_retval_range() for helpers that can refine
5019 * the return value. C type of helper is u32 so we pull register
5020 * bound from umax_value however, if negative verifier errors
5021 * out. Only upper bounds can be learned because retval is an
5022 * int type and negative retvals are allowed.
849fa506 5023 */
10060503 5024 meta->msize_max_value = reg->umax_value;
849fa506 5025
f1174f77
EC
5026 /* The register is SCALAR_VALUE; the access check
5027 * happens using its boundaries.
06c1c049 5028 */
f1174f77 5029 if (!tnum_is_const(reg->var_off))
06c1c049
GB
5030 /* For unprivileged variable accesses, disable raw
5031 * mode so that the program is required to
5032 * initialize all the memory that the helper could
5033 * just partially fill up.
5034 */
5035 meta = NULL;
5036
b03c9f9f 5037 if (reg->smin_value < 0) {
61bd5218 5038 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
f1174f77
EC
5039 regno);
5040 return -EACCES;
5041 }
06c1c049 5042
b03c9f9f 5043 if (reg->umin_value == 0) {
f1174f77
EC
5044 err = check_helper_mem_access(env, regno - 1, 0,
5045 zero_size_allowed,
5046 meta);
06c1c049
GB
5047 if (err)
5048 return err;
06c1c049 5049 }
f1174f77 5050
b03c9f9f 5051 if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
61bd5218 5052 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
f1174f77
EC
5053 regno);
5054 return -EACCES;
5055 }
5056 err = check_helper_mem_access(env, regno - 1,
b03c9f9f 5057 reg->umax_value,
f1174f77 5058 zero_size_allowed, meta);
b5dc0163
AS
5059 if (!err)
5060 err = mark_chain_precision(env, regno);
457f4436
AN
5061 } else if (arg_type_is_alloc_size(arg_type)) {
5062 if (!tnum_is_const(reg->var_off)) {
28a8add6 5063 verbose(env, "R%d is not a known constant'\n",
457f4436
AN
5064 regno);
5065 return -EACCES;
5066 }
5067 meta->mem_size = reg->var_off.value;
57c3bb72
AI
5068 } else if (arg_type_is_int_ptr(arg_type)) {
5069 int size = int_ptr_type_to_size(arg_type);
5070
5071 err = check_helper_mem_access(env, regno, size, false, meta);
5072 if (err)
5073 return err;
5074 err = check_ptr_alignment(env, reg, 0, size, true);
fff13c4b
FR
5075 } else if (arg_type == ARG_PTR_TO_CONST_STR) {
5076 struct bpf_map *map = reg->map_ptr;
5077 int map_off;
5078 u64 map_addr;
5079 char *str_ptr;
5080
a8fad73e 5081 if (!bpf_map_is_rdonly(map)) {
fff13c4b
FR
5082 verbose(env, "R%d does not point to a readonly map'\n", regno);
5083 return -EACCES;
5084 }
5085
5086 if (!tnum_is_const(reg->var_off)) {
5087 verbose(env, "R%d is not a constant address'\n", regno);
5088 return -EACCES;
5089 }
5090
5091 if (!map->ops->map_direct_value_addr) {
5092 verbose(env, "no direct value access support for this map type\n");
5093 return -EACCES;
5094 }
5095
5096 err = check_map_access(env, regno, reg->off,
5097 map->value_size - reg->off, false);
5098 if (err)
5099 return err;
5100
5101 map_off = reg->off + reg->var_off.value;
5102 err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
5103 if (err) {
5104 verbose(env, "direct value access on string failed\n");
5105 return err;
5106 }
5107
5108 str_ptr = (char *)(long)(map_addr);
5109 if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
5110 verbose(env, "string is not zero-terminated\n");
5111 return -EINVAL;
5112 }
17a52670
AS
5113 }
5114
5115 return err;
5116}
5117
0126240f
LB
5118static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
5119{
5120 enum bpf_attach_type eatype = env->prog->expected_attach_type;
7e40781c 5121 enum bpf_prog_type type = resolve_prog_type(env->prog);
0126240f
LB
5122
5123 if (func_id != BPF_FUNC_map_update_elem)
5124 return false;
5125
5126 /* It's not possible to get access to a locked struct sock in these
5127 * contexts, so updating is safe.
5128 */
5129 switch (type) {
5130 case BPF_PROG_TYPE_TRACING:
5131 if (eatype == BPF_TRACE_ITER)
5132 return true;
5133 break;
5134 case BPF_PROG_TYPE_SOCKET_FILTER:
5135 case BPF_PROG_TYPE_SCHED_CLS:
5136 case BPF_PROG_TYPE_SCHED_ACT:
5137 case BPF_PROG_TYPE_XDP:
5138 case BPF_PROG_TYPE_SK_REUSEPORT:
5139 case BPF_PROG_TYPE_FLOW_DISSECTOR:
5140 case BPF_PROG_TYPE_SK_LOOKUP:
5141 return true;
5142 default:
5143 break;
5144 }
5145
5146 verbose(env, "cannot update sockmap in this context\n");
5147 return false;
5148}
5149
e411901c
MF
5150static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
5151{
5152 return env->prog->jit_requested && IS_ENABLED(CONFIG_X86_64);
5153}
5154
61bd5218
JK
5155static int check_map_func_compatibility(struct bpf_verifier_env *env,
5156 struct bpf_map *map, int func_id)
35578d79 5157{
35578d79
KX
5158 if (!map)
5159 return 0;
5160
6aff67c8
AS
5161 /* We need a two way check, first is from map perspective ... */
5162 switch (map->map_type) {
5163 case BPF_MAP_TYPE_PROG_ARRAY:
5164 if (func_id != BPF_FUNC_tail_call)
5165 goto error;
5166 break;
5167 case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
5168 if (func_id != BPF_FUNC_perf_event_read &&
908432ca 5169 func_id != BPF_FUNC_perf_event_output &&
a7658e1a 5170 func_id != BPF_FUNC_skb_output &&
d831ee84
EC
5171 func_id != BPF_FUNC_perf_event_read_value &&
5172 func_id != BPF_FUNC_xdp_output)
6aff67c8
AS
5173 goto error;
5174 break;
457f4436
AN
5175 case BPF_MAP_TYPE_RINGBUF:
5176 if (func_id != BPF_FUNC_ringbuf_output &&
5177 func_id != BPF_FUNC_ringbuf_reserve &&
5178 func_id != BPF_FUNC_ringbuf_submit &&
5179 func_id != BPF_FUNC_ringbuf_discard &&
5180 func_id != BPF_FUNC_ringbuf_query)
5181 goto error;
5182 break;
6aff67c8
AS
5183 case BPF_MAP_TYPE_STACK_TRACE:
5184 if (func_id != BPF_FUNC_get_stackid)
5185 goto error;
5186 break;
4ed8ec52 5187 case BPF_MAP_TYPE_CGROUP_ARRAY:
60747ef4 5188 if (func_id != BPF_FUNC_skb_under_cgroup &&
60d20f91 5189 func_id != BPF_FUNC_current_task_under_cgroup)
4a482f34
MKL
5190 goto error;
5191 break;
cd339431 5192 case BPF_MAP_TYPE_CGROUP_STORAGE:
b741f163 5193 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
cd339431
RG
5194 if (func_id != BPF_FUNC_get_local_storage)
5195 goto error;
5196 break;
546ac1ff 5197 case BPF_MAP_TYPE_DEVMAP:
6f9d451a 5198 case BPF_MAP_TYPE_DEVMAP_HASH:
0cdbb4b0
THJ
5199 if (func_id != BPF_FUNC_redirect_map &&
5200 func_id != BPF_FUNC_map_lookup_elem)
546ac1ff
JF
5201 goto error;
5202 break;
fbfc504a
BT
5203 /* Restrict bpf side of cpumap and xskmap, open when use-cases
5204 * appear.
5205 */
6710e112
JDB
5206 case BPF_MAP_TYPE_CPUMAP:
5207 if (func_id != BPF_FUNC_redirect_map)
5208 goto error;
5209 break;
fada7fdc
JL
5210 case BPF_MAP_TYPE_XSKMAP:
5211 if (func_id != BPF_FUNC_redirect_map &&
5212 func_id != BPF_FUNC_map_lookup_elem)
5213 goto error;
5214 break;
56f668df 5215 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
bcc6b1b7 5216 case BPF_MAP_TYPE_HASH_OF_MAPS:
56f668df
MKL
5217 if (func_id != BPF_FUNC_map_lookup_elem)
5218 goto error;
16a43625 5219 break;
174a79ff
JF
5220 case BPF_MAP_TYPE_SOCKMAP:
5221 if (func_id != BPF_FUNC_sk_redirect_map &&
5222 func_id != BPF_FUNC_sock_map_update &&
4f738adb 5223 func_id != BPF_FUNC_map_delete_elem &&
9fed9000 5224 func_id != BPF_FUNC_msg_redirect_map &&
64d85290 5225 func_id != BPF_FUNC_sk_select_reuseport &&
0126240f
LB
5226 func_id != BPF_FUNC_map_lookup_elem &&
5227 !may_update_sockmap(env, func_id))
174a79ff
JF
5228 goto error;
5229 break;
81110384
JF
5230 case BPF_MAP_TYPE_SOCKHASH:
5231 if (func_id != BPF_FUNC_sk_redirect_hash &&
5232 func_id != BPF_FUNC_sock_hash_update &&
5233 func_id != BPF_FUNC_map_delete_elem &&
9fed9000 5234 func_id != BPF_FUNC_msg_redirect_hash &&
64d85290 5235 func_id != BPF_FUNC_sk_select_reuseport &&
0126240f
LB
5236 func_id != BPF_FUNC_map_lookup_elem &&
5237 !may_update_sockmap(env, func_id))
81110384
JF
5238 goto error;
5239 break;
2dbb9b9e
MKL
5240 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
5241 if (func_id != BPF_FUNC_sk_select_reuseport)
5242 goto error;
5243 break;
f1a2e44a
MV
5244 case BPF_MAP_TYPE_QUEUE:
5245 case BPF_MAP_TYPE_STACK:
5246 if (func_id != BPF_FUNC_map_peek_elem &&
5247 func_id != BPF_FUNC_map_pop_elem &&
5248 func_id != BPF_FUNC_map_push_elem)
5249 goto error;
5250 break;
6ac99e8f
MKL
5251 case BPF_MAP_TYPE_SK_STORAGE:
5252 if (func_id != BPF_FUNC_sk_storage_get &&
5253 func_id != BPF_FUNC_sk_storage_delete)
5254 goto error;
5255 break;
8ea63684
KS
5256 case BPF_MAP_TYPE_INODE_STORAGE:
5257 if (func_id != BPF_FUNC_inode_storage_get &&
5258 func_id != BPF_FUNC_inode_storage_delete)
5259 goto error;
5260 break;
4cf1bc1f
KS
5261 case BPF_MAP_TYPE_TASK_STORAGE:
5262 if (func_id != BPF_FUNC_task_storage_get &&
5263 func_id != BPF_FUNC_task_storage_delete)
5264 goto error;
5265 break;
6aff67c8
AS
5266 default:
5267 break;
5268 }
5269
5270 /* ... and second from the function itself. */
5271 switch (func_id) {
5272 case BPF_FUNC_tail_call:
5273 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
5274 goto error;
e411901c
MF
5275 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
5276 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
f4d7e40a
AS
5277 return -EINVAL;
5278 }
6aff67c8
AS
5279 break;
5280 case BPF_FUNC_perf_event_read:
5281 case BPF_FUNC_perf_event_output:
908432ca 5282 case BPF_FUNC_perf_event_read_value:
a7658e1a 5283 case BPF_FUNC_skb_output:
d831ee84 5284 case BPF_FUNC_xdp_output:
6aff67c8
AS
5285 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
5286 goto error;
5287 break;
5288 case BPF_FUNC_get_stackid:
5289 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
5290 goto error;
5291 break;
60d20f91 5292 case BPF_FUNC_current_task_under_cgroup:
747ea55e 5293 case BPF_FUNC_skb_under_cgroup:
4a482f34
MKL
5294 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
5295 goto error;
5296 break;
97f91a7c 5297 case BPF_FUNC_redirect_map:
9c270af3 5298 if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
6f9d451a 5299 map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
fbfc504a
BT
5300 map->map_type != BPF_MAP_TYPE_CPUMAP &&
5301 map->map_type != BPF_MAP_TYPE_XSKMAP)
97f91a7c
JF
5302 goto error;
5303 break;
174a79ff 5304 case BPF_FUNC_sk_redirect_map:
4f738adb 5305 case BPF_FUNC_msg_redirect_map:
81110384 5306 case BPF_FUNC_sock_map_update:
174a79ff
JF
5307 if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
5308 goto error;
5309 break;
81110384
JF
5310 case BPF_FUNC_sk_redirect_hash:
5311 case BPF_FUNC_msg_redirect_hash:
5312 case BPF_FUNC_sock_hash_update:
5313 if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
174a79ff
JF
5314 goto error;
5315 break;
cd339431 5316 case BPF_FUNC_get_local_storage:
b741f163
RG
5317 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
5318 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
cd339431
RG
5319 goto error;
5320 break;
2dbb9b9e 5321 case BPF_FUNC_sk_select_reuseport:
9fed9000
JS
5322 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
5323 map->map_type != BPF_MAP_TYPE_SOCKMAP &&
5324 map->map_type != BPF_MAP_TYPE_SOCKHASH)
2dbb9b9e
MKL
5325 goto error;
5326 break;
f1a2e44a
MV
5327 case BPF_FUNC_map_peek_elem:
5328 case BPF_FUNC_map_pop_elem:
5329 case BPF_FUNC_map_push_elem:
5330 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
5331 map->map_type != BPF_MAP_TYPE_STACK)
5332 goto error;
5333 break;
6ac99e8f
MKL
5334 case BPF_FUNC_sk_storage_get:
5335 case BPF_FUNC_sk_storage_delete:
5336 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
5337 goto error;
5338 break;
8ea63684
KS
5339 case BPF_FUNC_inode_storage_get:
5340 case BPF_FUNC_inode_storage_delete:
5341 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
5342 goto error;
5343 break;
4cf1bc1f
KS
5344 case BPF_FUNC_task_storage_get:
5345 case BPF_FUNC_task_storage_delete:
5346 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
5347 goto error;
5348 break;
6aff67c8
AS
5349 default:
5350 break;
35578d79
KX
5351 }
5352
5353 return 0;
6aff67c8 5354error:
61bd5218 5355 verbose(env, "cannot pass map_type %d into func %s#%d\n",
ebb676da 5356 map->map_type, func_id_name(func_id), func_id);
6aff67c8 5357 return -EINVAL;
35578d79
KX
5358}
5359
90133415 5360static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
435faee1
DB
5361{
5362 int count = 0;
5363
39f19ebb 5364 if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
435faee1 5365 count++;
39f19ebb 5366 if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
435faee1 5367 count++;
39f19ebb 5368 if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
435faee1 5369 count++;
39f19ebb 5370 if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
435faee1 5371 count++;
39f19ebb 5372 if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
435faee1
DB
5373 count++;
5374
90133415
DB
5375 /* We only support one arg being in raw mode at the moment,
5376 * which is sufficient for the helper functions we have
5377 * right now.
5378 */
5379 return count <= 1;
5380}
5381
5382static bool check_args_pair_invalid(enum bpf_arg_type arg_curr,
5383 enum bpf_arg_type arg_next)
5384{
5385 return (arg_type_is_mem_ptr(arg_curr) &&
5386 !arg_type_is_mem_size(arg_next)) ||
5387 (!arg_type_is_mem_ptr(arg_curr) &&
5388 arg_type_is_mem_size(arg_next));
5389}
5390
5391static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
5392{
5393 /* bpf_xxx(..., buf, len) call will access 'len'
5394 * bytes from memory 'buf'. Both arg types need
5395 * to be paired, so make sure there's no buggy
5396 * helper function specification.
5397 */
5398 if (arg_type_is_mem_size(fn->arg1_type) ||
5399 arg_type_is_mem_ptr(fn->arg5_type) ||
5400 check_args_pair_invalid(fn->arg1_type, fn->arg2_type) ||
5401 check_args_pair_invalid(fn->arg2_type, fn->arg3_type) ||
5402 check_args_pair_invalid(fn->arg3_type, fn->arg4_type) ||
5403 check_args_pair_invalid(fn->arg4_type, fn->arg5_type))
5404 return false;
5405
5406 return true;
5407}
5408
1b986589 5409static bool check_refcount_ok(const struct bpf_func_proto *fn, int func_id)
fd978bf7
JS
5410{
5411 int count = 0;
5412
1b986589 5413 if (arg_type_may_be_refcounted(fn->arg1_type))
fd978bf7 5414 count++;
1b986589 5415 if (arg_type_may_be_refcounted(fn->arg2_type))
fd978bf7 5416 count++;
1b986589 5417 if (arg_type_may_be_refcounted(fn->arg3_type))
fd978bf7 5418 count++;
1b986589 5419 if (arg_type_may_be_refcounted(fn->arg4_type))
fd978bf7 5420 count++;
1b986589 5421 if (arg_type_may_be_refcounted(fn->arg5_type))
fd978bf7
JS
5422 count++;
5423
1b986589
MKL
5424 /* A reference acquiring function cannot acquire
5425 * another refcounted ptr.
5426 */
64d85290 5427 if (may_be_acquire_function(func_id) && count)
1b986589
MKL
5428 return false;
5429
fd978bf7
JS
5430 /* We only support one arg being unreferenced at the moment,
5431 * which is sufficient for the helper functions we have right now.
5432 */
5433 return count <= 1;
5434}
5435
9436ef6e
LB
5436static bool check_btf_id_ok(const struct bpf_func_proto *fn)
5437{
5438 int i;
5439
1df8f55a 5440 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
9436ef6e
LB
5441 if (fn->arg_type[i] == ARG_PTR_TO_BTF_ID && !fn->arg_btf_id[i])
5442 return false;
5443
1df8f55a
MKL
5444 if (fn->arg_type[i] != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i])
5445 return false;
5446 }
5447
9436ef6e
LB
5448 return true;
5449}
5450
1b986589 5451static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
90133415
DB
5452{
5453 return check_raw_mode_ok(fn) &&
fd978bf7 5454 check_arg_pair_ok(fn) &&
9436ef6e 5455 check_btf_id_ok(fn) &&
1b986589 5456 check_refcount_ok(fn, func_id) ? 0 : -EINVAL;
435faee1
DB
5457}
5458
de8f3a83
DB
5459/* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
5460 * are now invalid, so turn them into unknown SCALAR_VALUE.
f1174f77 5461 */
f4d7e40a
AS
5462static void __clear_all_pkt_pointers(struct bpf_verifier_env *env,
5463 struct bpf_func_state *state)
969bf05e 5464{
58e2af8b 5465 struct bpf_reg_state *regs = state->regs, *reg;
969bf05e
AS
5466 int i;
5467
5468 for (i = 0; i < MAX_BPF_REG; i++)
de8f3a83 5469 if (reg_is_pkt_pointer_any(&regs[i]))
61bd5218 5470 mark_reg_unknown(env, regs, i);
969bf05e 5471
f3709f69
JS
5472 bpf_for_each_spilled_reg(i, state, reg) {
5473 if (!reg)
969bf05e 5474 continue;
de8f3a83 5475 if (reg_is_pkt_pointer_any(reg))
f54c7898 5476 __mark_reg_unknown(env, reg);
969bf05e
AS
5477 }
5478}
5479
f4d7e40a
AS
5480static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
5481{
5482 struct bpf_verifier_state *vstate = env->cur_state;
5483 int i;
5484
5485 for (i = 0; i <= vstate->curframe; i++)
5486 __clear_all_pkt_pointers(env, vstate->frame[i]);
5487}
5488
6d94e741
AS
5489enum {
5490 AT_PKT_END = -1,
5491 BEYOND_PKT_END = -2,
5492};
5493
5494static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
5495{
5496 struct bpf_func_state *state = vstate->frame[vstate->curframe];
5497 struct bpf_reg_state *reg = &state->regs[regn];
5498
5499 if (reg->type != PTR_TO_PACKET)
5500 /* PTR_TO_PACKET_META is not supported yet */
5501 return;
5502
5503 /* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
5504 * How far beyond pkt_end it goes is unknown.
5505 * if (!range_open) it's the case of pkt >= pkt_end
5506 * if (range_open) it's the case of pkt > pkt_end
5507 * hence this pointer is at least 1 byte bigger than pkt_end
5508 */
5509 if (range_open)
5510 reg->range = BEYOND_PKT_END;
5511 else
5512 reg->range = AT_PKT_END;
5513}
5514
fd978bf7 5515static void release_reg_references(struct bpf_verifier_env *env,
1b986589
MKL
5516 struct bpf_func_state *state,
5517 int ref_obj_id)
fd978bf7
JS
5518{
5519 struct bpf_reg_state *regs = state->regs, *reg;
5520 int i;
5521
5522 for (i = 0; i < MAX_BPF_REG; i++)
1b986589 5523 if (regs[i].ref_obj_id == ref_obj_id)
fd978bf7
JS
5524 mark_reg_unknown(env, regs, i);
5525
5526 bpf_for_each_spilled_reg(i, state, reg) {
5527 if (!reg)
5528 continue;
1b986589 5529 if (reg->ref_obj_id == ref_obj_id)
f54c7898 5530 __mark_reg_unknown(env, reg);
fd978bf7
JS
5531 }
5532}
5533
5534/* The pointer with the specified id has released its reference to kernel
5535 * resources. Identify all copies of the same pointer and clear the reference.
5536 */
5537static int release_reference(struct bpf_verifier_env *env,
1b986589 5538 int ref_obj_id)
fd978bf7
JS
5539{
5540 struct bpf_verifier_state *vstate = env->cur_state;
1b986589 5541 int err;
fd978bf7
JS
5542 int i;
5543
1b986589
MKL
5544 err = release_reference_state(cur_func(env), ref_obj_id);
5545 if (err)
5546 return err;
5547
fd978bf7 5548 for (i = 0; i <= vstate->curframe; i++)
1b986589 5549 release_reg_references(env, vstate->frame[i], ref_obj_id);
fd978bf7 5550
1b986589 5551 return 0;
fd978bf7
JS
5552}
5553
51c39bb1
AS
5554static void clear_caller_saved_regs(struct bpf_verifier_env *env,
5555 struct bpf_reg_state *regs)
5556{
5557 int i;
5558
5559 /* after the call registers r0 - r5 were scratched */
5560 for (i = 0; i < CALLER_SAVED_REGS; i++) {
5561 mark_reg_not_init(env, regs, caller_saved[i]);
5562 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
5563 }
5564}
5565
14351375
YS
5566typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
5567 struct bpf_func_state *caller,
5568 struct bpf_func_state *callee,
5569 int insn_idx);
5570
5571static int __check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
5572 int *insn_idx, int subprog,
5573 set_callee_state_fn set_callee_state_cb)
f4d7e40a
AS
5574{
5575 struct bpf_verifier_state *state = env->cur_state;
51c39bb1 5576 struct bpf_func_info_aux *func_info_aux;
f4d7e40a 5577 struct bpf_func_state *caller, *callee;
14351375 5578 int err;
51c39bb1 5579 bool is_global = false;
f4d7e40a 5580
aada9ce6 5581 if (state->curframe + 1 >= MAX_CALL_FRAMES) {
f4d7e40a 5582 verbose(env, "the call stack of %d frames is too deep\n",
aada9ce6 5583 state->curframe + 2);
f4d7e40a
AS
5584 return -E2BIG;
5585 }
5586
f4d7e40a
AS
5587 caller = state->frame[state->curframe];
5588 if (state->frame[state->curframe + 1]) {
5589 verbose(env, "verifier bug. Frame %d already allocated\n",
5590 state->curframe + 1);
5591 return -EFAULT;
5592 }
5593
51c39bb1
AS
5594 func_info_aux = env->prog->aux->func_info_aux;
5595 if (func_info_aux)
5596 is_global = func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
34747c41 5597 err = btf_check_subprog_arg_match(env, subprog, caller->regs);
51c39bb1
AS
5598 if (err == -EFAULT)
5599 return err;
5600 if (is_global) {
5601 if (err) {
5602 verbose(env, "Caller passes invalid args into func#%d\n",
5603 subprog);
5604 return err;
5605 } else {
5606 if (env->log.level & BPF_LOG_LEVEL)
5607 verbose(env,
5608 "Func#%d is global and valid. Skipping.\n",
5609 subprog);
5610 clear_caller_saved_regs(env, caller->regs);
5611
45159b27 5612 /* All global functions return a 64-bit SCALAR_VALUE */
51c39bb1 5613 mark_reg_unknown(env, caller->regs, BPF_REG_0);
45159b27 5614 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
51c39bb1
AS
5615
5616 /* continue with next insn after call */
5617 return 0;
5618 }
5619 }
5620
f4d7e40a
AS
5621 callee = kzalloc(sizeof(*callee), GFP_KERNEL);
5622 if (!callee)
5623 return -ENOMEM;
5624 state->frame[state->curframe + 1] = callee;
5625
5626 /* callee cannot access r0, r6 - r9 for reading and has to write
5627 * into its own stack before reading from it.
5628 * callee can read/write into caller's stack
5629 */
5630 init_func_state(env, callee,
5631 /* remember the callsite, it will be used by bpf_exit */
5632 *insn_idx /* callsite */,
5633 state->curframe + 1 /* frameno within this callchain */,
f910cefa 5634 subprog /* subprog number within this prog */);
f4d7e40a 5635
fd978bf7 5636 /* Transfer references to the callee */
c69431aa 5637 err = copy_reference_state(callee, caller);
fd978bf7
JS
5638 if (err)
5639 return err;
5640
14351375
YS
5641 err = set_callee_state_cb(env, caller, callee, *insn_idx);
5642 if (err)
5643 return err;
f4d7e40a 5644
51c39bb1 5645 clear_caller_saved_regs(env, caller->regs);
f4d7e40a
AS
5646
5647 /* only increment it after check_reg_arg() finished */
5648 state->curframe++;
5649
5650 /* and go analyze first insn of the callee */
14351375 5651 *insn_idx = env->subprog_info[subprog].start - 1;
f4d7e40a 5652
06ee7115 5653 if (env->log.level & BPF_LOG_LEVEL) {
f4d7e40a
AS
5654 verbose(env, "caller:\n");
5655 print_verifier_state(env, caller);
5656 verbose(env, "callee:\n");
5657 print_verifier_state(env, callee);
5658 }
5659 return 0;
5660}
5661
314ee05e
YS
5662int map_set_for_each_callback_args(struct bpf_verifier_env *env,
5663 struct bpf_func_state *caller,
5664 struct bpf_func_state *callee)
5665{
5666 /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
5667 * void *callback_ctx, u64 flags);
5668 * callback_fn(struct bpf_map *map, void *key, void *value,
5669 * void *callback_ctx);
5670 */
5671 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
5672
5673 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
5674 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
5675 callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
5676
5677 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
5678 __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
5679 callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
5680
5681 /* pointer to stack or null */
5682 callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
5683
5684 /* unused */
5685 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
5686 return 0;
5687}
5688
14351375
YS
5689static int set_callee_state(struct bpf_verifier_env *env,
5690 struct bpf_func_state *caller,
5691 struct bpf_func_state *callee, int insn_idx)
5692{
5693 int i;
5694
5695 /* copy r1 - r5 args that callee can access. The copy includes parent
5696 * pointers, which connects us up to the liveness chain
5697 */
5698 for (i = BPF_REG_1; i <= BPF_REG_5; i++)
5699 callee->regs[i] = caller->regs[i];
5700 return 0;
5701}
5702
5703static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
5704 int *insn_idx)
5705{
5706 int subprog, target_insn;
5707
5708 target_insn = *insn_idx + insn->imm + 1;
5709 subprog = find_subprog(env, target_insn);
5710 if (subprog < 0) {
5711 verbose(env, "verifier bug. No program starts at insn %d\n",
5712 target_insn);
5713 return -EFAULT;
5714 }
5715
5716 return __check_func_call(env, insn, insn_idx, subprog, set_callee_state);
5717}
5718
69c087ba
YS
5719static int set_map_elem_callback_state(struct bpf_verifier_env *env,
5720 struct bpf_func_state *caller,
5721 struct bpf_func_state *callee,
5722 int insn_idx)
5723{
5724 struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
5725 struct bpf_map *map;
5726 int err;
5727
5728 if (bpf_map_ptr_poisoned(insn_aux)) {
5729 verbose(env, "tail_call abusing map_ptr\n");
5730 return -EINVAL;
5731 }
5732
5733 map = BPF_MAP_PTR(insn_aux->map_ptr_state);
5734 if (!map->ops->map_set_for_each_callback_args ||
5735 !map->ops->map_for_each_callback) {
5736 verbose(env, "callback function not allowed for map\n");
5737 return -ENOTSUPP;
5738 }
5739
5740 err = map->ops->map_set_for_each_callback_args(env, caller, callee);
5741 if (err)
5742 return err;
5743
5744 callee->in_callback_fn = true;
5745 return 0;
5746}
5747
f4d7e40a
AS
5748static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
5749{
5750 struct bpf_verifier_state *state = env->cur_state;
5751 struct bpf_func_state *caller, *callee;
5752 struct bpf_reg_state *r0;
fd978bf7 5753 int err;
f4d7e40a
AS
5754
5755 callee = state->frame[state->curframe];
5756 r0 = &callee->regs[BPF_REG_0];
5757 if (r0->type == PTR_TO_STACK) {
5758 /* technically it's ok to return caller's stack pointer
5759 * (or caller's caller's pointer) back to the caller,
5760 * since these pointers are valid. Only current stack
5761 * pointer will be invalid as soon as function exits,
5762 * but let's be conservative
5763 */
5764 verbose(env, "cannot return stack pointer to the caller\n");
5765 return -EINVAL;
5766 }
5767
5768 state->curframe--;
5769 caller = state->frame[state->curframe];
69c087ba
YS
5770 if (callee->in_callback_fn) {
5771 /* enforce R0 return value range [0, 1]. */
5772 struct tnum range = tnum_range(0, 1);
5773
5774 if (r0->type != SCALAR_VALUE) {
5775 verbose(env, "R0 not a scalar value\n");
5776 return -EACCES;
5777 }
5778 if (!tnum_in(range, r0->var_off)) {
5779 verbose_invalid_scalar(env, r0, &range, "callback return", "R0");
5780 return -EINVAL;
5781 }
5782 } else {
5783 /* return to the caller whatever r0 had in the callee */
5784 caller->regs[BPF_REG_0] = *r0;
5785 }
f4d7e40a 5786
fd978bf7 5787 /* Transfer references to the caller */
c69431aa 5788 err = copy_reference_state(caller, callee);
fd978bf7
JS
5789 if (err)
5790 return err;
5791
f4d7e40a 5792 *insn_idx = callee->callsite + 1;
06ee7115 5793 if (env->log.level & BPF_LOG_LEVEL) {
f4d7e40a
AS
5794 verbose(env, "returning from callee:\n");
5795 print_verifier_state(env, callee);
5796 verbose(env, "to caller at %d:\n", *insn_idx);
5797 print_verifier_state(env, caller);
5798 }
5799 /* clear everything in the callee */
5800 free_func_state(callee);
5801 state->frame[state->curframe + 1] = NULL;
5802 return 0;
5803}
5804
849fa506
YS
5805static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
5806 int func_id,
5807 struct bpf_call_arg_meta *meta)
5808{
5809 struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
5810
5811 if (ret_type != RET_INTEGER ||
5812 (func_id != BPF_FUNC_get_stack &&
fd0b88f7 5813 func_id != BPF_FUNC_get_task_stack &&
47cc0ed5
DB
5814 func_id != BPF_FUNC_probe_read_str &&
5815 func_id != BPF_FUNC_probe_read_kernel_str &&
5816 func_id != BPF_FUNC_probe_read_user_str))
849fa506
YS
5817 return;
5818
10060503 5819 ret_reg->smax_value = meta->msize_max_value;
fa123ac0 5820 ret_reg->s32_max_value = meta->msize_max_value;
b0270958
AS
5821 ret_reg->smin_value = -MAX_ERRNO;
5822 ret_reg->s32_min_value = -MAX_ERRNO;
849fa506
YS
5823 __reg_deduce_bounds(ret_reg);
5824 __reg_bound_offset(ret_reg);
10060503 5825 __update_reg_bounds(ret_reg);
849fa506
YS
5826}
5827
c93552c4
DB
5828static int
5829record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
5830 int func_id, int insn_idx)
5831{
5832 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
591fe988 5833 struct bpf_map *map = meta->map_ptr;
c93552c4
DB
5834
5835 if (func_id != BPF_FUNC_tail_call &&
09772d92
DB
5836 func_id != BPF_FUNC_map_lookup_elem &&
5837 func_id != BPF_FUNC_map_update_elem &&
f1a2e44a
MV
5838 func_id != BPF_FUNC_map_delete_elem &&
5839 func_id != BPF_FUNC_map_push_elem &&
5840 func_id != BPF_FUNC_map_pop_elem &&
69c087ba 5841 func_id != BPF_FUNC_map_peek_elem &&
e6a4750f
BT
5842 func_id != BPF_FUNC_for_each_map_elem &&
5843 func_id != BPF_FUNC_redirect_map)
c93552c4 5844 return 0;
09772d92 5845
591fe988 5846 if (map == NULL) {
c93552c4
DB
5847 verbose(env, "kernel subsystem misconfigured verifier\n");
5848 return -EINVAL;
5849 }
5850
591fe988
DB
5851 /* In case of read-only, some additional restrictions
5852 * need to be applied in order to prevent altering the
5853 * state of the map from program side.
5854 */
5855 if ((map->map_flags & BPF_F_RDONLY_PROG) &&
5856 (func_id == BPF_FUNC_map_delete_elem ||
5857 func_id == BPF_FUNC_map_update_elem ||
5858 func_id == BPF_FUNC_map_push_elem ||
5859 func_id == BPF_FUNC_map_pop_elem)) {
5860 verbose(env, "write into map forbidden\n");
5861 return -EACCES;
5862 }
5863
d2e4c1e6 5864 if (!BPF_MAP_PTR(aux->map_ptr_state))
c93552c4 5865 bpf_map_ptr_store(aux, meta->map_ptr,
2c78ee89 5866 !meta->map_ptr->bypass_spec_v1);
d2e4c1e6 5867 else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
c93552c4 5868 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
2c78ee89 5869 !meta->map_ptr->bypass_spec_v1);
c93552c4
DB
5870 return 0;
5871}
5872
d2e4c1e6
DB
5873static int
5874record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
5875 int func_id, int insn_idx)
5876{
5877 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
5878 struct bpf_reg_state *regs = cur_regs(env), *reg;
5879 struct bpf_map *map = meta->map_ptr;
5880 struct tnum range;
5881 u64 val;
cc52d914 5882 int err;
d2e4c1e6
DB
5883
5884 if (func_id != BPF_FUNC_tail_call)
5885 return 0;
5886 if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
5887 verbose(env, "kernel subsystem misconfigured verifier\n");
5888 return -EINVAL;
5889 }
5890
5891 range = tnum_range(0, map->max_entries - 1);
5892 reg = &regs[BPF_REG_3];
5893
5894 if (!register_is_const(reg) || !tnum_in(range, reg->var_off)) {
5895 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
5896 return 0;
5897 }
5898
cc52d914
DB
5899 err = mark_chain_precision(env, BPF_REG_3);
5900 if (err)
5901 return err;
5902
d2e4c1e6
DB
5903 val = reg->var_off.value;
5904 if (bpf_map_key_unseen(aux))
5905 bpf_map_key_store(aux, val);
5906 else if (!bpf_map_key_poisoned(aux) &&
5907 bpf_map_key_immediate(aux) != val)
5908 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
5909 return 0;
5910}
5911
fd978bf7
JS
5912static int check_reference_leak(struct bpf_verifier_env *env)
5913{
5914 struct bpf_func_state *state = cur_func(env);
5915 int i;
5916
5917 for (i = 0; i < state->acquired_refs; i++) {
5918 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
5919 state->refs[i].id, state->refs[i].insn_idx);
5920 }
5921 return state->acquired_refs ? -EINVAL : 0;
5922}
5923
7b15523a
FR
5924static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
5925 struct bpf_reg_state *regs)
5926{
5927 struct bpf_reg_state *fmt_reg = &regs[BPF_REG_3];
5928 struct bpf_reg_state *data_len_reg = &regs[BPF_REG_5];
5929 struct bpf_map *fmt_map = fmt_reg->map_ptr;
5930 int err, fmt_map_off, num_args;
5931 u64 fmt_addr;
5932 char *fmt;
5933
5934 /* data must be an array of u64 */
5935 if (data_len_reg->var_off.value % 8)
5936 return -EINVAL;
5937 num_args = data_len_reg->var_off.value / 8;
5938
5939 /* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
5940 * and map_direct_value_addr is set.
5941 */
5942 fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
5943 err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
5944 fmt_map_off);
8e8ee109
FR
5945 if (err) {
5946 verbose(env, "verifier bug\n");
5947 return -EFAULT;
5948 }
7b15523a
FR
5949 fmt = (char *)(long)fmt_addr + fmt_map_off;
5950
5951 /* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
5952 * can focus on validating the format specifiers.
5953 */
48cac3f4 5954 err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, NULL, num_args);
7b15523a
FR
5955 if (err < 0)
5956 verbose(env, "Invalid format string\n");
5957
5958 return err;
5959}
5960
69c087ba
YS
5961static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
5962 int *insn_idx_p)
17a52670 5963{
17a52670 5964 const struct bpf_func_proto *fn = NULL;
638f5b90 5965 struct bpf_reg_state *regs;
33ff9823 5966 struct bpf_call_arg_meta meta;
69c087ba 5967 int insn_idx = *insn_idx_p;
969bf05e 5968 bool changes_data;
69c087ba 5969 int i, err, func_id;
17a52670
AS
5970
5971 /* find function prototype */
69c087ba 5972 func_id = insn->imm;
17a52670 5973 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
61bd5218
JK
5974 verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
5975 func_id);
17a52670
AS
5976 return -EINVAL;
5977 }
5978
00176a34 5979 if (env->ops->get_func_proto)
5e43f899 5980 fn = env->ops->get_func_proto(func_id, env->prog);
17a52670 5981 if (!fn) {
61bd5218
JK
5982 verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
5983 func_id);
17a52670
AS
5984 return -EINVAL;
5985 }
5986
5987 /* eBPF programs must be GPL compatible to use GPL-ed functions */
24701ece 5988 if (!env->prog->gpl_compatible && fn->gpl_only) {
3fe2867c 5989 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
17a52670
AS
5990 return -EINVAL;
5991 }
5992
eae2e83e
JO
5993 if (fn->allowed && !fn->allowed(env->prog)) {
5994 verbose(env, "helper call is not allowed in probe\n");
5995 return -EINVAL;
5996 }
5997
04514d13 5998 /* With LD_ABS/IND some JITs save/restore skb from r1. */
17bedab2 5999 changes_data = bpf_helper_changes_pkt_data(fn->func);
04514d13
DB
6000 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
6001 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
6002 func_id_name(func_id), func_id);
6003 return -EINVAL;
6004 }
969bf05e 6005
33ff9823 6006 memset(&meta, 0, sizeof(meta));
36bbef52 6007 meta.pkt_access = fn->pkt_access;
33ff9823 6008
1b986589 6009 err = check_func_proto(fn, func_id);
435faee1 6010 if (err) {
61bd5218 6011 verbose(env, "kernel subsystem misconfigured func %s#%d\n",
ebb676da 6012 func_id_name(func_id), func_id);
435faee1
DB
6013 return err;
6014 }
6015
d83525ca 6016 meta.func_id = func_id;
17a52670 6017 /* check args */
523a4cf4 6018 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
af7ec138 6019 err = check_func_arg(env, i, &meta, fn);
a7658e1a
AS
6020 if (err)
6021 return err;
6022 }
17a52670 6023
c93552c4
DB
6024 err = record_func_map(env, &meta, func_id, insn_idx);
6025 if (err)
6026 return err;
6027
d2e4c1e6
DB
6028 err = record_func_key(env, &meta, func_id, insn_idx);
6029 if (err)
6030 return err;
6031
435faee1
DB
6032 /* Mark slots with STACK_MISC in case of raw mode, stack offset
6033 * is inferred from register state.
6034 */
6035 for (i = 0; i < meta.access_size; i++) {
ca369602
DB
6036 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
6037 BPF_WRITE, -1, false);
435faee1
DB
6038 if (err)
6039 return err;
6040 }
6041
fd978bf7
JS
6042 if (func_id == BPF_FUNC_tail_call) {
6043 err = check_reference_leak(env);
6044 if (err) {
6045 verbose(env, "tail_call would lead to reference leak\n");
6046 return err;
6047 }
6048 } else if (is_release_function(func_id)) {
1b986589 6049 err = release_reference(env, meta.ref_obj_id);
46f8bc92
MKL
6050 if (err) {
6051 verbose(env, "func %s#%d reference has not been acquired before\n",
6052 func_id_name(func_id), func_id);
fd978bf7 6053 return err;
46f8bc92 6054 }
fd978bf7
JS
6055 }
6056
638f5b90 6057 regs = cur_regs(env);
cd339431
RG
6058
6059 /* check that flags argument in get_local_storage(map, flags) is 0,
6060 * this is required because get_local_storage() can't return an error.
6061 */
6062 if (func_id == BPF_FUNC_get_local_storage &&
6063 !register_is_null(&regs[BPF_REG_2])) {
6064 verbose(env, "get_local_storage() doesn't support non-zero flags\n");
6065 return -EINVAL;
6066 }
6067
69c087ba
YS
6068 if (func_id == BPF_FUNC_for_each_map_elem) {
6069 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
6070 set_map_elem_callback_state);
6071 if (err < 0)
6072 return -EINVAL;
6073 }
6074
7b15523a
FR
6075 if (func_id == BPF_FUNC_snprintf) {
6076 err = check_bpf_snprintf_call(env, regs);
6077 if (err < 0)
6078 return err;
6079 }
6080
17a52670 6081 /* reset caller saved regs */
dc503a8a 6082 for (i = 0; i < CALLER_SAVED_REGS; i++) {
61bd5218 6083 mark_reg_not_init(env, regs, caller_saved[i]);
dc503a8a
EC
6084 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
6085 }
17a52670 6086
5327ed3d
JW
6087 /* helper call returns 64-bit value. */
6088 regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
6089
dc503a8a 6090 /* update return register (already marked as written above) */
17a52670 6091 if (fn->ret_type == RET_INTEGER) {
f1174f77 6092 /* sets type to SCALAR_VALUE */
61bd5218 6093 mark_reg_unknown(env, regs, BPF_REG_0);
17a52670
AS
6094 } else if (fn->ret_type == RET_VOID) {
6095 regs[BPF_REG_0].type = NOT_INIT;
3e6a4b3e
RG
6096 } else if (fn->ret_type == RET_PTR_TO_MAP_VALUE_OR_NULL ||
6097 fn->ret_type == RET_PTR_TO_MAP_VALUE) {
f1174f77 6098 /* There is no offset yet applied, variable or fixed */
61bd5218 6099 mark_reg_known_zero(env, regs, BPF_REG_0);
17a52670
AS
6100 /* remember map_ptr, so that check_map_access()
6101 * can check 'value_size' boundary of memory access
6102 * to map element returned from bpf_map_lookup_elem()
6103 */
33ff9823 6104 if (meta.map_ptr == NULL) {
61bd5218
JK
6105 verbose(env,
6106 "kernel subsystem misconfigured verifier\n");
17a52670
AS
6107 return -EINVAL;
6108 }
33ff9823 6109 regs[BPF_REG_0].map_ptr = meta.map_ptr;
4d31f301
DB
6110 if (fn->ret_type == RET_PTR_TO_MAP_VALUE) {
6111 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE;
e16d2f1a
AS
6112 if (map_value_has_spin_lock(meta.map_ptr))
6113 regs[BPF_REG_0].id = ++env->id_gen;
4d31f301
DB
6114 } else {
6115 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE_OR_NULL;
4d31f301 6116 }
c64b7983
JS
6117 } else if (fn->ret_type == RET_PTR_TO_SOCKET_OR_NULL) {
6118 mark_reg_known_zero(env, regs, BPF_REG_0);
6119 regs[BPF_REG_0].type = PTR_TO_SOCKET_OR_NULL;
85a51f8c
LB
6120 } else if (fn->ret_type == RET_PTR_TO_SOCK_COMMON_OR_NULL) {
6121 mark_reg_known_zero(env, regs, BPF_REG_0);
6122 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON_OR_NULL;
655a51e5
MKL
6123 } else if (fn->ret_type == RET_PTR_TO_TCP_SOCK_OR_NULL) {
6124 mark_reg_known_zero(env, regs, BPF_REG_0);
6125 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK_OR_NULL;
457f4436
AN
6126 } else if (fn->ret_type == RET_PTR_TO_ALLOC_MEM_OR_NULL) {
6127 mark_reg_known_zero(env, regs, BPF_REG_0);
6128 regs[BPF_REG_0].type = PTR_TO_MEM_OR_NULL;
457f4436 6129 regs[BPF_REG_0].mem_size = meta.mem_size;
63d9b80d
HL
6130 } else if (fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID_OR_NULL ||
6131 fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID) {
eaa6bcb7
HL
6132 const struct btf_type *t;
6133
6134 mark_reg_known_zero(env, regs, BPF_REG_0);
22dc4a0f 6135 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
eaa6bcb7
HL
6136 if (!btf_type_is_struct(t)) {
6137 u32 tsize;
6138 const struct btf_type *ret;
6139 const char *tname;
6140
6141 /* resolve the type size of ksym. */
22dc4a0f 6142 ret = btf_resolve_size(meta.ret_btf, t, &tsize);
eaa6bcb7 6143 if (IS_ERR(ret)) {
22dc4a0f 6144 tname = btf_name_by_offset(meta.ret_btf, t->name_off);
eaa6bcb7
HL
6145 verbose(env, "unable to resolve the size of type '%s': %ld\n",
6146 tname, PTR_ERR(ret));
6147 return -EINVAL;
6148 }
63d9b80d
HL
6149 regs[BPF_REG_0].type =
6150 fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID ?
6151 PTR_TO_MEM : PTR_TO_MEM_OR_NULL;
eaa6bcb7
HL
6152 regs[BPF_REG_0].mem_size = tsize;
6153 } else {
63d9b80d
HL
6154 regs[BPF_REG_0].type =
6155 fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID ?
6156 PTR_TO_BTF_ID : PTR_TO_BTF_ID_OR_NULL;
22dc4a0f 6157 regs[BPF_REG_0].btf = meta.ret_btf;
eaa6bcb7
HL
6158 regs[BPF_REG_0].btf_id = meta.ret_btf_id;
6159 }
3ca1032a
KS
6160 } else if (fn->ret_type == RET_PTR_TO_BTF_ID_OR_NULL ||
6161 fn->ret_type == RET_PTR_TO_BTF_ID) {
af7ec138
YS
6162 int ret_btf_id;
6163
6164 mark_reg_known_zero(env, regs, BPF_REG_0);
3ca1032a
KS
6165 regs[BPF_REG_0].type = fn->ret_type == RET_PTR_TO_BTF_ID ?
6166 PTR_TO_BTF_ID :
6167 PTR_TO_BTF_ID_OR_NULL;
af7ec138
YS
6168 ret_btf_id = *fn->ret_btf_id;
6169 if (ret_btf_id == 0) {
6170 verbose(env, "invalid return type %d of func %s#%d\n",
6171 fn->ret_type, func_id_name(func_id), func_id);
6172 return -EINVAL;
6173 }
22dc4a0f
AN
6174 /* current BPF helper definitions are only coming from
6175 * built-in code with type IDs from vmlinux BTF
6176 */
6177 regs[BPF_REG_0].btf = btf_vmlinux;
af7ec138 6178 regs[BPF_REG_0].btf_id = ret_btf_id;
17a52670 6179 } else {
61bd5218 6180 verbose(env, "unknown return type %d of func %s#%d\n",
ebb676da 6181 fn->ret_type, func_id_name(func_id), func_id);
17a52670
AS
6182 return -EINVAL;
6183 }
04fd61ab 6184
93c230e3
MKL
6185 if (reg_type_may_be_null(regs[BPF_REG_0].type))
6186 regs[BPF_REG_0].id = ++env->id_gen;
6187
0f3adc28 6188 if (is_ptr_cast_function(func_id)) {
1b986589
MKL
6189 /* For release_reference() */
6190 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
64d85290 6191 } else if (is_acquire_function(func_id, meta.map_ptr)) {
0f3adc28
LB
6192 int id = acquire_reference_state(env, insn_idx);
6193
6194 if (id < 0)
6195 return id;
6196 /* For mark_ptr_or_null_reg() */
6197 regs[BPF_REG_0].id = id;
6198 /* For release_reference() */
6199 regs[BPF_REG_0].ref_obj_id = id;
6200 }
1b986589 6201
849fa506
YS
6202 do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
6203
61bd5218 6204 err = check_map_func_compatibility(env, meta.map_ptr, func_id);
35578d79
KX
6205 if (err)
6206 return err;
04fd61ab 6207
fa28dcb8
SL
6208 if ((func_id == BPF_FUNC_get_stack ||
6209 func_id == BPF_FUNC_get_task_stack) &&
6210 !env->prog->has_callchain_buf) {
c195651e
YS
6211 const char *err_str;
6212
6213#ifdef CONFIG_PERF_EVENTS
6214 err = get_callchain_buffers(sysctl_perf_event_max_stack);
6215 err_str = "cannot get callchain buffer for func %s#%d\n";
6216#else
6217 err = -ENOTSUPP;
6218 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
6219#endif
6220 if (err) {
6221 verbose(env, err_str, func_id_name(func_id), func_id);
6222 return err;
6223 }
6224
6225 env->prog->has_callchain_buf = true;
6226 }
6227
5d99cb2c
SL
6228 if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
6229 env->prog->call_get_stack = true;
6230
969bf05e
AS
6231 if (changes_data)
6232 clear_all_pkt_pointers(env);
6233 return 0;
6234}
6235
e6ac2450
MKL
6236/* mark_btf_func_reg_size() is used when the reg size is determined by
6237 * the BTF func_proto's return value size and argument.
6238 */
6239static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
6240 size_t reg_size)
6241{
6242 struct bpf_reg_state *reg = &cur_regs(env)[regno];
6243
6244 if (regno == BPF_REG_0) {
6245 /* Function return value */
6246 reg->live |= REG_LIVE_WRITTEN;
6247 reg->subreg_def = reg_size == sizeof(u64) ?
6248 DEF_NOT_SUBREG : env->insn_idx + 1;
6249 } else {
6250 /* Function argument */
6251 if (reg_size == sizeof(u64)) {
6252 mark_insn_zext(env, reg);
6253 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
6254 } else {
6255 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
6256 }
6257 }
6258}
6259
6260static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn)
6261{
6262 const struct btf_type *t, *func, *func_proto, *ptr_type;
6263 struct bpf_reg_state *regs = cur_regs(env);
6264 const char *func_name, *ptr_type_name;
6265 u32 i, nargs, func_id, ptr_type_id;
6266 const struct btf_param *args;
6267 int err;
6268
6269 func_id = insn->imm;
6270 func = btf_type_by_id(btf_vmlinux, func_id);
6271 func_name = btf_name_by_offset(btf_vmlinux, func->name_off);
6272 func_proto = btf_type_by_id(btf_vmlinux, func->type);
6273
6274 if (!env->ops->check_kfunc_call ||
6275 !env->ops->check_kfunc_call(func_id)) {
6276 verbose(env, "calling kernel function %s is not allowed\n",
6277 func_name);
6278 return -EACCES;
6279 }
6280
6281 /* Check the arguments */
6282 err = btf_check_kfunc_arg_match(env, btf_vmlinux, func_id, regs);
6283 if (err)
6284 return err;
6285
6286 for (i = 0; i < CALLER_SAVED_REGS; i++)
6287 mark_reg_not_init(env, regs, caller_saved[i]);
6288
6289 /* Check return type */
6290 t = btf_type_skip_modifiers(btf_vmlinux, func_proto->type, NULL);
6291 if (btf_type_is_scalar(t)) {
6292 mark_reg_unknown(env, regs, BPF_REG_0);
6293 mark_btf_func_reg_size(env, BPF_REG_0, t->size);
6294 } else if (btf_type_is_ptr(t)) {
6295 ptr_type = btf_type_skip_modifiers(btf_vmlinux, t->type,
6296 &ptr_type_id);
6297 if (!btf_type_is_struct(ptr_type)) {
6298 ptr_type_name = btf_name_by_offset(btf_vmlinux,
6299 ptr_type->name_off);
6300 verbose(env, "kernel function %s returns pointer type %s %s is not supported\n",
6301 func_name, btf_type_str(ptr_type),
6302 ptr_type_name);
6303 return -EINVAL;
6304 }
6305 mark_reg_known_zero(env, regs, BPF_REG_0);
6306 regs[BPF_REG_0].btf = btf_vmlinux;
6307 regs[BPF_REG_0].type = PTR_TO_BTF_ID;
6308 regs[BPF_REG_0].btf_id = ptr_type_id;
6309 mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
6310 } /* else { add_kfunc_call() ensures it is btf_type_is_void(t) } */
6311
6312 nargs = btf_type_vlen(func_proto);
6313 args = (const struct btf_param *)(func_proto + 1);
6314 for (i = 0; i < nargs; i++) {
6315 u32 regno = i + 1;
6316
6317 t = btf_type_skip_modifiers(btf_vmlinux, args[i].type, NULL);
6318 if (btf_type_is_ptr(t))
6319 mark_btf_func_reg_size(env, regno, sizeof(void *));
6320 else
6321 /* scalar. ensured by btf_check_kfunc_arg_match() */
6322 mark_btf_func_reg_size(env, regno, t->size);
6323 }
6324
6325 return 0;
6326}
6327
b03c9f9f
EC
6328static bool signed_add_overflows(s64 a, s64 b)
6329{
6330 /* Do the add in u64, where overflow is well-defined */
6331 s64 res = (s64)((u64)a + (u64)b);
6332
6333 if (b < 0)
6334 return res > a;
6335 return res < a;
6336}
6337
bc895e8b 6338static bool signed_add32_overflows(s32 a, s32 b)
3f50f132
JF
6339{
6340 /* Do the add in u32, where overflow is well-defined */
6341 s32 res = (s32)((u32)a + (u32)b);
6342
6343 if (b < 0)
6344 return res > a;
6345 return res < a;
6346}
6347
bc895e8b 6348static bool signed_sub_overflows(s64 a, s64 b)
b03c9f9f
EC
6349{
6350 /* Do the sub in u64, where overflow is well-defined */
6351 s64 res = (s64)((u64)a - (u64)b);
6352
6353 if (b < 0)
6354 return res < a;
6355 return res > a;
969bf05e
AS
6356}
6357
3f50f132
JF
6358static bool signed_sub32_overflows(s32 a, s32 b)
6359{
bc895e8b 6360 /* Do the sub in u32, where overflow is well-defined */
3f50f132
JF
6361 s32 res = (s32)((u32)a - (u32)b);
6362
6363 if (b < 0)
6364 return res < a;
6365 return res > a;
6366}
6367
bb7f0f98
AS
6368static bool check_reg_sane_offset(struct bpf_verifier_env *env,
6369 const struct bpf_reg_state *reg,
6370 enum bpf_reg_type type)
6371{
6372 bool known = tnum_is_const(reg->var_off);
6373 s64 val = reg->var_off.value;
6374 s64 smin = reg->smin_value;
6375
6376 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
6377 verbose(env, "math between %s pointer and %lld is not allowed\n",
6378 reg_type_str[type], val);
6379 return false;
6380 }
6381
6382 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
6383 verbose(env, "%s pointer offset %d is not allowed\n",
6384 reg_type_str[type], reg->off);
6385 return false;
6386 }
6387
6388 if (smin == S64_MIN) {
6389 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
6390 reg_type_str[type]);
6391 return false;
6392 }
6393
6394 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
6395 verbose(env, "value %lld makes %s pointer be out of bounds\n",
6396 smin, reg_type_str[type]);
6397 return false;
6398 }
6399
6400 return true;
6401}
6402
979d63d5
DB
6403static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
6404{
6405 return &env->insn_aux_data[env->insn_idx];
6406}
6407
a6aaece0
DB
6408enum {
6409 REASON_BOUNDS = -1,
6410 REASON_TYPE = -2,
6411 REASON_PATHS = -3,
6412 REASON_LIMIT = -4,
6413 REASON_STACK = -5,
6414};
6415
979d63d5 6416static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
24c109bb 6417 const struct bpf_reg_state *off_reg,
b658bbb8 6418 u32 *alu_limit, u8 opcode)
979d63d5 6419{
24c109bb 6420 bool off_is_neg = off_reg->smin_value < 0;
979d63d5
DB
6421 bool mask_to_left = (opcode == BPF_ADD && off_is_neg) ||
6422 (opcode == BPF_SUB && !off_is_neg);
7fedb63a 6423 u32 max = 0, ptr_limit = 0;
979d63d5 6424
24c109bb
DB
6425 if (!tnum_is_const(off_reg->var_off) &&
6426 (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
a6aaece0 6427 return REASON_BOUNDS;
979d63d5
DB
6428
6429 switch (ptr_reg->type) {
6430 case PTR_TO_STACK:
1b1597e6 6431 /* Offset 0 is out-of-bounds, but acceptable start for the
7fedb63a
DB
6432 * left direction, see BPF_REG_FP. Also, unknown scalar
6433 * offset where we would need to deal with min/max bounds is
6434 * currently prohibited for unprivileged.
1b1597e6
PK
6435 */
6436 max = MAX_BPF_STACK + mask_to_left;
7fedb63a 6437 ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
b658bbb8 6438 break;
979d63d5 6439 case PTR_TO_MAP_VALUE:
1b1597e6 6440 max = ptr_reg->map_ptr->value_size;
7fedb63a
DB
6441 ptr_limit = (mask_to_left ?
6442 ptr_reg->smin_value :
6443 ptr_reg->umax_value) + ptr_reg->off;
b658bbb8 6444 break;
979d63d5 6445 default:
a6aaece0 6446 return REASON_TYPE;
979d63d5 6447 }
b658bbb8
DB
6448
6449 if (ptr_limit >= max)
a6aaece0 6450 return REASON_LIMIT;
b658bbb8
DB
6451 *alu_limit = ptr_limit;
6452 return 0;
979d63d5
DB
6453}
6454
d3bd7413
DB
6455static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
6456 const struct bpf_insn *insn)
6457{
2c78ee89 6458 return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
d3bd7413
DB
6459}
6460
6461static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
6462 u32 alu_state, u32 alu_limit)
6463{
6464 /* If we arrived here from different branches with different
6465 * state or limits to sanitize, then this won't work.
6466 */
6467 if (aux->alu_state &&
6468 (aux->alu_state != alu_state ||
6469 aux->alu_limit != alu_limit))
a6aaece0 6470 return REASON_PATHS;
d3bd7413 6471
e6ac5933 6472 /* Corresponding fixup done in do_misc_fixups(). */
d3bd7413
DB
6473 aux->alu_state = alu_state;
6474 aux->alu_limit = alu_limit;
6475 return 0;
6476}
6477
6478static int sanitize_val_alu(struct bpf_verifier_env *env,
6479 struct bpf_insn *insn)
6480{
6481 struct bpf_insn_aux_data *aux = cur_aux(env);
6482
6483 if (can_skip_alu_sanitation(env, insn))
6484 return 0;
6485
6486 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
6487}
6488
f5288193
DB
6489static bool sanitize_needed(u8 opcode)
6490{
6491 return opcode == BPF_ADD || opcode == BPF_SUB;
6492}
6493
979d63d5
DB
6494static int sanitize_ptr_alu(struct bpf_verifier_env *env,
6495 struct bpf_insn *insn,
6496 const struct bpf_reg_state *ptr_reg,
6f55b2f2 6497 const struct bpf_reg_state *off_reg,
979d63d5 6498 struct bpf_reg_state *dst_reg,
7fedb63a
DB
6499 struct bpf_insn_aux_data *tmp_aux,
6500 const bool commit_window)
979d63d5 6501{
7fedb63a 6502 struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : tmp_aux;
979d63d5 6503 struct bpf_verifier_state *vstate = env->cur_state;
801c6058 6504 bool off_is_imm = tnum_is_const(off_reg->var_off);
6f55b2f2 6505 bool off_is_neg = off_reg->smin_value < 0;
979d63d5
DB
6506 bool ptr_is_dst_reg = ptr_reg == dst_reg;
6507 u8 opcode = BPF_OP(insn->code);
6508 u32 alu_state, alu_limit;
6509 struct bpf_reg_state tmp;
6510 bool ret;
f232326f 6511 int err;
979d63d5 6512
d3bd7413 6513 if (can_skip_alu_sanitation(env, insn))
979d63d5
DB
6514 return 0;
6515
6516 /* We already marked aux for masking from non-speculative
6517 * paths, thus we got here in the first place. We only care
6518 * to explore bad access from here.
6519 */
6520 if (vstate->speculative)
6521 goto do_sim;
6522
24c109bb 6523 err = retrieve_ptr_limit(ptr_reg, off_reg, &alu_limit, opcode);
f232326f
PK
6524 if (err < 0)
6525 return err;
6526
7fedb63a
DB
6527 if (commit_window) {
6528 /* In commit phase we narrow the masking window based on
6529 * the observed pointer move after the simulated operation.
6530 */
6531 alu_state = tmp_aux->alu_state;
6532 alu_limit = abs(tmp_aux->alu_limit - alu_limit);
6533 } else {
6534 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
801c6058 6535 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
7fedb63a
DB
6536 alu_state |= ptr_is_dst_reg ?
6537 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
6538 }
6539
f232326f
PK
6540 err = update_alu_sanitation_state(aux, alu_state, alu_limit);
6541 if (err < 0)
6542 return err;
979d63d5 6543do_sim:
7fedb63a
DB
6544 /* If we're in commit phase, we're done here given we already
6545 * pushed the truncated dst_reg into the speculative verification
6546 * stack.
6547 */
6548 if (commit_window)
6549 return 0;
6550
979d63d5
DB
6551 /* Simulate and find potential out-of-bounds access under
6552 * speculative execution from truncation as a result of
6553 * masking when off was not within expected range. If off
6554 * sits in dst, then we temporarily need to move ptr there
6555 * to simulate dst (== 0) +/-= ptr. Needed, for example,
6556 * for cases where we use K-based arithmetic in one direction
6557 * and truncated reg-based in the other in order to explore
6558 * bad access.
6559 */
6560 if (!ptr_is_dst_reg) {
6561 tmp = *dst_reg;
6562 *dst_reg = *ptr_reg;
6563 }
6564 ret = push_stack(env, env->insn_idx + 1, env->insn_idx, true);
0803278b 6565 if (!ptr_is_dst_reg && ret)
979d63d5 6566 *dst_reg = tmp;
a6aaece0
DB
6567 return !ret ? REASON_STACK : 0;
6568}
6569
6570static int sanitize_err(struct bpf_verifier_env *env,
6571 const struct bpf_insn *insn, int reason,
6572 const struct bpf_reg_state *off_reg,
6573 const struct bpf_reg_state *dst_reg)
6574{
6575 static const char *err = "pointer arithmetic with it prohibited for !root";
6576 const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
6577 u32 dst = insn->dst_reg, src = insn->src_reg;
6578
6579 switch (reason) {
6580 case REASON_BOUNDS:
6581 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
6582 off_reg == dst_reg ? dst : src, err);
6583 break;
6584 case REASON_TYPE:
6585 verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
6586 off_reg == dst_reg ? src : dst, err);
6587 break;
6588 case REASON_PATHS:
6589 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
6590 dst, op, err);
6591 break;
6592 case REASON_LIMIT:
6593 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
6594 dst, op, err);
6595 break;
6596 case REASON_STACK:
6597 verbose(env, "R%d could not be pushed for speculative verification, %s\n",
6598 dst, err);
6599 break;
6600 default:
6601 verbose(env, "verifier internal error: unknown reason (%d)\n",
6602 reason);
6603 break;
6604 }
6605
6606 return -EACCES;
979d63d5
DB
6607}
6608
01f810ac
AM
6609/* check that stack access falls within stack limits and that 'reg' doesn't
6610 * have a variable offset.
6611 *
6612 * Variable offset is prohibited for unprivileged mode for simplicity since it
6613 * requires corresponding support in Spectre masking for stack ALU. See also
6614 * retrieve_ptr_limit().
6615 *
6616 *
6617 * 'off' includes 'reg->off'.
6618 */
6619static int check_stack_access_for_ptr_arithmetic(
6620 struct bpf_verifier_env *env,
6621 int regno,
6622 const struct bpf_reg_state *reg,
6623 int off)
6624{
6625 if (!tnum_is_const(reg->var_off)) {
6626 char tn_buf[48];
6627
6628 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6629 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
6630 regno, tn_buf, off);
6631 return -EACCES;
6632 }
6633
6634 if (off >= 0 || off < -MAX_BPF_STACK) {
6635 verbose(env, "R%d stack pointer arithmetic goes out of range, "
6636 "prohibited for !root; off=%d\n", regno, off);
6637 return -EACCES;
6638 }
6639
6640 return 0;
6641}
6642
073815b7
DB
6643static int sanitize_check_bounds(struct bpf_verifier_env *env,
6644 const struct bpf_insn *insn,
6645 const struct bpf_reg_state *dst_reg)
6646{
6647 u32 dst = insn->dst_reg;
6648
6649 /* For unprivileged we require that resulting offset must be in bounds
6650 * in order to be able to sanitize access later on.
6651 */
6652 if (env->bypass_spec_v1)
6653 return 0;
6654
6655 switch (dst_reg->type) {
6656 case PTR_TO_STACK:
6657 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
6658 dst_reg->off + dst_reg->var_off.value))
6659 return -EACCES;
6660 break;
6661 case PTR_TO_MAP_VALUE:
6662 if (check_map_access(env, dst, dst_reg->off, 1, false)) {
6663 verbose(env, "R%d pointer arithmetic of map value goes out of range, "
6664 "prohibited for !root\n", dst);
6665 return -EACCES;
6666 }
6667 break;
6668 default:
6669 break;
6670 }
6671
6672 return 0;
6673}
01f810ac 6674
f1174f77 6675/* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
f1174f77
EC
6676 * Caller should also handle BPF_MOV case separately.
6677 * If we return -EACCES, caller may want to try again treating pointer as a
6678 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks.
6679 */
6680static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
6681 struct bpf_insn *insn,
6682 const struct bpf_reg_state *ptr_reg,
6683 const struct bpf_reg_state *off_reg)
969bf05e 6684{
f4d7e40a
AS
6685 struct bpf_verifier_state *vstate = env->cur_state;
6686 struct bpf_func_state *state = vstate->frame[vstate->curframe];
6687 struct bpf_reg_state *regs = state->regs, *dst_reg;
f1174f77 6688 bool known = tnum_is_const(off_reg->var_off);
b03c9f9f
EC
6689 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
6690 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
6691 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
6692 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
7fedb63a 6693 struct bpf_insn_aux_data tmp_aux = {};
969bf05e 6694 u8 opcode = BPF_OP(insn->code);
24c109bb 6695 u32 dst = insn->dst_reg;
979d63d5 6696 int ret;
969bf05e 6697
f1174f77 6698 dst_reg = &regs[dst];
969bf05e 6699
6f16101e
DB
6700 if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
6701 smin_val > smax_val || umin_val > umax_val) {
6702 /* Taint dst register if offset had invalid bounds derived from
6703 * e.g. dead branches.
6704 */
f54c7898 6705 __mark_reg_unknown(env, dst_reg);
6f16101e 6706 return 0;
f1174f77
EC
6707 }
6708
6709 if (BPF_CLASS(insn->code) != BPF_ALU64) {
6710 /* 32-bit ALU ops on pointers produce (meaningless) scalars */
6c693541
YS
6711 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
6712 __mark_reg_unknown(env, dst_reg);
6713 return 0;
6714 }
6715
82abbf8d
AS
6716 verbose(env,
6717 "R%d 32-bit pointer arithmetic prohibited\n",
6718 dst);
f1174f77 6719 return -EACCES;
969bf05e
AS
6720 }
6721
aad2eeaf
JS
6722 switch (ptr_reg->type) {
6723 case PTR_TO_MAP_VALUE_OR_NULL:
6724 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
6725 dst, reg_type_str[ptr_reg->type]);
f1174f77 6726 return -EACCES;
aad2eeaf 6727 case CONST_PTR_TO_MAP:
7c696732
YS
6728 /* smin_val represents the known value */
6729 if (known && smin_val == 0 && opcode == BPF_ADD)
6730 break;
8731745e 6731 fallthrough;
aad2eeaf 6732 case PTR_TO_PACKET_END:
c64b7983
JS
6733 case PTR_TO_SOCKET:
6734 case PTR_TO_SOCKET_OR_NULL:
46f8bc92
MKL
6735 case PTR_TO_SOCK_COMMON:
6736 case PTR_TO_SOCK_COMMON_OR_NULL:
655a51e5
MKL
6737 case PTR_TO_TCP_SOCK:
6738 case PTR_TO_TCP_SOCK_OR_NULL:
fada7fdc 6739 case PTR_TO_XDP_SOCK:
aad2eeaf
JS
6740 verbose(env, "R%d pointer arithmetic on %s prohibited\n",
6741 dst, reg_type_str[ptr_reg->type]);
f1174f77 6742 return -EACCES;
aad2eeaf
JS
6743 default:
6744 break;
f1174f77
EC
6745 }
6746
6747 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
6748 * The id may be overwritten later if we create a new variable offset.
969bf05e 6749 */
f1174f77
EC
6750 dst_reg->type = ptr_reg->type;
6751 dst_reg->id = ptr_reg->id;
969bf05e 6752
bb7f0f98
AS
6753 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
6754 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
6755 return -EINVAL;
6756
3f50f132
JF
6757 /* pointer types do not carry 32-bit bounds at the moment. */
6758 __mark_reg32_unbounded(dst_reg);
6759
7fedb63a
DB
6760 if (sanitize_needed(opcode)) {
6761 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
6762 &tmp_aux, false);
a6aaece0
DB
6763 if (ret < 0)
6764 return sanitize_err(env, insn, ret, off_reg, dst_reg);
7fedb63a 6765 }
a6aaece0 6766
f1174f77
EC
6767 switch (opcode) {
6768 case BPF_ADD:
6769 /* We can take a fixed offset as long as it doesn't overflow
6770 * the s32 'off' field
969bf05e 6771 */
b03c9f9f
EC
6772 if (known && (ptr_reg->off + smin_val ==
6773 (s64)(s32)(ptr_reg->off + smin_val))) {
f1174f77 6774 /* pointer += K. Accumulate it into fixed offset */
b03c9f9f
EC
6775 dst_reg->smin_value = smin_ptr;
6776 dst_reg->smax_value = smax_ptr;
6777 dst_reg->umin_value = umin_ptr;
6778 dst_reg->umax_value = umax_ptr;
f1174f77 6779 dst_reg->var_off = ptr_reg->var_off;
b03c9f9f 6780 dst_reg->off = ptr_reg->off + smin_val;
0962590e 6781 dst_reg->raw = ptr_reg->raw;
f1174f77
EC
6782 break;
6783 }
f1174f77
EC
6784 /* A new variable offset is created. Note that off_reg->off
6785 * == 0, since it's a scalar.
6786 * dst_reg gets the pointer type and since some positive
6787 * integer value was added to the pointer, give it a new 'id'
6788 * if it's a PTR_TO_PACKET.
6789 * this creates a new 'base' pointer, off_reg (variable) gets
6790 * added into the variable offset, and we copy the fixed offset
6791 * from ptr_reg.
969bf05e 6792 */
b03c9f9f
EC
6793 if (signed_add_overflows(smin_ptr, smin_val) ||
6794 signed_add_overflows(smax_ptr, smax_val)) {
6795 dst_reg->smin_value = S64_MIN;
6796 dst_reg->smax_value = S64_MAX;
6797 } else {
6798 dst_reg->smin_value = smin_ptr + smin_val;
6799 dst_reg->smax_value = smax_ptr + smax_val;
6800 }
6801 if (umin_ptr + umin_val < umin_ptr ||
6802 umax_ptr + umax_val < umax_ptr) {
6803 dst_reg->umin_value = 0;
6804 dst_reg->umax_value = U64_MAX;
6805 } else {
6806 dst_reg->umin_value = umin_ptr + umin_val;
6807 dst_reg->umax_value = umax_ptr + umax_val;
6808 }
f1174f77
EC
6809 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
6810 dst_reg->off = ptr_reg->off;
0962590e 6811 dst_reg->raw = ptr_reg->raw;
de8f3a83 6812 if (reg_is_pkt_pointer(ptr_reg)) {
f1174f77
EC
6813 dst_reg->id = ++env->id_gen;
6814 /* something was added to pkt_ptr, set range to zero */
22dc4a0f 6815 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
f1174f77
EC
6816 }
6817 break;
6818 case BPF_SUB:
6819 if (dst_reg == off_reg) {
6820 /* scalar -= pointer. Creates an unknown scalar */
82abbf8d
AS
6821 verbose(env, "R%d tried to subtract pointer from scalar\n",
6822 dst);
f1174f77
EC
6823 return -EACCES;
6824 }
6825 /* We don't allow subtraction from FP, because (according to
6826 * test_verifier.c test "invalid fp arithmetic", JITs might not
6827 * be able to deal with it.
969bf05e 6828 */
f1174f77 6829 if (ptr_reg->type == PTR_TO_STACK) {
82abbf8d
AS
6830 verbose(env, "R%d subtraction from stack pointer prohibited\n",
6831 dst);
f1174f77
EC
6832 return -EACCES;
6833 }
b03c9f9f
EC
6834 if (known && (ptr_reg->off - smin_val ==
6835 (s64)(s32)(ptr_reg->off - smin_val))) {
f1174f77 6836 /* pointer -= K. Subtract it from fixed offset */
b03c9f9f
EC
6837 dst_reg->smin_value = smin_ptr;
6838 dst_reg->smax_value = smax_ptr;
6839 dst_reg->umin_value = umin_ptr;
6840 dst_reg->umax_value = umax_ptr;
f1174f77
EC
6841 dst_reg->var_off = ptr_reg->var_off;
6842 dst_reg->id = ptr_reg->id;
b03c9f9f 6843 dst_reg->off = ptr_reg->off - smin_val;
0962590e 6844 dst_reg->raw = ptr_reg->raw;
f1174f77
EC
6845 break;
6846 }
f1174f77
EC
6847 /* A new variable offset is created. If the subtrahend is known
6848 * nonnegative, then any reg->range we had before is still good.
969bf05e 6849 */
b03c9f9f
EC
6850 if (signed_sub_overflows(smin_ptr, smax_val) ||
6851 signed_sub_overflows(smax_ptr, smin_val)) {
6852 /* Overflow possible, we know nothing */
6853 dst_reg->smin_value = S64_MIN;
6854 dst_reg->smax_value = S64_MAX;
6855 } else {
6856 dst_reg->smin_value = smin_ptr - smax_val;
6857 dst_reg->smax_value = smax_ptr - smin_val;
6858 }
6859 if (umin_ptr < umax_val) {
6860 /* Overflow possible, we know nothing */
6861 dst_reg->umin_value = 0;
6862 dst_reg->umax_value = U64_MAX;
6863 } else {
6864 /* Cannot overflow (as long as bounds are consistent) */
6865 dst_reg->umin_value = umin_ptr - umax_val;
6866 dst_reg->umax_value = umax_ptr - umin_val;
6867 }
f1174f77
EC
6868 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
6869 dst_reg->off = ptr_reg->off;
0962590e 6870 dst_reg->raw = ptr_reg->raw;
de8f3a83 6871 if (reg_is_pkt_pointer(ptr_reg)) {
f1174f77
EC
6872 dst_reg->id = ++env->id_gen;
6873 /* something was added to pkt_ptr, set range to zero */
b03c9f9f 6874 if (smin_val < 0)
22dc4a0f 6875 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
43188702 6876 }
f1174f77
EC
6877 break;
6878 case BPF_AND:
6879 case BPF_OR:
6880 case BPF_XOR:
82abbf8d
AS
6881 /* bitwise ops on pointers are troublesome, prohibit. */
6882 verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
6883 dst, bpf_alu_string[opcode >> 4]);
f1174f77
EC
6884 return -EACCES;
6885 default:
6886 /* other operators (e.g. MUL,LSH) produce non-pointer results */
82abbf8d
AS
6887 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
6888 dst, bpf_alu_string[opcode >> 4]);
f1174f77 6889 return -EACCES;
43188702
JF
6890 }
6891
bb7f0f98
AS
6892 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
6893 return -EINVAL;
6894
b03c9f9f
EC
6895 __update_reg_bounds(dst_reg);
6896 __reg_deduce_bounds(dst_reg);
6897 __reg_bound_offset(dst_reg);
0d6303db 6898
073815b7
DB
6899 if (sanitize_check_bounds(env, insn, dst_reg) < 0)
6900 return -EACCES;
7fedb63a
DB
6901 if (sanitize_needed(opcode)) {
6902 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
6903 &tmp_aux, true);
6904 if (ret < 0)
6905 return sanitize_err(env, insn, ret, off_reg, dst_reg);
0d6303db
DB
6906 }
6907
43188702
JF
6908 return 0;
6909}
6910
3f50f132
JF
6911static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
6912 struct bpf_reg_state *src_reg)
6913{
6914 s32 smin_val = src_reg->s32_min_value;
6915 s32 smax_val = src_reg->s32_max_value;
6916 u32 umin_val = src_reg->u32_min_value;
6917 u32 umax_val = src_reg->u32_max_value;
6918
6919 if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
6920 signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
6921 dst_reg->s32_min_value = S32_MIN;
6922 dst_reg->s32_max_value = S32_MAX;
6923 } else {
6924 dst_reg->s32_min_value += smin_val;
6925 dst_reg->s32_max_value += smax_val;
6926 }
6927 if (dst_reg->u32_min_value + umin_val < umin_val ||
6928 dst_reg->u32_max_value + umax_val < umax_val) {
6929 dst_reg->u32_min_value = 0;
6930 dst_reg->u32_max_value = U32_MAX;
6931 } else {
6932 dst_reg->u32_min_value += umin_val;
6933 dst_reg->u32_max_value += umax_val;
6934 }
6935}
6936
07cd2631
JF
6937static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
6938 struct bpf_reg_state *src_reg)
6939{
6940 s64 smin_val = src_reg->smin_value;
6941 s64 smax_val = src_reg->smax_value;
6942 u64 umin_val = src_reg->umin_value;
6943 u64 umax_val = src_reg->umax_value;
6944
6945 if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
6946 signed_add_overflows(dst_reg->smax_value, smax_val)) {
6947 dst_reg->smin_value = S64_MIN;
6948 dst_reg->smax_value = S64_MAX;
6949 } else {
6950 dst_reg->smin_value += smin_val;
6951 dst_reg->smax_value += smax_val;
6952 }
6953 if (dst_reg->umin_value + umin_val < umin_val ||
6954 dst_reg->umax_value + umax_val < umax_val) {
6955 dst_reg->umin_value = 0;
6956 dst_reg->umax_value = U64_MAX;
6957 } else {
6958 dst_reg->umin_value += umin_val;
6959 dst_reg->umax_value += umax_val;
6960 }
3f50f132
JF
6961}
6962
6963static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
6964 struct bpf_reg_state *src_reg)
6965{
6966 s32 smin_val = src_reg->s32_min_value;
6967 s32 smax_val = src_reg->s32_max_value;
6968 u32 umin_val = src_reg->u32_min_value;
6969 u32 umax_val = src_reg->u32_max_value;
6970
6971 if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
6972 signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
6973 /* Overflow possible, we know nothing */
6974 dst_reg->s32_min_value = S32_MIN;
6975 dst_reg->s32_max_value = S32_MAX;
6976 } else {
6977 dst_reg->s32_min_value -= smax_val;
6978 dst_reg->s32_max_value -= smin_val;
6979 }
6980 if (dst_reg->u32_min_value < umax_val) {
6981 /* Overflow possible, we know nothing */
6982 dst_reg->u32_min_value = 0;
6983 dst_reg->u32_max_value = U32_MAX;
6984 } else {
6985 /* Cannot overflow (as long as bounds are consistent) */
6986 dst_reg->u32_min_value -= umax_val;
6987 dst_reg->u32_max_value -= umin_val;
6988 }
07cd2631
JF
6989}
6990
6991static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
6992 struct bpf_reg_state *src_reg)
6993{
6994 s64 smin_val = src_reg->smin_value;
6995 s64 smax_val = src_reg->smax_value;
6996 u64 umin_val = src_reg->umin_value;
6997 u64 umax_val = src_reg->umax_value;
6998
6999 if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
7000 signed_sub_overflows(dst_reg->smax_value, smin_val)) {
7001 /* Overflow possible, we know nothing */
7002 dst_reg->smin_value = S64_MIN;
7003 dst_reg->smax_value = S64_MAX;
7004 } else {
7005 dst_reg->smin_value -= smax_val;
7006 dst_reg->smax_value -= smin_val;
7007 }
7008 if (dst_reg->umin_value < umax_val) {
7009 /* Overflow possible, we know nothing */
7010 dst_reg->umin_value = 0;
7011 dst_reg->umax_value = U64_MAX;
7012 } else {
7013 /* Cannot overflow (as long as bounds are consistent) */
7014 dst_reg->umin_value -= umax_val;
7015 dst_reg->umax_value -= umin_val;
7016 }
3f50f132
JF
7017}
7018
7019static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
7020 struct bpf_reg_state *src_reg)
7021{
7022 s32 smin_val = src_reg->s32_min_value;
7023 u32 umin_val = src_reg->u32_min_value;
7024 u32 umax_val = src_reg->u32_max_value;
7025
7026 if (smin_val < 0 || dst_reg->s32_min_value < 0) {
7027 /* Ain't nobody got time to multiply that sign */
7028 __mark_reg32_unbounded(dst_reg);
7029 return;
7030 }
7031 /* Both values are positive, so we can work with unsigned and
7032 * copy the result to signed (unless it exceeds S32_MAX).
7033 */
7034 if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
7035 /* Potential overflow, we know nothing */
7036 __mark_reg32_unbounded(dst_reg);
7037 return;
7038 }
7039 dst_reg->u32_min_value *= umin_val;
7040 dst_reg->u32_max_value *= umax_val;
7041 if (dst_reg->u32_max_value > S32_MAX) {
7042 /* Overflow possible, we know nothing */
7043 dst_reg->s32_min_value = S32_MIN;
7044 dst_reg->s32_max_value = S32_MAX;
7045 } else {
7046 dst_reg->s32_min_value = dst_reg->u32_min_value;
7047 dst_reg->s32_max_value = dst_reg->u32_max_value;
7048 }
07cd2631
JF
7049}
7050
7051static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
7052 struct bpf_reg_state *src_reg)
7053{
7054 s64 smin_val = src_reg->smin_value;
7055 u64 umin_val = src_reg->umin_value;
7056 u64 umax_val = src_reg->umax_value;
7057
07cd2631
JF
7058 if (smin_val < 0 || dst_reg->smin_value < 0) {
7059 /* Ain't nobody got time to multiply that sign */
3f50f132 7060 __mark_reg64_unbounded(dst_reg);
07cd2631
JF
7061 return;
7062 }
7063 /* Both values are positive, so we can work with unsigned and
7064 * copy the result to signed (unless it exceeds S64_MAX).
7065 */
7066 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
7067 /* Potential overflow, we know nothing */
3f50f132 7068 __mark_reg64_unbounded(dst_reg);
07cd2631
JF
7069 return;
7070 }
7071 dst_reg->umin_value *= umin_val;
7072 dst_reg->umax_value *= umax_val;
7073 if (dst_reg->umax_value > S64_MAX) {
7074 /* Overflow possible, we know nothing */
7075 dst_reg->smin_value = S64_MIN;
7076 dst_reg->smax_value = S64_MAX;
7077 } else {
7078 dst_reg->smin_value = dst_reg->umin_value;
7079 dst_reg->smax_value = dst_reg->umax_value;
7080 }
7081}
7082
3f50f132
JF
7083static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
7084 struct bpf_reg_state *src_reg)
7085{
7086 bool src_known = tnum_subreg_is_const(src_reg->var_off);
7087 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
7088 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
7089 s32 smin_val = src_reg->s32_min_value;
7090 u32 umax_val = src_reg->u32_max_value;
7091
7092 /* Assuming scalar64_min_max_and will be called so its safe
7093 * to skip updating register for known 32-bit case.
7094 */
7095 if (src_known && dst_known)
7096 return;
7097
7098 /* We get our minimum from the var_off, since that's inherently
7099 * bitwise. Our maximum is the minimum of the operands' maxima.
7100 */
7101 dst_reg->u32_min_value = var32_off.value;
7102 dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
7103 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
7104 /* Lose signed bounds when ANDing negative numbers,
7105 * ain't nobody got time for that.
7106 */
7107 dst_reg->s32_min_value = S32_MIN;
7108 dst_reg->s32_max_value = S32_MAX;
7109 } else {
7110 /* ANDing two positives gives a positive, so safe to
7111 * cast result into s64.
7112 */
7113 dst_reg->s32_min_value = dst_reg->u32_min_value;
7114 dst_reg->s32_max_value = dst_reg->u32_max_value;
7115 }
7116
7117}
7118
07cd2631
JF
7119static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
7120 struct bpf_reg_state *src_reg)
7121{
3f50f132
JF
7122 bool src_known = tnum_is_const(src_reg->var_off);
7123 bool dst_known = tnum_is_const(dst_reg->var_off);
07cd2631
JF
7124 s64 smin_val = src_reg->smin_value;
7125 u64 umax_val = src_reg->umax_value;
7126
3f50f132 7127 if (src_known && dst_known) {
4fbb38a3 7128 __mark_reg_known(dst_reg, dst_reg->var_off.value);
3f50f132
JF
7129 return;
7130 }
7131
07cd2631
JF
7132 /* We get our minimum from the var_off, since that's inherently
7133 * bitwise. Our maximum is the minimum of the operands' maxima.
7134 */
07cd2631
JF
7135 dst_reg->umin_value = dst_reg->var_off.value;
7136 dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
7137 if (dst_reg->smin_value < 0 || smin_val < 0) {
7138 /* Lose signed bounds when ANDing negative numbers,
7139 * ain't nobody got time for that.
7140 */
7141 dst_reg->smin_value = S64_MIN;
7142 dst_reg->smax_value = S64_MAX;
7143 } else {
7144 /* ANDing two positives gives a positive, so safe to
7145 * cast result into s64.
7146 */
7147 dst_reg->smin_value = dst_reg->umin_value;
7148 dst_reg->smax_value = dst_reg->umax_value;
7149 }
7150 /* We may learn something more from the var_off */
7151 __update_reg_bounds(dst_reg);
7152}
7153
3f50f132
JF
7154static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
7155 struct bpf_reg_state *src_reg)
7156{
7157 bool src_known = tnum_subreg_is_const(src_reg->var_off);
7158 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
7159 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
5b9fbeb7
DB
7160 s32 smin_val = src_reg->s32_min_value;
7161 u32 umin_val = src_reg->u32_min_value;
3f50f132
JF
7162
7163 /* Assuming scalar64_min_max_or will be called so it is safe
7164 * to skip updating register for known case.
7165 */
7166 if (src_known && dst_known)
7167 return;
7168
7169 /* We get our maximum from the var_off, and our minimum is the
7170 * maximum of the operands' minima
7171 */
7172 dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
7173 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
7174 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
7175 /* Lose signed bounds when ORing negative numbers,
7176 * ain't nobody got time for that.
7177 */
7178 dst_reg->s32_min_value = S32_MIN;
7179 dst_reg->s32_max_value = S32_MAX;
7180 } else {
7181 /* ORing two positives gives a positive, so safe to
7182 * cast result into s64.
7183 */
5b9fbeb7
DB
7184 dst_reg->s32_min_value = dst_reg->u32_min_value;
7185 dst_reg->s32_max_value = dst_reg->u32_max_value;
3f50f132
JF
7186 }
7187}
7188
07cd2631
JF
7189static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
7190 struct bpf_reg_state *src_reg)
7191{
3f50f132
JF
7192 bool src_known = tnum_is_const(src_reg->var_off);
7193 bool dst_known = tnum_is_const(dst_reg->var_off);
07cd2631
JF
7194 s64 smin_val = src_reg->smin_value;
7195 u64 umin_val = src_reg->umin_value;
7196
3f50f132 7197 if (src_known && dst_known) {
4fbb38a3 7198 __mark_reg_known(dst_reg, dst_reg->var_off.value);
3f50f132
JF
7199 return;
7200 }
7201
07cd2631
JF
7202 /* We get our maximum from the var_off, and our minimum is the
7203 * maximum of the operands' minima
7204 */
07cd2631
JF
7205 dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
7206 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
7207 if (dst_reg->smin_value < 0 || smin_val < 0) {
7208 /* Lose signed bounds when ORing negative numbers,
7209 * ain't nobody got time for that.
7210 */
7211 dst_reg->smin_value = S64_MIN;
7212 dst_reg->smax_value = S64_MAX;
7213 } else {
7214 /* ORing two positives gives a positive, so safe to
7215 * cast result into s64.
7216 */
7217 dst_reg->smin_value = dst_reg->umin_value;
7218 dst_reg->smax_value = dst_reg->umax_value;
7219 }
7220 /* We may learn something more from the var_off */
7221 __update_reg_bounds(dst_reg);
7222}
7223
2921c90d
YS
7224static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
7225 struct bpf_reg_state *src_reg)
7226{
7227 bool src_known = tnum_subreg_is_const(src_reg->var_off);
7228 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
7229 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
7230 s32 smin_val = src_reg->s32_min_value;
7231
7232 /* Assuming scalar64_min_max_xor will be called so it is safe
7233 * to skip updating register for known case.
7234 */
7235 if (src_known && dst_known)
7236 return;
7237
7238 /* We get both minimum and maximum from the var32_off. */
7239 dst_reg->u32_min_value = var32_off.value;
7240 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
7241
7242 if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
7243 /* XORing two positive sign numbers gives a positive,
7244 * so safe to cast u32 result into s32.
7245 */
7246 dst_reg->s32_min_value = dst_reg->u32_min_value;
7247 dst_reg->s32_max_value = dst_reg->u32_max_value;
7248 } else {
7249 dst_reg->s32_min_value = S32_MIN;
7250 dst_reg->s32_max_value = S32_MAX;
7251 }
7252}
7253
7254static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
7255 struct bpf_reg_state *src_reg)
7256{
7257 bool src_known = tnum_is_const(src_reg->var_off);
7258 bool dst_known = tnum_is_const(dst_reg->var_off);
7259 s64 smin_val = src_reg->smin_value;
7260
7261 if (src_known && dst_known) {
7262 /* dst_reg->var_off.value has been updated earlier */
7263 __mark_reg_known(dst_reg, dst_reg->var_off.value);
7264 return;
7265 }
7266
7267 /* We get both minimum and maximum from the var_off. */
7268 dst_reg->umin_value = dst_reg->var_off.value;
7269 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
7270
7271 if (dst_reg->smin_value >= 0 && smin_val >= 0) {
7272 /* XORing two positive sign numbers gives a positive,
7273 * so safe to cast u64 result into s64.
7274 */
7275 dst_reg->smin_value = dst_reg->umin_value;
7276 dst_reg->smax_value = dst_reg->umax_value;
7277 } else {
7278 dst_reg->smin_value = S64_MIN;
7279 dst_reg->smax_value = S64_MAX;
7280 }
7281
7282 __update_reg_bounds(dst_reg);
7283}
7284
3f50f132
JF
7285static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
7286 u64 umin_val, u64 umax_val)
07cd2631 7287{
07cd2631
JF
7288 /* We lose all sign bit information (except what we can pick
7289 * up from var_off)
7290 */
3f50f132
JF
7291 dst_reg->s32_min_value = S32_MIN;
7292 dst_reg->s32_max_value = S32_MAX;
7293 /* If we might shift our top bit out, then we know nothing */
7294 if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
7295 dst_reg->u32_min_value = 0;
7296 dst_reg->u32_max_value = U32_MAX;
7297 } else {
7298 dst_reg->u32_min_value <<= umin_val;
7299 dst_reg->u32_max_value <<= umax_val;
7300 }
7301}
7302
7303static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
7304 struct bpf_reg_state *src_reg)
7305{
7306 u32 umax_val = src_reg->u32_max_value;
7307 u32 umin_val = src_reg->u32_min_value;
7308 /* u32 alu operation will zext upper bits */
7309 struct tnum subreg = tnum_subreg(dst_reg->var_off);
7310
7311 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
7312 dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
7313 /* Not required but being careful mark reg64 bounds as unknown so
7314 * that we are forced to pick them up from tnum and zext later and
7315 * if some path skips this step we are still safe.
7316 */
7317 __mark_reg64_unbounded(dst_reg);
7318 __update_reg32_bounds(dst_reg);
7319}
7320
7321static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
7322 u64 umin_val, u64 umax_val)
7323{
7324 /* Special case <<32 because it is a common compiler pattern to sign
7325 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
7326 * positive we know this shift will also be positive so we can track
7327 * bounds correctly. Otherwise we lose all sign bit information except
7328 * what we can pick up from var_off. Perhaps we can generalize this
7329 * later to shifts of any length.
7330 */
7331 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
7332 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
7333 else
7334 dst_reg->smax_value = S64_MAX;
7335
7336 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
7337 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
7338 else
7339 dst_reg->smin_value = S64_MIN;
7340
07cd2631
JF
7341 /* If we might shift our top bit out, then we know nothing */
7342 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
7343 dst_reg->umin_value = 0;
7344 dst_reg->umax_value = U64_MAX;
7345 } else {
7346 dst_reg->umin_value <<= umin_val;
7347 dst_reg->umax_value <<= umax_val;
7348 }
3f50f132
JF
7349}
7350
7351static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
7352 struct bpf_reg_state *src_reg)
7353{
7354 u64 umax_val = src_reg->umax_value;
7355 u64 umin_val = src_reg->umin_value;
7356
7357 /* scalar64 calc uses 32bit unshifted bounds so must be called first */
7358 __scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
7359 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
7360
07cd2631
JF
7361 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
7362 /* We may learn something more from the var_off */
7363 __update_reg_bounds(dst_reg);
7364}
7365
3f50f132
JF
7366static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
7367 struct bpf_reg_state *src_reg)
7368{
7369 struct tnum subreg = tnum_subreg(dst_reg->var_off);
7370 u32 umax_val = src_reg->u32_max_value;
7371 u32 umin_val = src_reg->u32_min_value;
7372
7373 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
7374 * be negative, then either:
7375 * 1) src_reg might be zero, so the sign bit of the result is
7376 * unknown, so we lose our signed bounds
7377 * 2) it's known negative, thus the unsigned bounds capture the
7378 * signed bounds
7379 * 3) the signed bounds cross zero, so they tell us nothing
7380 * about the result
7381 * If the value in dst_reg is known nonnegative, then again the
18b24d78 7382 * unsigned bounds capture the signed bounds.
3f50f132
JF
7383 * Thus, in all cases it suffices to blow away our signed bounds
7384 * and rely on inferring new ones from the unsigned bounds and
7385 * var_off of the result.
7386 */
7387 dst_reg->s32_min_value = S32_MIN;
7388 dst_reg->s32_max_value = S32_MAX;
7389
7390 dst_reg->var_off = tnum_rshift(subreg, umin_val);
7391 dst_reg->u32_min_value >>= umax_val;
7392 dst_reg->u32_max_value >>= umin_val;
7393
7394 __mark_reg64_unbounded(dst_reg);
7395 __update_reg32_bounds(dst_reg);
7396}
7397
07cd2631
JF
7398static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
7399 struct bpf_reg_state *src_reg)
7400{
7401 u64 umax_val = src_reg->umax_value;
7402 u64 umin_val = src_reg->umin_value;
7403
7404 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
7405 * be negative, then either:
7406 * 1) src_reg might be zero, so the sign bit of the result is
7407 * unknown, so we lose our signed bounds
7408 * 2) it's known negative, thus the unsigned bounds capture the
7409 * signed bounds
7410 * 3) the signed bounds cross zero, so they tell us nothing
7411 * about the result
7412 * If the value in dst_reg is known nonnegative, then again the
18b24d78 7413 * unsigned bounds capture the signed bounds.
07cd2631
JF
7414 * Thus, in all cases it suffices to blow away our signed bounds
7415 * and rely on inferring new ones from the unsigned bounds and
7416 * var_off of the result.
7417 */
7418 dst_reg->smin_value = S64_MIN;
7419 dst_reg->smax_value = S64_MAX;
7420 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
7421 dst_reg->umin_value >>= umax_val;
7422 dst_reg->umax_value >>= umin_val;
3f50f132
JF
7423
7424 /* Its not easy to operate on alu32 bounds here because it depends
7425 * on bits being shifted in. Take easy way out and mark unbounded
7426 * so we can recalculate later from tnum.
7427 */
7428 __mark_reg32_unbounded(dst_reg);
07cd2631
JF
7429 __update_reg_bounds(dst_reg);
7430}
7431
3f50f132
JF
7432static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
7433 struct bpf_reg_state *src_reg)
07cd2631 7434{
3f50f132 7435 u64 umin_val = src_reg->u32_min_value;
07cd2631
JF
7436
7437 /* Upon reaching here, src_known is true and
7438 * umax_val is equal to umin_val.
7439 */
3f50f132
JF
7440 dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
7441 dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
07cd2631 7442
3f50f132
JF
7443 dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
7444
7445 /* blow away the dst_reg umin_value/umax_value and rely on
7446 * dst_reg var_off to refine the result.
7447 */
7448 dst_reg->u32_min_value = 0;
7449 dst_reg->u32_max_value = U32_MAX;
7450
7451 __mark_reg64_unbounded(dst_reg);
7452 __update_reg32_bounds(dst_reg);
7453}
7454
7455static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
7456 struct bpf_reg_state *src_reg)
7457{
7458 u64 umin_val = src_reg->umin_value;
7459
7460 /* Upon reaching here, src_known is true and umax_val is equal
7461 * to umin_val.
7462 */
7463 dst_reg->smin_value >>= umin_val;
7464 dst_reg->smax_value >>= umin_val;
7465
7466 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
07cd2631
JF
7467
7468 /* blow away the dst_reg umin_value/umax_value and rely on
7469 * dst_reg var_off to refine the result.
7470 */
7471 dst_reg->umin_value = 0;
7472 dst_reg->umax_value = U64_MAX;
3f50f132
JF
7473
7474 /* Its not easy to operate on alu32 bounds here because it depends
7475 * on bits being shifted in from upper 32-bits. Take easy way out
7476 * and mark unbounded so we can recalculate later from tnum.
7477 */
7478 __mark_reg32_unbounded(dst_reg);
07cd2631
JF
7479 __update_reg_bounds(dst_reg);
7480}
7481
468f6eaf
JH
7482/* WARNING: This function does calculations on 64-bit values, but the actual
7483 * execution may occur on 32-bit values. Therefore, things like bitshifts
7484 * need extra checks in the 32-bit case.
7485 */
f1174f77
EC
7486static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
7487 struct bpf_insn *insn,
7488 struct bpf_reg_state *dst_reg,
7489 struct bpf_reg_state src_reg)
969bf05e 7490{
638f5b90 7491 struct bpf_reg_state *regs = cur_regs(env);
48461135 7492 u8 opcode = BPF_OP(insn->code);
b0b3fb67 7493 bool src_known;
b03c9f9f
EC
7494 s64 smin_val, smax_val;
7495 u64 umin_val, umax_val;
3f50f132
JF
7496 s32 s32_min_val, s32_max_val;
7497 u32 u32_min_val, u32_max_val;
468f6eaf 7498 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
3f50f132 7499 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
a6aaece0 7500 int ret;
b799207e 7501
b03c9f9f
EC
7502 smin_val = src_reg.smin_value;
7503 smax_val = src_reg.smax_value;
7504 umin_val = src_reg.umin_value;
7505 umax_val = src_reg.umax_value;
f23cc643 7506
3f50f132
JF
7507 s32_min_val = src_reg.s32_min_value;
7508 s32_max_val = src_reg.s32_max_value;
7509 u32_min_val = src_reg.u32_min_value;
7510 u32_max_val = src_reg.u32_max_value;
7511
7512 if (alu32) {
7513 src_known = tnum_subreg_is_const(src_reg.var_off);
3f50f132
JF
7514 if ((src_known &&
7515 (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
7516 s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
7517 /* Taint dst register if offset had invalid bounds
7518 * derived from e.g. dead branches.
7519 */
7520 __mark_reg_unknown(env, dst_reg);
7521 return 0;
7522 }
7523 } else {
7524 src_known = tnum_is_const(src_reg.var_off);
3f50f132
JF
7525 if ((src_known &&
7526 (smin_val != smax_val || umin_val != umax_val)) ||
7527 smin_val > smax_val || umin_val > umax_val) {
7528 /* Taint dst register if offset had invalid bounds
7529 * derived from e.g. dead branches.
7530 */
7531 __mark_reg_unknown(env, dst_reg);
7532 return 0;
7533 }
6f16101e
DB
7534 }
7535
bb7f0f98
AS
7536 if (!src_known &&
7537 opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
f54c7898 7538 __mark_reg_unknown(env, dst_reg);
bb7f0f98
AS
7539 return 0;
7540 }
7541
f5288193
DB
7542 if (sanitize_needed(opcode)) {
7543 ret = sanitize_val_alu(env, insn);
7544 if (ret < 0)
7545 return sanitize_err(env, insn, ret, NULL, NULL);
7546 }
7547
3f50f132
JF
7548 /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
7549 * There are two classes of instructions: The first class we track both
7550 * alu32 and alu64 sign/unsigned bounds independently this provides the
7551 * greatest amount of precision when alu operations are mixed with jmp32
7552 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
7553 * and BPF_OR. This is possible because these ops have fairly easy to
7554 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
7555 * See alu32 verifier tests for examples. The second class of
7556 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
7557 * with regards to tracking sign/unsigned bounds because the bits may
7558 * cross subreg boundaries in the alu64 case. When this happens we mark
7559 * the reg unbounded in the subreg bound space and use the resulting
7560 * tnum to calculate an approximation of the sign/unsigned bounds.
7561 */
48461135
JB
7562 switch (opcode) {
7563 case BPF_ADD:
3f50f132 7564 scalar32_min_max_add(dst_reg, &src_reg);
07cd2631 7565 scalar_min_max_add(dst_reg, &src_reg);
3f50f132 7566 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
48461135
JB
7567 break;
7568 case BPF_SUB:
3f50f132 7569 scalar32_min_max_sub(dst_reg, &src_reg);
07cd2631 7570 scalar_min_max_sub(dst_reg, &src_reg);
3f50f132 7571 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
48461135
JB
7572 break;
7573 case BPF_MUL:
3f50f132
JF
7574 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
7575 scalar32_min_max_mul(dst_reg, &src_reg);
07cd2631 7576 scalar_min_max_mul(dst_reg, &src_reg);
48461135
JB
7577 break;
7578 case BPF_AND:
3f50f132
JF
7579 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
7580 scalar32_min_max_and(dst_reg, &src_reg);
07cd2631 7581 scalar_min_max_and(dst_reg, &src_reg);
f1174f77
EC
7582 break;
7583 case BPF_OR:
3f50f132
JF
7584 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
7585 scalar32_min_max_or(dst_reg, &src_reg);
07cd2631 7586 scalar_min_max_or(dst_reg, &src_reg);
48461135 7587 break;
2921c90d
YS
7588 case BPF_XOR:
7589 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
7590 scalar32_min_max_xor(dst_reg, &src_reg);
7591 scalar_min_max_xor(dst_reg, &src_reg);
7592 break;
48461135 7593 case BPF_LSH:
468f6eaf
JH
7594 if (umax_val >= insn_bitness) {
7595 /* Shifts greater than 31 or 63 are undefined.
7596 * This includes shifts by a negative number.
b03c9f9f 7597 */
61bd5218 7598 mark_reg_unknown(env, regs, insn->dst_reg);
f1174f77
EC
7599 break;
7600 }
3f50f132
JF
7601 if (alu32)
7602 scalar32_min_max_lsh(dst_reg, &src_reg);
7603 else
7604 scalar_min_max_lsh(dst_reg, &src_reg);
48461135
JB
7605 break;
7606 case BPF_RSH:
468f6eaf
JH
7607 if (umax_val >= insn_bitness) {
7608 /* Shifts greater than 31 or 63 are undefined.
7609 * This includes shifts by a negative number.
b03c9f9f 7610 */
61bd5218 7611 mark_reg_unknown(env, regs, insn->dst_reg);
f1174f77
EC
7612 break;
7613 }
3f50f132
JF
7614 if (alu32)
7615 scalar32_min_max_rsh(dst_reg, &src_reg);
7616 else
7617 scalar_min_max_rsh(dst_reg, &src_reg);
48461135 7618 break;
9cbe1f5a
YS
7619 case BPF_ARSH:
7620 if (umax_val >= insn_bitness) {
7621 /* Shifts greater than 31 or 63 are undefined.
7622 * This includes shifts by a negative number.
7623 */
7624 mark_reg_unknown(env, regs, insn->dst_reg);
7625 break;
7626 }
3f50f132
JF
7627 if (alu32)
7628 scalar32_min_max_arsh(dst_reg, &src_reg);
7629 else
7630 scalar_min_max_arsh(dst_reg, &src_reg);
9cbe1f5a 7631 break;
48461135 7632 default:
61bd5218 7633 mark_reg_unknown(env, regs, insn->dst_reg);
48461135
JB
7634 break;
7635 }
7636
3f50f132
JF
7637 /* ALU32 ops are zero extended into 64bit register */
7638 if (alu32)
7639 zext_32_to_64(dst_reg);
468f6eaf 7640
294f2fc6 7641 __update_reg_bounds(dst_reg);
b03c9f9f
EC
7642 __reg_deduce_bounds(dst_reg);
7643 __reg_bound_offset(dst_reg);
f1174f77
EC
7644 return 0;
7645}
7646
7647/* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
7648 * and var_off.
7649 */
7650static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
7651 struct bpf_insn *insn)
7652{
f4d7e40a
AS
7653 struct bpf_verifier_state *vstate = env->cur_state;
7654 struct bpf_func_state *state = vstate->frame[vstate->curframe];
7655 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
f1174f77
EC
7656 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
7657 u8 opcode = BPF_OP(insn->code);
b5dc0163 7658 int err;
f1174f77
EC
7659
7660 dst_reg = &regs[insn->dst_reg];
f1174f77
EC
7661 src_reg = NULL;
7662 if (dst_reg->type != SCALAR_VALUE)
7663 ptr_reg = dst_reg;
75748837
AS
7664 else
7665 /* Make sure ID is cleared otherwise dst_reg min/max could be
7666 * incorrectly propagated into other registers by find_equal_scalars()
7667 */
7668 dst_reg->id = 0;
f1174f77
EC
7669 if (BPF_SRC(insn->code) == BPF_X) {
7670 src_reg = &regs[insn->src_reg];
f1174f77
EC
7671 if (src_reg->type != SCALAR_VALUE) {
7672 if (dst_reg->type != SCALAR_VALUE) {
7673 /* Combining two pointers by any ALU op yields
82abbf8d
AS
7674 * an arbitrary scalar. Disallow all math except
7675 * pointer subtraction
f1174f77 7676 */
dd066823 7677 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
82abbf8d
AS
7678 mark_reg_unknown(env, regs, insn->dst_reg);
7679 return 0;
f1174f77 7680 }
82abbf8d
AS
7681 verbose(env, "R%d pointer %s pointer prohibited\n",
7682 insn->dst_reg,
7683 bpf_alu_string[opcode >> 4]);
7684 return -EACCES;
f1174f77
EC
7685 } else {
7686 /* scalar += pointer
7687 * This is legal, but we have to reverse our
7688 * src/dest handling in computing the range
7689 */
b5dc0163
AS
7690 err = mark_chain_precision(env, insn->dst_reg);
7691 if (err)
7692 return err;
82abbf8d
AS
7693 return adjust_ptr_min_max_vals(env, insn,
7694 src_reg, dst_reg);
f1174f77
EC
7695 }
7696 } else if (ptr_reg) {
7697 /* pointer += scalar */
b5dc0163
AS
7698 err = mark_chain_precision(env, insn->src_reg);
7699 if (err)
7700 return err;
82abbf8d
AS
7701 return adjust_ptr_min_max_vals(env, insn,
7702 dst_reg, src_reg);
f1174f77
EC
7703 }
7704 } else {
7705 /* Pretend the src is a reg with a known value, since we only
7706 * need to be able to read from this state.
7707 */
7708 off_reg.type = SCALAR_VALUE;
b03c9f9f 7709 __mark_reg_known(&off_reg, insn->imm);
f1174f77 7710 src_reg = &off_reg;
82abbf8d
AS
7711 if (ptr_reg) /* pointer += K */
7712 return adjust_ptr_min_max_vals(env, insn,
7713 ptr_reg, src_reg);
f1174f77
EC
7714 }
7715
7716 /* Got here implies adding two SCALAR_VALUEs */
7717 if (WARN_ON_ONCE(ptr_reg)) {
f4d7e40a 7718 print_verifier_state(env, state);
61bd5218 7719 verbose(env, "verifier internal error: unexpected ptr_reg\n");
f1174f77
EC
7720 return -EINVAL;
7721 }
7722 if (WARN_ON(!src_reg)) {
f4d7e40a 7723 print_verifier_state(env, state);
61bd5218 7724 verbose(env, "verifier internal error: no src_reg\n");
f1174f77
EC
7725 return -EINVAL;
7726 }
7727 return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
48461135
JB
7728}
7729
17a52670 7730/* check validity of 32-bit and 64-bit arithmetic operations */
58e2af8b 7731static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
17a52670 7732{
638f5b90 7733 struct bpf_reg_state *regs = cur_regs(env);
17a52670
AS
7734 u8 opcode = BPF_OP(insn->code);
7735 int err;
7736
7737 if (opcode == BPF_END || opcode == BPF_NEG) {
7738 if (opcode == BPF_NEG) {
7739 if (BPF_SRC(insn->code) != 0 ||
7740 insn->src_reg != BPF_REG_0 ||
7741 insn->off != 0 || insn->imm != 0) {
61bd5218 7742 verbose(env, "BPF_NEG uses reserved fields\n");
17a52670
AS
7743 return -EINVAL;
7744 }
7745 } else {
7746 if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
e67b8a68
EC
7747 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
7748 BPF_CLASS(insn->code) == BPF_ALU64) {
61bd5218 7749 verbose(env, "BPF_END uses reserved fields\n");
17a52670
AS
7750 return -EINVAL;
7751 }
7752 }
7753
7754 /* check src operand */
dc503a8a 7755 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17a52670
AS
7756 if (err)
7757 return err;
7758
1be7f75d 7759 if (is_pointer_value(env, insn->dst_reg)) {
61bd5218 7760 verbose(env, "R%d pointer arithmetic prohibited\n",
1be7f75d
AS
7761 insn->dst_reg);
7762 return -EACCES;
7763 }
7764
17a52670 7765 /* check dest operand */
dc503a8a 7766 err = check_reg_arg(env, insn->dst_reg, DST_OP);
17a52670
AS
7767 if (err)
7768 return err;
7769
7770 } else if (opcode == BPF_MOV) {
7771
7772 if (BPF_SRC(insn->code) == BPF_X) {
7773 if (insn->imm != 0 || insn->off != 0) {
61bd5218 7774 verbose(env, "BPF_MOV uses reserved fields\n");
17a52670
AS
7775 return -EINVAL;
7776 }
7777
7778 /* check src operand */
dc503a8a 7779 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17a52670
AS
7780 if (err)
7781 return err;
7782 } else {
7783 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
61bd5218 7784 verbose(env, "BPF_MOV uses reserved fields\n");
17a52670
AS
7785 return -EINVAL;
7786 }
7787 }
7788
fbeb1603
AF
7789 /* check dest operand, mark as required later */
7790 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
17a52670
AS
7791 if (err)
7792 return err;
7793
7794 if (BPF_SRC(insn->code) == BPF_X) {
e434b8cd
JW
7795 struct bpf_reg_state *src_reg = regs + insn->src_reg;
7796 struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
7797
17a52670
AS
7798 if (BPF_CLASS(insn->code) == BPF_ALU64) {
7799 /* case: R1 = R2
7800 * copy register state to dest reg
7801 */
75748837
AS
7802 if (src_reg->type == SCALAR_VALUE && !src_reg->id)
7803 /* Assign src and dst registers the same ID
7804 * that will be used by find_equal_scalars()
7805 * to propagate min/max range.
7806 */
7807 src_reg->id = ++env->id_gen;
e434b8cd
JW
7808 *dst_reg = *src_reg;
7809 dst_reg->live |= REG_LIVE_WRITTEN;
5327ed3d 7810 dst_reg->subreg_def = DEF_NOT_SUBREG;
17a52670 7811 } else {
f1174f77 7812 /* R1 = (u32) R2 */
1be7f75d 7813 if (is_pointer_value(env, insn->src_reg)) {
61bd5218
JK
7814 verbose(env,
7815 "R%d partial copy of pointer\n",
1be7f75d
AS
7816 insn->src_reg);
7817 return -EACCES;
e434b8cd
JW
7818 } else if (src_reg->type == SCALAR_VALUE) {
7819 *dst_reg = *src_reg;
75748837
AS
7820 /* Make sure ID is cleared otherwise
7821 * dst_reg min/max could be incorrectly
7822 * propagated into src_reg by find_equal_scalars()
7823 */
7824 dst_reg->id = 0;
e434b8cd 7825 dst_reg->live |= REG_LIVE_WRITTEN;
5327ed3d 7826 dst_reg->subreg_def = env->insn_idx + 1;
e434b8cd
JW
7827 } else {
7828 mark_reg_unknown(env, regs,
7829 insn->dst_reg);
1be7f75d 7830 }
3f50f132 7831 zext_32_to_64(dst_reg);
17a52670
AS
7832 }
7833 } else {
7834 /* case: R = imm
7835 * remember the value we stored into this reg
7836 */
fbeb1603
AF
7837 /* clear any state __mark_reg_known doesn't set */
7838 mark_reg_unknown(env, regs, insn->dst_reg);
f1174f77 7839 regs[insn->dst_reg].type = SCALAR_VALUE;
95a762e2
JH
7840 if (BPF_CLASS(insn->code) == BPF_ALU64) {
7841 __mark_reg_known(regs + insn->dst_reg,
7842 insn->imm);
7843 } else {
7844 __mark_reg_known(regs + insn->dst_reg,
7845 (u32)insn->imm);
7846 }
17a52670
AS
7847 }
7848
7849 } else if (opcode > BPF_END) {
61bd5218 7850 verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
17a52670
AS
7851 return -EINVAL;
7852
7853 } else { /* all other ALU ops: and, sub, xor, add, ... */
7854
17a52670
AS
7855 if (BPF_SRC(insn->code) == BPF_X) {
7856 if (insn->imm != 0 || insn->off != 0) {
61bd5218 7857 verbose(env, "BPF_ALU uses reserved fields\n");
17a52670
AS
7858 return -EINVAL;
7859 }
7860 /* check src1 operand */
dc503a8a 7861 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17a52670
AS
7862 if (err)
7863 return err;
7864 } else {
7865 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
61bd5218 7866 verbose(env, "BPF_ALU uses reserved fields\n");
17a52670
AS
7867 return -EINVAL;
7868 }
7869 }
7870
7871 /* check src2 operand */
dc503a8a 7872 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17a52670
AS
7873 if (err)
7874 return err;
7875
7876 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
7877 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
61bd5218 7878 verbose(env, "div by zero\n");
17a52670
AS
7879 return -EINVAL;
7880 }
7881
229394e8
RV
7882 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
7883 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
7884 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
7885
7886 if (insn->imm < 0 || insn->imm >= size) {
61bd5218 7887 verbose(env, "invalid shift %d\n", insn->imm);
229394e8
RV
7888 return -EINVAL;
7889 }
7890 }
7891
1a0dc1ac 7892 /* check dest operand */
dc503a8a 7893 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
1a0dc1ac
AS
7894 if (err)
7895 return err;
7896
f1174f77 7897 return adjust_reg_min_max_vals(env, insn);
17a52670
AS
7898 }
7899
7900 return 0;
7901}
7902
c6a9efa1
PC
7903static void __find_good_pkt_pointers(struct bpf_func_state *state,
7904 struct bpf_reg_state *dst_reg,
6d94e741 7905 enum bpf_reg_type type, int new_range)
c6a9efa1
PC
7906{
7907 struct bpf_reg_state *reg;
7908 int i;
7909
7910 for (i = 0; i < MAX_BPF_REG; i++) {
7911 reg = &state->regs[i];
7912 if (reg->type == type && reg->id == dst_reg->id)
7913 /* keep the maximum range already checked */
7914 reg->range = max(reg->range, new_range);
7915 }
7916
7917 bpf_for_each_spilled_reg(i, state, reg) {
7918 if (!reg)
7919 continue;
7920 if (reg->type == type && reg->id == dst_reg->id)
7921 reg->range = max(reg->range, new_range);
7922 }
7923}
7924
f4d7e40a 7925static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
de8f3a83 7926 struct bpf_reg_state *dst_reg,
f8ddadc4 7927 enum bpf_reg_type type,
fb2a311a 7928 bool range_right_open)
969bf05e 7929{
6d94e741 7930 int new_range, i;
2d2be8ca 7931
fb2a311a
DB
7932 if (dst_reg->off < 0 ||
7933 (dst_reg->off == 0 && range_right_open))
f1174f77
EC
7934 /* This doesn't give us any range */
7935 return;
7936
b03c9f9f
EC
7937 if (dst_reg->umax_value > MAX_PACKET_OFF ||
7938 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
f1174f77
EC
7939 /* Risk of overflow. For instance, ptr + (1<<63) may be less
7940 * than pkt_end, but that's because it's also less than pkt.
7941 */
7942 return;
7943
fb2a311a
DB
7944 new_range = dst_reg->off;
7945 if (range_right_open)
7946 new_range--;
7947
7948 /* Examples for register markings:
2d2be8ca 7949 *
fb2a311a 7950 * pkt_data in dst register:
2d2be8ca
DB
7951 *
7952 * r2 = r3;
7953 * r2 += 8;
7954 * if (r2 > pkt_end) goto <handle exception>
7955 * <access okay>
7956 *
b4e432f1
DB
7957 * r2 = r3;
7958 * r2 += 8;
7959 * if (r2 < pkt_end) goto <access okay>
7960 * <handle exception>
7961 *
2d2be8ca
DB
7962 * Where:
7963 * r2 == dst_reg, pkt_end == src_reg
7964 * r2=pkt(id=n,off=8,r=0)
7965 * r3=pkt(id=n,off=0,r=0)
7966 *
fb2a311a 7967 * pkt_data in src register:
2d2be8ca
DB
7968 *
7969 * r2 = r3;
7970 * r2 += 8;
7971 * if (pkt_end >= r2) goto <access okay>
7972 * <handle exception>
7973 *
b4e432f1
DB
7974 * r2 = r3;
7975 * r2 += 8;
7976 * if (pkt_end <= r2) goto <handle exception>
7977 * <access okay>
7978 *
2d2be8ca
DB
7979 * Where:
7980 * pkt_end == dst_reg, r2 == src_reg
7981 * r2=pkt(id=n,off=8,r=0)
7982 * r3=pkt(id=n,off=0,r=0)
7983 *
7984 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
fb2a311a
DB
7985 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
7986 * and [r3, r3 + 8-1) respectively is safe to access depending on
7987 * the check.
969bf05e 7988 */
2d2be8ca 7989
f1174f77
EC
7990 /* If our ids match, then we must have the same max_value. And we
7991 * don't care about the other reg's fixed offset, since if it's too big
7992 * the range won't allow anything.
7993 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
7994 */
c6a9efa1
PC
7995 for (i = 0; i <= vstate->curframe; i++)
7996 __find_good_pkt_pointers(vstate->frame[i], dst_reg, type,
7997 new_range);
969bf05e
AS
7998}
7999
3f50f132 8000static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
4f7b3e82 8001{
3f50f132
JF
8002 struct tnum subreg = tnum_subreg(reg->var_off);
8003 s32 sval = (s32)val;
a72dafaf 8004
3f50f132
JF
8005 switch (opcode) {
8006 case BPF_JEQ:
8007 if (tnum_is_const(subreg))
8008 return !!tnum_equals_const(subreg, val);
8009 break;
8010 case BPF_JNE:
8011 if (tnum_is_const(subreg))
8012 return !tnum_equals_const(subreg, val);
8013 break;
8014 case BPF_JSET:
8015 if ((~subreg.mask & subreg.value) & val)
8016 return 1;
8017 if (!((subreg.mask | subreg.value) & val))
8018 return 0;
8019 break;
8020 case BPF_JGT:
8021 if (reg->u32_min_value > val)
8022 return 1;
8023 else if (reg->u32_max_value <= val)
8024 return 0;
8025 break;
8026 case BPF_JSGT:
8027 if (reg->s32_min_value > sval)
8028 return 1;
ee114dd6 8029 else if (reg->s32_max_value <= sval)
3f50f132
JF
8030 return 0;
8031 break;
8032 case BPF_JLT:
8033 if (reg->u32_max_value < val)
8034 return 1;
8035 else if (reg->u32_min_value >= val)
8036 return 0;
8037 break;
8038 case BPF_JSLT:
8039 if (reg->s32_max_value < sval)
8040 return 1;
8041 else if (reg->s32_min_value >= sval)
8042 return 0;
8043 break;
8044 case BPF_JGE:
8045 if (reg->u32_min_value >= val)
8046 return 1;
8047 else if (reg->u32_max_value < val)
8048 return 0;
8049 break;
8050 case BPF_JSGE:
8051 if (reg->s32_min_value >= sval)
8052 return 1;
8053 else if (reg->s32_max_value < sval)
8054 return 0;
8055 break;
8056 case BPF_JLE:
8057 if (reg->u32_max_value <= val)
8058 return 1;
8059 else if (reg->u32_min_value > val)
8060 return 0;
8061 break;
8062 case BPF_JSLE:
8063 if (reg->s32_max_value <= sval)
8064 return 1;
8065 else if (reg->s32_min_value > sval)
8066 return 0;
8067 break;
8068 }
4f7b3e82 8069
3f50f132
JF
8070 return -1;
8071}
092ed096 8072
3f50f132
JF
8073
8074static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
8075{
8076 s64 sval = (s64)val;
a72dafaf 8077
4f7b3e82
AS
8078 switch (opcode) {
8079 case BPF_JEQ:
8080 if (tnum_is_const(reg->var_off))
8081 return !!tnum_equals_const(reg->var_off, val);
8082 break;
8083 case BPF_JNE:
8084 if (tnum_is_const(reg->var_off))
8085 return !tnum_equals_const(reg->var_off, val);
8086 break;
960ea056
JK
8087 case BPF_JSET:
8088 if ((~reg->var_off.mask & reg->var_off.value) & val)
8089 return 1;
8090 if (!((reg->var_off.mask | reg->var_off.value) & val))
8091 return 0;
8092 break;
4f7b3e82
AS
8093 case BPF_JGT:
8094 if (reg->umin_value > val)
8095 return 1;
8096 else if (reg->umax_value <= val)
8097 return 0;
8098 break;
8099 case BPF_JSGT:
a72dafaf 8100 if (reg->smin_value > sval)
4f7b3e82 8101 return 1;
ee114dd6 8102 else if (reg->smax_value <= sval)
4f7b3e82
AS
8103 return 0;
8104 break;
8105 case BPF_JLT:
8106 if (reg->umax_value < val)
8107 return 1;
8108 else if (reg->umin_value >= val)
8109 return 0;
8110 break;
8111 case BPF_JSLT:
a72dafaf 8112 if (reg->smax_value < sval)
4f7b3e82 8113 return 1;
a72dafaf 8114 else if (reg->smin_value >= sval)
4f7b3e82
AS
8115 return 0;
8116 break;
8117 case BPF_JGE:
8118 if (reg->umin_value >= val)
8119 return 1;
8120 else if (reg->umax_value < val)
8121 return 0;
8122 break;
8123 case BPF_JSGE:
a72dafaf 8124 if (reg->smin_value >= sval)
4f7b3e82 8125 return 1;
a72dafaf 8126 else if (reg->smax_value < sval)
4f7b3e82
AS
8127 return 0;
8128 break;
8129 case BPF_JLE:
8130 if (reg->umax_value <= val)
8131 return 1;
8132 else if (reg->umin_value > val)
8133 return 0;
8134 break;
8135 case BPF_JSLE:
a72dafaf 8136 if (reg->smax_value <= sval)
4f7b3e82 8137 return 1;
a72dafaf 8138 else if (reg->smin_value > sval)
4f7b3e82
AS
8139 return 0;
8140 break;
8141 }
8142
8143 return -1;
8144}
8145
3f50f132
JF
8146/* compute branch direction of the expression "if (reg opcode val) goto target;"
8147 * and return:
8148 * 1 - branch will be taken and "goto target" will be executed
8149 * 0 - branch will not be taken and fall-through to next insn
8150 * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
8151 * range [0,10]
604dca5e 8152 */
3f50f132
JF
8153static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
8154 bool is_jmp32)
604dca5e 8155{
cac616db
JF
8156 if (__is_pointer_value(false, reg)) {
8157 if (!reg_type_not_null(reg->type))
8158 return -1;
8159
8160 /* If pointer is valid tests against zero will fail so we can
8161 * use this to direct branch taken.
8162 */
8163 if (val != 0)
8164 return -1;
8165
8166 switch (opcode) {
8167 case BPF_JEQ:
8168 return 0;
8169 case BPF_JNE:
8170 return 1;
8171 default:
8172 return -1;
8173 }
8174 }
604dca5e 8175
3f50f132
JF
8176 if (is_jmp32)
8177 return is_branch32_taken(reg, val, opcode);
8178 return is_branch64_taken(reg, val, opcode);
604dca5e
JH
8179}
8180
6d94e741
AS
8181static int flip_opcode(u32 opcode)
8182{
8183 /* How can we transform "a <op> b" into "b <op> a"? */
8184 static const u8 opcode_flip[16] = {
8185 /* these stay the same */
8186 [BPF_JEQ >> 4] = BPF_JEQ,
8187 [BPF_JNE >> 4] = BPF_JNE,
8188 [BPF_JSET >> 4] = BPF_JSET,
8189 /* these swap "lesser" and "greater" (L and G in the opcodes) */
8190 [BPF_JGE >> 4] = BPF_JLE,
8191 [BPF_JGT >> 4] = BPF_JLT,
8192 [BPF_JLE >> 4] = BPF_JGE,
8193 [BPF_JLT >> 4] = BPF_JGT,
8194 [BPF_JSGE >> 4] = BPF_JSLE,
8195 [BPF_JSGT >> 4] = BPF_JSLT,
8196 [BPF_JSLE >> 4] = BPF_JSGE,
8197 [BPF_JSLT >> 4] = BPF_JSGT
8198 };
8199 return opcode_flip[opcode >> 4];
8200}
8201
8202static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
8203 struct bpf_reg_state *src_reg,
8204 u8 opcode)
8205{
8206 struct bpf_reg_state *pkt;
8207
8208 if (src_reg->type == PTR_TO_PACKET_END) {
8209 pkt = dst_reg;
8210 } else if (dst_reg->type == PTR_TO_PACKET_END) {
8211 pkt = src_reg;
8212 opcode = flip_opcode(opcode);
8213 } else {
8214 return -1;
8215 }
8216
8217 if (pkt->range >= 0)
8218 return -1;
8219
8220 switch (opcode) {
8221 case BPF_JLE:
8222 /* pkt <= pkt_end */
8223 fallthrough;
8224 case BPF_JGT:
8225 /* pkt > pkt_end */
8226 if (pkt->range == BEYOND_PKT_END)
8227 /* pkt has at last one extra byte beyond pkt_end */
8228 return opcode == BPF_JGT;
8229 break;
8230 case BPF_JLT:
8231 /* pkt < pkt_end */
8232 fallthrough;
8233 case BPF_JGE:
8234 /* pkt >= pkt_end */
8235 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
8236 return opcode == BPF_JGE;
8237 break;
8238 }
8239 return -1;
8240}
8241
48461135
JB
8242/* Adjusts the register min/max values in the case that the dst_reg is the
8243 * variable register that we are working on, and src_reg is a constant or we're
8244 * simply doing a BPF_K check.
f1174f77 8245 * In JEQ/JNE cases we also adjust the var_off values.
48461135
JB
8246 */
8247static void reg_set_min_max(struct bpf_reg_state *true_reg,
3f50f132
JF
8248 struct bpf_reg_state *false_reg,
8249 u64 val, u32 val32,
092ed096 8250 u8 opcode, bool is_jmp32)
48461135 8251{
3f50f132
JF
8252 struct tnum false_32off = tnum_subreg(false_reg->var_off);
8253 struct tnum false_64off = false_reg->var_off;
8254 struct tnum true_32off = tnum_subreg(true_reg->var_off);
8255 struct tnum true_64off = true_reg->var_off;
8256 s64 sval = (s64)val;
8257 s32 sval32 = (s32)val32;
a72dafaf 8258
f1174f77
EC
8259 /* If the dst_reg is a pointer, we can't learn anything about its
8260 * variable offset from the compare (unless src_reg were a pointer into
8261 * the same object, but we don't bother with that.
8262 * Since false_reg and true_reg have the same type by construction, we
8263 * only need to check one of them for pointerness.
8264 */
8265 if (__is_pointer_value(false, false_reg))
8266 return;
4cabc5b1 8267
48461135
JB
8268 switch (opcode) {
8269 case BPF_JEQ:
48461135 8270 case BPF_JNE:
a72dafaf
JW
8271 {
8272 struct bpf_reg_state *reg =
8273 opcode == BPF_JEQ ? true_reg : false_reg;
8274
e688c3db
AS
8275 /* JEQ/JNE comparison doesn't change the register equivalence.
8276 * r1 = r2;
8277 * if (r1 == 42) goto label;
8278 * ...
8279 * label: // here both r1 and r2 are known to be 42.
8280 *
8281 * Hence when marking register as known preserve it's ID.
48461135 8282 */
3f50f132
JF
8283 if (is_jmp32)
8284 __mark_reg32_known(reg, val32);
8285 else
e688c3db 8286 ___mark_reg_known(reg, val);
48461135 8287 break;
a72dafaf 8288 }
960ea056 8289 case BPF_JSET:
3f50f132
JF
8290 if (is_jmp32) {
8291 false_32off = tnum_and(false_32off, tnum_const(~val32));
8292 if (is_power_of_2(val32))
8293 true_32off = tnum_or(true_32off,
8294 tnum_const(val32));
8295 } else {
8296 false_64off = tnum_and(false_64off, tnum_const(~val));
8297 if (is_power_of_2(val))
8298 true_64off = tnum_or(true_64off,
8299 tnum_const(val));
8300 }
960ea056 8301 break;
48461135 8302 case BPF_JGE:
a72dafaf
JW
8303 case BPF_JGT:
8304 {
3f50f132
JF
8305 if (is_jmp32) {
8306 u32 false_umax = opcode == BPF_JGT ? val32 : val32 - 1;
8307 u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
8308
8309 false_reg->u32_max_value = min(false_reg->u32_max_value,
8310 false_umax);
8311 true_reg->u32_min_value = max(true_reg->u32_min_value,
8312 true_umin);
8313 } else {
8314 u64 false_umax = opcode == BPF_JGT ? val : val - 1;
8315 u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
8316
8317 false_reg->umax_value = min(false_reg->umax_value, false_umax);
8318 true_reg->umin_value = max(true_reg->umin_value, true_umin);
8319 }
b03c9f9f 8320 break;
a72dafaf 8321 }
48461135 8322 case BPF_JSGE:
a72dafaf
JW
8323 case BPF_JSGT:
8324 {
3f50f132
JF
8325 if (is_jmp32) {
8326 s32 false_smax = opcode == BPF_JSGT ? sval32 : sval32 - 1;
8327 s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
a72dafaf 8328
3f50f132
JF
8329 false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
8330 true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
8331 } else {
8332 s64 false_smax = opcode == BPF_JSGT ? sval : sval - 1;
8333 s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
8334
8335 false_reg->smax_value = min(false_reg->smax_value, false_smax);
8336 true_reg->smin_value = max(true_reg->smin_value, true_smin);
8337 }
48461135 8338 break;
a72dafaf 8339 }
b4e432f1 8340 case BPF_JLE:
a72dafaf
JW
8341 case BPF_JLT:
8342 {
3f50f132
JF
8343 if (is_jmp32) {
8344 u32 false_umin = opcode == BPF_JLT ? val32 : val32 + 1;
8345 u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
8346
8347 false_reg->u32_min_value = max(false_reg->u32_min_value,
8348 false_umin);
8349 true_reg->u32_max_value = min(true_reg->u32_max_value,
8350 true_umax);
8351 } else {
8352 u64 false_umin = opcode == BPF_JLT ? val : val + 1;
8353 u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
8354
8355 false_reg->umin_value = max(false_reg->umin_value, false_umin);
8356 true_reg->umax_value = min(true_reg->umax_value, true_umax);
8357 }
b4e432f1 8358 break;
a72dafaf 8359 }
b4e432f1 8360 case BPF_JSLE:
a72dafaf
JW
8361 case BPF_JSLT:
8362 {
3f50f132
JF
8363 if (is_jmp32) {
8364 s32 false_smin = opcode == BPF_JSLT ? sval32 : sval32 + 1;
8365 s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
a72dafaf 8366
3f50f132
JF
8367 false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
8368 true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
8369 } else {
8370 s64 false_smin = opcode == BPF_JSLT ? sval : sval + 1;
8371 s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
8372
8373 false_reg->smin_value = max(false_reg->smin_value, false_smin);
8374 true_reg->smax_value = min(true_reg->smax_value, true_smax);
8375 }
b4e432f1 8376 break;
a72dafaf 8377 }
48461135 8378 default:
0fc31b10 8379 return;
48461135
JB
8380 }
8381
3f50f132
JF
8382 if (is_jmp32) {
8383 false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
8384 tnum_subreg(false_32off));
8385 true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
8386 tnum_subreg(true_32off));
8387 __reg_combine_32_into_64(false_reg);
8388 __reg_combine_32_into_64(true_reg);
8389 } else {
8390 false_reg->var_off = false_64off;
8391 true_reg->var_off = true_64off;
8392 __reg_combine_64_into_32(false_reg);
8393 __reg_combine_64_into_32(true_reg);
8394 }
48461135
JB
8395}
8396
f1174f77
EC
8397/* Same as above, but for the case that dst_reg holds a constant and src_reg is
8398 * the variable reg.
48461135
JB
8399 */
8400static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
3f50f132
JF
8401 struct bpf_reg_state *false_reg,
8402 u64 val, u32 val32,
092ed096 8403 u8 opcode, bool is_jmp32)
48461135 8404{
6d94e741 8405 opcode = flip_opcode(opcode);
0fc31b10
JH
8406 /* This uses zero as "not present in table"; luckily the zero opcode,
8407 * BPF_JA, can't get here.
b03c9f9f 8408 */
0fc31b10 8409 if (opcode)
3f50f132 8410 reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
f1174f77
EC
8411}
8412
8413/* Regs are known to be equal, so intersect their min/max/var_off */
8414static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
8415 struct bpf_reg_state *dst_reg)
8416{
b03c9f9f
EC
8417 src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
8418 dst_reg->umin_value);
8419 src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
8420 dst_reg->umax_value);
8421 src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
8422 dst_reg->smin_value);
8423 src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
8424 dst_reg->smax_value);
f1174f77
EC
8425 src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
8426 dst_reg->var_off);
b03c9f9f
EC
8427 /* We might have learned new bounds from the var_off. */
8428 __update_reg_bounds(src_reg);
8429 __update_reg_bounds(dst_reg);
8430 /* We might have learned something about the sign bit. */
8431 __reg_deduce_bounds(src_reg);
8432 __reg_deduce_bounds(dst_reg);
8433 /* We might have learned some bits from the bounds. */
8434 __reg_bound_offset(src_reg);
8435 __reg_bound_offset(dst_reg);
8436 /* Intersecting with the old var_off might have improved our bounds
8437 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
8438 * then new var_off is (0; 0x7f...fc) which improves our umax.
8439 */
8440 __update_reg_bounds(src_reg);
8441 __update_reg_bounds(dst_reg);
f1174f77
EC
8442}
8443
8444static void reg_combine_min_max(struct bpf_reg_state *true_src,
8445 struct bpf_reg_state *true_dst,
8446 struct bpf_reg_state *false_src,
8447 struct bpf_reg_state *false_dst,
8448 u8 opcode)
8449{
8450 switch (opcode) {
8451 case BPF_JEQ:
8452 __reg_combine_min_max(true_src, true_dst);
8453 break;
8454 case BPF_JNE:
8455 __reg_combine_min_max(false_src, false_dst);
b03c9f9f 8456 break;
4cabc5b1 8457 }
48461135
JB
8458}
8459
fd978bf7
JS
8460static void mark_ptr_or_null_reg(struct bpf_func_state *state,
8461 struct bpf_reg_state *reg, u32 id,
840b9615 8462 bool is_null)
57a09bf0 8463{
93c230e3
MKL
8464 if (reg_type_may_be_null(reg->type) && reg->id == id &&
8465 !WARN_ON_ONCE(!reg->id)) {
f1174f77
EC
8466 /* Old offset (both fixed and variable parts) should
8467 * have been known-zero, because we don't allow pointer
8468 * arithmetic on pointers that might be NULL.
8469 */
b03c9f9f
EC
8470 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value ||
8471 !tnum_equals_const(reg->var_off, 0) ||
f1174f77 8472 reg->off)) {
b03c9f9f
EC
8473 __mark_reg_known_zero(reg);
8474 reg->off = 0;
f1174f77
EC
8475 }
8476 if (is_null) {
8477 reg->type = SCALAR_VALUE;
1b986589
MKL
8478 /* We don't need id and ref_obj_id from this point
8479 * onwards anymore, thus we should better reset it,
8480 * so that state pruning has chances to take effect.
8481 */
8482 reg->id = 0;
8483 reg->ref_obj_id = 0;
4ddb7416
DB
8484
8485 return;
8486 }
8487
8488 mark_ptr_not_null_reg(reg);
8489
8490 if (!reg_may_point_to_spin_lock(reg)) {
1b986589
MKL
8491 /* For not-NULL ptr, reg->ref_obj_id will be reset
8492 * in release_reg_references().
8493 *
8494 * reg->id is still used by spin_lock ptr. Other
8495 * than spin_lock ptr type, reg->id can be reset.
fd978bf7
JS
8496 */
8497 reg->id = 0;
56f668df 8498 }
57a09bf0
TG
8499 }
8500}
8501
c6a9efa1
PC
8502static void __mark_ptr_or_null_regs(struct bpf_func_state *state, u32 id,
8503 bool is_null)
8504{
8505 struct bpf_reg_state *reg;
8506 int i;
8507
8508 for (i = 0; i < MAX_BPF_REG; i++)
8509 mark_ptr_or_null_reg(state, &state->regs[i], id, is_null);
8510
8511 bpf_for_each_spilled_reg(i, state, reg) {
8512 if (!reg)
8513 continue;
8514 mark_ptr_or_null_reg(state, reg, id, is_null);
8515 }
8516}
8517
57a09bf0
TG
8518/* The logic is similar to find_good_pkt_pointers(), both could eventually
8519 * be folded together at some point.
8520 */
840b9615
JS
8521static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
8522 bool is_null)
57a09bf0 8523{
f4d7e40a 8524 struct bpf_func_state *state = vstate->frame[vstate->curframe];
c6a9efa1 8525 struct bpf_reg_state *regs = state->regs;
1b986589 8526 u32 ref_obj_id = regs[regno].ref_obj_id;
a08dd0da 8527 u32 id = regs[regno].id;
c6a9efa1 8528 int i;
57a09bf0 8529
1b986589
MKL
8530 if (ref_obj_id && ref_obj_id == id && is_null)
8531 /* regs[regno] is in the " == NULL" branch.
8532 * No one could have freed the reference state before
8533 * doing the NULL check.
8534 */
8535 WARN_ON_ONCE(release_reference_state(state, id));
fd978bf7 8536
c6a9efa1
PC
8537 for (i = 0; i <= vstate->curframe; i++)
8538 __mark_ptr_or_null_regs(vstate->frame[i], id, is_null);
57a09bf0
TG
8539}
8540
5beca081
DB
8541static bool try_match_pkt_pointers(const struct bpf_insn *insn,
8542 struct bpf_reg_state *dst_reg,
8543 struct bpf_reg_state *src_reg,
8544 struct bpf_verifier_state *this_branch,
8545 struct bpf_verifier_state *other_branch)
8546{
8547 if (BPF_SRC(insn->code) != BPF_X)
8548 return false;
8549
092ed096
JW
8550 /* Pointers are always 64-bit. */
8551 if (BPF_CLASS(insn->code) == BPF_JMP32)
8552 return false;
8553
5beca081
DB
8554 switch (BPF_OP(insn->code)) {
8555 case BPF_JGT:
8556 if ((dst_reg->type == PTR_TO_PACKET &&
8557 src_reg->type == PTR_TO_PACKET_END) ||
8558 (dst_reg->type == PTR_TO_PACKET_META &&
8559 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
8560 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
8561 find_good_pkt_pointers(this_branch, dst_reg,
8562 dst_reg->type, false);
6d94e741 8563 mark_pkt_end(other_branch, insn->dst_reg, true);
5beca081
DB
8564 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
8565 src_reg->type == PTR_TO_PACKET) ||
8566 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
8567 src_reg->type == PTR_TO_PACKET_META)) {
8568 /* pkt_end > pkt_data', pkt_data > pkt_meta' */
8569 find_good_pkt_pointers(other_branch, src_reg,
8570 src_reg->type, true);
6d94e741 8571 mark_pkt_end(this_branch, insn->src_reg, false);
5beca081
DB
8572 } else {
8573 return false;
8574 }
8575 break;
8576 case BPF_JLT:
8577 if ((dst_reg->type == PTR_TO_PACKET &&
8578 src_reg->type == PTR_TO_PACKET_END) ||
8579 (dst_reg->type == PTR_TO_PACKET_META &&
8580 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
8581 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
8582 find_good_pkt_pointers(other_branch, dst_reg,
8583 dst_reg->type, true);
6d94e741 8584 mark_pkt_end(this_branch, insn->dst_reg, false);
5beca081
DB
8585 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
8586 src_reg->type == PTR_TO_PACKET) ||
8587 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
8588 src_reg->type == PTR_TO_PACKET_META)) {
8589 /* pkt_end < pkt_data', pkt_data > pkt_meta' */
8590 find_good_pkt_pointers(this_branch, src_reg,
8591 src_reg->type, false);
6d94e741 8592 mark_pkt_end(other_branch, insn->src_reg, true);
5beca081
DB
8593 } else {
8594 return false;
8595 }
8596 break;
8597 case BPF_JGE:
8598 if ((dst_reg->type == PTR_TO_PACKET &&
8599 src_reg->type == PTR_TO_PACKET_END) ||
8600 (dst_reg->type == PTR_TO_PACKET_META &&
8601 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
8602 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
8603 find_good_pkt_pointers(this_branch, dst_reg,
8604 dst_reg->type, true);
6d94e741 8605 mark_pkt_end(other_branch, insn->dst_reg, false);
5beca081
DB
8606 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
8607 src_reg->type == PTR_TO_PACKET) ||
8608 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
8609 src_reg->type == PTR_TO_PACKET_META)) {
8610 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
8611 find_good_pkt_pointers(other_branch, src_reg,
8612 src_reg->type, false);
6d94e741 8613 mark_pkt_end(this_branch, insn->src_reg, true);
5beca081
DB
8614 } else {
8615 return false;
8616 }
8617 break;
8618 case BPF_JLE:
8619 if ((dst_reg->type == PTR_TO_PACKET &&
8620 src_reg->type == PTR_TO_PACKET_END) ||
8621 (dst_reg->type == PTR_TO_PACKET_META &&
8622 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
8623 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
8624 find_good_pkt_pointers(other_branch, dst_reg,
8625 dst_reg->type, false);
6d94e741 8626 mark_pkt_end(this_branch, insn->dst_reg, true);
5beca081
DB
8627 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
8628 src_reg->type == PTR_TO_PACKET) ||
8629 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
8630 src_reg->type == PTR_TO_PACKET_META)) {
8631 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
8632 find_good_pkt_pointers(this_branch, src_reg,
8633 src_reg->type, true);
6d94e741 8634 mark_pkt_end(other_branch, insn->src_reg, false);
5beca081
DB
8635 } else {
8636 return false;
8637 }
8638 break;
8639 default:
8640 return false;
8641 }
8642
8643 return true;
8644}
8645
75748837
AS
8646static void find_equal_scalars(struct bpf_verifier_state *vstate,
8647 struct bpf_reg_state *known_reg)
8648{
8649 struct bpf_func_state *state;
8650 struct bpf_reg_state *reg;
8651 int i, j;
8652
8653 for (i = 0; i <= vstate->curframe; i++) {
8654 state = vstate->frame[i];
8655 for (j = 0; j < MAX_BPF_REG; j++) {
8656 reg = &state->regs[j];
8657 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
8658 *reg = *known_reg;
8659 }
8660
8661 bpf_for_each_spilled_reg(j, state, reg) {
8662 if (!reg)
8663 continue;
8664 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
8665 *reg = *known_reg;
8666 }
8667 }
8668}
8669
58e2af8b 8670static int check_cond_jmp_op(struct bpf_verifier_env *env,
17a52670
AS
8671 struct bpf_insn *insn, int *insn_idx)
8672{
f4d7e40a
AS
8673 struct bpf_verifier_state *this_branch = env->cur_state;
8674 struct bpf_verifier_state *other_branch;
8675 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
fb8d251e 8676 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
17a52670 8677 u8 opcode = BPF_OP(insn->code);
092ed096 8678 bool is_jmp32;
fb8d251e 8679 int pred = -1;
17a52670
AS
8680 int err;
8681
092ed096
JW
8682 /* Only conditional jumps are expected to reach here. */
8683 if (opcode == BPF_JA || opcode > BPF_JSLE) {
8684 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
17a52670
AS
8685 return -EINVAL;
8686 }
8687
8688 if (BPF_SRC(insn->code) == BPF_X) {
8689 if (insn->imm != 0) {
092ed096 8690 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
17a52670
AS
8691 return -EINVAL;
8692 }
8693
8694 /* check src1 operand */
dc503a8a 8695 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17a52670
AS
8696 if (err)
8697 return err;
1be7f75d
AS
8698
8699 if (is_pointer_value(env, insn->src_reg)) {
61bd5218 8700 verbose(env, "R%d pointer comparison prohibited\n",
1be7f75d
AS
8701 insn->src_reg);
8702 return -EACCES;
8703 }
fb8d251e 8704 src_reg = &regs[insn->src_reg];
17a52670
AS
8705 } else {
8706 if (insn->src_reg != BPF_REG_0) {
092ed096 8707 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
17a52670
AS
8708 return -EINVAL;
8709 }
8710 }
8711
8712 /* check src2 operand */
dc503a8a 8713 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17a52670
AS
8714 if (err)
8715 return err;
8716
1a0dc1ac 8717 dst_reg = &regs[insn->dst_reg];
092ed096 8718 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
1a0dc1ac 8719
3f50f132
JF
8720 if (BPF_SRC(insn->code) == BPF_K) {
8721 pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
8722 } else if (src_reg->type == SCALAR_VALUE &&
8723 is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
8724 pred = is_branch_taken(dst_reg,
8725 tnum_subreg(src_reg->var_off).value,
8726 opcode,
8727 is_jmp32);
8728 } else if (src_reg->type == SCALAR_VALUE &&
8729 !is_jmp32 && tnum_is_const(src_reg->var_off)) {
8730 pred = is_branch_taken(dst_reg,
8731 src_reg->var_off.value,
8732 opcode,
8733 is_jmp32);
6d94e741
AS
8734 } else if (reg_is_pkt_pointer_any(dst_reg) &&
8735 reg_is_pkt_pointer_any(src_reg) &&
8736 !is_jmp32) {
8737 pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
3f50f132
JF
8738 }
8739
b5dc0163 8740 if (pred >= 0) {
cac616db
JF
8741 /* If we get here with a dst_reg pointer type it is because
8742 * above is_branch_taken() special cased the 0 comparison.
8743 */
8744 if (!__is_pointer_value(false, dst_reg))
8745 err = mark_chain_precision(env, insn->dst_reg);
6d94e741
AS
8746 if (BPF_SRC(insn->code) == BPF_X && !err &&
8747 !__is_pointer_value(false, src_reg))
b5dc0163
AS
8748 err = mark_chain_precision(env, insn->src_reg);
8749 if (err)
8750 return err;
8751 }
fb8d251e
AS
8752 if (pred == 1) {
8753 /* only follow the goto, ignore fall-through */
8754 *insn_idx += insn->off;
8755 return 0;
8756 } else if (pred == 0) {
8757 /* only follow fall-through branch, since
8758 * that's where the program will go
8759 */
8760 return 0;
17a52670
AS
8761 }
8762
979d63d5
DB
8763 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
8764 false);
17a52670
AS
8765 if (!other_branch)
8766 return -EFAULT;
f4d7e40a 8767 other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
17a52670 8768
48461135
JB
8769 /* detect if we are comparing against a constant value so we can adjust
8770 * our min/max values for our dst register.
f1174f77
EC
8771 * this is only legit if both are scalars (or pointers to the same
8772 * object, I suppose, but we don't support that right now), because
8773 * otherwise the different base pointers mean the offsets aren't
8774 * comparable.
48461135
JB
8775 */
8776 if (BPF_SRC(insn->code) == BPF_X) {
092ed096 8777 struct bpf_reg_state *src_reg = &regs[insn->src_reg];
092ed096 8778
f1174f77 8779 if (dst_reg->type == SCALAR_VALUE &&
092ed096
JW
8780 src_reg->type == SCALAR_VALUE) {
8781 if (tnum_is_const(src_reg->var_off) ||
3f50f132
JF
8782 (is_jmp32 &&
8783 tnum_is_const(tnum_subreg(src_reg->var_off))))
f4d7e40a 8784 reg_set_min_max(&other_branch_regs[insn->dst_reg],
092ed096 8785 dst_reg,
3f50f132
JF
8786 src_reg->var_off.value,
8787 tnum_subreg(src_reg->var_off).value,
092ed096
JW
8788 opcode, is_jmp32);
8789 else if (tnum_is_const(dst_reg->var_off) ||
3f50f132
JF
8790 (is_jmp32 &&
8791 tnum_is_const(tnum_subreg(dst_reg->var_off))))
f4d7e40a 8792 reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
092ed096 8793 src_reg,
3f50f132
JF
8794 dst_reg->var_off.value,
8795 tnum_subreg(dst_reg->var_off).value,
092ed096
JW
8796 opcode, is_jmp32);
8797 else if (!is_jmp32 &&
8798 (opcode == BPF_JEQ || opcode == BPF_JNE))
f1174f77 8799 /* Comparing for equality, we can combine knowledge */
f4d7e40a
AS
8800 reg_combine_min_max(&other_branch_regs[insn->src_reg],
8801 &other_branch_regs[insn->dst_reg],
092ed096 8802 src_reg, dst_reg, opcode);
e688c3db
AS
8803 if (src_reg->id &&
8804 !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
75748837
AS
8805 find_equal_scalars(this_branch, src_reg);
8806 find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
8807 }
8808
f1174f77
EC
8809 }
8810 } else if (dst_reg->type == SCALAR_VALUE) {
f4d7e40a 8811 reg_set_min_max(&other_branch_regs[insn->dst_reg],
3f50f132
JF
8812 dst_reg, insn->imm, (u32)insn->imm,
8813 opcode, is_jmp32);
48461135
JB
8814 }
8815
e688c3db
AS
8816 if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
8817 !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
75748837
AS
8818 find_equal_scalars(this_branch, dst_reg);
8819 find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
8820 }
8821
092ed096
JW
8822 /* detect if R == 0 where R is returned from bpf_map_lookup_elem().
8823 * NOTE: these optimizations below are related with pointer comparison
8824 * which will never be JMP32.
8825 */
8826 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
1a0dc1ac 8827 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
840b9615
JS
8828 reg_type_may_be_null(dst_reg->type)) {
8829 /* Mark all identical registers in each branch as either
57a09bf0
TG
8830 * safe or unknown depending R == 0 or R != 0 conditional.
8831 */
840b9615
JS
8832 mark_ptr_or_null_regs(this_branch, insn->dst_reg,
8833 opcode == BPF_JNE);
8834 mark_ptr_or_null_regs(other_branch, insn->dst_reg,
8835 opcode == BPF_JEQ);
5beca081
DB
8836 } else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
8837 this_branch, other_branch) &&
8838 is_pointer_value(env, insn->dst_reg)) {
61bd5218
JK
8839 verbose(env, "R%d pointer comparison prohibited\n",
8840 insn->dst_reg);
1be7f75d 8841 return -EACCES;
17a52670 8842 }
06ee7115 8843 if (env->log.level & BPF_LOG_LEVEL)
f4d7e40a 8844 print_verifier_state(env, this_branch->frame[this_branch->curframe]);
17a52670
AS
8845 return 0;
8846}
8847
17a52670 8848/* verify BPF_LD_IMM64 instruction */
58e2af8b 8849static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
17a52670 8850{
d8eca5bb 8851 struct bpf_insn_aux_data *aux = cur_aux(env);
638f5b90 8852 struct bpf_reg_state *regs = cur_regs(env);
4976b718 8853 struct bpf_reg_state *dst_reg;
d8eca5bb 8854 struct bpf_map *map;
17a52670
AS
8855 int err;
8856
8857 if (BPF_SIZE(insn->code) != BPF_DW) {
61bd5218 8858 verbose(env, "invalid BPF_LD_IMM insn\n");
17a52670
AS
8859 return -EINVAL;
8860 }
8861 if (insn->off != 0) {
61bd5218 8862 verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
17a52670
AS
8863 return -EINVAL;
8864 }
8865
dc503a8a 8866 err = check_reg_arg(env, insn->dst_reg, DST_OP);
17a52670
AS
8867 if (err)
8868 return err;
8869
4976b718 8870 dst_reg = &regs[insn->dst_reg];
6b173873 8871 if (insn->src_reg == 0) {
6b173873
JK
8872 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
8873
4976b718 8874 dst_reg->type = SCALAR_VALUE;
b03c9f9f 8875 __mark_reg_known(&regs[insn->dst_reg], imm);
17a52670 8876 return 0;
6b173873 8877 }
17a52670 8878
4976b718
HL
8879 if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
8880 mark_reg_known_zero(env, regs, insn->dst_reg);
8881
8882 dst_reg->type = aux->btf_var.reg_type;
8883 switch (dst_reg->type) {
8884 case PTR_TO_MEM:
8885 dst_reg->mem_size = aux->btf_var.mem_size;
8886 break;
8887 case PTR_TO_BTF_ID:
eaa6bcb7 8888 case PTR_TO_PERCPU_BTF_ID:
22dc4a0f 8889 dst_reg->btf = aux->btf_var.btf;
4976b718
HL
8890 dst_reg->btf_id = aux->btf_var.btf_id;
8891 break;
8892 default:
8893 verbose(env, "bpf verifier is misconfigured\n");
8894 return -EFAULT;
8895 }
8896 return 0;
8897 }
8898
69c087ba
YS
8899 if (insn->src_reg == BPF_PSEUDO_FUNC) {
8900 struct bpf_prog_aux *aux = env->prog->aux;
8901 u32 subprogno = insn[1].imm;
8902
8903 if (!aux->func_info) {
8904 verbose(env, "missing btf func_info\n");
8905 return -EINVAL;
8906 }
8907 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
8908 verbose(env, "callback function not static\n");
8909 return -EINVAL;
8910 }
8911
8912 dst_reg->type = PTR_TO_FUNC;
8913 dst_reg->subprogno = subprogno;
8914 return 0;
8915 }
8916
d8eca5bb
DB
8917 map = env->used_maps[aux->map_index];
8918 mark_reg_known_zero(env, regs, insn->dst_reg);
4976b718 8919 dst_reg->map_ptr = map;
d8eca5bb
DB
8920
8921 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE) {
4976b718
HL
8922 dst_reg->type = PTR_TO_MAP_VALUE;
8923 dst_reg->off = aux->map_off;
d8eca5bb 8924 if (map_value_has_spin_lock(map))
4976b718 8925 dst_reg->id = ++env->id_gen;
d8eca5bb 8926 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD) {
4976b718 8927 dst_reg->type = CONST_PTR_TO_MAP;
d8eca5bb
DB
8928 } else {
8929 verbose(env, "bpf verifier is misconfigured\n");
8930 return -EINVAL;
8931 }
17a52670 8932
17a52670
AS
8933 return 0;
8934}
8935
96be4325
DB
8936static bool may_access_skb(enum bpf_prog_type type)
8937{
8938 switch (type) {
8939 case BPF_PROG_TYPE_SOCKET_FILTER:
8940 case BPF_PROG_TYPE_SCHED_CLS:
94caee8c 8941 case BPF_PROG_TYPE_SCHED_ACT:
96be4325
DB
8942 return true;
8943 default:
8944 return false;
8945 }
8946}
8947
ddd872bc
AS
8948/* verify safety of LD_ABS|LD_IND instructions:
8949 * - they can only appear in the programs where ctx == skb
8950 * - since they are wrappers of function calls, they scratch R1-R5 registers,
8951 * preserve R6-R9, and store return value into R0
8952 *
8953 * Implicit input:
8954 * ctx == skb == R6 == CTX
8955 *
8956 * Explicit input:
8957 * SRC == any register
8958 * IMM == 32-bit immediate
8959 *
8960 * Output:
8961 * R0 - 8/16/32-bit skb data converted to cpu endianness
8962 */
58e2af8b 8963static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
ddd872bc 8964{
638f5b90 8965 struct bpf_reg_state *regs = cur_regs(env);
6d4f151a 8966 static const int ctx_reg = BPF_REG_6;
ddd872bc 8967 u8 mode = BPF_MODE(insn->code);
ddd872bc
AS
8968 int i, err;
8969
7e40781c 8970 if (!may_access_skb(resolve_prog_type(env->prog))) {
61bd5218 8971 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
ddd872bc
AS
8972 return -EINVAL;
8973 }
8974
e0cea7ce
DB
8975 if (!env->ops->gen_ld_abs) {
8976 verbose(env, "bpf verifier is misconfigured\n");
8977 return -EINVAL;
8978 }
8979
ddd872bc 8980 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
d82bccc6 8981 BPF_SIZE(insn->code) == BPF_DW ||
ddd872bc 8982 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
61bd5218 8983 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
ddd872bc
AS
8984 return -EINVAL;
8985 }
8986
8987 /* check whether implicit source operand (register R6) is readable */
6d4f151a 8988 err = check_reg_arg(env, ctx_reg, SRC_OP);
ddd872bc
AS
8989 if (err)
8990 return err;
8991
fd978bf7
JS
8992 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
8993 * gen_ld_abs() may terminate the program at runtime, leading to
8994 * reference leak.
8995 */
8996 err = check_reference_leak(env);
8997 if (err) {
8998 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
8999 return err;
9000 }
9001
d83525ca
AS
9002 if (env->cur_state->active_spin_lock) {
9003 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
9004 return -EINVAL;
9005 }
9006
6d4f151a 9007 if (regs[ctx_reg].type != PTR_TO_CTX) {
61bd5218
JK
9008 verbose(env,
9009 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
ddd872bc
AS
9010 return -EINVAL;
9011 }
9012
9013 if (mode == BPF_IND) {
9014 /* check explicit source operand */
dc503a8a 9015 err = check_reg_arg(env, insn->src_reg, SRC_OP);
ddd872bc
AS
9016 if (err)
9017 return err;
9018 }
9019
6d4f151a
DB
9020 err = check_ctx_reg(env, &regs[ctx_reg], ctx_reg);
9021 if (err < 0)
9022 return err;
9023
ddd872bc 9024 /* reset caller saved regs to unreadable */
dc503a8a 9025 for (i = 0; i < CALLER_SAVED_REGS; i++) {
61bd5218 9026 mark_reg_not_init(env, regs, caller_saved[i]);
dc503a8a
EC
9027 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
9028 }
ddd872bc
AS
9029
9030 /* mark destination R0 register as readable, since it contains
dc503a8a
EC
9031 * the value fetched from the packet.
9032 * Already marked as written above.
ddd872bc 9033 */
61bd5218 9034 mark_reg_unknown(env, regs, BPF_REG_0);
5327ed3d
JW
9035 /* ld_abs load up to 32-bit skb data. */
9036 regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
ddd872bc
AS
9037 return 0;
9038}
9039
390ee7e2
AS
9040static int check_return_code(struct bpf_verifier_env *env)
9041{
5cf1e914 9042 struct tnum enforce_attach_type_range = tnum_unknown;
27ae7997 9043 const struct bpf_prog *prog = env->prog;
390ee7e2
AS
9044 struct bpf_reg_state *reg;
9045 struct tnum range = tnum_range(0, 1);
7e40781c 9046 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
27ae7997 9047 int err;
f782e2c3 9048 const bool is_subprog = env->cur_state->frame[0]->subprogno;
27ae7997 9049
9e4e01df 9050 /* LSM and struct_ops func-ptr's return type could be "void" */
f782e2c3
DB
9051 if (!is_subprog &&
9052 (prog_type == BPF_PROG_TYPE_STRUCT_OPS ||
7e40781c 9053 prog_type == BPF_PROG_TYPE_LSM) &&
27ae7997
MKL
9054 !prog->aux->attach_func_proto->type)
9055 return 0;
9056
9057 /* eBPF calling convetion is such that R0 is used
9058 * to return the value from eBPF program.
9059 * Make sure that it's readable at this time
9060 * of bpf_exit, which means that program wrote
9061 * something into it earlier
9062 */
9063 err = check_reg_arg(env, BPF_REG_0, SRC_OP);
9064 if (err)
9065 return err;
9066
9067 if (is_pointer_value(env, BPF_REG_0)) {
9068 verbose(env, "R0 leaks addr as return value\n");
9069 return -EACCES;
9070 }
390ee7e2 9071
f782e2c3
DB
9072 reg = cur_regs(env) + BPF_REG_0;
9073 if (is_subprog) {
9074 if (reg->type != SCALAR_VALUE) {
9075 verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
9076 reg_type_str[reg->type]);
9077 return -EINVAL;
9078 }
9079 return 0;
9080 }
9081
7e40781c 9082 switch (prog_type) {
983695fa
DB
9083 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
9084 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
1b66d253
DB
9085 env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
9086 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
9087 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
9088 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
9089 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
983695fa 9090 range = tnum_range(1, 1);
77241217
SF
9091 if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
9092 env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
9093 range = tnum_range(0, 3);
ed4ed404 9094 break;
390ee7e2 9095 case BPF_PROG_TYPE_CGROUP_SKB:
5cf1e914 9096 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
9097 range = tnum_range(0, 3);
9098 enforce_attach_type_range = tnum_range(2, 3);
9099 }
ed4ed404 9100 break;
390ee7e2
AS
9101 case BPF_PROG_TYPE_CGROUP_SOCK:
9102 case BPF_PROG_TYPE_SOCK_OPS:
ebc614f6 9103 case BPF_PROG_TYPE_CGROUP_DEVICE:
7b146ceb 9104 case BPF_PROG_TYPE_CGROUP_SYSCTL:
0d01da6a 9105 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
390ee7e2 9106 break;
15ab09bd
AS
9107 case BPF_PROG_TYPE_RAW_TRACEPOINT:
9108 if (!env->prog->aux->attach_btf_id)
9109 return 0;
9110 range = tnum_const(0);
9111 break;
15d83c4d 9112 case BPF_PROG_TYPE_TRACING:
e92888c7
YS
9113 switch (env->prog->expected_attach_type) {
9114 case BPF_TRACE_FENTRY:
9115 case BPF_TRACE_FEXIT:
9116 range = tnum_const(0);
9117 break;
9118 case BPF_TRACE_RAW_TP:
9119 case BPF_MODIFY_RETURN:
15d83c4d 9120 return 0;
2ec0616e
DB
9121 case BPF_TRACE_ITER:
9122 break;
e92888c7
YS
9123 default:
9124 return -ENOTSUPP;
9125 }
15d83c4d 9126 break;
e9ddbb77
JS
9127 case BPF_PROG_TYPE_SK_LOOKUP:
9128 range = tnum_range(SK_DROP, SK_PASS);
9129 break;
e92888c7
YS
9130 case BPF_PROG_TYPE_EXT:
9131 /* freplace program can return anything as its return value
9132 * depends on the to-be-replaced kernel func or bpf program.
9133 */
390ee7e2
AS
9134 default:
9135 return 0;
9136 }
9137
390ee7e2 9138 if (reg->type != SCALAR_VALUE) {
61bd5218 9139 verbose(env, "At program exit the register R0 is not a known value (%s)\n",
390ee7e2
AS
9140 reg_type_str[reg->type]);
9141 return -EINVAL;
9142 }
9143
9144 if (!tnum_in(range, reg->var_off)) {
bc2591d6 9145 verbose_invalid_scalar(env, reg, &range, "program exit", "R0");
390ee7e2
AS
9146 return -EINVAL;
9147 }
5cf1e914 9148
9149 if (!tnum_is_unknown(enforce_attach_type_range) &&
9150 tnum_in(enforce_attach_type_range, reg->var_off))
9151 env->prog->enforce_expected_attach_type = 1;
390ee7e2
AS
9152 return 0;
9153}
9154
475fb78f
AS
9155/* non-recursive DFS pseudo code
9156 * 1 procedure DFS-iterative(G,v):
9157 * 2 label v as discovered
9158 * 3 let S be a stack
9159 * 4 S.push(v)
9160 * 5 while S is not empty
9161 * 6 t <- S.pop()
9162 * 7 if t is what we're looking for:
9163 * 8 return t
9164 * 9 for all edges e in G.adjacentEdges(t) do
9165 * 10 if edge e is already labelled
9166 * 11 continue with the next edge
9167 * 12 w <- G.adjacentVertex(t,e)
9168 * 13 if vertex w is not discovered and not explored
9169 * 14 label e as tree-edge
9170 * 15 label w as discovered
9171 * 16 S.push(w)
9172 * 17 continue at 5
9173 * 18 else if vertex w is discovered
9174 * 19 label e as back-edge
9175 * 20 else
9176 * 21 // vertex w is explored
9177 * 22 label e as forward- or cross-edge
9178 * 23 label t as explored
9179 * 24 S.pop()
9180 *
9181 * convention:
9182 * 0x10 - discovered
9183 * 0x11 - discovered and fall-through edge labelled
9184 * 0x12 - discovered and fall-through and branch edges labelled
9185 * 0x20 - explored
9186 */
9187
9188enum {
9189 DISCOVERED = 0x10,
9190 EXPLORED = 0x20,
9191 FALLTHROUGH = 1,
9192 BRANCH = 2,
9193};
9194
dc2a4ebc
AS
9195static u32 state_htab_size(struct bpf_verifier_env *env)
9196{
9197 return env->prog->len;
9198}
9199
5d839021
AS
9200static struct bpf_verifier_state_list **explored_state(
9201 struct bpf_verifier_env *env,
9202 int idx)
9203{
dc2a4ebc
AS
9204 struct bpf_verifier_state *cur = env->cur_state;
9205 struct bpf_func_state *state = cur->frame[cur->curframe];
9206
9207 return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
5d839021
AS
9208}
9209
9210static void init_explored_state(struct bpf_verifier_env *env, int idx)
9211{
a8f500af 9212 env->insn_aux_data[idx].prune_point = true;
5d839021 9213}
f1bca824 9214
59e2e27d
WAF
9215enum {
9216 DONE_EXPLORING = 0,
9217 KEEP_EXPLORING = 1,
9218};
9219
475fb78f
AS
9220/* t, w, e - match pseudo-code above:
9221 * t - index of current instruction
9222 * w - next instruction
9223 * e - edge
9224 */
2589726d
AS
9225static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
9226 bool loop_ok)
475fb78f 9227{
7df737e9
AS
9228 int *insn_stack = env->cfg.insn_stack;
9229 int *insn_state = env->cfg.insn_state;
9230
475fb78f 9231 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
59e2e27d 9232 return DONE_EXPLORING;
475fb78f
AS
9233
9234 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
59e2e27d 9235 return DONE_EXPLORING;
475fb78f
AS
9236
9237 if (w < 0 || w >= env->prog->len) {
d9762e84 9238 verbose_linfo(env, t, "%d: ", t);
61bd5218 9239 verbose(env, "jump out of range from insn %d to %d\n", t, w);
475fb78f
AS
9240 return -EINVAL;
9241 }
9242
f1bca824
AS
9243 if (e == BRANCH)
9244 /* mark branch target for state pruning */
5d839021 9245 init_explored_state(env, w);
f1bca824 9246
475fb78f
AS
9247 if (insn_state[w] == 0) {
9248 /* tree-edge */
9249 insn_state[t] = DISCOVERED | e;
9250 insn_state[w] = DISCOVERED;
7df737e9 9251 if (env->cfg.cur_stack >= env->prog->len)
475fb78f 9252 return -E2BIG;
7df737e9 9253 insn_stack[env->cfg.cur_stack++] = w;
59e2e27d 9254 return KEEP_EXPLORING;
475fb78f 9255 } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
2c78ee89 9256 if (loop_ok && env->bpf_capable)
59e2e27d 9257 return DONE_EXPLORING;
d9762e84
MKL
9258 verbose_linfo(env, t, "%d: ", t);
9259 verbose_linfo(env, w, "%d: ", w);
61bd5218 9260 verbose(env, "back-edge from insn %d to %d\n", t, w);
475fb78f
AS
9261 return -EINVAL;
9262 } else if (insn_state[w] == EXPLORED) {
9263 /* forward- or cross-edge */
9264 insn_state[t] = DISCOVERED | e;
9265 } else {
61bd5218 9266 verbose(env, "insn state internal bug\n");
475fb78f
AS
9267 return -EFAULT;
9268 }
59e2e27d
WAF
9269 return DONE_EXPLORING;
9270}
9271
efdb22de
YS
9272static int visit_func_call_insn(int t, int insn_cnt,
9273 struct bpf_insn *insns,
9274 struct bpf_verifier_env *env,
9275 bool visit_callee)
9276{
9277 int ret;
9278
9279 ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
9280 if (ret)
9281 return ret;
9282
9283 if (t + 1 < insn_cnt)
9284 init_explored_state(env, t + 1);
9285 if (visit_callee) {
9286 init_explored_state(env, t);
9287 ret = push_insn(t, t + insns[t].imm + 1, BRANCH,
9288 env, false);
9289 }
9290 return ret;
9291}
9292
59e2e27d
WAF
9293/* Visits the instruction at index t and returns one of the following:
9294 * < 0 - an error occurred
9295 * DONE_EXPLORING - the instruction was fully explored
9296 * KEEP_EXPLORING - there is still work to be done before it is fully explored
9297 */
9298static int visit_insn(int t, int insn_cnt, struct bpf_verifier_env *env)
9299{
9300 struct bpf_insn *insns = env->prog->insnsi;
9301 int ret;
9302
69c087ba
YS
9303 if (bpf_pseudo_func(insns + t))
9304 return visit_func_call_insn(t, insn_cnt, insns, env, true);
9305
59e2e27d
WAF
9306 /* All non-branch instructions have a single fall-through edge. */
9307 if (BPF_CLASS(insns[t].code) != BPF_JMP &&
9308 BPF_CLASS(insns[t].code) != BPF_JMP32)
9309 return push_insn(t, t + 1, FALLTHROUGH, env, false);
9310
9311 switch (BPF_OP(insns[t].code)) {
9312 case BPF_EXIT:
9313 return DONE_EXPLORING;
9314
9315 case BPF_CALL:
efdb22de
YS
9316 return visit_func_call_insn(t, insn_cnt, insns, env,
9317 insns[t].src_reg == BPF_PSEUDO_CALL);
59e2e27d
WAF
9318
9319 case BPF_JA:
9320 if (BPF_SRC(insns[t].code) != BPF_K)
9321 return -EINVAL;
9322
9323 /* unconditional jump with single edge */
9324 ret = push_insn(t, t + insns[t].off + 1, FALLTHROUGH, env,
9325 true);
9326 if (ret)
9327 return ret;
9328
9329 /* unconditional jmp is not a good pruning point,
9330 * but it's marked, since backtracking needs
9331 * to record jmp history in is_state_visited().
9332 */
9333 init_explored_state(env, t + insns[t].off + 1);
9334 /* tell verifier to check for equivalent states
9335 * after every call and jump
9336 */
9337 if (t + 1 < insn_cnt)
9338 init_explored_state(env, t + 1);
9339
9340 return ret;
9341
9342 default:
9343 /* conditional jump with two edges */
9344 init_explored_state(env, t);
9345 ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
9346 if (ret)
9347 return ret;
9348
9349 return push_insn(t, t + insns[t].off + 1, BRANCH, env, true);
9350 }
475fb78f
AS
9351}
9352
9353/* non-recursive depth-first-search to detect loops in BPF program
9354 * loop == back-edge in directed graph
9355 */
58e2af8b 9356static int check_cfg(struct bpf_verifier_env *env)
475fb78f 9357{
475fb78f 9358 int insn_cnt = env->prog->len;
7df737e9 9359 int *insn_stack, *insn_state;
475fb78f 9360 int ret = 0;
59e2e27d 9361 int i;
475fb78f 9362
7df737e9 9363 insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
475fb78f
AS
9364 if (!insn_state)
9365 return -ENOMEM;
9366
7df737e9 9367 insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
475fb78f 9368 if (!insn_stack) {
71dde681 9369 kvfree(insn_state);
475fb78f
AS
9370 return -ENOMEM;
9371 }
9372
9373 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
9374 insn_stack[0] = 0; /* 0 is the first instruction */
7df737e9 9375 env->cfg.cur_stack = 1;
475fb78f 9376
59e2e27d
WAF
9377 while (env->cfg.cur_stack > 0) {
9378 int t = insn_stack[env->cfg.cur_stack - 1];
475fb78f 9379
59e2e27d
WAF
9380 ret = visit_insn(t, insn_cnt, env);
9381 switch (ret) {
9382 case DONE_EXPLORING:
9383 insn_state[t] = EXPLORED;
9384 env->cfg.cur_stack--;
9385 break;
9386 case KEEP_EXPLORING:
9387 break;
9388 default:
9389 if (ret > 0) {
9390 verbose(env, "visit_insn internal bug\n");
9391 ret = -EFAULT;
475fb78f 9392 }
475fb78f 9393 goto err_free;
59e2e27d 9394 }
475fb78f
AS
9395 }
9396
59e2e27d 9397 if (env->cfg.cur_stack < 0) {
61bd5218 9398 verbose(env, "pop stack internal bug\n");
475fb78f
AS
9399 ret = -EFAULT;
9400 goto err_free;
9401 }
475fb78f 9402
475fb78f
AS
9403 for (i = 0; i < insn_cnt; i++) {
9404 if (insn_state[i] != EXPLORED) {
61bd5218 9405 verbose(env, "unreachable insn %d\n", i);
475fb78f
AS
9406 ret = -EINVAL;
9407 goto err_free;
9408 }
9409 }
9410 ret = 0; /* cfg looks good */
9411
9412err_free:
71dde681
AS
9413 kvfree(insn_state);
9414 kvfree(insn_stack);
7df737e9 9415 env->cfg.insn_state = env->cfg.insn_stack = NULL;
475fb78f
AS
9416 return ret;
9417}
9418
09b28d76
AS
9419static int check_abnormal_return(struct bpf_verifier_env *env)
9420{
9421 int i;
9422
9423 for (i = 1; i < env->subprog_cnt; i++) {
9424 if (env->subprog_info[i].has_ld_abs) {
9425 verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
9426 return -EINVAL;
9427 }
9428 if (env->subprog_info[i].has_tail_call) {
9429 verbose(env, "tail_call is not allowed in subprogs without BTF\n");
9430 return -EINVAL;
9431 }
9432 }
9433 return 0;
9434}
9435
838e9690
YS
9436/* The minimum supported BTF func info size */
9437#define MIN_BPF_FUNCINFO_SIZE 8
9438#define MAX_FUNCINFO_REC_SIZE 252
9439
c454a46b
MKL
9440static int check_btf_func(struct bpf_verifier_env *env,
9441 const union bpf_attr *attr,
9442 union bpf_attr __user *uattr)
838e9690 9443{
09b28d76 9444 const struct btf_type *type, *func_proto, *ret_type;
d0b2818e 9445 u32 i, nfuncs, urec_size, min_size;
838e9690 9446 u32 krec_size = sizeof(struct bpf_func_info);
c454a46b 9447 struct bpf_func_info *krecord;
8c1b6e69 9448 struct bpf_func_info_aux *info_aux = NULL;
c454a46b
MKL
9449 struct bpf_prog *prog;
9450 const struct btf *btf;
838e9690 9451 void __user *urecord;
d0b2818e 9452 u32 prev_offset = 0;
09b28d76 9453 bool scalar_return;
e7ed83d6 9454 int ret = -ENOMEM;
838e9690
YS
9455
9456 nfuncs = attr->func_info_cnt;
09b28d76
AS
9457 if (!nfuncs) {
9458 if (check_abnormal_return(env))
9459 return -EINVAL;
838e9690 9460 return 0;
09b28d76 9461 }
838e9690
YS
9462
9463 if (nfuncs != env->subprog_cnt) {
9464 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
9465 return -EINVAL;
9466 }
9467
9468 urec_size = attr->func_info_rec_size;
9469 if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
9470 urec_size > MAX_FUNCINFO_REC_SIZE ||
9471 urec_size % sizeof(u32)) {
9472 verbose(env, "invalid func info rec size %u\n", urec_size);
9473 return -EINVAL;
9474 }
9475
c454a46b
MKL
9476 prog = env->prog;
9477 btf = prog->aux->btf;
838e9690
YS
9478
9479 urecord = u64_to_user_ptr(attr->func_info);
9480 min_size = min_t(u32, krec_size, urec_size);
9481
ba64e7d8 9482 krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
c454a46b
MKL
9483 if (!krecord)
9484 return -ENOMEM;
8c1b6e69
AS
9485 info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
9486 if (!info_aux)
9487 goto err_free;
ba64e7d8 9488
838e9690
YS
9489 for (i = 0; i < nfuncs; i++) {
9490 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
9491 if (ret) {
9492 if (ret == -E2BIG) {
9493 verbose(env, "nonzero tailing record in func info");
9494 /* set the size kernel expects so loader can zero
9495 * out the rest of the record.
9496 */
9497 if (put_user(min_size, &uattr->func_info_rec_size))
9498 ret = -EFAULT;
9499 }
c454a46b 9500 goto err_free;
838e9690
YS
9501 }
9502
ba64e7d8 9503 if (copy_from_user(&krecord[i], urecord, min_size)) {
838e9690 9504 ret = -EFAULT;
c454a46b 9505 goto err_free;
838e9690
YS
9506 }
9507
d30d42e0 9508 /* check insn_off */
09b28d76 9509 ret = -EINVAL;
838e9690 9510 if (i == 0) {
d30d42e0 9511 if (krecord[i].insn_off) {
838e9690 9512 verbose(env,
d30d42e0
MKL
9513 "nonzero insn_off %u for the first func info record",
9514 krecord[i].insn_off);
c454a46b 9515 goto err_free;
838e9690 9516 }
d30d42e0 9517 } else if (krecord[i].insn_off <= prev_offset) {
838e9690
YS
9518 verbose(env,
9519 "same or smaller insn offset (%u) than previous func info record (%u)",
d30d42e0 9520 krecord[i].insn_off, prev_offset);
c454a46b 9521 goto err_free;
838e9690
YS
9522 }
9523
d30d42e0 9524 if (env->subprog_info[i].start != krecord[i].insn_off) {
838e9690 9525 verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
c454a46b 9526 goto err_free;
838e9690
YS
9527 }
9528
9529 /* check type_id */
ba64e7d8 9530 type = btf_type_by_id(btf, krecord[i].type_id);
51c39bb1 9531 if (!type || !btf_type_is_func(type)) {
838e9690 9532 verbose(env, "invalid type id %d in func info",
ba64e7d8 9533 krecord[i].type_id);
c454a46b 9534 goto err_free;
838e9690 9535 }
51c39bb1 9536 info_aux[i].linkage = BTF_INFO_VLEN(type->info);
09b28d76
AS
9537
9538 func_proto = btf_type_by_id(btf, type->type);
9539 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
9540 /* btf_func_check() already verified it during BTF load */
9541 goto err_free;
9542 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
9543 scalar_return =
9544 btf_type_is_small_int(ret_type) || btf_type_is_enum(ret_type);
9545 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
9546 verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
9547 goto err_free;
9548 }
9549 if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
9550 verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
9551 goto err_free;
9552 }
9553
d30d42e0 9554 prev_offset = krecord[i].insn_off;
838e9690
YS
9555 urecord += urec_size;
9556 }
9557
ba64e7d8
YS
9558 prog->aux->func_info = krecord;
9559 prog->aux->func_info_cnt = nfuncs;
8c1b6e69 9560 prog->aux->func_info_aux = info_aux;
838e9690
YS
9561 return 0;
9562
c454a46b 9563err_free:
ba64e7d8 9564 kvfree(krecord);
8c1b6e69 9565 kfree(info_aux);
838e9690
YS
9566 return ret;
9567}
9568
ba64e7d8
YS
9569static void adjust_btf_func(struct bpf_verifier_env *env)
9570{
8c1b6e69 9571 struct bpf_prog_aux *aux = env->prog->aux;
ba64e7d8
YS
9572 int i;
9573
8c1b6e69 9574 if (!aux->func_info)
ba64e7d8
YS
9575 return;
9576
9577 for (i = 0; i < env->subprog_cnt; i++)
8c1b6e69 9578 aux->func_info[i].insn_off = env->subprog_info[i].start;
ba64e7d8
YS
9579}
9580
c454a46b
MKL
9581#define MIN_BPF_LINEINFO_SIZE (offsetof(struct bpf_line_info, line_col) + \
9582 sizeof(((struct bpf_line_info *)(0))->line_col))
9583#define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE
9584
9585static int check_btf_line(struct bpf_verifier_env *env,
9586 const union bpf_attr *attr,
9587 union bpf_attr __user *uattr)
9588{
9589 u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
9590 struct bpf_subprog_info *sub;
9591 struct bpf_line_info *linfo;
9592 struct bpf_prog *prog;
9593 const struct btf *btf;
9594 void __user *ulinfo;
9595 int err;
9596
9597 nr_linfo = attr->line_info_cnt;
9598 if (!nr_linfo)
9599 return 0;
9600
9601 rec_size = attr->line_info_rec_size;
9602 if (rec_size < MIN_BPF_LINEINFO_SIZE ||
9603 rec_size > MAX_LINEINFO_REC_SIZE ||
9604 rec_size & (sizeof(u32) - 1))
9605 return -EINVAL;
9606
9607 /* Need to zero it in case the userspace may
9608 * pass in a smaller bpf_line_info object.
9609 */
9610 linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
9611 GFP_KERNEL | __GFP_NOWARN);
9612 if (!linfo)
9613 return -ENOMEM;
9614
9615 prog = env->prog;
9616 btf = prog->aux->btf;
9617
9618 s = 0;
9619 sub = env->subprog_info;
9620 ulinfo = u64_to_user_ptr(attr->line_info);
9621 expected_size = sizeof(struct bpf_line_info);
9622 ncopy = min_t(u32, expected_size, rec_size);
9623 for (i = 0; i < nr_linfo; i++) {
9624 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
9625 if (err) {
9626 if (err == -E2BIG) {
9627 verbose(env, "nonzero tailing record in line_info");
9628 if (put_user(expected_size,
9629 &uattr->line_info_rec_size))
9630 err = -EFAULT;
9631 }
9632 goto err_free;
9633 }
9634
9635 if (copy_from_user(&linfo[i], ulinfo, ncopy)) {
9636 err = -EFAULT;
9637 goto err_free;
9638 }
9639
9640 /*
9641 * Check insn_off to ensure
9642 * 1) strictly increasing AND
9643 * 2) bounded by prog->len
9644 *
9645 * The linfo[0].insn_off == 0 check logically falls into
9646 * the later "missing bpf_line_info for func..." case
9647 * because the first linfo[0].insn_off must be the
9648 * first sub also and the first sub must have
9649 * subprog_info[0].start == 0.
9650 */
9651 if ((i && linfo[i].insn_off <= prev_offset) ||
9652 linfo[i].insn_off >= prog->len) {
9653 verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
9654 i, linfo[i].insn_off, prev_offset,
9655 prog->len);
9656 err = -EINVAL;
9657 goto err_free;
9658 }
9659
fdbaa0be
MKL
9660 if (!prog->insnsi[linfo[i].insn_off].code) {
9661 verbose(env,
9662 "Invalid insn code at line_info[%u].insn_off\n",
9663 i);
9664 err = -EINVAL;
9665 goto err_free;
9666 }
9667
23127b33
MKL
9668 if (!btf_name_by_offset(btf, linfo[i].line_off) ||
9669 !btf_name_by_offset(btf, linfo[i].file_name_off)) {
c454a46b
MKL
9670 verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
9671 err = -EINVAL;
9672 goto err_free;
9673 }
9674
9675 if (s != env->subprog_cnt) {
9676 if (linfo[i].insn_off == sub[s].start) {
9677 sub[s].linfo_idx = i;
9678 s++;
9679 } else if (sub[s].start < linfo[i].insn_off) {
9680 verbose(env, "missing bpf_line_info for func#%u\n", s);
9681 err = -EINVAL;
9682 goto err_free;
9683 }
9684 }
9685
9686 prev_offset = linfo[i].insn_off;
9687 ulinfo += rec_size;
9688 }
9689
9690 if (s != env->subprog_cnt) {
9691 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
9692 env->subprog_cnt - s, s);
9693 err = -EINVAL;
9694 goto err_free;
9695 }
9696
9697 prog->aux->linfo = linfo;
9698 prog->aux->nr_linfo = nr_linfo;
9699
9700 return 0;
9701
9702err_free:
9703 kvfree(linfo);
9704 return err;
9705}
9706
9707static int check_btf_info(struct bpf_verifier_env *env,
9708 const union bpf_attr *attr,
9709 union bpf_attr __user *uattr)
9710{
9711 struct btf *btf;
9712 int err;
9713
09b28d76
AS
9714 if (!attr->func_info_cnt && !attr->line_info_cnt) {
9715 if (check_abnormal_return(env))
9716 return -EINVAL;
c454a46b 9717 return 0;
09b28d76 9718 }
c454a46b
MKL
9719
9720 btf = btf_get_by_fd(attr->prog_btf_fd);
9721 if (IS_ERR(btf))
9722 return PTR_ERR(btf);
350a5c4d
AS
9723 if (btf_is_kernel(btf)) {
9724 btf_put(btf);
9725 return -EACCES;
9726 }
c454a46b
MKL
9727 env->prog->aux->btf = btf;
9728
9729 err = check_btf_func(env, attr, uattr);
9730 if (err)
9731 return err;
9732
9733 err = check_btf_line(env, attr, uattr);
9734 if (err)
9735 return err;
9736
9737 return 0;
ba64e7d8
YS
9738}
9739
f1174f77
EC
9740/* check %cur's range satisfies %old's */
9741static bool range_within(struct bpf_reg_state *old,
9742 struct bpf_reg_state *cur)
9743{
b03c9f9f
EC
9744 return old->umin_value <= cur->umin_value &&
9745 old->umax_value >= cur->umax_value &&
9746 old->smin_value <= cur->smin_value &&
fd675184
DB
9747 old->smax_value >= cur->smax_value &&
9748 old->u32_min_value <= cur->u32_min_value &&
9749 old->u32_max_value >= cur->u32_max_value &&
9750 old->s32_min_value <= cur->s32_min_value &&
9751 old->s32_max_value >= cur->s32_max_value;
f1174f77
EC
9752}
9753
9754/* Maximum number of register states that can exist at once */
9755#define ID_MAP_SIZE (MAX_BPF_REG + MAX_BPF_STACK / BPF_REG_SIZE)
9756struct idpair {
9757 u32 old;
9758 u32 cur;
9759};
9760
9761/* If in the old state two registers had the same id, then they need to have
9762 * the same id in the new state as well. But that id could be different from
9763 * the old state, so we need to track the mapping from old to new ids.
9764 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
9765 * regs with old id 5 must also have new id 9 for the new state to be safe. But
9766 * regs with a different old id could still have new id 9, we don't care about
9767 * that.
9768 * So we look through our idmap to see if this old id has been seen before. If
9769 * so, we require the new id to match; otherwise, we add the id pair to the map.
969bf05e 9770 */
f1174f77 9771static bool check_ids(u32 old_id, u32 cur_id, struct idpair *idmap)
969bf05e 9772{
f1174f77 9773 unsigned int i;
969bf05e 9774
f1174f77
EC
9775 for (i = 0; i < ID_MAP_SIZE; i++) {
9776 if (!idmap[i].old) {
9777 /* Reached an empty slot; haven't seen this id before */
9778 idmap[i].old = old_id;
9779 idmap[i].cur = cur_id;
9780 return true;
9781 }
9782 if (idmap[i].old == old_id)
9783 return idmap[i].cur == cur_id;
9784 }
9785 /* We ran out of idmap slots, which should be impossible */
9786 WARN_ON_ONCE(1);
9787 return false;
9788}
9789
9242b5f5
AS
9790static void clean_func_state(struct bpf_verifier_env *env,
9791 struct bpf_func_state *st)
9792{
9793 enum bpf_reg_liveness live;
9794 int i, j;
9795
9796 for (i = 0; i < BPF_REG_FP; i++) {
9797 live = st->regs[i].live;
9798 /* liveness must not touch this register anymore */
9799 st->regs[i].live |= REG_LIVE_DONE;
9800 if (!(live & REG_LIVE_READ))
9801 /* since the register is unused, clear its state
9802 * to make further comparison simpler
9803 */
f54c7898 9804 __mark_reg_not_init(env, &st->regs[i]);
9242b5f5
AS
9805 }
9806
9807 for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
9808 live = st->stack[i].spilled_ptr.live;
9809 /* liveness must not touch this stack slot anymore */
9810 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
9811 if (!(live & REG_LIVE_READ)) {
f54c7898 9812 __mark_reg_not_init(env, &st->stack[i].spilled_ptr);
9242b5f5
AS
9813 for (j = 0; j < BPF_REG_SIZE; j++)
9814 st->stack[i].slot_type[j] = STACK_INVALID;
9815 }
9816 }
9817}
9818
9819static void clean_verifier_state(struct bpf_verifier_env *env,
9820 struct bpf_verifier_state *st)
9821{
9822 int i;
9823
9824 if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
9825 /* all regs in this state in all frames were already marked */
9826 return;
9827
9828 for (i = 0; i <= st->curframe; i++)
9829 clean_func_state(env, st->frame[i]);
9830}
9831
9832/* the parentage chains form a tree.
9833 * the verifier states are added to state lists at given insn and
9834 * pushed into state stack for future exploration.
9835 * when the verifier reaches bpf_exit insn some of the verifer states
9836 * stored in the state lists have their final liveness state already,
9837 * but a lot of states will get revised from liveness point of view when
9838 * the verifier explores other branches.
9839 * Example:
9840 * 1: r0 = 1
9841 * 2: if r1 == 100 goto pc+1
9842 * 3: r0 = 2
9843 * 4: exit
9844 * when the verifier reaches exit insn the register r0 in the state list of
9845 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
9846 * of insn 2 and goes exploring further. At the insn 4 it will walk the
9847 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
9848 *
9849 * Since the verifier pushes the branch states as it sees them while exploring
9850 * the program the condition of walking the branch instruction for the second
9851 * time means that all states below this branch were already explored and
9852 * their final liveness markes are already propagated.
9853 * Hence when the verifier completes the search of state list in is_state_visited()
9854 * we can call this clean_live_states() function to mark all liveness states
9855 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
9856 * will not be used.
9857 * This function also clears the registers and stack for states that !READ
9858 * to simplify state merging.
9859 *
9860 * Important note here that walking the same branch instruction in the callee
9861 * doesn't meant that the states are DONE. The verifier has to compare
9862 * the callsites
9863 */
9864static void clean_live_states(struct bpf_verifier_env *env, int insn,
9865 struct bpf_verifier_state *cur)
9866{
9867 struct bpf_verifier_state_list *sl;
9868 int i;
9869
5d839021 9870 sl = *explored_state(env, insn);
a8f500af 9871 while (sl) {
2589726d
AS
9872 if (sl->state.branches)
9873 goto next;
dc2a4ebc
AS
9874 if (sl->state.insn_idx != insn ||
9875 sl->state.curframe != cur->curframe)
9242b5f5
AS
9876 goto next;
9877 for (i = 0; i <= cur->curframe; i++)
9878 if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
9879 goto next;
9880 clean_verifier_state(env, &sl->state);
9881next:
9882 sl = sl->next;
9883 }
9884}
9885
f1174f77 9886/* Returns true if (rold safe implies rcur safe) */
1b688a19
EC
9887static bool regsafe(struct bpf_reg_state *rold, struct bpf_reg_state *rcur,
9888 struct idpair *idmap)
f1174f77 9889{
f4d7e40a
AS
9890 bool equal;
9891
dc503a8a
EC
9892 if (!(rold->live & REG_LIVE_READ))
9893 /* explored state didn't use this */
9894 return true;
9895
679c782d 9896 equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, parent)) == 0;
f4d7e40a
AS
9897
9898 if (rold->type == PTR_TO_STACK)
9899 /* two stack pointers are equal only if they're pointing to
9900 * the same stack frame, since fp-8 in foo != fp-8 in bar
9901 */
9902 return equal && rold->frameno == rcur->frameno;
9903
9904 if (equal)
969bf05e
AS
9905 return true;
9906
f1174f77
EC
9907 if (rold->type == NOT_INIT)
9908 /* explored state can't have used this */
969bf05e 9909 return true;
f1174f77
EC
9910 if (rcur->type == NOT_INIT)
9911 return false;
9912 switch (rold->type) {
9913 case SCALAR_VALUE:
9914 if (rcur->type == SCALAR_VALUE) {
b5dc0163
AS
9915 if (!rold->precise && !rcur->precise)
9916 return true;
f1174f77
EC
9917 /* new val must satisfy old val knowledge */
9918 return range_within(rold, rcur) &&
9919 tnum_in(rold->var_off, rcur->var_off);
9920 } else {
179d1c56
JH
9921 /* We're trying to use a pointer in place of a scalar.
9922 * Even if the scalar was unbounded, this could lead to
9923 * pointer leaks because scalars are allowed to leak
9924 * while pointers are not. We could make this safe in
9925 * special cases if root is calling us, but it's
9926 * probably not worth the hassle.
f1174f77 9927 */
179d1c56 9928 return false;
f1174f77 9929 }
69c087ba 9930 case PTR_TO_MAP_KEY:
f1174f77 9931 case PTR_TO_MAP_VALUE:
1b688a19
EC
9932 /* If the new min/max/var_off satisfy the old ones and
9933 * everything else matches, we are OK.
d83525ca
AS
9934 * 'id' is not compared, since it's only used for maps with
9935 * bpf_spin_lock inside map element and in such cases if
9936 * the rest of the prog is valid for one map element then
9937 * it's valid for all map elements regardless of the key
9938 * used in bpf_map_lookup()
1b688a19
EC
9939 */
9940 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
9941 range_within(rold, rcur) &&
9942 tnum_in(rold->var_off, rcur->var_off);
f1174f77
EC
9943 case PTR_TO_MAP_VALUE_OR_NULL:
9944 /* a PTR_TO_MAP_VALUE could be safe to use as a
9945 * PTR_TO_MAP_VALUE_OR_NULL into the same map.
9946 * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
9947 * checked, doing so could have affected others with the same
9948 * id, and we can't check for that because we lost the id when
9949 * we converted to a PTR_TO_MAP_VALUE.
9950 */
9951 if (rcur->type != PTR_TO_MAP_VALUE_OR_NULL)
9952 return false;
9953 if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
9954 return false;
9955 /* Check our ids match any regs they're supposed to */
9956 return check_ids(rold->id, rcur->id, idmap);
de8f3a83 9957 case PTR_TO_PACKET_META:
f1174f77 9958 case PTR_TO_PACKET:
de8f3a83 9959 if (rcur->type != rold->type)
f1174f77
EC
9960 return false;
9961 /* We must have at least as much range as the old ptr
9962 * did, so that any accesses which were safe before are
9963 * still safe. This is true even if old range < old off,
9964 * since someone could have accessed through (ptr - k), or
9965 * even done ptr -= k in a register, to get a safe access.
9966 */
9967 if (rold->range > rcur->range)
9968 return false;
9969 /* If the offsets don't match, we can't trust our alignment;
9970 * nor can we be sure that we won't fall out of range.
9971 */
9972 if (rold->off != rcur->off)
9973 return false;
9974 /* id relations must be preserved */
9975 if (rold->id && !check_ids(rold->id, rcur->id, idmap))
9976 return false;
9977 /* new val must satisfy old val knowledge */
9978 return range_within(rold, rcur) &&
9979 tnum_in(rold->var_off, rcur->var_off);
9980 case PTR_TO_CTX:
9981 case CONST_PTR_TO_MAP:
f1174f77 9982 case PTR_TO_PACKET_END:
d58e468b 9983 case PTR_TO_FLOW_KEYS:
c64b7983
JS
9984 case PTR_TO_SOCKET:
9985 case PTR_TO_SOCKET_OR_NULL:
46f8bc92
MKL
9986 case PTR_TO_SOCK_COMMON:
9987 case PTR_TO_SOCK_COMMON_OR_NULL:
655a51e5
MKL
9988 case PTR_TO_TCP_SOCK:
9989 case PTR_TO_TCP_SOCK_OR_NULL:
fada7fdc 9990 case PTR_TO_XDP_SOCK:
f1174f77
EC
9991 /* Only valid matches are exact, which memcmp() above
9992 * would have accepted
9993 */
9994 default:
9995 /* Don't know what's going on, just say it's not safe */
9996 return false;
9997 }
969bf05e 9998
f1174f77
EC
9999 /* Shouldn't get here; if we do, say it's not safe */
10000 WARN_ON_ONCE(1);
969bf05e
AS
10001 return false;
10002}
10003
f4d7e40a
AS
10004static bool stacksafe(struct bpf_func_state *old,
10005 struct bpf_func_state *cur,
638f5b90
AS
10006 struct idpair *idmap)
10007{
10008 int i, spi;
10009
638f5b90
AS
10010 /* walk slots of the explored stack and ignore any additional
10011 * slots in the current stack, since explored(safe) state
10012 * didn't use them
10013 */
10014 for (i = 0; i < old->allocated_stack; i++) {
10015 spi = i / BPF_REG_SIZE;
10016
b233920c
AS
10017 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
10018 i += BPF_REG_SIZE - 1;
cc2b14d5 10019 /* explored state didn't use this */
fd05e57b 10020 continue;
b233920c 10021 }
cc2b14d5 10022
638f5b90
AS
10023 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
10024 continue;
19e2dbb7
AS
10025
10026 /* explored stack has more populated slots than current stack
10027 * and these slots were used
10028 */
10029 if (i >= cur->allocated_stack)
10030 return false;
10031
cc2b14d5
AS
10032 /* if old state was safe with misc data in the stack
10033 * it will be safe with zero-initialized stack.
10034 * The opposite is not true
10035 */
10036 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
10037 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
10038 continue;
638f5b90
AS
10039 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
10040 cur->stack[spi].slot_type[i % BPF_REG_SIZE])
10041 /* Ex: old explored (safe) state has STACK_SPILL in
b8c1a309 10042 * this stack slot, but current has STACK_MISC ->
638f5b90
AS
10043 * this verifier states are not equivalent,
10044 * return false to continue verification of this path
10045 */
10046 return false;
10047 if (i % BPF_REG_SIZE)
10048 continue;
10049 if (old->stack[spi].slot_type[0] != STACK_SPILL)
10050 continue;
10051 if (!regsafe(&old->stack[spi].spilled_ptr,
10052 &cur->stack[spi].spilled_ptr,
10053 idmap))
10054 /* when explored and current stack slot are both storing
10055 * spilled registers, check that stored pointers types
10056 * are the same as well.
10057 * Ex: explored safe path could have stored
10058 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
10059 * but current path has stored:
10060 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
10061 * such verifier states are not equivalent.
10062 * return false to continue verification of this path
10063 */
10064 return false;
10065 }
10066 return true;
10067}
10068
fd978bf7
JS
10069static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur)
10070{
10071 if (old->acquired_refs != cur->acquired_refs)
10072 return false;
10073 return !memcmp(old->refs, cur->refs,
10074 sizeof(*old->refs) * old->acquired_refs);
10075}
10076
f1bca824
AS
10077/* compare two verifier states
10078 *
10079 * all states stored in state_list are known to be valid, since
10080 * verifier reached 'bpf_exit' instruction through them
10081 *
10082 * this function is called when verifier exploring different branches of
10083 * execution popped from the state stack. If it sees an old state that has
10084 * more strict register state and more strict stack state then this execution
10085 * branch doesn't need to be explored further, since verifier already
10086 * concluded that more strict state leads to valid finish.
10087 *
10088 * Therefore two states are equivalent if register state is more conservative
10089 * and explored stack state is more conservative than the current one.
10090 * Example:
10091 * explored current
10092 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
10093 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
10094 *
10095 * In other words if current stack state (one being explored) has more
10096 * valid slots than old one that already passed validation, it means
10097 * the verifier can stop exploring and conclude that current state is valid too
10098 *
10099 * Similarly with registers. If explored state has register type as invalid
10100 * whereas register type in current state is meaningful, it means that
10101 * the current state will reach 'bpf_exit' instruction safely
10102 */
f4d7e40a
AS
10103static bool func_states_equal(struct bpf_func_state *old,
10104 struct bpf_func_state *cur)
f1bca824 10105{
f1174f77
EC
10106 struct idpair *idmap;
10107 bool ret = false;
f1bca824
AS
10108 int i;
10109
f1174f77
EC
10110 idmap = kcalloc(ID_MAP_SIZE, sizeof(struct idpair), GFP_KERNEL);
10111 /* If we failed to allocate the idmap, just say it's not safe */
10112 if (!idmap)
1a0dc1ac 10113 return false;
f1174f77
EC
10114
10115 for (i = 0; i < MAX_BPF_REG; i++) {
1b688a19 10116 if (!regsafe(&old->regs[i], &cur->regs[i], idmap))
f1174f77 10117 goto out_free;
f1bca824
AS
10118 }
10119
638f5b90
AS
10120 if (!stacksafe(old, cur, idmap))
10121 goto out_free;
fd978bf7
JS
10122
10123 if (!refsafe(old, cur))
10124 goto out_free;
f1174f77
EC
10125 ret = true;
10126out_free:
10127 kfree(idmap);
10128 return ret;
f1bca824
AS
10129}
10130
f4d7e40a
AS
10131static bool states_equal(struct bpf_verifier_env *env,
10132 struct bpf_verifier_state *old,
10133 struct bpf_verifier_state *cur)
10134{
10135 int i;
10136
10137 if (old->curframe != cur->curframe)
10138 return false;
10139
979d63d5
DB
10140 /* Verification state from speculative execution simulation
10141 * must never prune a non-speculative execution one.
10142 */
10143 if (old->speculative && !cur->speculative)
10144 return false;
10145
d83525ca
AS
10146 if (old->active_spin_lock != cur->active_spin_lock)
10147 return false;
10148
f4d7e40a
AS
10149 /* for states to be equal callsites have to be the same
10150 * and all frame states need to be equivalent
10151 */
10152 for (i = 0; i <= old->curframe; i++) {
10153 if (old->frame[i]->callsite != cur->frame[i]->callsite)
10154 return false;
10155 if (!func_states_equal(old->frame[i], cur->frame[i]))
10156 return false;
10157 }
10158 return true;
10159}
10160
5327ed3d
JW
10161/* Return 0 if no propagation happened. Return negative error code if error
10162 * happened. Otherwise, return the propagated bit.
10163 */
55e7f3b5
JW
10164static int propagate_liveness_reg(struct bpf_verifier_env *env,
10165 struct bpf_reg_state *reg,
10166 struct bpf_reg_state *parent_reg)
10167{
5327ed3d
JW
10168 u8 parent_flag = parent_reg->live & REG_LIVE_READ;
10169 u8 flag = reg->live & REG_LIVE_READ;
55e7f3b5
JW
10170 int err;
10171
5327ed3d
JW
10172 /* When comes here, read flags of PARENT_REG or REG could be any of
10173 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
10174 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
10175 */
10176 if (parent_flag == REG_LIVE_READ64 ||
10177 /* Or if there is no read flag from REG. */
10178 !flag ||
10179 /* Or if the read flag from REG is the same as PARENT_REG. */
10180 parent_flag == flag)
55e7f3b5
JW
10181 return 0;
10182
5327ed3d 10183 err = mark_reg_read(env, reg, parent_reg, flag);
55e7f3b5
JW
10184 if (err)
10185 return err;
10186
5327ed3d 10187 return flag;
55e7f3b5
JW
10188}
10189
8e9cd9ce 10190/* A write screens off any subsequent reads; but write marks come from the
f4d7e40a
AS
10191 * straight-line code between a state and its parent. When we arrive at an
10192 * equivalent state (jump target or such) we didn't arrive by the straight-line
10193 * code, so read marks in the state must propagate to the parent regardless
10194 * of the state's write marks. That's what 'parent == state->parent' comparison
679c782d 10195 * in mark_reg_read() is for.
8e9cd9ce 10196 */
f4d7e40a
AS
10197static int propagate_liveness(struct bpf_verifier_env *env,
10198 const struct bpf_verifier_state *vstate,
10199 struct bpf_verifier_state *vparent)
dc503a8a 10200{
3f8cafa4 10201 struct bpf_reg_state *state_reg, *parent_reg;
f4d7e40a 10202 struct bpf_func_state *state, *parent;
3f8cafa4 10203 int i, frame, err = 0;
dc503a8a 10204
f4d7e40a
AS
10205 if (vparent->curframe != vstate->curframe) {
10206 WARN(1, "propagate_live: parent frame %d current frame %d\n",
10207 vparent->curframe, vstate->curframe);
10208 return -EFAULT;
10209 }
dc503a8a
EC
10210 /* Propagate read liveness of registers... */
10211 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
83d16312 10212 for (frame = 0; frame <= vstate->curframe; frame++) {
3f8cafa4
JW
10213 parent = vparent->frame[frame];
10214 state = vstate->frame[frame];
10215 parent_reg = parent->regs;
10216 state_reg = state->regs;
83d16312
JK
10217 /* We don't need to worry about FP liveness, it's read-only */
10218 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
55e7f3b5
JW
10219 err = propagate_liveness_reg(env, &state_reg[i],
10220 &parent_reg[i]);
5327ed3d 10221 if (err < 0)
3f8cafa4 10222 return err;
5327ed3d
JW
10223 if (err == REG_LIVE_READ64)
10224 mark_insn_zext(env, &parent_reg[i]);
dc503a8a 10225 }
f4d7e40a 10226
1b04aee7 10227 /* Propagate stack slots. */
f4d7e40a
AS
10228 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
10229 i < parent->allocated_stack / BPF_REG_SIZE; i++) {
3f8cafa4
JW
10230 parent_reg = &parent->stack[i].spilled_ptr;
10231 state_reg = &state->stack[i].spilled_ptr;
55e7f3b5
JW
10232 err = propagate_liveness_reg(env, state_reg,
10233 parent_reg);
5327ed3d 10234 if (err < 0)
3f8cafa4 10235 return err;
dc503a8a
EC
10236 }
10237 }
5327ed3d 10238 return 0;
dc503a8a
EC
10239}
10240
a3ce685d
AS
10241/* find precise scalars in the previous equivalent state and
10242 * propagate them into the current state
10243 */
10244static int propagate_precision(struct bpf_verifier_env *env,
10245 const struct bpf_verifier_state *old)
10246{
10247 struct bpf_reg_state *state_reg;
10248 struct bpf_func_state *state;
10249 int i, err = 0;
10250
10251 state = old->frame[old->curframe];
10252 state_reg = state->regs;
10253 for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
10254 if (state_reg->type != SCALAR_VALUE ||
10255 !state_reg->precise)
10256 continue;
10257 if (env->log.level & BPF_LOG_LEVEL2)
10258 verbose(env, "propagating r%d\n", i);
10259 err = mark_chain_precision(env, i);
10260 if (err < 0)
10261 return err;
10262 }
10263
10264 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
10265 if (state->stack[i].slot_type[0] != STACK_SPILL)
10266 continue;
10267 state_reg = &state->stack[i].spilled_ptr;
10268 if (state_reg->type != SCALAR_VALUE ||
10269 !state_reg->precise)
10270 continue;
10271 if (env->log.level & BPF_LOG_LEVEL2)
10272 verbose(env, "propagating fp%d\n",
10273 (-i - 1) * BPF_REG_SIZE);
10274 err = mark_chain_precision_stack(env, i);
10275 if (err < 0)
10276 return err;
10277 }
10278 return 0;
10279}
10280
2589726d
AS
10281static bool states_maybe_looping(struct bpf_verifier_state *old,
10282 struct bpf_verifier_state *cur)
10283{
10284 struct bpf_func_state *fold, *fcur;
10285 int i, fr = cur->curframe;
10286
10287 if (old->curframe != fr)
10288 return false;
10289
10290 fold = old->frame[fr];
10291 fcur = cur->frame[fr];
10292 for (i = 0; i < MAX_BPF_REG; i++)
10293 if (memcmp(&fold->regs[i], &fcur->regs[i],
10294 offsetof(struct bpf_reg_state, parent)))
10295 return false;
10296 return true;
10297}
10298
10299
58e2af8b 10300static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
f1bca824 10301{
58e2af8b 10302 struct bpf_verifier_state_list *new_sl;
9f4686c4 10303 struct bpf_verifier_state_list *sl, **pprev;
679c782d 10304 struct bpf_verifier_state *cur = env->cur_state, *new;
ceefbc96 10305 int i, j, err, states_cnt = 0;
10d274e8 10306 bool add_new_state = env->test_state_freq ? true : false;
f1bca824 10307
b5dc0163 10308 cur->last_insn_idx = env->prev_insn_idx;
a8f500af 10309 if (!env->insn_aux_data[insn_idx].prune_point)
f1bca824
AS
10310 /* this 'insn_idx' instruction wasn't marked, so we will not
10311 * be doing state search here
10312 */
10313 return 0;
10314
2589726d
AS
10315 /* bpf progs typically have pruning point every 4 instructions
10316 * http://vger.kernel.org/bpfconf2019.html#session-1
10317 * Do not add new state for future pruning if the verifier hasn't seen
10318 * at least 2 jumps and at least 8 instructions.
10319 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
10320 * In tests that amounts to up to 50% reduction into total verifier
10321 * memory consumption and 20% verifier time speedup.
10322 */
10323 if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
10324 env->insn_processed - env->prev_insn_processed >= 8)
10325 add_new_state = true;
10326
a8f500af
AS
10327 pprev = explored_state(env, insn_idx);
10328 sl = *pprev;
10329
9242b5f5
AS
10330 clean_live_states(env, insn_idx, cur);
10331
a8f500af 10332 while (sl) {
dc2a4ebc
AS
10333 states_cnt++;
10334 if (sl->state.insn_idx != insn_idx)
10335 goto next;
2589726d
AS
10336 if (sl->state.branches) {
10337 if (states_maybe_looping(&sl->state, cur) &&
10338 states_equal(env, &sl->state, cur)) {
10339 verbose_linfo(env, insn_idx, "; ");
10340 verbose(env, "infinite loop detected at insn %d\n", insn_idx);
10341 return -EINVAL;
10342 }
10343 /* if the verifier is processing a loop, avoid adding new state
10344 * too often, since different loop iterations have distinct
10345 * states and may not help future pruning.
10346 * This threshold shouldn't be too low to make sure that
10347 * a loop with large bound will be rejected quickly.
10348 * The most abusive loop will be:
10349 * r1 += 1
10350 * if r1 < 1000000 goto pc-2
10351 * 1M insn_procssed limit / 100 == 10k peak states.
10352 * This threshold shouldn't be too high either, since states
10353 * at the end of the loop are likely to be useful in pruning.
10354 */
10355 if (env->jmps_processed - env->prev_jmps_processed < 20 &&
10356 env->insn_processed - env->prev_insn_processed < 100)
10357 add_new_state = false;
10358 goto miss;
10359 }
638f5b90 10360 if (states_equal(env, &sl->state, cur)) {
9f4686c4 10361 sl->hit_cnt++;
f1bca824 10362 /* reached equivalent register/stack state,
dc503a8a
EC
10363 * prune the search.
10364 * Registers read by the continuation are read by us.
8e9cd9ce
EC
10365 * If we have any write marks in env->cur_state, they
10366 * will prevent corresponding reads in the continuation
10367 * from reaching our parent (an explored_state). Our
10368 * own state will get the read marks recorded, but
10369 * they'll be immediately forgotten as we're pruning
10370 * this state and will pop a new one.
f1bca824 10371 */
f4d7e40a 10372 err = propagate_liveness(env, &sl->state, cur);
a3ce685d
AS
10373
10374 /* if previous state reached the exit with precision and
10375 * current state is equivalent to it (except precsion marks)
10376 * the precision needs to be propagated back in
10377 * the current state.
10378 */
10379 err = err ? : push_jmp_history(env, cur);
10380 err = err ? : propagate_precision(env, &sl->state);
f4d7e40a
AS
10381 if (err)
10382 return err;
f1bca824 10383 return 1;
dc503a8a 10384 }
2589726d
AS
10385miss:
10386 /* when new state is not going to be added do not increase miss count.
10387 * Otherwise several loop iterations will remove the state
10388 * recorded earlier. The goal of these heuristics is to have
10389 * states from some iterations of the loop (some in the beginning
10390 * and some at the end) to help pruning.
10391 */
10392 if (add_new_state)
10393 sl->miss_cnt++;
9f4686c4
AS
10394 /* heuristic to determine whether this state is beneficial
10395 * to keep checking from state equivalence point of view.
10396 * Higher numbers increase max_states_per_insn and verification time,
10397 * but do not meaningfully decrease insn_processed.
10398 */
10399 if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
10400 /* the state is unlikely to be useful. Remove it to
10401 * speed up verification
10402 */
10403 *pprev = sl->next;
10404 if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
2589726d
AS
10405 u32 br = sl->state.branches;
10406
10407 WARN_ONCE(br,
10408 "BUG live_done but branches_to_explore %d\n",
10409 br);
9f4686c4
AS
10410 free_verifier_state(&sl->state, false);
10411 kfree(sl);
10412 env->peak_states--;
10413 } else {
10414 /* cannot free this state, since parentage chain may
10415 * walk it later. Add it for free_list instead to
10416 * be freed at the end of verification
10417 */
10418 sl->next = env->free_list;
10419 env->free_list = sl;
10420 }
10421 sl = *pprev;
10422 continue;
10423 }
dc2a4ebc 10424next:
9f4686c4
AS
10425 pprev = &sl->next;
10426 sl = *pprev;
f1bca824
AS
10427 }
10428
06ee7115
AS
10429 if (env->max_states_per_insn < states_cnt)
10430 env->max_states_per_insn = states_cnt;
10431
2c78ee89 10432 if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
b5dc0163 10433 return push_jmp_history(env, cur);
ceefbc96 10434
2589726d 10435 if (!add_new_state)
b5dc0163 10436 return push_jmp_history(env, cur);
ceefbc96 10437
2589726d
AS
10438 /* There were no equivalent states, remember the current one.
10439 * Technically the current state is not proven to be safe yet,
f4d7e40a 10440 * but it will either reach outer most bpf_exit (which means it's safe)
2589726d 10441 * or it will be rejected. When there are no loops the verifier won't be
f4d7e40a 10442 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
2589726d
AS
10443 * again on the way to bpf_exit.
10444 * When looping the sl->state.branches will be > 0 and this state
10445 * will not be considered for equivalence until branches == 0.
f1bca824 10446 */
638f5b90 10447 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
f1bca824
AS
10448 if (!new_sl)
10449 return -ENOMEM;
06ee7115
AS
10450 env->total_states++;
10451 env->peak_states++;
2589726d
AS
10452 env->prev_jmps_processed = env->jmps_processed;
10453 env->prev_insn_processed = env->insn_processed;
f1bca824
AS
10454
10455 /* add new state to the head of linked list */
679c782d
EC
10456 new = &new_sl->state;
10457 err = copy_verifier_state(new, cur);
1969db47 10458 if (err) {
679c782d 10459 free_verifier_state(new, false);
1969db47
AS
10460 kfree(new_sl);
10461 return err;
10462 }
dc2a4ebc 10463 new->insn_idx = insn_idx;
2589726d
AS
10464 WARN_ONCE(new->branches != 1,
10465 "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
b5dc0163 10466
2589726d 10467 cur->parent = new;
b5dc0163
AS
10468 cur->first_insn_idx = insn_idx;
10469 clear_jmp_history(cur);
5d839021
AS
10470 new_sl->next = *explored_state(env, insn_idx);
10471 *explored_state(env, insn_idx) = new_sl;
7640ead9
JK
10472 /* connect new state to parentage chain. Current frame needs all
10473 * registers connected. Only r6 - r9 of the callers are alive (pushed
10474 * to the stack implicitly by JITs) so in callers' frames connect just
10475 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
10476 * the state of the call instruction (with WRITTEN set), and r0 comes
10477 * from callee with its full parentage chain, anyway.
10478 */
8e9cd9ce
EC
10479 /* clear write marks in current state: the writes we did are not writes
10480 * our child did, so they don't screen off its reads from us.
10481 * (There are no read marks in current state, because reads always mark
10482 * their parent and current state never has children yet. Only
10483 * explored_states can get read marks.)
10484 */
eea1c227
AS
10485 for (j = 0; j <= cur->curframe; j++) {
10486 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
10487 cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
10488 for (i = 0; i < BPF_REG_FP; i++)
10489 cur->frame[j]->regs[i].live = REG_LIVE_NONE;
10490 }
f4d7e40a
AS
10491
10492 /* all stack frames are accessible from callee, clear them all */
10493 for (j = 0; j <= cur->curframe; j++) {
10494 struct bpf_func_state *frame = cur->frame[j];
679c782d 10495 struct bpf_func_state *newframe = new->frame[j];
f4d7e40a 10496
679c782d 10497 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
cc2b14d5 10498 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
679c782d
EC
10499 frame->stack[i].spilled_ptr.parent =
10500 &newframe->stack[i].spilled_ptr;
10501 }
f4d7e40a 10502 }
f1bca824
AS
10503 return 0;
10504}
10505
c64b7983
JS
10506/* Return true if it's OK to have the same insn return a different type. */
10507static bool reg_type_mismatch_ok(enum bpf_reg_type type)
10508{
10509 switch (type) {
10510 case PTR_TO_CTX:
10511 case PTR_TO_SOCKET:
10512 case PTR_TO_SOCKET_OR_NULL:
46f8bc92
MKL
10513 case PTR_TO_SOCK_COMMON:
10514 case PTR_TO_SOCK_COMMON_OR_NULL:
655a51e5
MKL
10515 case PTR_TO_TCP_SOCK:
10516 case PTR_TO_TCP_SOCK_OR_NULL:
fada7fdc 10517 case PTR_TO_XDP_SOCK:
2a02759e 10518 case PTR_TO_BTF_ID:
b121b341 10519 case PTR_TO_BTF_ID_OR_NULL:
c64b7983
JS
10520 return false;
10521 default:
10522 return true;
10523 }
10524}
10525
10526/* If an instruction was previously used with particular pointer types, then we
10527 * need to be careful to avoid cases such as the below, where it may be ok
10528 * for one branch accessing the pointer, but not ok for the other branch:
10529 *
10530 * R1 = sock_ptr
10531 * goto X;
10532 * ...
10533 * R1 = some_other_valid_ptr;
10534 * goto X;
10535 * ...
10536 * R2 = *(u32 *)(R1 + 0);
10537 */
10538static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
10539{
10540 return src != prev && (!reg_type_mismatch_ok(src) ||
10541 !reg_type_mismatch_ok(prev));
10542}
10543
58e2af8b 10544static int do_check(struct bpf_verifier_env *env)
17a52670 10545{
6f8a57cc 10546 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
51c39bb1 10547 struct bpf_verifier_state *state = env->cur_state;
17a52670 10548 struct bpf_insn *insns = env->prog->insnsi;
638f5b90 10549 struct bpf_reg_state *regs;
06ee7115 10550 int insn_cnt = env->prog->len;
17a52670 10551 bool do_print_state = false;
b5dc0163 10552 int prev_insn_idx = -1;
17a52670 10553
17a52670
AS
10554 for (;;) {
10555 struct bpf_insn *insn;
10556 u8 class;
10557 int err;
10558
b5dc0163 10559 env->prev_insn_idx = prev_insn_idx;
c08435ec 10560 if (env->insn_idx >= insn_cnt) {
61bd5218 10561 verbose(env, "invalid insn idx %d insn_cnt %d\n",
c08435ec 10562 env->insn_idx, insn_cnt);
17a52670
AS
10563 return -EFAULT;
10564 }
10565
c08435ec 10566 insn = &insns[env->insn_idx];
17a52670
AS
10567 class = BPF_CLASS(insn->code);
10568
06ee7115 10569 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
61bd5218
JK
10570 verbose(env,
10571 "BPF program is too large. Processed %d insn\n",
06ee7115 10572 env->insn_processed);
17a52670
AS
10573 return -E2BIG;
10574 }
10575
c08435ec 10576 err = is_state_visited(env, env->insn_idx);
f1bca824
AS
10577 if (err < 0)
10578 return err;
10579 if (err == 1) {
10580 /* found equivalent state, can prune the search */
06ee7115 10581 if (env->log.level & BPF_LOG_LEVEL) {
f1bca824 10582 if (do_print_state)
979d63d5
DB
10583 verbose(env, "\nfrom %d to %d%s: safe\n",
10584 env->prev_insn_idx, env->insn_idx,
10585 env->cur_state->speculative ?
10586 " (speculative execution)" : "");
f1bca824 10587 else
c08435ec 10588 verbose(env, "%d: safe\n", env->insn_idx);
f1bca824
AS
10589 }
10590 goto process_bpf_exit;
10591 }
10592
c3494801
AS
10593 if (signal_pending(current))
10594 return -EAGAIN;
10595
3c2ce60b
DB
10596 if (need_resched())
10597 cond_resched();
10598
06ee7115
AS
10599 if (env->log.level & BPF_LOG_LEVEL2 ||
10600 (env->log.level & BPF_LOG_LEVEL && do_print_state)) {
10601 if (env->log.level & BPF_LOG_LEVEL2)
c08435ec 10602 verbose(env, "%d:", env->insn_idx);
c5fc9692 10603 else
979d63d5
DB
10604 verbose(env, "\nfrom %d to %d%s:",
10605 env->prev_insn_idx, env->insn_idx,
10606 env->cur_state->speculative ?
10607 " (speculative execution)" : "");
f4d7e40a 10608 print_verifier_state(env, state->frame[state->curframe]);
17a52670
AS
10609 do_print_state = false;
10610 }
10611
06ee7115 10612 if (env->log.level & BPF_LOG_LEVEL) {
7105e828 10613 const struct bpf_insn_cbs cbs = {
e6ac2450 10614 .cb_call = disasm_kfunc_name,
7105e828 10615 .cb_print = verbose,
abe08840 10616 .private_data = env,
7105e828
DB
10617 };
10618
c08435ec
DB
10619 verbose_linfo(env, env->insn_idx, "; ");
10620 verbose(env, "%d: ", env->insn_idx);
abe08840 10621 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
17a52670
AS
10622 }
10623
cae1927c 10624 if (bpf_prog_is_dev_bound(env->prog->aux)) {
c08435ec
DB
10625 err = bpf_prog_offload_verify_insn(env, env->insn_idx,
10626 env->prev_insn_idx);
cae1927c
JK
10627 if (err)
10628 return err;
10629 }
13a27dfc 10630
638f5b90 10631 regs = cur_regs(env);
51c39bb1 10632 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
b5dc0163 10633 prev_insn_idx = env->insn_idx;
fd978bf7 10634
17a52670 10635 if (class == BPF_ALU || class == BPF_ALU64) {
1be7f75d 10636 err = check_alu_op(env, insn);
17a52670
AS
10637 if (err)
10638 return err;
10639
10640 } else if (class == BPF_LDX) {
3df126f3 10641 enum bpf_reg_type *prev_src_type, src_reg_type;
9bac3d6d
AS
10642
10643 /* check for reserved fields is already done */
10644
17a52670 10645 /* check src operand */
dc503a8a 10646 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17a52670
AS
10647 if (err)
10648 return err;
10649
dc503a8a 10650 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
17a52670
AS
10651 if (err)
10652 return err;
10653
725f9dcd
AS
10654 src_reg_type = regs[insn->src_reg].type;
10655
17a52670
AS
10656 /* check that memory (src_reg + off) is readable,
10657 * the state of dst_reg will be updated by this func
10658 */
c08435ec
DB
10659 err = check_mem_access(env, env->insn_idx, insn->src_reg,
10660 insn->off, BPF_SIZE(insn->code),
10661 BPF_READ, insn->dst_reg, false);
17a52670
AS
10662 if (err)
10663 return err;
10664
c08435ec 10665 prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type;
3df126f3
JK
10666
10667 if (*prev_src_type == NOT_INIT) {
9bac3d6d
AS
10668 /* saw a valid insn
10669 * dst_reg = *(u32 *)(src_reg + off)
3df126f3 10670 * save type to validate intersecting paths
9bac3d6d 10671 */
3df126f3 10672 *prev_src_type = src_reg_type;
9bac3d6d 10673
c64b7983 10674 } else if (reg_type_mismatch(src_reg_type, *prev_src_type)) {
9bac3d6d
AS
10675 /* ABuser program is trying to use the same insn
10676 * dst_reg = *(u32*) (src_reg + off)
10677 * with different pointer types:
10678 * src_reg == ctx in one branch and
10679 * src_reg == stack|map in some other branch.
10680 * Reject it.
10681 */
61bd5218 10682 verbose(env, "same insn cannot be used with different pointers\n");
9bac3d6d
AS
10683 return -EINVAL;
10684 }
10685
17a52670 10686 } else if (class == BPF_STX) {
3df126f3 10687 enum bpf_reg_type *prev_dst_type, dst_reg_type;
d691f9e8 10688
91c960b0
BJ
10689 if (BPF_MODE(insn->code) == BPF_ATOMIC) {
10690 err = check_atomic(env, env->insn_idx, insn);
17a52670
AS
10691 if (err)
10692 return err;
c08435ec 10693 env->insn_idx++;
17a52670
AS
10694 continue;
10695 }
10696
5ca419f2
BJ
10697 if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
10698 verbose(env, "BPF_STX uses reserved fields\n");
10699 return -EINVAL;
10700 }
10701
17a52670 10702 /* check src1 operand */
dc503a8a 10703 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17a52670
AS
10704 if (err)
10705 return err;
10706 /* check src2 operand */
dc503a8a 10707 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17a52670
AS
10708 if (err)
10709 return err;
10710
d691f9e8
AS
10711 dst_reg_type = regs[insn->dst_reg].type;
10712
17a52670 10713 /* check that memory (dst_reg + off) is writeable */
c08435ec
DB
10714 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
10715 insn->off, BPF_SIZE(insn->code),
10716 BPF_WRITE, insn->src_reg, false);
17a52670
AS
10717 if (err)
10718 return err;
10719
c08435ec 10720 prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type;
3df126f3
JK
10721
10722 if (*prev_dst_type == NOT_INIT) {
10723 *prev_dst_type = dst_reg_type;
c64b7983 10724 } else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) {
61bd5218 10725 verbose(env, "same insn cannot be used with different pointers\n");
d691f9e8
AS
10726 return -EINVAL;
10727 }
10728
17a52670
AS
10729 } else if (class == BPF_ST) {
10730 if (BPF_MODE(insn->code) != BPF_MEM ||
10731 insn->src_reg != BPF_REG_0) {
61bd5218 10732 verbose(env, "BPF_ST uses reserved fields\n");
17a52670
AS
10733 return -EINVAL;
10734 }
10735 /* check src operand */
dc503a8a 10736 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17a52670
AS
10737 if (err)
10738 return err;
10739
f37a8cb8 10740 if (is_ctx_reg(env, insn->dst_reg)) {
9d2be44a 10741 verbose(env, "BPF_ST stores into R%d %s is not allowed\n",
2a159c6f
DB
10742 insn->dst_reg,
10743 reg_type_str[reg_state(env, insn->dst_reg)->type]);
f37a8cb8
DB
10744 return -EACCES;
10745 }
10746
17a52670 10747 /* check that memory (dst_reg + off) is writeable */
c08435ec
DB
10748 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
10749 insn->off, BPF_SIZE(insn->code),
10750 BPF_WRITE, -1, false);
17a52670
AS
10751 if (err)
10752 return err;
10753
092ed096 10754 } else if (class == BPF_JMP || class == BPF_JMP32) {
17a52670
AS
10755 u8 opcode = BPF_OP(insn->code);
10756
2589726d 10757 env->jmps_processed++;
17a52670
AS
10758 if (opcode == BPF_CALL) {
10759 if (BPF_SRC(insn->code) != BPF_K ||
10760 insn->off != 0 ||
f4d7e40a 10761 (insn->src_reg != BPF_REG_0 &&
e6ac2450
MKL
10762 insn->src_reg != BPF_PSEUDO_CALL &&
10763 insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
092ed096
JW
10764 insn->dst_reg != BPF_REG_0 ||
10765 class == BPF_JMP32) {
61bd5218 10766 verbose(env, "BPF_CALL uses reserved fields\n");
17a52670
AS
10767 return -EINVAL;
10768 }
10769
d83525ca
AS
10770 if (env->cur_state->active_spin_lock &&
10771 (insn->src_reg == BPF_PSEUDO_CALL ||
10772 insn->imm != BPF_FUNC_spin_unlock)) {
10773 verbose(env, "function calls are not allowed while holding a lock\n");
10774 return -EINVAL;
10775 }
f4d7e40a 10776 if (insn->src_reg == BPF_PSEUDO_CALL)
c08435ec 10777 err = check_func_call(env, insn, &env->insn_idx);
e6ac2450
MKL
10778 else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL)
10779 err = check_kfunc_call(env, insn);
f4d7e40a 10780 else
69c087ba 10781 err = check_helper_call(env, insn, &env->insn_idx);
17a52670
AS
10782 if (err)
10783 return err;
17a52670
AS
10784 } else if (opcode == BPF_JA) {
10785 if (BPF_SRC(insn->code) != BPF_K ||
10786 insn->imm != 0 ||
10787 insn->src_reg != BPF_REG_0 ||
092ed096
JW
10788 insn->dst_reg != BPF_REG_0 ||
10789 class == BPF_JMP32) {
61bd5218 10790 verbose(env, "BPF_JA uses reserved fields\n");
17a52670
AS
10791 return -EINVAL;
10792 }
10793
c08435ec 10794 env->insn_idx += insn->off + 1;
17a52670
AS
10795 continue;
10796
10797 } else if (opcode == BPF_EXIT) {
10798 if (BPF_SRC(insn->code) != BPF_K ||
10799 insn->imm != 0 ||
10800 insn->src_reg != BPF_REG_0 ||
092ed096
JW
10801 insn->dst_reg != BPF_REG_0 ||
10802 class == BPF_JMP32) {
61bd5218 10803 verbose(env, "BPF_EXIT uses reserved fields\n");
17a52670
AS
10804 return -EINVAL;
10805 }
10806
d83525ca
AS
10807 if (env->cur_state->active_spin_lock) {
10808 verbose(env, "bpf_spin_unlock is missing\n");
10809 return -EINVAL;
10810 }
10811
f4d7e40a
AS
10812 if (state->curframe) {
10813 /* exit from nested function */
c08435ec 10814 err = prepare_func_exit(env, &env->insn_idx);
f4d7e40a
AS
10815 if (err)
10816 return err;
10817 do_print_state = true;
10818 continue;
10819 }
10820
fd978bf7
JS
10821 err = check_reference_leak(env);
10822 if (err)
10823 return err;
10824
390ee7e2
AS
10825 err = check_return_code(env);
10826 if (err)
10827 return err;
f1bca824 10828process_bpf_exit:
2589726d 10829 update_branch_counts(env, env->cur_state);
b5dc0163 10830 err = pop_stack(env, &prev_insn_idx,
6f8a57cc 10831 &env->insn_idx, pop_log);
638f5b90
AS
10832 if (err < 0) {
10833 if (err != -ENOENT)
10834 return err;
17a52670
AS
10835 break;
10836 } else {
10837 do_print_state = true;
10838 continue;
10839 }
10840 } else {
c08435ec 10841 err = check_cond_jmp_op(env, insn, &env->insn_idx);
17a52670
AS
10842 if (err)
10843 return err;
10844 }
10845 } else if (class == BPF_LD) {
10846 u8 mode = BPF_MODE(insn->code);
10847
10848 if (mode == BPF_ABS || mode == BPF_IND) {
ddd872bc
AS
10849 err = check_ld_abs(env, insn);
10850 if (err)
10851 return err;
10852
17a52670
AS
10853 } else if (mode == BPF_IMM) {
10854 err = check_ld_imm(env, insn);
10855 if (err)
10856 return err;
10857
c08435ec 10858 env->insn_idx++;
51c39bb1 10859 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
17a52670 10860 } else {
61bd5218 10861 verbose(env, "invalid BPF_LD mode\n");
17a52670
AS
10862 return -EINVAL;
10863 }
10864 } else {
61bd5218 10865 verbose(env, "unknown insn class %d\n", class);
17a52670
AS
10866 return -EINVAL;
10867 }
10868
c08435ec 10869 env->insn_idx++;
17a52670
AS
10870 }
10871
10872 return 0;
10873}
10874
541c3bad
AN
10875static int find_btf_percpu_datasec(struct btf *btf)
10876{
10877 const struct btf_type *t;
10878 const char *tname;
10879 int i, n;
10880
10881 /*
10882 * Both vmlinux and module each have their own ".data..percpu"
10883 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
10884 * types to look at only module's own BTF types.
10885 */
10886 n = btf_nr_types(btf);
10887 if (btf_is_module(btf))
10888 i = btf_nr_types(btf_vmlinux);
10889 else
10890 i = 1;
10891
10892 for(; i < n; i++) {
10893 t = btf_type_by_id(btf, i);
10894 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
10895 continue;
10896
10897 tname = btf_name_by_offset(btf, t->name_off);
10898 if (!strcmp(tname, ".data..percpu"))
10899 return i;
10900 }
10901
10902 return -ENOENT;
10903}
10904
4976b718
HL
10905/* replace pseudo btf_id with kernel symbol address */
10906static int check_pseudo_btf_id(struct bpf_verifier_env *env,
10907 struct bpf_insn *insn,
10908 struct bpf_insn_aux_data *aux)
10909{
eaa6bcb7
HL
10910 const struct btf_var_secinfo *vsi;
10911 const struct btf_type *datasec;
541c3bad 10912 struct btf_mod_pair *btf_mod;
4976b718
HL
10913 const struct btf_type *t;
10914 const char *sym_name;
eaa6bcb7 10915 bool percpu = false;
f16e6313 10916 u32 type, id = insn->imm;
541c3bad 10917 struct btf *btf;
f16e6313 10918 s32 datasec_id;
4976b718 10919 u64 addr;
541c3bad 10920 int i, btf_fd, err;
4976b718 10921
541c3bad
AN
10922 btf_fd = insn[1].imm;
10923 if (btf_fd) {
10924 btf = btf_get_by_fd(btf_fd);
10925 if (IS_ERR(btf)) {
10926 verbose(env, "invalid module BTF object FD specified.\n");
10927 return -EINVAL;
10928 }
10929 } else {
10930 if (!btf_vmlinux) {
10931 verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
10932 return -EINVAL;
10933 }
10934 btf = btf_vmlinux;
10935 btf_get(btf);
4976b718
HL
10936 }
10937
541c3bad 10938 t = btf_type_by_id(btf, id);
4976b718
HL
10939 if (!t) {
10940 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
541c3bad
AN
10941 err = -ENOENT;
10942 goto err_put;
4976b718
HL
10943 }
10944
10945 if (!btf_type_is_var(t)) {
541c3bad
AN
10946 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR.\n", id);
10947 err = -EINVAL;
10948 goto err_put;
4976b718
HL
10949 }
10950
541c3bad 10951 sym_name = btf_name_by_offset(btf, t->name_off);
4976b718
HL
10952 addr = kallsyms_lookup_name(sym_name);
10953 if (!addr) {
10954 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
10955 sym_name);
541c3bad
AN
10956 err = -ENOENT;
10957 goto err_put;
4976b718
HL
10958 }
10959
541c3bad 10960 datasec_id = find_btf_percpu_datasec(btf);
eaa6bcb7 10961 if (datasec_id > 0) {
541c3bad 10962 datasec = btf_type_by_id(btf, datasec_id);
eaa6bcb7
HL
10963 for_each_vsi(i, datasec, vsi) {
10964 if (vsi->type == id) {
10965 percpu = true;
10966 break;
10967 }
10968 }
10969 }
10970
4976b718
HL
10971 insn[0].imm = (u32)addr;
10972 insn[1].imm = addr >> 32;
10973
10974 type = t->type;
541c3bad 10975 t = btf_type_skip_modifiers(btf, type, NULL);
eaa6bcb7
HL
10976 if (percpu) {
10977 aux->btf_var.reg_type = PTR_TO_PERCPU_BTF_ID;
541c3bad 10978 aux->btf_var.btf = btf;
eaa6bcb7
HL
10979 aux->btf_var.btf_id = type;
10980 } else if (!btf_type_is_struct(t)) {
4976b718
HL
10981 const struct btf_type *ret;
10982 const char *tname;
10983 u32 tsize;
10984
10985 /* resolve the type size of ksym. */
541c3bad 10986 ret = btf_resolve_size(btf, t, &tsize);
4976b718 10987 if (IS_ERR(ret)) {
541c3bad 10988 tname = btf_name_by_offset(btf, t->name_off);
4976b718
HL
10989 verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
10990 tname, PTR_ERR(ret));
541c3bad
AN
10991 err = -EINVAL;
10992 goto err_put;
4976b718
HL
10993 }
10994 aux->btf_var.reg_type = PTR_TO_MEM;
10995 aux->btf_var.mem_size = tsize;
10996 } else {
10997 aux->btf_var.reg_type = PTR_TO_BTF_ID;
541c3bad 10998 aux->btf_var.btf = btf;
4976b718
HL
10999 aux->btf_var.btf_id = type;
11000 }
541c3bad
AN
11001
11002 /* check whether we recorded this BTF (and maybe module) already */
11003 for (i = 0; i < env->used_btf_cnt; i++) {
11004 if (env->used_btfs[i].btf == btf) {
11005 btf_put(btf);
11006 return 0;
11007 }
11008 }
11009
11010 if (env->used_btf_cnt >= MAX_USED_BTFS) {
11011 err = -E2BIG;
11012 goto err_put;
11013 }
11014
11015 btf_mod = &env->used_btfs[env->used_btf_cnt];
11016 btf_mod->btf = btf;
11017 btf_mod->module = NULL;
11018
11019 /* if we reference variables from kernel module, bump its refcount */
11020 if (btf_is_module(btf)) {
11021 btf_mod->module = btf_try_get_module(btf);
11022 if (!btf_mod->module) {
11023 err = -ENXIO;
11024 goto err_put;
11025 }
11026 }
11027
11028 env->used_btf_cnt++;
11029
4976b718 11030 return 0;
541c3bad
AN
11031err_put:
11032 btf_put(btf);
11033 return err;
4976b718
HL
11034}
11035
56f668df
MKL
11036static int check_map_prealloc(struct bpf_map *map)
11037{
11038 return (map->map_type != BPF_MAP_TYPE_HASH &&
bcc6b1b7
MKL
11039 map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
11040 map->map_type != BPF_MAP_TYPE_HASH_OF_MAPS) ||
56f668df
MKL
11041 !(map->map_flags & BPF_F_NO_PREALLOC);
11042}
11043
d83525ca
AS
11044static bool is_tracing_prog_type(enum bpf_prog_type type)
11045{
11046 switch (type) {
11047 case BPF_PROG_TYPE_KPROBE:
11048 case BPF_PROG_TYPE_TRACEPOINT:
11049 case BPF_PROG_TYPE_PERF_EVENT:
11050 case BPF_PROG_TYPE_RAW_TRACEPOINT:
11051 return true;
11052 default:
11053 return false;
11054 }
11055}
11056
94dacdbd
TG
11057static bool is_preallocated_map(struct bpf_map *map)
11058{
11059 if (!check_map_prealloc(map))
11060 return false;
11061 if (map->inner_map_meta && !check_map_prealloc(map->inner_map_meta))
11062 return false;
11063 return true;
11064}
11065
61bd5218
JK
11066static int check_map_prog_compatibility(struct bpf_verifier_env *env,
11067 struct bpf_map *map,
fdc15d38
AS
11068 struct bpf_prog *prog)
11069
11070{
7e40781c 11071 enum bpf_prog_type prog_type = resolve_prog_type(prog);
94dacdbd
TG
11072 /*
11073 * Validate that trace type programs use preallocated hash maps.
11074 *
11075 * For programs attached to PERF events this is mandatory as the
11076 * perf NMI can hit any arbitrary code sequence.
11077 *
11078 * All other trace types using preallocated hash maps are unsafe as
11079 * well because tracepoint or kprobes can be inside locked regions
11080 * of the memory allocator or at a place where a recursion into the
11081 * memory allocator would see inconsistent state.
11082 *
2ed905c5
TG
11083 * On RT enabled kernels run-time allocation of all trace type
11084 * programs is strictly prohibited due to lock type constraints. On
11085 * !RT kernels it is allowed for backwards compatibility reasons for
11086 * now, but warnings are emitted so developers are made aware of
11087 * the unsafety and can fix their programs before this is enforced.
56f668df 11088 */
7e40781c
UP
11089 if (is_tracing_prog_type(prog_type) && !is_preallocated_map(map)) {
11090 if (prog_type == BPF_PROG_TYPE_PERF_EVENT) {
61bd5218 11091 verbose(env, "perf_event programs can only use preallocated hash map\n");
56f668df
MKL
11092 return -EINVAL;
11093 }
2ed905c5
TG
11094 if (IS_ENABLED(CONFIG_PREEMPT_RT)) {
11095 verbose(env, "trace type programs can only use preallocated hash map\n");
11096 return -EINVAL;
11097 }
94dacdbd
TG
11098 WARN_ONCE(1, "trace type BPF program uses run-time allocation\n");
11099 verbose(env, "trace type programs with run-time allocated hash maps are unsafe. Switch to preallocated hash maps.\n");
fdc15d38 11100 }
a3884572 11101
9e7a4d98
KS
11102 if (map_value_has_spin_lock(map)) {
11103 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
11104 verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
11105 return -EINVAL;
11106 }
11107
11108 if (is_tracing_prog_type(prog_type)) {
11109 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
11110 return -EINVAL;
11111 }
11112
11113 if (prog->aux->sleepable) {
11114 verbose(env, "sleepable progs cannot use bpf_spin_lock yet\n");
11115 return -EINVAL;
11116 }
d83525ca
AS
11117 }
11118
a3884572 11119 if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) &&
09728266 11120 !bpf_offload_prog_map_match(prog, map)) {
a3884572
JK
11121 verbose(env, "offload device mismatch between prog and map\n");
11122 return -EINVAL;
11123 }
11124
85d33df3
MKL
11125 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
11126 verbose(env, "bpf_struct_ops map cannot be used in prog\n");
11127 return -EINVAL;
11128 }
11129
1e6c62a8
AS
11130 if (prog->aux->sleepable)
11131 switch (map->map_type) {
11132 case BPF_MAP_TYPE_HASH:
11133 case BPF_MAP_TYPE_LRU_HASH:
11134 case BPF_MAP_TYPE_ARRAY:
638e4b82
AS
11135 case BPF_MAP_TYPE_PERCPU_HASH:
11136 case BPF_MAP_TYPE_PERCPU_ARRAY:
11137 case BPF_MAP_TYPE_LRU_PERCPU_HASH:
11138 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
11139 case BPF_MAP_TYPE_HASH_OF_MAPS:
1e6c62a8
AS
11140 if (!is_preallocated_map(map)) {
11141 verbose(env,
638e4b82 11142 "Sleepable programs can only use preallocated maps\n");
1e6c62a8
AS
11143 return -EINVAL;
11144 }
11145 break;
ba90c2cc
KS
11146 case BPF_MAP_TYPE_RINGBUF:
11147 break;
1e6c62a8
AS
11148 default:
11149 verbose(env,
ba90c2cc 11150 "Sleepable programs can only use array, hash, and ringbuf maps\n");
1e6c62a8
AS
11151 return -EINVAL;
11152 }
11153
fdc15d38
AS
11154 return 0;
11155}
11156
b741f163
RG
11157static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
11158{
11159 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
11160 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
11161}
11162
4976b718
HL
11163/* find and rewrite pseudo imm in ld_imm64 instructions:
11164 *
11165 * 1. if it accesses map FD, replace it with actual map pointer.
11166 * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
11167 *
11168 * NOTE: btf_vmlinux is required for converting pseudo btf_id.
0246e64d 11169 */
4976b718 11170static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
0246e64d
AS
11171{
11172 struct bpf_insn *insn = env->prog->insnsi;
11173 int insn_cnt = env->prog->len;
fdc15d38 11174 int i, j, err;
0246e64d 11175
f1f7714e 11176 err = bpf_prog_calc_tag(env->prog);
aafe6ae9
DB
11177 if (err)
11178 return err;
11179
0246e64d 11180 for (i = 0; i < insn_cnt; i++, insn++) {
9bac3d6d 11181 if (BPF_CLASS(insn->code) == BPF_LDX &&
d691f9e8 11182 (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
61bd5218 11183 verbose(env, "BPF_LDX uses reserved fields\n");
d691f9e8
AS
11184 return -EINVAL;
11185 }
11186
0246e64d 11187 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
d8eca5bb 11188 struct bpf_insn_aux_data *aux;
0246e64d
AS
11189 struct bpf_map *map;
11190 struct fd f;
d8eca5bb 11191 u64 addr;
0246e64d
AS
11192
11193 if (i == insn_cnt - 1 || insn[1].code != 0 ||
11194 insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
11195 insn[1].off != 0) {
61bd5218 11196 verbose(env, "invalid bpf_ld_imm64 insn\n");
0246e64d
AS
11197 return -EINVAL;
11198 }
11199
d8eca5bb 11200 if (insn[0].src_reg == 0)
0246e64d
AS
11201 /* valid generic load 64-bit imm */
11202 goto next_insn;
11203
4976b718
HL
11204 if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
11205 aux = &env->insn_aux_data[i];
11206 err = check_pseudo_btf_id(env, insn, aux);
11207 if (err)
11208 return err;
11209 goto next_insn;
11210 }
11211
69c087ba
YS
11212 if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
11213 aux = &env->insn_aux_data[i];
11214 aux->ptr_type = PTR_TO_FUNC;
11215 goto next_insn;
11216 }
11217
d8eca5bb
DB
11218 /* In final convert_pseudo_ld_imm64() step, this is
11219 * converted into regular 64-bit imm load insn.
11220 */
11221 if ((insn[0].src_reg != BPF_PSEUDO_MAP_FD &&
11222 insn[0].src_reg != BPF_PSEUDO_MAP_VALUE) ||
11223 (insn[0].src_reg == BPF_PSEUDO_MAP_FD &&
11224 insn[1].imm != 0)) {
11225 verbose(env,
11226 "unrecognized bpf_ld_imm64 insn\n");
0246e64d
AS
11227 return -EINVAL;
11228 }
11229
20182390 11230 f = fdget(insn[0].imm);
c2101297 11231 map = __bpf_map_get(f);
0246e64d 11232 if (IS_ERR(map)) {
61bd5218 11233 verbose(env, "fd %d is not pointing to valid bpf_map\n",
20182390 11234 insn[0].imm);
0246e64d
AS
11235 return PTR_ERR(map);
11236 }
11237
61bd5218 11238 err = check_map_prog_compatibility(env, map, env->prog);
fdc15d38
AS
11239 if (err) {
11240 fdput(f);
11241 return err;
11242 }
11243
d8eca5bb
DB
11244 aux = &env->insn_aux_data[i];
11245 if (insn->src_reg == BPF_PSEUDO_MAP_FD) {
11246 addr = (unsigned long)map;
11247 } else {
11248 u32 off = insn[1].imm;
11249
11250 if (off >= BPF_MAX_VAR_OFF) {
11251 verbose(env, "direct value offset of %u is not allowed\n", off);
11252 fdput(f);
11253 return -EINVAL;
11254 }
11255
11256 if (!map->ops->map_direct_value_addr) {
11257 verbose(env, "no direct value access support for this map type\n");
11258 fdput(f);
11259 return -EINVAL;
11260 }
11261
11262 err = map->ops->map_direct_value_addr(map, &addr, off);
11263 if (err) {
11264 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
11265 map->value_size, off);
11266 fdput(f);
11267 return err;
11268 }
11269
11270 aux->map_off = off;
11271 addr += off;
11272 }
11273
11274 insn[0].imm = (u32)addr;
11275 insn[1].imm = addr >> 32;
0246e64d
AS
11276
11277 /* check whether we recorded this map already */
d8eca5bb 11278 for (j = 0; j < env->used_map_cnt; j++) {
0246e64d 11279 if (env->used_maps[j] == map) {
d8eca5bb 11280 aux->map_index = j;
0246e64d
AS
11281 fdput(f);
11282 goto next_insn;
11283 }
d8eca5bb 11284 }
0246e64d
AS
11285
11286 if (env->used_map_cnt >= MAX_USED_MAPS) {
11287 fdput(f);
11288 return -E2BIG;
11289 }
11290
0246e64d
AS
11291 /* hold the map. If the program is rejected by verifier,
11292 * the map will be released by release_maps() or it
11293 * will be used by the valid program until it's unloaded
ab7f5bf0 11294 * and all maps are released in free_used_maps()
0246e64d 11295 */
1e0bd5a0 11296 bpf_map_inc(map);
d8eca5bb
DB
11297
11298 aux->map_index = env->used_map_cnt;
92117d84
AS
11299 env->used_maps[env->used_map_cnt++] = map;
11300
b741f163 11301 if (bpf_map_is_cgroup_storage(map) &&
e4730423 11302 bpf_cgroup_storage_assign(env->prog->aux, map)) {
b741f163 11303 verbose(env, "only one cgroup storage of each type is allowed\n");
de9cbbaa
RG
11304 fdput(f);
11305 return -EBUSY;
11306 }
11307
0246e64d
AS
11308 fdput(f);
11309next_insn:
11310 insn++;
11311 i++;
5e581dad
DB
11312 continue;
11313 }
11314
11315 /* Basic sanity check before we invest more work here. */
11316 if (!bpf_opcode_in_insntable(insn->code)) {
11317 verbose(env, "unknown opcode %02x\n", insn->code);
11318 return -EINVAL;
0246e64d
AS
11319 }
11320 }
11321
11322 /* now all pseudo BPF_LD_IMM64 instructions load valid
11323 * 'struct bpf_map *' into a register instead of user map_fd.
11324 * These pointers will be used later by verifier to validate map access.
11325 */
11326 return 0;
11327}
11328
11329/* drop refcnt of maps used by the rejected program */
58e2af8b 11330static void release_maps(struct bpf_verifier_env *env)
0246e64d 11331{
a2ea0746
DB
11332 __bpf_free_used_maps(env->prog->aux, env->used_maps,
11333 env->used_map_cnt);
0246e64d
AS
11334}
11335
541c3bad
AN
11336/* drop refcnt of maps used by the rejected program */
11337static void release_btfs(struct bpf_verifier_env *env)
11338{
11339 __bpf_free_used_btfs(env->prog->aux, env->used_btfs,
11340 env->used_btf_cnt);
11341}
11342
0246e64d 11343/* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
58e2af8b 11344static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
0246e64d
AS
11345{
11346 struct bpf_insn *insn = env->prog->insnsi;
11347 int insn_cnt = env->prog->len;
11348 int i;
11349
69c087ba
YS
11350 for (i = 0; i < insn_cnt; i++, insn++) {
11351 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
11352 continue;
11353 if (insn->src_reg == BPF_PSEUDO_FUNC)
11354 continue;
11355 insn->src_reg = 0;
11356 }
0246e64d
AS
11357}
11358
8041902d
AS
11359/* single env->prog->insni[off] instruction was replaced with the range
11360 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying
11361 * [0, off) and [off, end) to new locations, so the patched range stays zero
11362 */
b325fbca
JW
11363static int adjust_insn_aux_data(struct bpf_verifier_env *env,
11364 struct bpf_prog *new_prog, u32 off, u32 cnt)
8041902d
AS
11365{
11366 struct bpf_insn_aux_data *new_data, *old_data = env->insn_aux_data;
b325fbca
JW
11367 struct bpf_insn *insn = new_prog->insnsi;
11368 u32 prog_len;
c131187d 11369 int i;
8041902d 11370
b325fbca
JW
11371 /* aux info at OFF always needs adjustment, no matter fast path
11372 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
11373 * original insn at old prog.
11374 */
11375 old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
11376
8041902d
AS
11377 if (cnt == 1)
11378 return 0;
b325fbca 11379 prog_len = new_prog->len;
fad953ce
KC
11380 new_data = vzalloc(array_size(prog_len,
11381 sizeof(struct bpf_insn_aux_data)));
8041902d
AS
11382 if (!new_data)
11383 return -ENOMEM;
11384 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
11385 memcpy(new_data + off + cnt - 1, old_data + off,
11386 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
b325fbca 11387 for (i = off; i < off + cnt - 1; i++) {
51c39bb1 11388 new_data[i].seen = env->pass_cnt;
b325fbca
JW
11389 new_data[i].zext_dst = insn_has_def32(env, insn + i);
11390 }
8041902d
AS
11391 env->insn_aux_data = new_data;
11392 vfree(old_data);
11393 return 0;
11394}
11395
cc8b0b92
AS
11396static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
11397{
11398 int i;
11399
11400 if (len == 1)
11401 return;
4cb3d99c
JW
11402 /* NOTE: fake 'exit' subprog should be updated as well. */
11403 for (i = 0; i <= env->subprog_cnt; i++) {
afd59424 11404 if (env->subprog_info[i].start <= off)
cc8b0b92 11405 continue;
9c8105bd 11406 env->subprog_info[i].start += len - 1;
cc8b0b92
AS
11407 }
11408}
11409
a748c697
MF
11410static void adjust_poke_descs(struct bpf_prog *prog, u32 len)
11411{
11412 struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
11413 int i, sz = prog->aux->size_poke_tab;
11414 struct bpf_jit_poke_descriptor *desc;
11415
11416 for (i = 0; i < sz; i++) {
11417 desc = &tab[i];
11418 desc->insn_idx += len - 1;
11419 }
11420}
11421
8041902d
AS
11422static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
11423 const struct bpf_insn *patch, u32 len)
11424{
11425 struct bpf_prog *new_prog;
11426
11427 new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
4f73379e
AS
11428 if (IS_ERR(new_prog)) {
11429 if (PTR_ERR(new_prog) == -ERANGE)
11430 verbose(env,
11431 "insn %d cannot be patched due to 16-bit range\n",
11432 env->insn_aux_data[off].orig_idx);
8041902d 11433 return NULL;
4f73379e 11434 }
b325fbca 11435 if (adjust_insn_aux_data(env, new_prog, off, len))
8041902d 11436 return NULL;
cc8b0b92 11437 adjust_subprog_starts(env, off, len);
a748c697 11438 adjust_poke_descs(new_prog, len);
8041902d
AS
11439 return new_prog;
11440}
11441
52875a04
JK
11442static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
11443 u32 off, u32 cnt)
11444{
11445 int i, j;
11446
11447 /* find first prog starting at or after off (first to remove) */
11448 for (i = 0; i < env->subprog_cnt; i++)
11449 if (env->subprog_info[i].start >= off)
11450 break;
11451 /* find first prog starting at or after off + cnt (first to stay) */
11452 for (j = i; j < env->subprog_cnt; j++)
11453 if (env->subprog_info[j].start >= off + cnt)
11454 break;
11455 /* if j doesn't start exactly at off + cnt, we are just removing
11456 * the front of previous prog
11457 */
11458 if (env->subprog_info[j].start != off + cnt)
11459 j--;
11460
11461 if (j > i) {
11462 struct bpf_prog_aux *aux = env->prog->aux;
11463 int move;
11464
11465 /* move fake 'exit' subprog as well */
11466 move = env->subprog_cnt + 1 - j;
11467
11468 memmove(env->subprog_info + i,
11469 env->subprog_info + j,
11470 sizeof(*env->subprog_info) * move);
11471 env->subprog_cnt -= j - i;
11472
11473 /* remove func_info */
11474 if (aux->func_info) {
11475 move = aux->func_info_cnt - j;
11476
11477 memmove(aux->func_info + i,
11478 aux->func_info + j,
11479 sizeof(*aux->func_info) * move);
11480 aux->func_info_cnt -= j - i;
11481 /* func_info->insn_off is set after all code rewrites,
11482 * in adjust_btf_func() - no need to adjust
11483 */
11484 }
11485 } else {
11486 /* convert i from "first prog to remove" to "first to adjust" */
11487 if (env->subprog_info[i].start == off)
11488 i++;
11489 }
11490
11491 /* update fake 'exit' subprog as well */
11492 for (; i <= env->subprog_cnt; i++)
11493 env->subprog_info[i].start -= cnt;
11494
11495 return 0;
11496}
11497
11498static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
11499 u32 cnt)
11500{
11501 struct bpf_prog *prog = env->prog;
11502 u32 i, l_off, l_cnt, nr_linfo;
11503 struct bpf_line_info *linfo;
11504
11505 nr_linfo = prog->aux->nr_linfo;
11506 if (!nr_linfo)
11507 return 0;
11508
11509 linfo = prog->aux->linfo;
11510
11511 /* find first line info to remove, count lines to be removed */
11512 for (i = 0; i < nr_linfo; i++)
11513 if (linfo[i].insn_off >= off)
11514 break;
11515
11516 l_off = i;
11517 l_cnt = 0;
11518 for (; i < nr_linfo; i++)
11519 if (linfo[i].insn_off < off + cnt)
11520 l_cnt++;
11521 else
11522 break;
11523
11524 /* First live insn doesn't match first live linfo, it needs to "inherit"
11525 * last removed linfo. prog is already modified, so prog->len == off
11526 * means no live instructions after (tail of the program was removed).
11527 */
11528 if (prog->len != off && l_cnt &&
11529 (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
11530 l_cnt--;
11531 linfo[--i].insn_off = off + cnt;
11532 }
11533
11534 /* remove the line info which refer to the removed instructions */
11535 if (l_cnt) {
11536 memmove(linfo + l_off, linfo + i,
11537 sizeof(*linfo) * (nr_linfo - i));
11538
11539 prog->aux->nr_linfo -= l_cnt;
11540 nr_linfo = prog->aux->nr_linfo;
11541 }
11542
11543 /* pull all linfo[i].insn_off >= off + cnt in by cnt */
11544 for (i = l_off; i < nr_linfo; i++)
11545 linfo[i].insn_off -= cnt;
11546
11547 /* fix up all subprogs (incl. 'exit') which start >= off */
11548 for (i = 0; i <= env->subprog_cnt; i++)
11549 if (env->subprog_info[i].linfo_idx > l_off) {
11550 /* program may have started in the removed region but
11551 * may not be fully removed
11552 */
11553 if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
11554 env->subprog_info[i].linfo_idx -= l_cnt;
11555 else
11556 env->subprog_info[i].linfo_idx = l_off;
11557 }
11558
11559 return 0;
11560}
11561
11562static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
11563{
11564 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
11565 unsigned int orig_prog_len = env->prog->len;
11566 int err;
11567
08ca90af
JK
11568 if (bpf_prog_is_dev_bound(env->prog->aux))
11569 bpf_prog_offload_remove_insns(env, off, cnt);
11570
52875a04
JK
11571 err = bpf_remove_insns(env->prog, off, cnt);
11572 if (err)
11573 return err;
11574
11575 err = adjust_subprog_starts_after_remove(env, off, cnt);
11576 if (err)
11577 return err;
11578
11579 err = bpf_adj_linfo_after_remove(env, off, cnt);
11580 if (err)
11581 return err;
11582
11583 memmove(aux_data + off, aux_data + off + cnt,
11584 sizeof(*aux_data) * (orig_prog_len - off - cnt));
11585
11586 return 0;
11587}
11588
2a5418a1
DB
11589/* The verifier does more data flow analysis than llvm and will not
11590 * explore branches that are dead at run time. Malicious programs can
11591 * have dead code too. Therefore replace all dead at-run-time code
11592 * with 'ja -1'.
11593 *
11594 * Just nops are not optimal, e.g. if they would sit at the end of the
11595 * program and through another bug we would manage to jump there, then
11596 * we'd execute beyond program memory otherwise. Returning exception
11597 * code also wouldn't work since we can have subprogs where the dead
11598 * code could be located.
c131187d
AS
11599 */
11600static void sanitize_dead_code(struct bpf_verifier_env *env)
11601{
11602 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
2a5418a1 11603 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
c131187d
AS
11604 struct bpf_insn *insn = env->prog->insnsi;
11605 const int insn_cnt = env->prog->len;
11606 int i;
11607
11608 for (i = 0; i < insn_cnt; i++) {
11609 if (aux_data[i].seen)
11610 continue;
2a5418a1 11611 memcpy(insn + i, &trap, sizeof(trap));
c131187d
AS
11612 }
11613}
11614
e2ae4ca2
JK
11615static bool insn_is_cond_jump(u8 code)
11616{
11617 u8 op;
11618
092ed096
JW
11619 if (BPF_CLASS(code) == BPF_JMP32)
11620 return true;
11621
e2ae4ca2
JK
11622 if (BPF_CLASS(code) != BPF_JMP)
11623 return false;
11624
11625 op = BPF_OP(code);
11626 return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
11627}
11628
11629static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
11630{
11631 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
11632 struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
11633 struct bpf_insn *insn = env->prog->insnsi;
11634 const int insn_cnt = env->prog->len;
11635 int i;
11636
11637 for (i = 0; i < insn_cnt; i++, insn++) {
11638 if (!insn_is_cond_jump(insn->code))
11639 continue;
11640
11641 if (!aux_data[i + 1].seen)
11642 ja.off = insn->off;
11643 else if (!aux_data[i + 1 + insn->off].seen)
11644 ja.off = 0;
11645 else
11646 continue;
11647
08ca90af
JK
11648 if (bpf_prog_is_dev_bound(env->prog->aux))
11649 bpf_prog_offload_replace_insn(env, i, &ja);
11650
e2ae4ca2
JK
11651 memcpy(insn, &ja, sizeof(ja));
11652 }
11653}
11654
52875a04
JK
11655static int opt_remove_dead_code(struct bpf_verifier_env *env)
11656{
11657 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
11658 int insn_cnt = env->prog->len;
11659 int i, err;
11660
11661 for (i = 0; i < insn_cnt; i++) {
11662 int j;
11663
11664 j = 0;
11665 while (i + j < insn_cnt && !aux_data[i + j].seen)
11666 j++;
11667 if (!j)
11668 continue;
11669
11670 err = verifier_remove_insns(env, i, j);
11671 if (err)
11672 return err;
11673 insn_cnt = env->prog->len;
11674 }
11675
11676 return 0;
11677}
11678
a1b14abc
JK
11679static int opt_remove_nops(struct bpf_verifier_env *env)
11680{
11681 const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
11682 struct bpf_insn *insn = env->prog->insnsi;
11683 int insn_cnt = env->prog->len;
11684 int i, err;
11685
11686 for (i = 0; i < insn_cnt; i++) {
11687 if (memcmp(&insn[i], &ja, sizeof(ja)))
11688 continue;
11689
11690 err = verifier_remove_insns(env, i, 1);
11691 if (err)
11692 return err;
11693 insn_cnt--;
11694 i--;
11695 }
11696
11697 return 0;
11698}
11699
d6c2308c
JW
11700static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
11701 const union bpf_attr *attr)
a4b1d3c1 11702{
d6c2308c 11703 struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
a4b1d3c1 11704 struct bpf_insn_aux_data *aux = env->insn_aux_data;
d6c2308c 11705 int i, patch_len, delta = 0, len = env->prog->len;
a4b1d3c1 11706 struct bpf_insn *insns = env->prog->insnsi;
a4b1d3c1 11707 struct bpf_prog *new_prog;
d6c2308c 11708 bool rnd_hi32;
a4b1d3c1 11709
d6c2308c 11710 rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
a4b1d3c1 11711 zext_patch[1] = BPF_ZEXT_REG(0);
d6c2308c
JW
11712 rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
11713 rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
11714 rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
a4b1d3c1
JW
11715 for (i = 0; i < len; i++) {
11716 int adj_idx = i + delta;
11717 struct bpf_insn insn;
83a28819 11718 int load_reg;
a4b1d3c1 11719
d6c2308c 11720 insn = insns[adj_idx];
83a28819 11721 load_reg = insn_def_regno(&insn);
d6c2308c
JW
11722 if (!aux[adj_idx].zext_dst) {
11723 u8 code, class;
11724 u32 imm_rnd;
11725
11726 if (!rnd_hi32)
11727 continue;
11728
11729 code = insn.code;
11730 class = BPF_CLASS(code);
83a28819 11731 if (load_reg == -1)
d6c2308c
JW
11732 continue;
11733
11734 /* NOTE: arg "reg" (the fourth one) is only used for
83a28819
IL
11735 * BPF_STX + SRC_OP, so it is safe to pass NULL
11736 * here.
d6c2308c 11737 */
83a28819 11738 if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
d6c2308c
JW
11739 if (class == BPF_LD &&
11740 BPF_MODE(code) == BPF_IMM)
11741 i++;
11742 continue;
11743 }
11744
11745 /* ctx load could be transformed into wider load. */
11746 if (class == BPF_LDX &&
11747 aux[adj_idx].ptr_type == PTR_TO_CTX)
11748 continue;
11749
11750 imm_rnd = get_random_int();
11751 rnd_hi32_patch[0] = insn;
11752 rnd_hi32_patch[1].imm = imm_rnd;
83a28819 11753 rnd_hi32_patch[3].dst_reg = load_reg;
d6c2308c
JW
11754 patch = rnd_hi32_patch;
11755 patch_len = 4;
11756 goto apply_patch_buffer;
11757 }
11758
39491867
BJ
11759 /* Add in an zero-extend instruction if a) the JIT has requested
11760 * it or b) it's a CMPXCHG.
11761 *
11762 * The latter is because: BPF_CMPXCHG always loads a value into
11763 * R0, therefore always zero-extends. However some archs'
11764 * equivalent instruction only does this load when the
11765 * comparison is successful. This detail of CMPXCHG is
11766 * orthogonal to the general zero-extension behaviour of the
11767 * CPU, so it's treated independently of bpf_jit_needs_zext.
11768 */
11769 if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
a4b1d3c1
JW
11770 continue;
11771
83a28819
IL
11772 if (WARN_ON(load_reg == -1)) {
11773 verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
11774 return -EFAULT;
b2e37a71
IL
11775 }
11776
a4b1d3c1 11777 zext_patch[0] = insn;
b2e37a71
IL
11778 zext_patch[1].dst_reg = load_reg;
11779 zext_patch[1].src_reg = load_reg;
d6c2308c
JW
11780 patch = zext_patch;
11781 patch_len = 2;
11782apply_patch_buffer:
11783 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
a4b1d3c1
JW
11784 if (!new_prog)
11785 return -ENOMEM;
11786 env->prog = new_prog;
11787 insns = new_prog->insnsi;
11788 aux = env->insn_aux_data;
d6c2308c 11789 delta += patch_len - 1;
a4b1d3c1
JW
11790 }
11791
11792 return 0;
11793}
11794
c64b7983
JS
11795/* convert load instructions that access fields of a context type into a
11796 * sequence of instructions that access fields of the underlying structure:
11797 * struct __sk_buff -> struct sk_buff
11798 * struct bpf_sock_ops -> struct sock
9bac3d6d 11799 */
58e2af8b 11800static int convert_ctx_accesses(struct bpf_verifier_env *env)
9bac3d6d 11801{
00176a34 11802 const struct bpf_verifier_ops *ops = env->ops;
f96da094 11803 int i, cnt, size, ctx_field_size, delta = 0;
3df126f3 11804 const int insn_cnt = env->prog->len;
36bbef52 11805 struct bpf_insn insn_buf[16], *insn;
46f53a65 11806 u32 target_size, size_default, off;
9bac3d6d 11807 struct bpf_prog *new_prog;
d691f9e8 11808 enum bpf_access_type type;
f96da094 11809 bool is_narrower_load;
9bac3d6d 11810
b09928b9
DB
11811 if (ops->gen_prologue || env->seen_direct_write) {
11812 if (!ops->gen_prologue) {
11813 verbose(env, "bpf verifier is misconfigured\n");
11814 return -EINVAL;
11815 }
36bbef52
DB
11816 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
11817 env->prog);
11818 if (cnt >= ARRAY_SIZE(insn_buf)) {
61bd5218 11819 verbose(env, "bpf verifier is misconfigured\n");
36bbef52
DB
11820 return -EINVAL;
11821 } else if (cnt) {
8041902d 11822 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
36bbef52
DB
11823 if (!new_prog)
11824 return -ENOMEM;
8041902d 11825
36bbef52 11826 env->prog = new_prog;
3df126f3 11827 delta += cnt - 1;
36bbef52
DB
11828 }
11829 }
11830
c64b7983 11831 if (bpf_prog_is_dev_bound(env->prog->aux))
9bac3d6d
AS
11832 return 0;
11833
3df126f3 11834 insn = env->prog->insnsi + delta;
36bbef52 11835
9bac3d6d 11836 for (i = 0; i < insn_cnt; i++, insn++) {
c64b7983
JS
11837 bpf_convert_ctx_access_t convert_ctx_access;
11838
62c7989b
DB
11839 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
11840 insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
11841 insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
ea2e7ce5 11842 insn->code == (BPF_LDX | BPF_MEM | BPF_DW))
d691f9e8 11843 type = BPF_READ;
62c7989b
DB
11844 else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
11845 insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
11846 insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
ea2e7ce5 11847 insn->code == (BPF_STX | BPF_MEM | BPF_DW))
d691f9e8
AS
11848 type = BPF_WRITE;
11849 else
9bac3d6d
AS
11850 continue;
11851
af86ca4e
AS
11852 if (type == BPF_WRITE &&
11853 env->insn_aux_data[i + delta].sanitize_stack_off) {
11854 struct bpf_insn patch[] = {
11855 /* Sanitize suspicious stack slot with zero.
11856 * There are no memory dependencies for this store,
11857 * since it's only using frame pointer and immediate
11858 * constant of zero
11859 */
11860 BPF_ST_MEM(BPF_DW, BPF_REG_FP,
11861 env->insn_aux_data[i + delta].sanitize_stack_off,
11862 0),
11863 /* the original STX instruction will immediately
11864 * overwrite the same stack slot with appropriate value
11865 */
11866 *insn,
11867 };
11868
11869 cnt = ARRAY_SIZE(patch);
11870 new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
11871 if (!new_prog)
11872 return -ENOMEM;
11873
11874 delta += cnt - 1;
11875 env->prog = new_prog;
11876 insn = new_prog->insnsi + i + delta;
11877 continue;
11878 }
11879
c64b7983
JS
11880 switch (env->insn_aux_data[i + delta].ptr_type) {
11881 case PTR_TO_CTX:
11882 if (!ops->convert_ctx_access)
11883 continue;
11884 convert_ctx_access = ops->convert_ctx_access;
11885 break;
11886 case PTR_TO_SOCKET:
46f8bc92 11887 case PTR_TO_SOCK_COMMON:
c64b7983
JS
11888 convert_ctx_access = bpf_sock_convert_ctx_access;
11889 break;
655a51e5
MKL
11890 case PTR_TO_TCP_SOCK:
11891 convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
11892 break;
fada7fdc
JL
11893 case PTR_TO_XDP_SOCK:
11894 convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
11895 break;
2a02759e 11896 case PTR_TO_BTF_ID:
27ae7997
MKL
11897 if (type == BPF_READ) {
11898 insn->code = BPF_LDX | BPF_PROBE_MEM |
11899 BPF_SIZE((insn)->code);
11900 env->prog->aux->num_exentries++;
7e40781c 11901 } else if (resolve_prog_type(env->prog) != BPF_PROG_TYPE_STRUCT_OPS) {
2a02759e
AS
11902 verbose(env, "Writes through BTF pointers are not allowed\n");
11903 return -EINVAL;
11904 }
2a02759e 11905 continue;
c64b7983 11906 default:
9bac3d6d 11907 continue;
c64b7983 11908 }
9bac3d6d 11909
31fd8581 11910 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
f96da094 11911 size = BPF_LDST_BYTES(insn);
31fd8581
YS
11912
11913 /* If the read access is a narrower load of the field,
11914 * convert to a 4/8-byte load, to minimum program type specific
11915 * convert_ctx_access changes. If conversion is successful,
11916 * we will apply proper mask to the result.
11917 */
f96da094 11918 is_narrower_load = size < ctx_field_size;
46f53a65
AI
11919 size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
11920 off = insn->off;
31fd8581 11921 if (is_narrower_load) {
f96da094
DB
11922 u8 size_code;
11923
11924 if (type == BPF_WRITE) {
61bd5218 11925 verbose(env, "bpf verifier narrow ctx access misconfigured\n");
f96da094
DB
11926 return -EINVAL;
11927 }
31fd8581 11928
f96da094 11929 size_code = BPF_H;
31fd8581
YS
11930 if (ctx_field_size == 4)
11931 size_code = BPF_W;
11932 else if (ctx_field_size == 8)
11933 size_code = BPF_DW;
f96da094 11934
bc23105c 11935 insn->off = off & ~(size_default - 1);
31fd8581
YS
11936 insn->code = BPF_LDX | BPF_MEM | size_code;
11937 }
f96da094
DB
11938
11939 target_size = 0;
c64b7983
JS
11940 cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
11941 &target_size);
f96da094
DB
11942 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
11943 (ctx_field_size && !target_size)) {
61bd5218 11944 verbose(env, "bpf verifier is misconfigured\n");
9bac3d6d
AS
11945 return -EINVAL;
11946 }
f96da094
DB
11947
11948 if (is_narrower_load && size < target_size) {
d895a0f1
IL
11949 u8 shift = bpf_ctx_narrow_access_offset(
11950 off, size, size_default) * 8;
46f53a65
AI
11951 if (ctx_field_size <= 4) {
11952 if (shift)
11953 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
11954 insn->dst_reg,
11955 shift);
31fd8581 11956 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
f96da094 11957 (1 << size * 8) - 1);
46f53a65
AI
11958 } else {
11959 if (shift)
11960 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
11961 insn->dst_reg,
11962 shift);
31fd8581 11963 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
e2f7fc0a 11964 (1ULL << size * 8) - 1);
46f53a65 11965 }
31fd8581 11966 }
9bac3d6d 11967
8041902d 11968 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
9bac3d6d
AS
11969 if (!new_prog)
11970 return -ENOMEM;
11971
3df126f3 11972 delta += cnt - 1;
9bac3d6d
AS
11973
11974 /* keep walking new program and skip insns we just inserted */
11975 env->prog = new_prog;
3df126f3 11976 insn = new_prog->insnsi + i + delta;
9bac3d6d
AS
11977 }
11978
11979 return 0;
11980}
11981
1c2a088a
AS
11982static int jit_subprogs(struct bpf_verifier_env *env)
11983{
11984 struct bpf_prog *prog = env->prog, **func, *tmp;
11985 int i, j, subprog_start, subprog_end = 0, len, subprog;
a748c697 11986 struct bpf_map *map_ptr;
7105e828 11987 struct bpf_insn *insn;
1c2a088a 11988 void *old_bpf_func;
c4c0bdc0 11989 int err, num_exentries;
1c2a088a 11990
f910cefa 11991 if (env->subprog_cnt <= 1)
1c2a088a
AS
11992 return 0;
11993
7105e828 11994 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
69c087ba
YS
11995 if (bpf_pseudo_func(insn)) {
11996 env->insn_aux_data[i].call_imm = insn->imm;
11997 /* subprog is encoded in insn[1].imm */
11998 continue;
11999 }
12000
23a2d70c 12001 if (!bpf_pseudo_call(insn))
1c2a088a 12002 continue;
c7a89784
DB
12003 /* Upon error here we cannot fall back to interpreter but
12004 * need a hard reject of the program. Thus -EFAULT is
12005 * propagated in any case.
12006 */
1c2a088a
AS
12007 subprog = find_subprog(env, i + insn->imm + 1);
12008 if (subprog < 0) {
12009 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
12010 i + insn->imm + 1);
12011 return -EFAULT;
12012 }
12013 /* temporarily remember subprog id inside insn instead of
12014 * aux_data, since next loop will split up all insns into funcs
12015 */
f910cefa 12016 insn->off = subprog;
1c2a088a
AS
12017 /* remember original imm in case JIT fails and fallback
12018 * to interpreter will be needed
12019 */
12020 env->insn_aux_data[i].call_imm = insn->imm;
12021 /* point imm to __bpf_call_base+1 from JITs point of view */
12022 insn->imm = 1;
12023 }
12024
c454a46b
MKL
12025 err = bpf_prog_alloc_jited_linfo(prog);
12026 if (err)
12027 goto out_undo_insn;
12028
12029 err = -ENOMEM;
6396bb22 12030 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
1c2a088a 12031 if (!func)
c7a89784 12032 goto out_undo_insn;
1c2a088a 12033
f910cefa 12034 for (i = 0; i < env->subprog_cnt; i++) {
1c2a088a 12035 subprog_start = subprog_end;
4cb3d99c 12036 subprog_end = env->subprog_info[i + 1].start;
1c2a088a
AS
12037
12038 len = subprog_end - subprog_start;
492ecee8
AS
12039 /* BPF_PROG_RUN doesn't call subprogs directly,
12040 * hence main prog stats include the runtime of subprogs.
12041 * subprogs don't have IDs and not reachable via prog_get_next_id
700d4796 12042 * func[i]->stats will never be accessed and stays NULL
492ecee8
AS
12043 */
12044 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
1c2a088a
AS
12045 if (!func[i])
12046 goto out_free;
12047 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
12048 len * sizeof(struct bpf_insn));
4f74d809 12049 func[i]->type = prog->type;
1c2a088a 12050 func[i]->len = len;
4f74d809
DB
12051 if (bpf_prog_calc_tag(func[i]))
12052 goto out_free;
1c2a088a 12053 func[i]->is_func = 1;
ba64e7d8
YS
12054 func[i]->aux->func_idx = i;
12055 /* the btf and func_info will be freed only at prog->aux */
12056 func[i]->aux->btf = prog->aux->btf;
12057 func[i]->aux->func_info = prog->aux->func_info;
12058
a748c697
MF
12059 for (j = 0; j < prog->aux->size_poke_tab; j++) {
12060 u32 insn_idx = prog->aux->poke_tab[j].insn_idx;
12061 int ret;
12062
12063 if (!(insn_idx >= subprog_start &&
12064 insn_idx <= subprog_end))
12065 continue;
12066
12067 ret = bpf_jit_add_poke_descriptor(func[i],
12068 &prog->aux->poke_tab[j]);
12069 if (ret < 0) {
12070 verbose(env, "adding tail call poke descriptor failed\n");
12071 goto out_free;
12072 }
12073
12074 func[i]->insnsi[insn_idx - subprog_start].imm = ret + 1;
12075
12076 map_ptr = func[i]->aux->poke_tab[ret].tail_call.map;
12077 ret = map_ptr->ops->map_poke_track(map_ptr, func[i]->aux);
12078 if (ret < 0) {
12079 verbose(env, "tracking tail call prog failed\n");
12080 goto out_free;
12081 }
12082 }
12083
1c2a088a
AS
12084 /* Use bpf_prog_F_tag to indicate functions in stack traces.
12085 * Long term would need debug info to populate names
12086 */
12087 func[i]->aux->name[0] = 'F';
9c8105bd 12088 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
1c2a088a 12089 func[i]->jit_requested = 1;
e6ac2450 12090 func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
c454a46b
MKL
12091 func[i]->aux->linfo = prog->aux->linfo;
12092 func[i]->aux->nr_linfo = prog->aux->nr_linfo;
12093 func[i]->aux->jited_linfo = prog->aux->jited_linfo;
12094 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
c4c0bdc0
YS
12095 num_exentries = 0;
12096 insn = func[i]->insnsi;
12097 for (j = 0; j < func[i]->len; j++, insn++) {
12098 if (BPF_CLASS(insn->code) == BPF_LDX &&
12099 BPF_MODE(insn->code) == BPF_PROBE_MEM)
12100 num_exentries++;
12101 }
12102 func[i]->aux->num_exentries = num_exentries;
ebf7d1f5 12103 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
1c2a088a
AS
12104 func[i] = bpf_int_jit_compile(func[i]);
12105 if (!func[i]->jited) {
12106 err = -ENOTSUPP;
12107 goto out_free;
12108 }
12109 cond_resched();
12110 }
a748c697
MF
12111
12112 /* Untrack main program's aux structs so that during map_poke_run()
12113 * we will not stumble upon the unfilled poke descriptors; each
12114 * of the main program's poke descs got distributed across subprogs
12115 * and got tracked onto map, so we are sure that none of them will
12116 * be missed after the operation below
12117 */
12118 for (i = 0; i < prog->aux->size_poke_tab; i++) {
12119 map_ptr = prog->aux->poke_tab[i].tail_call.map;
12120
12121 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
12122 }
12123
1c2a088a
AS
12124 /* at this point all bpf functions were successfully JITed
12125 * now populate all bpf_calls with correct addresses and
12126 * run last pass of JIT
12127 */
f910cefa 12128 for (i = 0; i < env->subprog_cnt; i++) {
1c2a088a
AS
12129 insn = func[i]->insnsi;
12130 for (j = 0; j < func[i]->len; j++, insn++) {
69c087ba
YS
12131 if (bpf_pseudo_func(insn)) {
12132 subprog = insn[1].imm;
12133 insn[0].imm = (u32)(long)func[subprog]->bpf_func;
12134 insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
12135 continue;
12136 }
23a2d70c 12137 if (!bpf_pseudo_call(insn))
1c2a088a
AS
12138 continue;
12139 subprog = insn->off;
0d306c31
PB
12140 insn->imm = BPF_CAST_CALL(func[subprog]->bpf_func) -
12141 __bpf_call_base;
1c2a088a 12142 }
2162fed4
SD
12143
12144 /* we use the aux data to keep a list of the start addresses
12145 * of the JITed images for each function in the program
12146 *
12147 * for some architectures, such as powerpc64, the imm field
12148 * might not be large enough to hold the offset of the start
12149 * address of the callee's JITed image from __bpf_call_base
12150 *
12151 * in such cases, we can lookup the start address of a callee
12152 * by using its subprog id, available from the off field of
12153 * the call instruction, as an index for this list
12154 */
12155 func[i]->aux->func = func;
12156 func[i]->aux->func_cnt = env->subprog_cnt;
1c2a088a 12157 }
f910cefa 12158 for (i = 0; i < env->subprog_cnt; i++) {
1c2a088a
AS
12159 old_bpf_func = func[i]->bpf_func;
12160 tmp = bpf_int_jit_compile(func[i]);
12161 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
12162 verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
c7a89784 12163 err = -ENOTSUPP;
1c2a088a
AS
12164 goto out_free;
12165 }
12166 cond_resched();
12167 }
12168
12169 /* finally lock prog and jit images for all functions and
12170 * populate kallsysm
12171 */
f910cefa 12172 for (i = 0; i < env->subprog_cnt; i++) {
1c2a088a
AS
12173 bpf_prog_lock_ro(func[i]);
12174 bpf_prog_kallsyms_add(func[i]);
12175 }
7105e828
DB
12176
12177 /* Last step: make now unused interpreter insns from main
12178 * prog consistent for later dump requests, so they can
12179 * later look the same as if they were interpreted only.
12180 */
12181 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
69c087ba
YS
12182 if (bpf_pseudo_func(insn)) {
12183 insn[0].imm = env->insn_aux_data[i].call_imm;
12184 insn[1].imm = find_subprog(env, i + insn[0].imm + 1);
12185 continue;
12186 }
23a2d70c 12187 if (!bpf_pseudo_call(insn))
7105e828
DB
12188 continue;
12189 insn->off = env->insn_aux_data[i].call_imm;
12190 subprog = find_subprog(env, i + insn->off + 1);
dbecd738 12191 insn->imm = subprog;
7105e828
DB
12192 }
12193
1c2a088a
AS
12194 prog->jited = 1;
12195 prog->bpf_func = func[0]->bpf_func;
12196 prog->aux->func = func;
f910cefa 12197 prog->aux->func_cnt = env->subprog_cnt;
e16301fb 12198 bpf_prog_jit_attempt_done(prog);
1c2a088a
AS
12199 return 0;
12200out_free:
a748c697
MF
12201 for (i = 0; i < env->subprog_cnt; i++) {
12202 if (!func[i])
12203 continue;
12204
12205 for (j = 0; j < func[i]->aux->size_poke_tab; j++) {
12206 map_ptr = func[i]->aux->poke_tab[j].tail_call.map;
12207 map_ptr->ops->map_poke_untrack(map_ptr, func[i]->aux);
12208 }
12209 bpf_jit_free(func[i]);
12210 }
1c2a088a 12211 kfree(func);
c7a89784 12212out_undo_insn:
1c2a088a
AS
12213 /* cleanup main prog to be interpreted */
12214 prog->jit_requested = 0;
12215 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
23a2d70c 12216 if (!bpf_pseudo_call(insn))
1c2a088a
AS
12217 continue;
12218 insn->off = 0;
12219 insn->imm = env->insn_aux_data[i].call_imm;
12220 }
e16301fb 12221 bpf_prog_jit_attempt_done(prog);
1c2a088a
AS
12222 return err;
12223}
12224
1ea47e01
AS
12225static int fixup_call_args(struct bpf_verifier_env *env)
12226{
19d28fbd 12227#ifndef CONFIG_BPF_JIT_ALWAYS_ON
1ea47e01
AS
12228 struct bpf_prog *prog = env->prog;
12229 struct bpf_insn *insn = prog->insnsi;
e6ac2450 12230 bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
1ea47e01 12231 int i, depth;
19d28fbd 12232#endif
e4052d06 12233 int err = 0;
1ea47e01 12234
e4052d06
QM
12235 if (env->prog->jit_requested &&
12236 !bpf_prog_is_dev_bound(env->prog->aux)) {
19d28fbd
DM
12237 err = jit_subprogs(env);
12238 if (err == 0)
1c2a088a 12239 return 0;
c7a89784
DB
12240 if (err == -EFAULT)
12241 return err;
19d28fbd
DM
12242 }
12243#ifndef CONFIG_BPF_JIT_ALWAYS_ON
e6ac2450
MKL
12244 if (has_kfunc_call) {
12245 verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
12246 return -EINVAL;
12247 }
e411901c
MF
12248 if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
12249 /* When JIT fails the progs with bpf2bpf calls and tail_calls
12250 * have to be rejected, since interpreter doesn't support them yet.
12251 */
12252 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
12253 return -EINVAL;
12254 }
1ea47e01 12255 for (i = 0; i < prog->len; i++, insn++) {
69c087ba
YS
12256 if (bpf_pseudo_func(insn)) {
12257 /* When JIT fails the progs with callback calls
12258 * have to be rejected, since interpreter doesn't support them yet.
12259 */
12260 verbose(env, "callbacks are not allowed in non-JITed programs\n");
12261 return -EINVAL;
12262 }
12263
23a2d70c 12264 if (!bpf_pseudo_call(insn))
1ea47e01
AS
12265 continue;
12266 depth = get_callee_stack_depth(env, insn, i);
12267 if (depth < 0)
12268 return depth;
12269 bpf_patch_call_args(insn, depth);
12270 }
19d28fbd
DM
12271 err = 0;
12272#endif
12273 return err;
1ea47e01
AS
12274}
12275
e6ac2450
MKL
12276static int fixup_kfunc_call(struct bpf_verifier_env *env,
12277 struct bpf_insn *insn)
12278{
12279 const struct bpf_kfunc_desc *desc;
12280
12281 /* insn->imm has the btf func_id. Replace it with
12282 * an address (relative to __bpf_base_call).
12283 */
12284 desc = find_kfunc_desc(env->prog, insn->imm);
12285 if (!desc) {
12286 verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
12287 insn->imm);
12288 return -EFAULT;
12289 }
12290
12291 insn->imm = desc->imm;
12292
12293 return 0;
12294}
12295
e6ac5933
BJ
12296/* Do various post-verification rewrites in a single program pass.
12297 * These rewrites simplify JIT and interpreter implementations.
e245c5c6 12298 */
e6ac5933 12299static int do_misc_fixups(struct bpf_verifier_env *env)
e245c5c6 12300{
79741b3b 12301 struct bpf_prog *prog = env->prog;
d2e4c1e6 12302 bool expect_blinding = bpf_jit_blinding_enabled(prog);
79741b3b 12303 struct bpf_insn *insn = prog->insnsi;
e245c5c6 12304 const struct bpf_func_proto *fn;
79741b3b 12305 const int insn_cnt = prog->len;
09772d92 12306 const struct bpf_map_ops *ops;
c93552c4 12307 struct bpf_insn_aux_data *aux;
81ed18ab
AS
12308 struct bpf_insn insn_buf[16];
12309 struct bpf_prog *new_prog;
12310 struct bpf_map *map_ptr;
d2e4c1e6 12311 int i, ret, cnt, delta = 0;
e245c5c6 12312
79741b3b 12313 for (i = 0; i < insn_cnt; i++, insn++) {
e6ac5933 12314 /* Make divide-by-zero exceptions impossible. */
f6b1b3bf
DB
12315 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
12316 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
12317 insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
68fda450 12318 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
f6b1b3bf 12319 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
e88b2c6e
DB
12320 bool isdiv = BPF_OP(insn->code) == BPF_DIV;
12321 struct bpf_insn *patchlet;
12322 struct bpf_insn chk_and_div[] = {
9b00f1b7 12323 /* [R,W]x div 0 -> 0 */
e88b2c6e
DB
12324 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
12325 BPF_JNE | BPF_K, insn->src_reg,
12326 0, 2, 0),
f6b1b3bf
DB
12327 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
12328 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
12329 *insn,
12330 };
e88b2c6e 12331 struct bpf_insn chk_and_mod[] = {
9b00f1b7 12332 /* [R,W]x mod 0 -> [R,W]x */
e88b2c6e
DB
12333 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
12334 BPF_JEQ | BPF_K, insn->src_reg,
9b00f1b7 12335 0, 1 + (is64 ? 0 : 1), 0),
f6b1b3bf 12336 *insn,
9b00f1b7
DB
12337 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
12338 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
f6b1b3bf 12339 };
f6b1b3bf 12340
e88b2c6e
DB
12341 patchlet = isdiv ? chk_and_div : chk_and_mod;
12342 cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
9b00f1b7 12343 ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
f6b1b3bf
DB
12344
12345 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
68fda450
AS
12346 if (!new_prog)
12347 return -ENOMEM;
12348
12349 delta += cnt - 1;
12350 env->prog = prog = new_prog;
12351 insn = new_prog->insnsi + i + delta;
12352 continue;
12353 }
12354
e6ac5933 12355 /* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
e0cea7ce
DB
12356 if (BPF_CLASS(insn->code) == BPF_LD &&
12357 (BPF_MODE(insn->code) == BPF_ABS ||
12358 BPF_MODE(insn->code) == BPF_IND)) {
12359 cnt = env->ops->gen_ld_abs(insn, insn_buf);
12360 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
12361 verbose(env, "bpf verifier is misconfigured\n");
12362 return -EINVAL;
12363 }
12364
12365 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
12366 if (!new_prog)
12367 return -ENOMEM;
12368
12369 delta += cnt - 1;
12370 env->prog = prog = new_prog;
12371 insn = new_prog->insnsi + i + delta;
12372 continue;
12373 }
12374
e6ac5933 12375 /* Rewrite pointer arithmetic to mitigate speculation attacks. */
979d63d5
DB
12376 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
12377 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
12378 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
12379 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
979d63d5 12380 struct bpf_insn *patch = &insn_buf[0];
801c6058 12381 bool issrc, isneg, isimm;
979d63d5
DB
12382 u32 off_reg;
12383
12384 aux = &env->insn_aux_data[i + delta];
3612af78
DB
12385 if (!aux->alu_state ||
12386 aux->alu_state == BPF_ALU_NON_POINTER)
979d63d5
DB
12387 continue;
12388
12389 isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
12390 issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
12391 BPF_ALU_SANITIZE_SRC;
801c6058 12392 isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
979d63d5
DB
12393
12394 off_reg = issrc ? insn->src_reg : insn->dst_reg;
801c6058
DB
12395 if (isimm) {
12396 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
12397 } else {
12398 if (isneg)
12399 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
12400 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
12401 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
12402 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
12403 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
12404 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
12405 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
12406 }
b9b34ddb
DB
12407 if (!issrc)
12408 *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
12409 insn->src_reg = BPF_REG_AX;
979d63d5
DB
12410 if (isneg)
12411 insn->code = insn->code == code_add ?
12412 code_sub : code_add;
12413 *patch++ = *insn;
801c6058 12414 if (issrc && isneg && !isimm)
979d63d5
DB
12415 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
12416 cnt = patch - insn_buf;
12417
12418 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
12419 if (!new_prog)
12420 return -ENOMEM;
12421
12422 delta += cnt - 1;
12423 env->prog = prog = new_prog;
12424 insn = new_prog->insnsi + i + delta;
12425 continue;
12426 }
12427
79741b3b
AS
12428 if (insn->code != (BPF_JMP | BPF_CALL))
12429 continue;
cc8b0b92
AS
12430 if (insn->src_reg == BPF_PSEUDO_CALL)
12431 continue;
e6ac2450
MKL
12432 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
12433 ret = fixup_kfunc_call(env, insn);
12434 if (ret)
12435 return ret;
12436 continue;
12437 }
e245c5c6 12438
79741b3b
AS
12439 if (insn->imm == BPF_FUNC_get_route_realm)
12440 prog->dst_needed = 1;
12441 if (insn->imm == BPF_FUNC_get_prandom_u32)
12442 bpf_user_rnd_init_once();
9802d865
JB
12443 if (insn->imm == BPF_FUNC_override_return)
12444 prog->kprobe_override = 1;
79741b3b 12445 if (insn->imm == BPF_FUNC_tail_call) {
7b9f6da1
DM
12446 /* If we tail call into other programs, we
12447 * cannot make any assumptions since they can
12448 * be replaced dynamically during runtime in
12449 * the program array.
12450 */
12451 prog->cb_access = 1;
e411901c
MF
12452 if (!allow_tail_call_in_subprogs(env))
12453 prog->aux->stack_depth = MAX_BPF_STACK;
12454 prog->aux->max_pkt_offset = MAX_PACKET_OFF;
7b9f6da1 12455
79741b3b
AS
12456 /* mark bpf_tail_call as different opcode to avoid
12457 * conditional branch in the interpeter for every normal
12458 * call and to prevent accidental JITing by JIT compiler
12459 * that doesn't support bpf_tail_call yet
e245c5c6 12460 */
79741b3b 12461 insn->imm = 0;
71189fa9 12462 insn->code = BPF_JMP | BPF_TAIL_CALL;
b2157399 12463
c93552c4 12464 aux = &env->insn_aux_data[i + delta];
2c78ee89 12465 if (env->bpf_capable && !expect_blinding &&
cc52d914 12466 prog->jit_requested &&
d2e4c1e6
DB
12467 !bpf_map_key_poisoned(aux) &&
12468 !bpf_map_ptr_poisoned(aux) &&
12469 !bpf_map_ptr_unpriv(aux)) {
12470 struct bpf_jit_poke_descriptor desc = {
12471 .reason = BPF_POKE_REASON_TAIL_CALL,
12472 .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
12473 .tail_call.key = bpf_map_key_immediate(aux),
a748c697 12474 .insn_idx = i + delta,
d2e4c1e6
DB
12475 };
12476
12477 ret = bpf_jit_add_poke_descriptor(prog, &desc);
12478 if (ret < 0) {
12479 verbose(env, "adding tail call poke descriptor failed\n");
12480 return ret;
12481 }
12482
12483 insn->imm = ret + 1;
12484 continue;
12485 }
12486
c93552c4
DB
12487 if (!bpf_map_ptr_unpriv(aux))
12488 continue;
12489
b2157399
AS
12490 /* instead of changing every JIT dealing with tail_call
12491 * emit two extra insns:
12492 * if (index >= max_entries) goto out;
12493 * index &= array->index_mask;
12494 * to avoid out-of-bounds cpu speculation
12495 */
c93552c4 12496 if (bpf_map_ptr_poisoned(aux)) {
40950343 12497 verbose(env, "tail_call abusing map_ptr\n");
b2157399
AS
12498 return -EINVAL;
12499 }
c93552c4 12500
d2e4c1e6 12501 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
b2157399
AS
12502 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
12503 map_ptr->max_entries, 2);
12504 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
12505 container_of(map_ptr,
12506 struct bpf_array,
12507 map)->index_mask);
12508 insn_buf[2] = *insn;
12509 cnt = 3;
12510 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
12511 if (!new_prog)
12512 return -ENOMEM;
12513
12514 delta += cnt - 1;
12515 env->prog = prog = new_prog;
12516 insn = new_prog->insnsi + i + delta;
79741b3b
AS
12517 continue;
12518 }
e245c5c6 12519
89c63074 12520 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
09772d92
DB
12521 * and other inlining handlers are currently limited to 64 bit
12522 * only.
89c63074 12523 */
60b58afc 12524 if (prog->jit_requested && BITS_PER_LONG == 64 &&
09772d92
DB
12525 (insn->imm == BPF_FUNC_map_lookup_elem ||
12526 insn->imm == BPF_FUNC_map_update_elem ||
84430d42
DB
12527 insn->imm == BPF_FUNC_map_delete_elem ||
12528 insn->imm == BPF_FUNC_map_push_elem ||
12529 insn->imm == BPF_FUNC_map_pop_elem ||
e6a4750f
BT
12530 insn->imm == BPF_FUNC_map_peek_elem ||
12531 insn->imm == BPF_FUNC_redirect_map)) {
c93552c4
DB
12532 aux = &env->insn_aux_data[i + delta];
12533 if (bpf_map_ptr_poisoned(aux))
12534 goto patch_call_imm;
12535
d2e4c1e6 12536 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
09772d92
DB
12537 ops = map_ptr->ops;
12538 if (insn->imm == BPF_FUNC_map_lookup_elem &&
12539 ops->map_gen_lookup) {
12540 cnt = ops->map_gen_lookup(map_ptr, insn_buf);
4a8f87e6
DB
12541 if (cnt == -EOPNOTSUPP)
12542 goto patch_map_ops_generic;
12543 if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
09772d92
DB
12544 verbose(env, "bpf verifier is misconfigured\n");
12545 return -EINVAL;
12546 }
81ed18ab 12547
09772d92
DB
12548 new_prog = bpf_patch_insn_data(env, i + delta,
12549 insn_buf, cnt);
12550 if (!new_prog)
12551 return -ENOMEM;
81ed18ab 12552
09772d92
DB
12553 delta += cnt - 1;
12554 env->prog = prog = new_prog;
12555 insn = new_prog->insnsi + i + delta;
12556 continue;
12557 }
81ed18ab 12558
09772d92
DB
12559 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
12560 (void *(*)(struct bpf_map *map, void *key))NULL));
12561 BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
12562 (int (*)(struct bpf_map *map, void *key))NULL));
12563 BUILD_BUG_ON(!__same_type(ops->map_update_elem,
12564 (int (*)(struct bpf_map *map, void *key, void *value,
12565 u64 flags))NULL));
84430d42
DB
12566 BUILD_BUG_ON(!__same_type(ops->map_push_elem,
12567 (int (*)(struct bpf_map *map, void *value,
12568 u64 flags))NULL));
12569 BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
12570 (int (*)(struct bpf_map *map, void *value))NULL));
12571 BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
12572 (int (*)(struct bpf_map *map, void *value))NULL));
e6a4750f
BT
12573 BUILD_BUG_ON(!__same_type(ops->map_redirect,
12574 (int (*)(struct bpf_map *map, u32 ifindex, u64 flags))NULL));
12575
4a8f87e6 12576patch_map_ops_generic:
09772d92
DB
12577 switch (insn->imm) {
12578 case BPF_FUNC_map_lookup_elem:
12579 insn->imm = BPF_CAST_CALL(ops->map_lookup_elem) -
12580 __bpf_call_base;
12581 continue;
12582 case BPF_FUNC_map_update_elem:
12583 insn->imm = BPF_CAST_CALL(ops->map_update_elem) -
12584 __bpf_call_base;
12585 continue;
12586 case BPF_FUNC_map_delete_elem:
12587 insn->imm = BPF_CAST_CALL(ops->map_delete_elem) -
12588 __bpf_call_base;
12589 continue;
84430d42
DB
12590 case BPF_FUNC_map_push_elem:
12591 insn->imm = BPF_CAST_CALL(ops->map_push_elem) -
12592 __bpf_call_base;
12593 continue;
12594 case BPF_FUNC_map_pop_elem:
12595 insn->imm = BPF_CAST_CALL(ops->map_pop_elem) -
12596 __bpf_call_base;
12597 continue;
12598 case BPF_FUNC_map_peek_elem:
12599 insn->imm = BPF_CAST_CALL(ops->map_peek_elem) -
12600 __bpf_call_base;
12601 continue;
e6a4750f
BT
12602 case BPF_FUNC_redirect_map:
12603 insn->imm = BPF_CAST_CALL(ops->map_redirect) -
12604 __bpf_call_base;
12605 continue;
09772d92 12606 }
81ed18ab 12607
09772d92 12608 goto patch_call_imm;
81ed18ab
AS
12609 }
12610
e6ac5933 12611 /* Implement bpf_jiffies64 inline. */
5576b991
MKL
12612 if (prog->jit_requested && BITS_PER_LONG == 64 &&
12613 insn->imm == BPF_FUNC_jiffies64) {
12614 struct bpf_insn ld_jiffies_addr[2] = {
12615 BPF_LD_IMM64(BPF_REG_0,
12616 (unsigned long)&jiffies),
12617 };
12618
12619 insn_buf[0] = ld_jiffies_addr[0];
12620 insn_buf[1] = ld_jiffies_addr[1];
12621 insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
12622 BPF_REG_0, 0);
12623 cnt = 3;
12624
12625 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
12626 cnt);
12627 if (!new_prog)
12628 return -ENOMEM;
12629
12630 delta += cnt - 1;
12631 env->prog = prog = new_prog;
12632 insn = new_prog->insnsi + i + delta;
12633 continue;
12634 }
12635
81ed18ab 12636patch_call_imm:
5e43f899 12637 fn = env->ops->get_func_proto(insn->imm, env->prog);
79741b3b
AS
12638 /* all functions that have prototype and verifier allowed
12639 * programs to call them, must be real in-kernel functions
12640 */
12641 if (!fn->func) {
61bd5218
JK
12642 verbose(env,
12643 "kernel subsystem misconfigured func %s#%d\n",
79741b3b
AS
12644 func_id_name(insn->imm), insn->imm);
12645 return -EFAULT;
e245c5c6 12646 }
79741b3b 12647 insn->imm = fn->func - __bpf_call_base;
e245c5c6 12648 }
e245c5c6 12649
d2e4c1e6
DB
12650 /* Since poke tab is now finalized, publish aux to tracker. */
12651 for (i = 0; i < prog->aux->size_poke_tab; i++) {
12652 map_ptr = prog->aux->poke_tab[i].tail_call.map;
12653 if (!map_ptr->ops->map_poke_track ||
12654 !map_ptr->ops->map_poke_untrack ||
12655 !map_ptr->ops->map_poke_run) {
12656 verbose(env, "bpf verifier is misconfigured\n");
12657 return -EINVAL;
12658 }
12659
12660 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
12661 if (ret < 0) {
12662 verbose(env, "tracking tail call prog failed\n");
12663 return ret;
12664 }
12665 }
12666
e6ac2450
MKL
12667 sort_kfunc_descs_by_imm(env->prog);
12668
79741b3b
AS
12669 return 0;
12670}
e245c5c6 12671
58e2af8b 12672static void free_states(struct bpf_verifier_env *env)
f1bca824 12673{
58e2af8b 12674 struct bpf_verifier_state_list *sl, *sln;
f1bca824
AS
12675 int i;
12676
9f4686c4
AS
12677 sl = env->free_list;
12678 while (sl) {
12679 sln = sl->next;
12680 free_verifier_state(&sl->state, false);
12681 kfree(sl);
12682 sl = sln;
12683 }
51c39bb1 12684 env->free_list = NULL;
9f4686c4 12685
f1bca824
AS
12686 if (!env->explored_states)
12687 return;
12688
dc2a4ebc 12689 for (i = 0; i < state_htab_size(env); i++) {
f1bca824
AS
12690 sl = env->explored_states[i];
12691
a8f500af
AS
12692 while (sl) {
12693 sln = sl->next;
12694 free_verifier_state(&sl->state, false);
12695 kfree(sl);
12696 sl = sln;
12697 }
51c39bb1 12698 env->explored_states[i] = NULL;
f1bca824 12699 }
51c39bb1 12700}
f1bca824 12701
51c39bb1
AS
12702/* The verifier is using insn_aux_data[] to store temporary data during
12703 * verification and to store information for passes that run after the
12704 * verification like dead code sanitization. do_check_common() for subprogram N
12705 * may analyze many other subprograms. sanitize_insn_aux_data() clears all
12706 * temporary data after do_check_common() finds that subprogram N cannot be
12707 * verified independently. pass_cnt counts the number of times
12708 * do_check_common() was run and insn->aux->seen tells the pass number
12709 * insn_aux_data was touched. These variables are compared to clear temporary
12710 * data from failed pass. For testing and experiments do_check_common() can be
12711 * run multiple times even when prior attempt to verify is unsuccessful.
12712 */
12713static void sanitize_insn_aux_data(struct bpf_verifier_env *env)
12714{
12715 struct bpf_insn *insn = env->prog->insnsi;
12716 struct bpf_insn_aux_data *aux;
12717 int i, class;
12718
12719 for (i = 0; i < env->prog->len; i++) {
12720 class = BPF_CLASS(insn[i].code);
12721 if (class != BPF_LDX && class != BPF_STX)
12722 continue;
12723 aux = &env->insn_aux_data[i];
12724 if (aux->seen != env->pass_cnt)
12725 continue;
12726 memset(aux, 0, offsetof(typeof(*aux), orig_idx));
12727 }
f1bca824
AS
12728}
12729
51c39bb1
AS
12730static int do_check_common(struct bpf_verifier_env *env, int subprog)
12731{
6f8a57cc 12732 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
51c39bb1
AS
12733 struct bpf_verifier_state *state;
12734 struct bpf_reg_state *regs;
12735 int ret, i;
12736
12737 env->prev_linfo = NULL;
12738 env->pass_cnt++;
12739
12740 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
12741 if (!state)
12742 return -ENOMEM;
12743 state->curframe = 0;
12744 state->speculative = false;
12745 state->branches = 1;
12746 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
12747 if (!state->frame[0]) {
12748 kfree(state);
12749 return -ENOMEM;
12750 }
12751 env->cur_state = state;
12752 init_func_state(env, state->frame[0],
12753 BPF_MAIN_FUNC /* callsite */,
12754 0 /* frameno */,
12755 subprog);
12756
12757 regs = state->frame[state->curframe]->regs;
be8704ff 12758 if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
51c39bb1
AS
12759 ret = btf_prepare_func_args(env, subprog, regs);
12760 if (ret)
12761 goto out;
12762 for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
12763 if (regs[i].type == PTR_TO_CTX)
12764 mark_reg_known_zero(env, regs, i);
12765 else if (regs[i].type == SCALAR_VALUE)
12766 mark_reg_unknown(env, regs, i);
e5069b9c
DB
12767 else if (regs[i].type == PTR_TO_MEM_OR_NULL) {
12768 const u32 mem_size = regs[i].mem_size;
12769
12770 mark_reg_known_zero(env, regs, i);
12771 regs[i].mem_size = mem_size;
12772 regs[i].id = ++env->id_gen;
12773 }
51c39bb1
AS
12774 }
12775 } else {
12776 /* 1st arg to a function */
12777 regs[BPF_REG_1].type = PTR_TO_CTX;
12778 mark_reg_known_zero(env, regs, BPF_REG_1);
34747c41 12779 ret = btf_check_subprog_arg_match(env, subprog, regs);
51c39bb1
AS
12780 if (ret == -EFAULT)
12781 /* unlikely verifier bug. abort.
12782 * ret == 0 and ret < 0 are sadly acceptable for
12783 * main() function due to backward compatibility.
12784 * Like socket filter program may be written as:
12785 * int bpf_prog(struct pt_regs *ctx)
12786 * and never dereference that ctx in the program.
12787 * 'struct pt_regs' is a type mismatch for socket
12788 * filter that should be using 'struct __sk_buff'.
12789 */
12790 goto out;
12791 }
12792
12793 ret = do_check(env);
12794out:
f59bbfc2
AS
12795 /* check for NULL is necessary, since cur_state can be freed inside
12796 * do_check() under memory pressure.
12797 */
12798 if (env->cur_state) {
12799 free_verifier_state(env->cur_state, true);
12800 env->cur_state = NULL;
12801 }
6f8a57cc
AN
12802 while (!pop_stack(env, NULL, NULL, false));
12803 if (!ret && pop_log)
12804 bpf_vlog_reset(&env->log, 0);
51c39bb1
AS
12805 free_states(env);
12806 if (ret)
12807 /* clean aux data in case subprog was rejected */
12808 sanitize_insn_aux_data(env);
12809 return ret;
12810}
12811
12812/* Verify all global functions in a BPF program one by one based on their BTF.
12813 * All global functions must pass verification. Otherwise the whole program is rejected.
12814 * Consider:
12815 * int bar(int);
12816 * int foo(int f)
12817 * {
12818 * return bar(f);
12819 * }
12820 * int bar(int b)
12821 * {
12822 * ...
12823 * }
12824 * foo() will be verified first for R1=any_scalar_value. During verification it
12825 * will be assumed that bar() already verified successfully and call to bar()
12826 * from foo() will be checked for type match only. Later bar() will be verified
12827 * independently to check that it's safe for R1=any_scalar_value.
12828 */
12829static int do_check_subprogs(struct bpf_verifier_env *env)
12830{
12831 struct bpf_prog_aux *aux = env->prog->aux;
12832 int i, ret;
12833
12834 if (!aux->func_info)
12835 return 0;
12836
12837 for (i = 1; i < env->subprog_cnt; i++) {
12838 if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
12839 continue;
12840 env->insn_idx = env->subprog_info[i].start;
12841 WARN_ON_ONCE(env->insn_idx == 0);
12842 ret = do_check_common(env, i);
12843 if (ret) {
12844 return ret;
12845 } else if (env->log.level & BPF_LOG_LEVEL) {
12846 verbose(env,
12847 "Func#%d is safe for any args that match its prototype\n",
12848 i);
12849 }
12850 }
12851 return 0;
12852}
12853
12854static int do_check_main(struct bpf_verifier_env *env)
12855{
12856 int ret;
12857
12858 env->insn_idx = 0;
12859 ret = do_check_common(env, 0);
12860 if (!ret)
12861 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
12862 return ret;
12863}
12864
12865
06ee7115
AS
12866static void print_verification_stats(struct bpf_verifier_env *env)
12867{
12868 int i;
12869
12870 if (env->log.level & BPF_LOG_STATS) {
12871 verbose(env, "verification time %lld usec\n",
12872 div_u64(env->verification_time, 1000));
12873 verbose(env, "stack depth ");
12874 for (i = 0; i < env->subprog_cnt; i++) {
12875 u32 depth = env->subprog_info[i].stack_depth;
12876
12877 verbose(env, "%d", depth);
12878 if (i + 1 < env->subprog_cnt)
12879 verbose(env, "+");
12880 }
12881 verbose(env, "\n");
12882 }
12883 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
12884 "total_states %d peak_states %d mark_read %d\n",
12885 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
12886 env->max_states_per_insn, env->total_states,
12887 env->peak_states, env->longest_mark_read_walk);
f1bca824
AS
12888}
12889
27ae7997
MKL
12890static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
12891{
12892 const struct btf_type *t, *func_proto;
12893 const struct bpf_struct_ops *st_ops;
12894 const struct btf_member *member;
12895 struct bpf_prog *prog = env->prog;
12896 u32 btf_id, member_idx;
12897 const char *mname;
12898
12aa8a94
THJ
12899 if (!prog->gpl_compatible) {
12900 verbose(env, "struct ops programs must have a GPL compatible license\n");
12901 return -EINVAL;
12902 }
12903
27ae7997
MKL
12904 btf_id = prog->aux->attach_btf_id;
12905 st_ops = bpf_struct_ops_find(btf_id);
12906 if (!st_ops) {
12907 verbose(env, "attach_btf_id %u is not a supported struct\n",
12908 btf_id);
12909 return -ENOTSUPP;
12910 }
12911
12912 t = st_ops->type;
12913 member_idx = prog->expected_attach_type;
12914 if (member_idx >= btf_type_vlen(t)) {
12915 verbose(env, "attach to invalid member idx %u of struct %s\n",
12916 member_idx, st_ops->name);
12917 return -EINVAL;
12918 }
12919
12920 member = &btf_type_member(t)[member_idx];
12921 mname = btf_name_by_offset(btf_vmlinux, member->name_off);
12922 func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
12923 NULL);
12924 if (!func_proto) {
12925 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
12926 mname, member_idx, st_ops->name);
12927 return -EINVAL;
12928 }
12929
12930 if (st_ops->check_member) {
12931 int err = st_ops->check_member(t, member);
12932
12933 if (err) {
12934 verbose(env, "attach to unsupported member %s of struct %s\n",
12935 mname, st_ops->name);
12936 return err;
12937 }
12938 }
12939
12940 prog->aux->attach_func_proto = func_proto;
12941 prog->aux->attach_func_name = mname;
12942 env->ops = st_ops->verifier_ops;
12943
12944 return 0;
12945}
6ba43b76
KS
12946#define SECURITY_PREFIX "security_"
12947
f7b12b6f 12948static int check_attach_modify_return(unsigned long addr, const char *func_name)
6ba43b76 12949{
69191754 12950 if (within_error_injection_list(addr) ||
f7b12b6f 12951 !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
6ba43b76 12952 return 0;
6ba43b76 12953
6ba43b76
KS
12954 return -EINVAL;
12955}
27ae7997 12956
1e6c62a8
AS
12957/* list of non-sleepable functions that are otherwise on
12958 * ALLOW_ERROR_INJECTION list
12959 */
12960BTF_SET_START(btf_non_sleepable_error_inject)
12961/* Three functions below can be called from sleepable and non-sleepable context.
12962 * Assume non-sleepable from bpf safety point of view.
12963 */
12964BTF_ID(func, __add_to_page_cache_locked)
12965BTF_ID(func, should_fail_alloc_page)
12966BTF_ID(func, should_failslab)
12967BTF_SET_END(btf_non_sleepable_error_inject)
12968
12969static int check_non_sleepable_error_inject(u32 btf_id)
12970{
12971 return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
12972}
12973
f7b12b6f
THJ
12974int bpf_check_attach_target(struct bpf_verifier_log *log,
12975 const struct bpf_prog *prog,
12976 const struct bpf_prog *tgt_prog,
12977 u32 btf_id,
12978 struct bpf_attach_target_info *tgt_info)
38207291 12979{
be8704ff 12980 bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
f1b9509c 12981 const char prefix[] = "btf_trace_";
5b92a28a 12982 int ret = 0, subprog = -1, i;
38207291 12983 const struct btf_type *t;
5b92a28a 12984 bool conservative = true;
38207291 12985 const char *tname;
5b92a28a 12986 struct btf *btf;
f7b12b6f 12987 long addr = 0;
38207291 12988
f1b9509c 12989 if (!btf_id) {
efc68158 12990 bpf_log(log, "Tracing programs must provide btf_id\n");
f1b9509c
AS
12991 return -EINVAL;
12992 }
22dc4a0f 12993 btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
5b92a28a 12994 if (!btf) {
efc68158 12995 bpf_log(log,
5b92a28a
AS
12996 "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
12997 return -EINVAL;
12998 }
12999 t = btf_type_by_id(btf, btf_id);
f1b9509c 13000 if (!t) {
efc68158 13001 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
f1b9509c
AS
13002 return -EINVAL;
13003 }
5b92a28a 13004 tname = btf_name_by_offset(btf, t->name_off);
f1b9509c 13005 if (!tname) {
efc68158 13006 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
f1b9509c
AS
13007 return -EINVAL;
13008 }
5b92a28a
AS
13009 if (tgt_prog) {
13010 struct bpf_prog_aux *aux = tgt_prog->aux;
13011
13012 for (i = 0; i < aux->func_info_cnt; i++)
13013 if (aux->func_info[i].type_id == btf_id) {
13014 subprog = i;
13015 break;
13016 }
13017 if (subprog == -1) {
efc68158 13018 bpf_log(log, "Subprog %s doesn't exist\n", tname);
5b92a28a
AS
13019 return -EINVAL;
13020 }
13021 conservative = aux->func_info_aux[subprog].unreliable;
be8704ff
AS
13022 if (prog_extension) {
13023 if (conservative) {
efc68158 13024 bpf_log(log,
be8704ff
AS
13025 "Cannot replace static functions\n");
13026 return -EINVAL;
13027 }
13028 if (!prog->jit_requested) {
efc68158 13029 bpf_log(log,
be8704ff
AS
13030 "Extension programs should be JITed\n");
13031 return -EINVAL;
13032 }
be8704ff
AS
13033 }
13034 if (!tgt_prog->jited) {
efc68158 13035 bpf_log(log, "Can attach to only JITed progs\n");
be8704ff
AS
13036 return -EINVAL;
13037 }
13038 if (tgt_prog->type == prog->type) {
13039 /* Cannot fentry/fexit another fentry/fexit program.
13040 * Cannot attach program extension to another extension.
13041 * It's ok to attach fentry/fexit to extension program.
13042 */
efc68158 13043 bpf_log(log, "Cannot recursively attach\n");
be8704ff
AS
13044 return -EINVAL;
13045 }
13046 if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
13047 prog_extension &&
13048 (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
13049 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
13050 /* Program extensions can extend all program types
13051 * except fentry/fexit. The reason is the following.
13052 * The fentry/fexit programs are used for performance
13053 * analysis, stats and can be attached to any program
13054 * type except themselves. When extension program is
13055 * replacing XDP function it is necessary to allow
13056 * performance analysis of all functions. Both original
13057 * XDP program and its program extension. Hence
13058 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
13059 * allowed. If extending of fentry/fexit was allowed it
13060 * would be possible to create long call chain
13061 * fentry->extension->fentry->extension beyond
13062 * reasonable stack size. Hence extending fentry is not
13063 * allowed.
13064 */
efc68158 13065 bpf_log(log, "Cannot extend fentry/fexit\n");
be8704ff
AS
13066 return -EINVAL;
13067 }
5b92a28a 13068 } else {
be8704ff 13069 if (prog_extension) {
efc68158 13070 bpf_log(log, "Cannot replace kernel functions\n");
be8704ff
AS
13071 return -EINVAL;
13072 }
5b92a28a 13073 }
f1b9509c
AS
13074
13075 switch (prog->expected_attach_type) {
13076 case BPF_TRACE_RAW_TP:
5b92a28a 13077 if (tgt_prog) {
efc68158 13078 bpf_log(log,
5b92a28a
AS
13079 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
13080 return -EINVAL;
13081 }
38207291 13082 if (!btf_type_is_typedef(t)) {
efc68158 13083 bpf_log(log, "attach_btf_id %u is not a typedef\n",
38207291
MKL
13084 btf_id);
13085 return -EINVAL;
13086 }
f1b9509c 13087 if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
efc68158 13088 bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
38207291
MKL
13089 btf_id, tname);
13090 return -EINVAL;
13091 }
13092 tname += sizeof(prefix) - 1;
5b92a28a 13093 t = btf_type_by_id(btf, t->type);
38207291
MKL
13094 if (!btf_type_is_ptr(t))
13095 /* should never happen in valid vmlinux build */
13096 return -EINVAL;
5b92a28a 13097 t = btf_type_by_id(btf, t->type);
38207291
MKL
13098 if (!btf_type_is_func_proto(t))
13099 /* should never happen in valid vmlinux build */
13100 return -EINVAL;
13101
f7b12b6f 13102 break;
15d83c4d
YS
13103 case BPF_TRACE_ITER:
13104 if (!btf_type_is_func(t)) {
efc68158 13105 bpf_log(log, "attach_btf_id %u is not a function\n",
15d83c4d
YS
13106 btf_id);
13107 return -EINVAL;
13108 }
13109 t = btf_type_by_id(btf, t->type);
13110 if (!btf_type_is_func_proto(t))
13111 return -EINVAL;
f7b12b6f
THJ
13112 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
13113 if (ret)
13114 return ret;
13115 break;
be8704ff
AS
13116 default:
13117 if (!prog_extension)
13118 return -EINVAL;
df561f66 13119 fallthrough;
ae240823 13120 case BPF_MODIFY_RETURN:
9e4e01df 13121 case BPF_LSM_MAC:
fec56f58
AS
13122 case BPF_TRACE_FENTRY:
13123 case BPF_TRACE_FEXIT:
13124 if (!btf_type_is_func(t)) {
efc68158 13125 bpf_log(log, "attach_btf_id %u is not a function\n",
fec56f58
AS
13126 btf_id);
13127 return -EINVAL;
13128 }
be8704ff 13129 if (prog_extension &&
efc68158 13130 btf_check_type_match(log, prog, btf, t))
be8704ff 13131 return -EINVAL;
5b92a28a 13132 t = btf_type_by_id(btf, t->type);
fec56f58
AS
13133 if (!btf_type_is_func_proto(t))
13134 return -EINVAL;
f7b12b6f 13135
4a1e7c0c
THJ
13136 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
13137 (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
13138 prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
13139 return -EINVAL;
13140
f7b12b6f 13141 if (tgt_prog && conservative)
5b92a28a 13142 t = NULL;
f7b12b6f
THJ
13143
13144 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
fec56f58 13145 if (ret < 0)
f7b12b6f
THJ
13146 return ret;
13147
5b92a28a 13148 if (tgt_prog) {
e9eeec58
YS
13149 if (subprog == 0)
13150 addr = (long) tgt_prog->bpf_func;
13151 else
13152 addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
5b92a28a
AS
13153 } else {
13154 addr = kallsyms_lookup_name(tname);
13155 if (!addr) {
efc68158 13156 bpf_log(log,
5b92a28a
AS
13157 "The address of function %s cannot be found\n",
13158 tname);
f7b12b6f 13159 return -ENOENT;
5b92a28a 13160 }
fec56f58 13161 }
18644cec 13162
1e6c62a8
AS
13163 if (prog->aux->sleepable) {
13164 ret = -EINVAL;
13165 switch (prog->type) {
13166 case BPF_PROG_TYPE_TRACING:
13167 /* fentry/fexit/fmod_ret progs can be sleepable only if they are
13168 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
13169 */
13170 if (!check_non_sleepable_error_inject(btf_id) &&
13171 within_error_injection_list(addr))
13172 ret = 0;
13173 break;
13174 case BPF_PROG_TYPE_LSM:
13175 /* LSM progs check that they are attached to bpf_lsm_*() funcs.
13176 * Only some of them are sleepable.
13177 */
423f1610 13178 if (bpf_lsm_is_sleepable_hook(btf_id))
1e6c62a8
AS
13179 ret = 0;
13180 break;
13181 default:
13182 break;
13183 }
f7b12b6f
THJ
13184 if (ret) {
13185 bpf_log(log, "%s is not sleepable\n", tname);
13186 return ret;
13187 }
1e6c62a8 13188 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
1af9270e 13189 if (tgt_prog) {
efc68158 13190 bpf_log(log, "can't modify return codes of BPF programs\n");
f7b12b6f
THJ
13191 return -EINVAL;
13192 }
13193 ret = check_attach_modify_return(addr, tname);
13194 if (ret) {
13195 bpf_log(log, "%s() is not modifiable\n", tname);
13196 return ret;
1af9270e 13197 }
18644cec 13198 }
f7b12b6f
THJ
13199
13200 break;
13201 }
13202 tgt_info->tgt_addr = addr;
13203 tgt_info->tgt_name = tname;
13204 tgt_info->tgt_type = t;
13205 return 0;
13206}
13207
13208static int check_attach_btf_id(struct bpf_verifier_env *env)
13209{
13210 struct bpf_prog *prog = env->prog;
3aac1ead 13211 struct bpf_prog *tgt_prog = prog->aux->dst_prog;
f7b12b6f
THJ
13212 struct bpf_attach_target_info tgt_info = {};
13213 u32 btf_id = prog->aux->attach_btf_id;
13214 struct bpf_trampoline *tr;
13215 int ret;
13216 u64 key;
13217
13218 if (prog->aux->sleepable && prog->type != BPF_PROG_TYPE_TRACING &&
13219 prog->type != BPF_PROG_TYPE_LSM) {
13220 verbose(env, "Only fentry/fexit/fmod_ret and lsm programs can be sleepable\n");
13221 return -EINVAL;
13222 }
13223
13224 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
13225 return check_struct_ops_btf_id(env);
13226
13227 if (prog->type != BPF_PROG_TYPE_TRACING &&
13228 prog->type != BPF_PROG_TYPE_LSM &&
13229 prog->type != BPF_PROG_TYPE_EXT)
13230 return 0;
13231
13232 ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
13233 if (ret)
fec56f58 13234 return ret;
f7b12b6f
THJ
13235
13236 if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
3aac1ead
THJ
13237 /* to make freplace equivalent to their targets, they need to
13238 * inherit env->ops and expected_attach_type for the rest of the
13239 * verification
13240 */
f7b12b6f
THJ
13241 env->ops = bpf_verifier_ops[tgt_prog->type];
13242 prog->expected_attach_type = tgt_prog->expected_attach_type;
13243 }
13244
13245 /* store info about the attachment target that will be used later */
13246 prog->aux->attach_func_proto = tgt_info.tgt_type;
13247 prog->aux->attach_func_name = tgt_info.tgt_name;
13248
4a1e7c0c
THJ
13249 if (tgt_prog) {
13250 prog->aux->saved_dst_prog_type = tgt_prog->type;
13251 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
13252 }
13253
f7b12b6f
THJ
13254 if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
13255 prog->aux->attach_btf_trace = true;
13256 return 0;
13257 } else if (prog->expected_attach_type == BPF_TRACE_ITER) {
13258 if (!bpf_iter_prog_supported(prog))
13259 return -EINVAL;
13260 return 0;
13261 }
13262
13263 if (prog->type == BPF_PROG_TYPE_LSM) {
13264 ret = bpf_lsm_verify_prog(&env->log, prog);
13265 if (ret < 0)
13266 return ret;
38207291 13267 }
f7b12b6f 13268
22dc4a0f 13269 key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
f7b12b6f
THJ
13270 tr = bpf_trampoline_get(key, &tgt_info);
13271 if (!tr)
13272 return -ENOMEM;
13273
3aac1ead 13274 prog->aux->dst_trampoline = tr;
f7b12b6f 13275 return 0;
38207291
MKL
13276}
13277
76654e67
AM
13278struct btf *bpf_get_btf_vmlinux(void)
13279{
13280 if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
13281 mutex_lock(&bpf_verifier_lock);
13282 if (!btf_vmlinux)
13283 btf_vmlinux = btf_parse_vmlinux();
13284 mutex_unlock(&bpf_verifier_lock);
13285 }
13286 return btf_vmlinux;
13287}
13288
838e9690
YS
13289int bpf_check(struct bpf_prog **prog, union bpf_attr *attr,
13290 union bpf_attr __user *uattr)
51580e79 13291{
06ee7115 13292 u64 start_time = ktime_get_ns();
58e2af8b 13293 struct bpf_verifier_env *env;
b9193c1b 13294 struct bpf_verifier_log *log;
9e4c24e7 13295 int i, len, ret = -EINVAL;
e2ae4ca2 13296 bool is_priv;
51580e79 13297
eba0c929
AB
13298 /* no program is valid */
13299 if (ARRAY_SIZE(bpf_verifier_ops) == 0)
13300 return -EINVAL;
13301
58e2af8b 13302 /* 'struct bpf_verifier_env' can be global, but since it's not small,
cbd35700
AS
13303 * allocate/free it every time bpf_check() is called
13304 */
58e2af8b 13305 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
cbd35700
AS
13306 if (!env)
13307 return -ENOMEM;
61bd5218 13308 log = &env->log;
cbd35700 13309
9e4c24e7 13310 len = (*prog)->len;
fad953ce 13311 env->insn_aux_data =
9e4c24e7 13312 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
3df126f3
JK
13313 ret = -ENOMEM;
13314 if (!env->insn_aux_data)
13315 goto err_free_env;
9e4c24e7
JK
13316 for (i = 0; i < len; i++)
13317 env->insn_aux_data[i].orig_idx = i;
9bac3d6d 13318 env->prog = *prog;
00176a34 13319 env->ops = bpf_verifier_ops[env->prog->type];
2c78ee89 13320 is_priv = bpf_capable();
0246e64d 13321
76654e67 13322 bpf_get_btf_vmlinux();
8580ac94 13323
cbd35700 13324 /* grab the mutex to protect few globals used by verifier */
45a73c17
AS
13325 if (!is_priv)
13326 mutex_lock(&bpf_verifier_lock);
cbd35700
AS
13327
13328 if (attr->log_level || attr->log_buf || attr->log_size) {
13329 /* user requested verbose verifier output
13330 * and supplied buffer to store the verification trace
13331 */
e7bf8249
JK
13332 log->level = attr->log_level;
13333 log->ubuf = (char __user *) (unsigned long) attr->log_buf;
13334 log->len_total = attr->log_size;
cbd35700
AS
13335
13336 ret = -EINVAL;
e7bf8249 13337 /* log attributes have to be sane */
7a9f5c65 13338 if (log->len_total < 128 || log->len_total > UINT_MAX >> 2 ||
06ee7115 13339 !log->level || !log->ubuf || log->level & ~BPF_LOG_MASK)
3df126f3 13340 goto err_unlock;
cbd35700 13341 }
1ad2f583 13342
8580ac94
AS
13343 if (IS_ERR(btf_vmlinux)) {
13344 /* Either gcc or pahole or kernel are broken. */
13345 verbose(env, "in-kernel BTF is malformed\n");
13346 ret = PTR_ERR(btf_vmlinux);
38207291 13347 goto skip_full_check;
8580ac94
AS
13348 }
13349
1ad2f583
DB
13350 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
13351 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
e07b98d9 13352 env->strict_alignment = true;
e9ee9efc
DM
13353 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
13354 env->strict_alignment = false;
cbd35700 13355
2c78ee89 13356 env->allow_ptr_leaks = bpf_allow_ptr_leaks();
01f810ac 13357 env->allow_uninit_stack = bpf_allow_uninit_stack();
41c48f3a 13358 env->allow_ptr_to_map_access = bpf_allow_ptr_to_map_access();
2c78ee89
AS
13359 env->bypass_spec_v1 = bpf_bypass_spec_v1();
13360 env->bypass_spec_v4 = bpf_bypass_spec_v4();
13361 env->bpf_capable = bpf_capable();
e2ae4ca2 13362
10d274e8
AS
13363 if (is_priv)
13364 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
13365
cae1927c 13366 if (bpf_prog_is_dev_bound(env->prog->aux)) {
a40a2632 13367 ret = bpf_prog_offload_verifier_prep(env->prog);
ab3f0063 13368 if (ret)
f4e3ec0d 13369 goto skip_full_check;
ab3f0063
JK
13370 }
13371
dc2a4ebc 13372 env->explored_states = kvcalloc(state_htab_size(env),
58e2af8b 13373 sizeof(struct bpf_verifier_state_list *),
f1bca824
AS
13374 GFP_USER);
13375 ret = -ENOMEM;
13376 if (!env->explored_states)
13377 goto skip_full_check;
13378
e6ac2450
MKL
13379 ret = add_subprog_and_kfunc(env);
13380 if (ret < 0)
13381 goto skip_full_check;
13382
d9762e84 13383 ret = check_subprogs(env);
475fb78f
AS
13384 if (ret < 0)
13385 goto skip_full_check;
13386
c454a46b 13387 ret = check_btf_info(env, attr, uattr);
838e9690
YS
13388 if (ret < 0)
13389 goto skip_full_check;
13390
be8704ff
AS
13391 ret = check_attach_btf_id(env);
13392 if (ret)
13393 goto skip_full_check;
13394
4976b718
HL
13395 ret = resolve_pseudo_ldimm64(env);
13396 if (ret < 0)
13397 goto skip_full_check;
13398
d9762e84
MKL
13399 ret = check_cfg(env);
13400 if (ret < 0)
13401 goto skip_full_check;
13402
51c39bb1
AS
13403 ret = do_check_subprogs(env);
13404 ret = ret ?: do_check_main(env);
cbd35700 13405
c941ce9c
QM
13406 if (ret == 0 && bpf_prog_is_dev_bound(env->prog->aux))
13407 ret = bpf_prog_offload_finalize(env);
13408
0246e64d 13409skip_full_check:
51c39bb1 13410 kvfree(env->explored_states);
0246e64d 13411
c131187d 13412 if (ret == 0)
9b38c405 13413 ret = check_max_stack_depth(env);
c131187d 13414
9b38c405 13415 /* instruction rewrites happen after this point */
e2ae4ca2
JK
13416 if (is_priv) {
13417 if (ret == 0)
13418 opt_hard_wire_dead_code_branches(env);
52875a04
JK
13419 if (ret == 0)
13420 ret = opt_remove_dead_code(env);
a1b14abc
JK
13421 if (ret == 0)
13422 ret = opt_remove_nops(env);
52875a04
JK
13423 } else {
13424 if (ret == 0)
13425 sanitize_dead_code(env);
e2ae4ca2
JK
13426 }
13427
9bac3d6d
AS
13428 if (ret == 0)
13429 /* program is valid, convert *(u32*)(ctx + off) accesses */
13430 ret = convert_ctx_accesses(env);
13431
e245c5c6 13432 if (ret == 0)
e6ac5933 13433 ret = do_misc_fixups(env);
e245c5c6 13434
a4b1d3c1
JW
13435 /* do 32-bit optimization after insn patching has done so those patched
13436 * insns could be handled correctly.
13437 */
d6c2308c
JW
13438 if (ret == 0 && !bpf_prog_is_dev_bound(env->prog->aux)) {
13439 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
13440 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
13441 : false;
a4b1d3c1
JW
13442 }
13443
1ea47e01
AS
13444 if (ret == 0)
13445 ret = fixup_call_args(env);
13446
06ee7115
AS
13447 env->verification_time = ktime_get_ns() - start_time;
13448 print_verification_stats(env);
13449
a2a7d570 13450 if (log->level && bpf_verifier_log_full(log))
cbd35700 13451 ret = -ENOSPC;
a2a7d570 13452 if (log->level && !log->ubuf) {
cbd35700 13453 ret = -EFAULT;
a2a7d570 13454 goto err_release_maps;
cbd35700
AS
13455 }
13456
541c3bad
AN
13457 if (ret)
13458 goto err_release_maps;
13459
13460 if (env->used_map_cnt) {
0246e64d 13461 /* if program passed verifier, update used_maps in bpf_prog_info */
9bac3d6d
AS
13462 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
13463 sizeof(env->used_maps[0]),
13464 GFP_KERNEL);
0246e64d 13465
9bac3d6d 13466 if (!env->prog->aux->used_maps) {
0246e64d 13467 ret = -ENOMEM;
a2a7d570 13468 goto err_release_maps;
0246e64d
AS
13469 }
13470
9bac3d6d 13471 memcpy(env->prog->aux->used_maps, env->used_maps,
0246e64d 13472 sizeof(env->used_maps[0]) * env->used_map_cnt);
9bac3d6d 13473 env->prog->aux->used_map_cnt = env->used_map_cnt;
541c3bad
AN
13474 }
13475 if (env->used_btf_cnt) {
13476 /* if program passed verifier, update used_btfs in bpf_prog_aux */
13477 env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
13478 sizeof(env->used_btfs[0]),
13479 GFP_KERNEL);
13480 if (!env->prog->aux->used_btfs) {
13481 ret = -ENOMEM;
13482 goto err_release_maps;
13483 }
0246e64d 13484
541c3bad
AN
13485 memcpy(env->prog->aux->used_btfs, env->used_btfs,
13486 sizeof(env->used_btfs[0]) * env->used_btf_cnt);
13487 env->prog->aux->used_btf_cnt = env->used_btf_cnt;
13488 }
13489 if (env->used_map_cnt || env->used_btf_cnt) {
0246e64d
AS
13490 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
13491 * bpf_ld_imm64 instructions
13492 */
13493 convert_pseudo_ld_imm64(env);
13494 }
cbd35700 13495
541c3bad 13496 adjust_btf_func(env);
ba64e7d8 13497
a2a7d570 13498err_release_maps:
9bac3d6d 13499 if (!env->prog->aux->used_maps)
0246e64d 13500 /* if we didn't copy map pointers into bpf_prog_info, release
ab7f5bf0 13501 * them now. Otherwise free_used_maps() will release them.
0246e64d
AS
13502 */
13503 release_maps(env);
541c3bad
AN
13504 if (!env->prog->aux->used_btfs)
13505 release_btfs(env);
03f87c0b
THJ
13506
13507 /* extension progs temporarily inherit the attach_type of their targets
13508 for verification purposes, so set it back to zero before returning
13509 */
13510 if (env->prog->type == BPF_PROG_TYPE_EXT)
13511 env->prog->expected_attach_type = 0;
13512
9bac3d6d 13513 *prog = env->prog;
3df126f3 13514err_unlock:
45a73c17
AS
13515 if (!is_priv)
13516 mutex_unlock(&bpf_verifier_lock);
3df126f3
JK
13517 vfree(env->insn_aux_data);
13518err_free_env:
13519 kfree(env);
51580e79
AS
13520 return ret;
13521}