bpf: Notify user if we ever hit a bpf_snprintf verifier bug
[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
84dbf350
JS
740#define COPY_STATE_FN(NAME, COUNT, FIELD, SIZE) \
741static int copy_##NAME##_state(struct bpf_func_state *dst, \
742 const struct bpf_func_state *src) \
743{ \
744 if (!src->FIELD) \
745 return 0; \
746 if (WARN_ON_ONCE(dst->COUNT < src->COUNT)) { \
747 /* internal bug, make state invalid to reject the program */ \
748 memset(dst, 0, sizeof(*dst)); \
749 return -EFAULT; \
750 } \
751 memcpy(dst->FIELD, src->FIELD, \
752 sizeof(*src->FIELD) * (src->COUNT / SIZE)); \
753 return 0; \
638f5b90 754}
fd978bf7
JS
755/* copy_reference_state() */
756COPY_STATE_FN(reference, acquired_refs, refs, 1)
84dbf350
JS
757/* copy_stack_state() */
758COPY_STATE_FN(stack, allocated_stack, stack, BPF_REG_SIZE)
759#undef COPY_STATE_FN
760
761#define REALLOC_STATE_FN(NAME, COUNT, FIELD, SIZE) \
762static int realloc_##NAME##_state(struct bpf_func_state *state, int size, \
763 bool copy_old) \
764{ \
765 u32 old_size = state->COUNT; \
766 struct bpf_##NAME##_state *new_##FIELD; \
767 int slot = size / SIZE; \
768 \
769 if (size <= old_size || !size) { \
770 if (copy_old) \
771 return 0; \
772 state->COUNT = slot * SIZE; \
773 if (!size && old_size) { \
774 kfree(state->FIELD); \
775 state->FIELD = NULL; \
776 } \
777 return 0; \
778 } \
779 new_##FIELD = kmalloc_array(slot, sizeof(struct bpf_##NAME##_state), \
780 GFP_KERNEL); \
781 if (!new_##FIELD) \
782 return -ENOMEM; \
783 if (copy_old) { \
784 if (state->FIELD) \
785 memcpy(new_##FIELD, state->FIELD, \
786 sizeof(*new_##FIELD) * (old_size / SIZE)); \
787 memset(new_##FIELD + old_size / SIZE, 0, \
788 sizeof(*new_##FIELD) * (size - old_size) / SIZE); \
789 } \
790 state->COUNT = slot * SIZE; \
791 kfree(state->FIELD); \
792 state->FIELD = new_##FIELD; \
793 return 0; \
794}
fd978bf7
JS
795/* realloc_reference_state() */
796REALLOC_STATE_FN(reference, acquired_refs, refs, 1)
84dbf350
JS
797/* realloc_stack_state() */
798REALLOC_STATE_FN(stack, allocated_stack, stack, BPF_REG_SIZE)
799#undef REALLOC_STATE_FN
638f5b90
AS
800
801/* do_check() starts with zero-sized stack in struct bpf_verifier_state to
802 * make it consume minimal amount of memory. check_stack_write() access from
f4d7e40a 803 * the program calls into realloc_func_state() to grow the stack size.
84dbf350
JS
804 * Note there is a non-zero 'parent' pointer inside bpf_verifier_state
805 * which realloc_stack_state() copies over. It points to previous
806 * bpf_verifier_state which is never reallocated.
638f5b90 807 */
fd978bf7
JS
808static int realloc_func_state(struct bpf_func_state *state, int stack_size,
809 int refs_size, bool copy_old)
638f5b90 810{
fd978bf7
JS
811 int err = realloc_reference_state(state, refs_size, copy_old);
812 if (err)
813 return err;
814 return realloc_stack_state(state, stack_size, copy_old);
815}
816
817/* Acquire a pointer id from the env and update the state->refs to include
818 * this new pointer reference.
819 * On success, returns a valid pointer id to associate with the register
820 * On failure, returns a negative errno.
638f5b90 821 */
fd978bf7 822static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
638f5b90 823{
fd978bf7
JS
824 struct bpf_func_state *state = cur_func(env);
825 int new_ofs = state->acquired_refs;
826 int id, err;
827
828 err = realloc_reference_state(state, state->acquired_refs + 1, true);
829 if (err)
830 return err;
831 id = ++env->id_gen;
832 state->refs[new_ofs].id = id;
833 state->refs[new_ofs].insn_idx = insn_idx;
638f5b90 834
fd978bf7
JS
835 return id;
836}
837
838/* release function corresponding to acquire_reference_state(). Idempotent. */
46f8bc92 839static int release_reference_state(struct bpf_func_state *state, int ptr_id)
fd978bf7
JS
840{
841 int i, last_idx;
842
fd978bf7
JS
843 last_idx = state->acquired_refs - 1;
844 for (i = 0; i < state->acquired_refs; i++) {
845 if (state->refs[i].id == ptr_id) {
846 if (last_idx && i != last_idx)
847 memcpy(&state->refs[i], &state->refs[last_idx],
848 sizeof(*state->refs));
849 memset(&state->refs[last_idx], 0, sizeof(*state->refs));
850 state->acquired_refs--;
638f5b90 851 return 0;
638f5b90 852 }
638f5b90 853 }
46f8bc92 854 return -EINVAL;
fd978bf7
JS
855}
856
857static int transfer_reference_state(struct bpf_func_state *dst,
858 struct bpf_func_state *src)
859{
860 int err = realloc_reference_state(dst, src->acquired_refs, false);
861 if (err)
862 return err;
863 err = copy_reference_state(dst, src);
864 if (err)
865 return err;
638f5b90
AS
866 return 0;
867}
868
f4d7e40a
AS
869static void free_func_state(struct bpf_func_state *state)
870{
5896351e
AS
871 if (!state)
872 return;
fd978bf7 873 kfree(state->refs);
f4d7e40a
AS
874 kfree(state->stack);
875 kfree(state);
876}
877
b5dc0163
AS
878static void clear_jmp_history(struct bpf_verifier_state *state)
879{
880 kfree(state->jmp_history);
881 state->jmp_history = NULL;
882 state->jmp_history_cnt = 0;
883}
884
1969db47
AS
885static void free_verifier_state(struct bpf_verifier_state *state,
886 bool free_self)
638f5b90 887{
f4d7e40a
AS
888 int i;
889
890 for (i = 0; i <= state->curframe; i++) {
891 free_func_state(state->frame[i]);
892 state->frame[i] = NULL;
893 }
b5dc0163 894 clear_jmp_history(state);
1969db47
AS
895 if (free_self)
896 kfree(state);
638f5b90
AS
897}
898
899/* copy verifier state from src to dst growing dst stack space
900 * when necessary to accommodate larger src stack
901 */
f4d7e40a
AS
902static int copy_func_state(struct bpf_func_state *dst,
903 const struct bpf_func_state *src)
638f5b90
AS
904{
905 int err;
906
fd978bf7
JS
907 err = realloc_func_state(dst, src->allocated_stack, src->acquired_refs,
908 false);
909 if (err)
910 return err;
911 memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
912 err = copy_reference_state(dst, src);
638f5b90
AS
913 if (err)
914 return err;
638f5b90
AS
915 return copy_stack_state(dst, src);
916}
917
f4d7e40a
AS
918static int copy_verifier_state(struct bpf_verifier_state *dst_state,
919 const struct bpf_verifier_state *src)
920{
921 struct bpf_func_state *dst;
b5dc0163 922 u32 jmp_sz = sizeof(struct bpf_idx_pair) * src->jmp_history_cnt;
f4d7e40a
AS
923 int i, err;
924
b5dc0163
AS
925 if (dst_state->jmp_history_cnt < src->jmp_history_cnt) {
926 kfree(dst_state->jmp_history);
927 dst_state->jmp_history = kmalloc(jmp_sz, GFP_USER);
928 if (!dst_state->jmp_history)
929 return -ENOMEM;
930 }
931 memcpy(dst_state->jmp_history, src->jmp_history, jmp_sz);
932 dst_state->jmp_history_cnt = src->jmp_history_cnt;
933
f4d7e40a
AS
934 /* if dst has more stack frames then src frame, free them */
935 for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
936 free_func_state(dst_state->frame[i]);
937 dst_state->frame[i] = NULL;
938 }
979d63d5 939 dst_state->speculative = src->speculative;
f4d7e40a 940 dst_state->curframe = src->curframe;
d83525ca 941 dst_state->active_spin_lock = src->active_spin_lock;
2589726d
AS
942 dst_state->branches = src->branches;
943 dst_state->parent = src->parent;
b5dc0163
AS
944 dst_state->first_insn_idx = src->first_insn_idx;
945 dst_state->last_insn_idx = src->last_insn_idx;
f4d7e40a
AS
946 for (i = 0; i <= src->curframe; i++) {
947 dst = dst_state->frame[i];
948 if (!dst) {
949 dst = kzalloc(sizeof(*dst), GFP_KERNEL);
950 if (!dst)
951 return -ENOMEM;
952 dst_state->frame[i] = dst;
953 }
954 err = copy_func_state(dst, src->frame[i]);
955 if (err)
956 return err;
957 }
958 return 0;
959}
960
2589726d
AS
961static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
962{
963 while (st) {
964 u32 br = --st->branches;
965
966 /* WARN_ON(br > 1) technically makes sense here,
967 * but see comment in push_stack(), hence:
968 */
969 WARN_ONCE((int)br < 0,
970 "BUG update_branch_counts:branches_to_explore=%d\n",
971 br);
972 if (br)
973 break;
974 st = st->parent;
975 }
976}
977
638f5b90 978static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
6f8a57cc 979 int *insn_idx, bool pop_log)
638f5b90
AS
980{
981 struct bpf_verifier_state *cur = env->cur_state;
982 struct bpf_verifier_stack_elem *elem, *head = env->head;
983 int err;
17a52670
AS
984
985 if (env->head == NULL)
638f5b90 986 return -ENOENT;
17a52670 987
638f5b90
AS
988 if (cur) {
989 err = copy_verifier_state(cur, &head->st);
990 if (err)
991 return err;
992 }
6f8a57cc
AN
993 if (pop_log)
994 bpf_vlog_reset(&env->log, head->log_pos);
638f5b90
AS
995 if (insn_idx)
996 *insn_idx = head->insn_idx;
17a52670 997 if (prev_insn_idx)
638f5b90
AS
998 *prev_insn_idx = head->prev_insn_idx;
999 elem = head->next;
1969db47 1000 free_verifier_state(&head->st, false);
638f5b90 1001 kfree(head);
17a52670
AS
1002 env->head = elem;
1003 env->stack_size--;
638f5b90 1004 return 0;
17a52670
AS
1005}
1006
58e2af8b 1007static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
979d63d5
DB
1008 int insn_idx, int prev_insn_idx,
1009 bool speculative)
17a52670 1010{
638f5b90 1011 struct bpf_verifier_state *cur = env->cur_state;
58e2af8b 1012 struct bpf_verifier_stack_elem *elem;
638f5b90 1013 int err;
17a52670 1014
638f5b90 1015 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
17a52670
AS
1016 if (!elem)
1017 goto err;
1018
17a52670
AS
1019 elem->insn_idx = insn_idx;
1020 elem->prev_insn_idx = prev_insn_idx;
1021 elem->next = env->head;
6f8a57cc 1022 elem->log_pos = env->log.len_used;
17a52670
AS
1023 env->head = elem;
1024 env->stack_size++;
1969db47
AS
1025 err = copy_verifier_state(&elem->st, cur);
1026 if (err)
1027 goto err;
979d63d5 1028 elem->st.speculative |= speculative;
b285fcb7
AS
1029 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1030 verbose(env, "The sequence of %d jumps is too complex.\n",
1031 env->stack_size);
17a52670
AS
1032 goto err;
1033 }
2589726d
AS
1034 if (elem->st.parent) {
1035 ++elem->st.parent->branches;
1036 /* WARN_ON(branches > 2) technically makes sense here,
1037 * but
1038 * 1. speculative states will bump 'branches' for non-branch
1039 * instructions
1040 * 2. is_state_visited() heuristics may decide not to create
1041 * a new state for a sequence of branches and all such current
1042 * and cloned states will be pointing to a single parent state
1043 * which might have large 'branches' count.
1044 */
1045 }
17a52670
AS
1046 return &elem->st;
1047err:
5896351e
AS
1048 free_verifier_state(env->cur_state, true);
1049 env->cur_state = NULL;
17a52670 1050 /* pop all elements and return */
6f8a57cc 1051 while (!pop_stack(env, NULL, NULL, false));
17a52670
AS
1052 return NULL;
1053}
1054
1055#define CALLER_SAVED_REGS 6
1056static const int caller_saved[CALLER_SAVED_REGS] = {
1057 BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
1058};
1059
f54c7898
DB
1060static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1061 struct bpf_reg_state *reg);
f1174f77 1062
e688c3db
AS
1063/* This helper doesn't clear reg->id */
1064static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
b03c9f9f 1065{
b03c9f9f
EC
1066 reg->var_off = tnum_const(imm);
1067 reg->smin_value = (s64)imm;
1068 reg->smax_value = (s64)imm;
1069 reg->umin_value = imm;
1070 reg->umax_value = imm;
3f50f132
JF
1071
1072 reg->s32_min_value = (s32)imm;
1073 reg->s32_max_value = (s32)imm;
1074 reg->u32_min_value = (u32)imm;
1075 reg->u32_max_value = (u32)imm;
1076}
1077
e688c3db
AS
1078/* Mark the unknown part of a register (variable offset or scalar value) as
1079 * known to have the value @imm.
1080 */
1081static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1082{
1083 /* Clear id, off, and union(map_ptr, range) */
1084 memset(((u8 *)reg) + sizeof(reg->type), 0,
1085 offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
1086 ___mark_reg_known(reg, imm);
1087}
1088
3f50f132
JF
1089static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1090{
1091 reg->var_off = tnum_const_subreg(reg->var_off, imm);
1092 reg->s32_min_value = (s32)imm;
1093 reg->s32_max_value = (s32)imm;
1094 reg->u32_min_value = (u32)imm;
1095 reg->u32_max_value = (u32)imm;
b03c9f9f
EC
1096}
1097
f1174f77
EC
1098/* Mark the 'variable offset' part of a register as zero. This should be
1099 * used only on registers holding a pointer type.
1100 */
1101static void __mark_reg_known_zero(struct bpf_reg_state *reg)
a9789ef9 1102{
b03c9f9f 1103 __mark_reg_known(reg, 0);
f1174f77 1104}
a9789ef9 1105
cc2b14d5
AS
1106static void __mark_reg_const_zero(struct bpf_reg_state *reg)
1107{
1108 __mark_reg_known(reg, 0);
cc2b14d5
AS
1109 reg->type = SCALAR_VALUE;
1110}
1111
61bd5218
JK
1112static void mark_reg_known_zero(struct bpf_verifier_env *env,
1113 struct bpf_reg_state *regs, u32 regno)
f1174f77
EC
1114{
1115 if (WARN_ON(regno >= MAX_BPF_REG)) {
61bd5218 1116 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
f1174f77
EC
1117 /* Something bad happened, let's kill all regs */
1118 for (regno = 0; regno < MAX_BPF_REG; regno++)
f54c7898 1119 __mark_reg_not_init(env, regs + regno);
f1174f77
EC
1120 return;
1121 }
1122 __mark_reg_known_zero(regs + regno);
1123}
1124
4ddb7416
DB
1125static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
1126{
1127 switch (reg->type) {
1128 case PTR_TO_MAP_VALUE_OR_NULL: {
1129 const struct bpf_map *map = reg->map_ptr;
1130
1131 if (map->inner_map_meta) {
1132 reg->type = CONST_PTR_TO_MAP;
1133 reg->map_ptr = map->inner_map_meta;
1134 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
1135 reg->type = PTR_TO_XDP_SOCK;
1136 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
1137 map->map_type == BPF_MAP_TYPE_SOCKHASH) {
1138 reg->type = PTR_TO_SOCKET;
1139 } else {
1140 reg->type = PTR_TO_MAP_VALUE;
1141 }
1142 break;
1143 }
1144 case PTR_TO_SOCKET_OR_NULL:
1145 reg->type = PTR_TO_SOCKET;
1146 break;
1147 case PTR_TO_SOCK_COMMON_OR_NULL:
1148 reg->type = PTR_TO_SOCK_COMMON;
1149 break;
1150 case PTR_TO_TCP_SOCK_OR_NULL:
1151 reg->type = PTR_TO_TCP_SOCK;
1152 break;
1153 case PTR_TO_BTF_ID_OR_NULL:
1154 reg->type = PTR_TO_BTF_ID;
1155 break;
1156 case PTR_TO_MEM_OR_NULL:
1157 reg->type = PTR_TO_MEM;
1158 break;
1159 case PTR_TO_RDONLY_BUF_OR_NULL:
1160 reg->type = PTR_TO_RDONLY_BUF;
1161 break;
1162 case PTR_TO_RDWR_BUF_OR_NULL:
1163 reg->type = PTR_TO_RDWR_BUF;
1164 break;
1165 default:
33ccec5f 1166 WARN_ONCE(1, "unknown nullable register type");
4ddb7416
DB
1167 }
1168}
1169
de8f3a83
DB
1170static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1171{
1172 return type_is_pkt_pointer(reg->type);
1173}
1174
1175static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
1176{
1177 return reg_is_pkt_pointer(reg) ||
1178 reg->type == PTR_TO_PACKET_END;
1179}
1180
1181/* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
1182static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
1183 enum bpf_reg_type which)
1184{
1185 /* The register can already have a range from prior markings.
1186 * This is fine as long as it hasn't been advanced from its
1187 * origin.
1188 */
1189 return reg->type == which &&
1190 reg->id == 0 &&
1191 reg->off == 0 &&
1192 tnum_equals_const(reg->var_off, 0);
1193}
1194
3f50f132
JF
1195/* Reset the min/max bounds of a register */
1196static void __mark_reg_unbounded(struct bpf_reg_state *reg)
1197{
1198 reg->smin_value = S64_MIN;
1199 reg->smax_value = S64_MAX;
1200 reg->umin_value = 0;
1201 reg->umax_value = U64_MAX;
1202
1203 reg->s32_min_value = S32_MIN;
1204 reg->s32_max_value = S32_MAX;
1205 reg->u32_min_value = 0;
1206 reg->u32_max_value = U32_MAX;
1207}
1208
1209static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
1210{
1211 reg->smin_value = S64_MIN;
1212 reg->smax_value = S64_MAX;
1213 reg->umin_value = 0;
1214 reg->umax_value = U64_MAX;
1215}
1216
1217static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
1218{
1219 reg->s32_min_value = S32_MIN;
1220 reg->s32_max_value = S32_MAX;
1221 reg->u32_min_value = 0;
1222 reg->u32_max_value = U32_MAX;
1223}
1224
1225static void __update_reg32_bounds(struct bpf_reg_state *reg)
1226{
1227 struct tnum var32_off = tnum_subreg(reg->var_off);
1228
1229 /* min signed is max(sign bit) | min(other bits) */
1230 reg->s32_min_value = max_t(s32, reg->s32_min_value,
1231 var32_off.value | (var32_off.mask & S32_MIN));
1232 /* max signed is min(sign bit) | max(other bits) */
1233 reg->s32_max_value = min_t(s32, reg->s32_max_value,
1234 var32_off.value | (var32_off.mask & S32_MAX));
1235 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
1236 reg->u32_max_value = min(reg->u32_max_value,
1237 (u32)(var32_off.value | var32_off.mask));
1238}
1239
1240static void __update_reg64_bounds(struct bpf_reg_state *reg)
b03c9f9f
EC
1241{
1242 /* min signed is max(sign bit) | min(other bits) */
1243 reg->smin_value = max_t(s64, reg->smin_value,
1244 reg->var_off.value | (reg->var_off.mask & S64_MIN));
1245 /* max signed is min(sign bit) | max(other bits) */
1246 reg->smax_value = min_t(s64, reg->smax_value,
1247 reg->var_off.value | (reg->var_off.mask & S64_MAX));
1248 reg->umin_value = max(reg->umin_value, reg->var_off.value);
1249 reg->umax_value = min(reg->umax_value,
1250 reg->var_off.value | reg->var_off.mask);
1251}
1252
3f50f132
JF
1253static void __update_reg_bounds(struct bpf_reg_state *reg)
1254{
1255 __update_reg32_bounds(reg);
1256 __update_reg64_bounds(reg);
1257}
1258
b03c9f9f 1259/* Uses signed min/max values to inform unsigned, and vice-versa */
3f50f132
JF
1260static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
1261{
1262 /* Learn sign from signed bounds.
1263 * If we cannot cross the sign boundary, then signed and unsigned bounds
1264 * are the same, so combine. This works even in the negative case, e.g.
1265 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1266 */
1267 if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) {
1268 reg->s32_min_value = reg->u32_min_value =
1269 max_t(u32, reg->s32_min_value, reg->u32_min_value);
1270 reg->s32_max_value = reg->u32_max_value =
1271 min_t(u32, reg->s32_max_value, reg->u32_max_value);
1272 return;
1273 }
1274 /* Learn sign from unsigned bounds. Signed bounds cross the sign
1275 * boundary, so we must be careful.
1276 */
1277 if ((s32)reg->u32_max_value >= 0) {
1278 /* Positive. We can't learn anything from the smin, but smax
1279 * is positive, hence safe.
1280 */
1281 reg->s32_min_value = reg->u32_min_value;
1282 reg->s32_max_value = reg->u32_max_value =
1283 min_t(u32, reg->s32_max_value, reg->u32_max_value);
1284 } else if ((s32)reg->u32_min_value < 0) {
1285 /* Negative. We can't learn anything from the smax, but smin
1286 * is negative, hence safe.
1287 */
1288 reg->s32_min_value = reg->u32_min_value =
1289 max_t(u32, reg->s32_min_value, reg->u32_min_value);
1290 reg->s32_max_value = reg->u32_max_value;
1291 }
1292}
1293
1294static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
b03c9f9f
EC
1295{
1296 /* Learn sign from signed bounds.
1297 * If we cannot cross the sign boundary, then signed and unsigned bounds
1298 * are the same, so combine. This works even in the negative case, e.g.
1299 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1300 */
1301 if (reg->smin_value >= 0 || reg->smax_value < 0) {
1302 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1303 reg->umin_value);
1304 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1305 reg->umax_value);
1306 return;
1307 }
1308 /* Learn sign from unsigned bounds. Signed bounds cross the sign
1309 * boundary, so we must be careful.
1310 */
1311 if ((s64)reg->umax_value >= 0) {
1312 /* Positive. We can't learn anything from the smin, but smax
1313 * is positive, hence safe.
1314 */
1315 reg->smin_value = reg->umin_value;
1316 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1317 reg->umax_value);
1318 } else if ((s64)reg->umin_value < 0) {
1319 /* Negative. We can't learn anything from the smax, but smin
1320 * is negative, hence safe.
1321 */
1322 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1323 reg->umin_value);
1324 reg->smax_value = reg->umax_value;
1325 }
1326}
1327
3f50f132
JF
1328static void __reg_deduce_bounds(struct bpf_reg_state *reg)
1329{
1330 __reg32_deduce_bounds(reg);
1331 __reg64_deduce_bounds(reg);
1332}
1333
b03c9f9f
EC
1334/* Attempts to improve var_off based on unsigned min/max information */
1335static void __reg_bound_offset(struct bpf_reg_state *reg)
1336{
3f50f132
JF
1337 struct tnum var64_off = tnum_intersect(reg->var_off,
1338 tnum_range(reg->umin_value,
1339 reg->umax_value));
1340 struct tnum var32_off = tnum_intersect(tnum_subreg(reg->var_off),
1341 tnum_range(reg->u32_min_value,
1342 reg->u32_max_value));
1343
1344 reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
b03c9f9f
EC
1345}
1346
3f50f132 1347static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
b03c9f9f 1348{
3f50f132
JF
1349 reg->umin_value = reg->u32_min_value;
1350 reg->umax_value = reg->u32_max_value;
1351 /* Attempt to pull 32-bit signed bounds into 64-bit bounds
1352 * but must be positive otherwise set to worse case bounds
1353 * and refine later from tnum.
1354 */
3a71dc36 1355 if (reg->s32_min_value >= 0 && reg->s32_max_value >= 0)
3f50f132
JF
1356 reg->smax_value = reg->s32_max_value;
1357 else
1358 reg->smax_value = U32_MAX;
3a71dc36
JF
1359 if (reg->s32_min_value >= 0)
1360 reg->smin_value = reg->s32_min_value;
1361 else
1362 reg->smin_value = 0;
3f50f132
JF
1363}
1364
1365static void __reg_combine_32_into_64(struct bpf_reg_state *reg)
1366{
1367 /* special case when 64-bit register has upper 32-bit register
1368 * zeroed. Typically happens after zext or <<32, >>32 sequence
1369 * allowing us to use 32-bit bounds directly,
1370 */
1371 if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) {
1372 __reg_assign_32_into_64(reg);
1373 } else {
1374 /* Otherwise the best we can do is push lower 32bit known and
1375 * unknown bits into register (var_off set from jmp logic)
1376 * then learn as much as possible from the 64-bit tnum
1377 * known and unknown bits. The previous smin/smax bounds are
1378 * invalid here because of jmp32 compare so mark them unknown
1379 * so they do not impact tnum bounds calculation.
1380 */
1381 __mark_reg64_unbounded(reg);
1382 __update_reg_bounds(reg);
1383 }
1384
1385 /* Intersecting with the old var_off might have improved our bounds
1386 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1387 * then new var_off is (0; 0x7f...fc) which improves our umax.
1388 */
1389 __reg_deduce_bounds(reg);
1390 __reg_bound_offset(reg);
1391 __update_reg_bounds(reg);
1392}
1393
1394static bool __reg64_bound_s32(s64 a)
1395{
b0270958 1396 return a > S32_MIN && a < S32_MAX;
3f50f132
JF
1397}
1398
1399static bool __reg64_bound_u32(u64 a)
1400{
1401 if (a > U32_MIN && a < U32_MAX)
1402 return true;
1403 return false;
1404}
1405
1406static void __reg_combine_64_into_32(struct bpf_reg_state *reg)
1407{
1408 __mark_reg32_unbounded(reg);
1409
b0270958 1410 if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) {
3f50f132 1411 reg->s32_min_value = (s32)reg->smin_value;
3f50f132 1412 reg->s32_max_value = (s32)reg->smax_value;
b0270958 1413 }
3f50f132
JF
1414 if (__reg64_bound_u32(reg->umin_value))
1415 reg->u32_min_value = (u32)reg->umin_value;
1416 if (__reg64_bound_u32(reg->umax_value))
1417 reg->u32_max_value = (u32)reg->umax_value;
1418
1419 /* Intersecting with the old var_off might have improved our bounds
1420 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1421 * then new var_off is (0; 0x7f...fc) which improves our umax.
1422 */
1423 __reg_deduce_bounds(reg);
1424 __reg_bound_offset(reg);
1425 __update_reg_bounds(reg);
b03c9f9f
EC
1426}
1427
f1174f77 1428/* Mark a register as having a completely unknown (scalar) value. */
f54c7898
DB
1429static void __mark_reg_unknown(const struct bpf_verifier_env *env,
1430 struct bpf_reg_state *reg)
f1174f77 1431{
a9c676bc
AS
1432 /*
1433 * Clear type, id, off, and union(map_ptr, range) and
1434 * padding between 'type' and union
1435 */
1436 memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
f1174f77 1437 reg->type = SCALAR_VALUE;
f1174f77 1438 reg->var_off = tnum_unknown;
f4d7e40a 1439 reg->frameno = 0;
2c78ee89 1440 reg->precise = env->subprog_cnt > 1 || !env->bpf_capable;
b03c9f9f 1441 __mark_reg_unbounded(reg);
f1174f77
EC
1442}
1443
61bd5218
JK
1444static void mark_reg_unknown(struct bpf_verifier_env *env,
1445 struct bpf_reg_state *regs, u32 regno)
f1174f77
EC
1446{
1447 if (WARN_ON(regno >= MAX_BPF_REG)) {
61bd5218 1448 verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
19ceb417
AS
1449 /* Something bad happened, let's kill all regs except FP */
1450 for (regno = 0; regno < BPF_REG_FP; regno++)
f54c7898 1451 __mark_reg_not_init(env, regs + regno);
f1174f77
EC
1452 return;
1453 }
f54c7898 1454 __mark_reg_unknown(env, regs + regno);
f1174f77
EC
1455}
1456
f54c7898
DB
1457static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1458 struct bpf_reg_state *reg)
f1174f77 1459{
f54c7898 1460 __mark_reg_unknown(env, reg);
f1174f77
EC
1461 reg->type = NOT_INIT;
1462}
1463
61bd5218
JK
1464static void mark_reg_not_init(struct bpf_verifier_env *env,
1465 struct bpf_reg_state *regs, u32 regno)
f1174f77
EC
1466{
1467 if (WARN_ON(regno >= MAX_BPF_REG)) {
61bd5218 1468 verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
19ceb417
AS
1469 /* Something bad happened, let's kill all regs except FP */
1470 for (regno = 0; regno < BPF_REG_FP; regno++)
f54c7898 1471 __mark_reg_not_init(env, regs + regno);
f1174f77
EC
1472 return;
1473 }
f54c7898 1474 __mark_reg_not_init(env, regs + regno);
a9789ef9
DB
1475}
1476
41c48f3a
AI
1477static void mark_btf_ld_reg(struct bpf_verifier_env *env,
1478 struct bpf_reg_state *regs, u32 regno,
22dc4a0f
AN
1479 enum bpf_reg_type reg_type,
1480 struct btf *btf, u32 btf_id)
41c48f3a
AI
1481{
1482 if (reg_type == SCALAR_VALUE) {
1483 mark_reg_unknown(env, regs, regno);
1484 return;
1485 }
1486 mark_reg_known_zero(env, regs, regno);
1487 regs[regno].type = PTR_TO_BTF_ID;
22dc4a0f 1488 regs[regno].btf = btf;
41c48f3a
AI
1489 regs[regno].btf_id = btf_id;
1490}
1491
5327ed3d 1492#define DEF_NOT_SUBREG (0)
61bd5218 1493static void init_reg_state(struct bpf_verifier_env *env,
f4d7e40a 1494 struct bpf_func_state *state)
17a52670 1495{
f4d7e40a 1496 struct bpf_reg_state *regs = state->regs;
17a52670
AS
1497 int i;
1498
dc503a8a 1499 for (i = 0; i < MAX_BPF_REG; i++) {
61bd5218 1500 mark_reg_not_init(env, regs, i);
dc503a8a 1501 regs[i].live = REG_LIVE_NONE;
679c782d 1502 regs[i].parent = NULL;
5327ed3d 1503 regs[i].subreg_def = DEF_NOT_SUBREG;
dc503a8a 1504 }
17a52670
AS
1505
1506 /* frame pointer */
f1174f77 1507 regs[BPF_REG_FP].type = PTR_TO_STACK;
61bd5218 1508 mark_reg_known_zero(env, regs, BPF_REG_FP);
f4d7e40a 1509 regs[BPF_REG_FP].frameno = state->frameno;
6760bf2d
DB
1510}
1511
f4d7e40a
AS
1512#define BPF_MAIN_FUNC (-1)
1513static void init_func_state(struct bpf_verifier_env *env,
1514 struct bpf_func_state *state,
1515 int callsite, int frameno, int subprogno)
1516{
1517 state->callsite = callsite;
1518 state->frameno = frameno;
1519 state->subprogno = subprogno;
1520 init_reg_state(env, state);
1521}
1522
17a52670
AS
1523enum reg_arg_type {
1524 SRC_OP, /* register is used as source operand */
1525 DST_OP, /* register is used as destination operand */
1526 DST_OP_NO_MARK /* same as above, check only, don't mark */
1527};
1528
cc8b0b92
AS
1529static int cmp_subprogs(const void *a, const void *b)
1530{
9c8105bd
JW
1531 return ((struct bpf_subprog_info *)a)->start -
1532 ((struct bpf_subprog_info *)b)->start;
cc8b0b92
AS
1533}
1534
1535static int find_subprog(struct bpf_verifier_env *env, int off)
1536{
9c8105bd 1537 struct bpf_subprog_info *p;
cc8b0b92 1538
9c8105bd
JW
1539 p = bsearch(&off, env->subprog_info, env->subprog_cnt,
1540 sizeof(env->subprog_info[0]), cmp_subprogs);
cc8b0b92
AS
1541 if (!p)
1542 return -ENOENT;
9c8105bd 1543 return p - env->subprog_info;
cc8b0b92
AS
1544
1545}
1546
1547static int add_subprog(struct bpf_verifier_env *env, int off)
1548{
1549 int insn_cnt = env->prog->len;
1550 int ret;
1551
1552 if (off >= insn_cnt || off < 0) {
1553 verbose(env, "call to invalid destination\n");
1554 return -EINVAL;
1555 }
1556 ret = find_subprog(env, off);
1557 if (ret >= 0)
282a0f46 1558 return ret;
4cb3d99c 1559 if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
cc8b0b92
AS
1560 verbose(env, "too many subprograms\n");
1561 return -E2BIG;
1562 }
e6ac2450 1563 /* determine subprog starts. The end is one before the next starts */
9c8105bd
JW
1564 env->subprog_info[env->subprog_cnt++].start = off;
1565 sort(env->subprog_info, env->subprog_cnt,
1566 sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
282a0f46 1567 return env->subprog_cnt - 1;
cc8b0b92
AS
1568}
1569
e6ac2450
MKL
1570struct bpf_kfunc_desc {
1571 struct btf_func_model func_model;
1572 u32 func_id;
1573 s32 imm;
1574};
1575
1576#define MAX_KFUNC_DESCS 256
1577struct bpf_kfunc_desc_tab {
1578 struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS];
1579 u32 nr_descs;
1580};
1581
1582static int kfunc_desc_cmp_by_id(const void *a, const void *b)
1583{
1584 const struct bpf_kfunc_desc *d0 = a;
1585 const struct bpf_kfunc_desc *d1 = b;
1586
1587 /* func_id is not greater than BTF_MAX_TYPE */
1588 return d0->func_id - d1->func_id;
1589}
1590
1591static const struct bpf_kfunc_desc *
1592find_kfunc_desc(const struct bpf_prog *prog, u32 func_id)
1593{
1594 struct bpf_kfunc_desc desc = {
1595 .func_id = func_id,
1596 };
1597 struct bpf_kfunc_desc_tab *tab;
1598
1599 tab = prog->aux->kfunc_tab;
1600 return bsearch(&desc, tab->descs, tab->nr_descs,
1601 sizeof(tab->descs[0]), kfunc_desc_cmp_by_id);
1602}
1603
1604static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id)
1605{
1606 const struct btf_type *func, *func_proto;
1607 struct bpf_kfunc_desc_tab *tab;
1608 struct bpf_prog_aux *prog_aux;
1609 struct bpf_kfunc_desc *desc;
1610 const char *func_name;
1611 unsigned long addr;
1612 int err;
1613
1614 prog_aux = env->prog->aux;
1615 tab = prog_aux->kfunc_tab;
1616 if (!tab) {
1617 if (!btf_vmlinux) {
1618 verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
1619 return -ENOTSUPP;
1620 }
1621
1622 if (!env->prog->jit_requested) {
1623 verbose(env, "JIT is required for calling kernel function\n");
1624 return -ENOTSUPP;
1625 }
1626
1627 if (!bpf_jit_supports_kfunc_call()) {
1628 verbose(env, "JIT does not support calling kernel function\n");
1629 return -ENOTSUPP;
1630 }
1631
1632 if (!env->prog->gpl_compatible) {
1633 verbose(env, "cannot call kernel function from non-GPL compatible program\n");
1634 return -EINVAL;
1635 }
1636
1637 tab = kzalloc(sizeof(*tab), GFP_KERNEL);
1638 if (!tab)
1639 return -ENOMEM;
1640 prog_aux->kfunc_tab = tab;
1641 }
1642
1643 if (find_kfunc_desc(env->prog, func_id))
1644 return 0;
1645
1646 if (tab->nr_descs == MAX_KFUNC_DESCS) {
1647 verbose(env, "too many different kernel function calls\n");
1648 return -E2BIG;
1649 }
1650
1651 func = btf_type_by_id(btf_vmlinux, func_id);
1652 if (!func || !btf_type_is_func(func)) {
1653 verbose(env, "kernel btf_id %u is not a function\n",
1654 func_id);
1655 return -EINVAL;
1656 }
1657 func_proto = btf_type_by_id(btf_vmlinux, func->type);
1658 if (!func_proto || !btf_type_is_func_proto(func_proto)) {
1659 verbose(env, "kernel function btf_id %u does not have a valid func_proto\n",
1660 func_id);
1661 return -EINVAL;
1662 }
1663
1664 func_name = btf_name_by_offset(btf_vmlinux, func->name_off);
1665 addr = kallsyms_lookup_name(func_name);
1666 if (!addr) {
1667 verbose(env, "cannot find address for kernel function %s\n",
1668 func_name);
1669 return -EINVAL;
1670 }
1671
1672 desc = &tab->descs[tab->nr_descs++];
1673 desc->func_id = func_id;
1674 desc->imm = BPF_CAST_CALL(addr) - __bpf_call_base;
1675 err = btf_distill_func_proto(&env->log, btf_vmlinux,
1676 func_proto, func_name,
1677 &desc->func_model);
1678 if (!err)
1679 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
1680 kfunc_desc_cmp_by_id, NULL);
1681 return err;
1682}
1683
1684static int kfunc_desc_cmp_by_imm(const void *a, const void *b)
1685{
1686 const struct bpf_kfunc_desc *d0 = a;
1687 const struct bpf_kfunc_desc *d1 = b;
1688
1689 if (d0->imm > d1->imm)
1690 return 1;
1691 else if (d0->imm < d1->imm)
1692 return -1;
1693 return 0;
1694}
1695
1696static void sort_kfunc_descs_by_imm(struct bpf_prog *prog)
1697{
1698 struct bpf_kfunc_desc_tab *tab;
1699
1700 tab = prog->aux->kfunc_tab;
1701 if (!tab)
1702 return;
1703
1704 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
1705 kfunc_desc_cmp_by_imm, NULL);
1706}
1707
1708bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
1709{
1710 return !!prog->aux->kfunc_tab;
1711}
1712
1713const struct btf_func_model *
1714bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
1715 const struct bpf_insn *insn)
1716{
1717 const struct bpf_kfunc_desc desc = {
1718 .imm = insn->imm,
1719 };
1720 const struct bpf_kfunc_desc *res;
1721 struct bpf_kfunc_desc_tab *tab;
1722
1723 tab = prog->aux->kfunc_tab;
1724 res = bsearch(&desc, tab->descs, tab->nr_descs,
1725 sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm);
1726
1727 return res ? &res->func_model : NULL;
1728}
1729
1730static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
cc8b0b92 1731{
9c8105bd 1732 struct bpf_subprog_info *subprog = env->subprog_info;
cc8b0b92 1733 struct bpf_insn *insn = env->prog->insnsi;
e6ac2450 1734 int i, ret, insn_cnt = env->prog->len;
cc8b0b92 1735
f910cefa
JW
1736 /* Add entry function. */
1737 ret = add_subprog(env, 0);
e6ac2450 1738 if (ret)
f910cefa
JW
1739 return ret;
1740
e6ac2450
MKL
1741 for (i = 0; i < insn_cnt; i++, insn++) {
1742 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
1743 !bpf_pseudo_kfunc_call(insn))
cc8b0b92 1744 continue;
e6ac2450 1745
2c78ee89 1746 if (!env->bpf_capable) {
e6ac2450 1747 verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
cc8b0b92
AS
1748 return -EPERM;
1749 }
e6ac2450
MKL
1750
1751 if (bpf_pseudo_func(insn)) {
1752 ret = add_subprog(env, i + insn->imm + 1);
1753 if (ret >= 0)
1754 /* remember subprog */
1755 insn[1].imm = ret;
1756 } else if (bpf_pseudo_call(insn)) {
1757 ret = add_subprog(env, i + insn->imm + 1);
1758 } else {
1759 ret = add_kfunc_call(env, insn->imm);
1760 }
1761
cc8b0b92
AS
1762 if (ret < 0)
1763 return ret;
1764 }
1765
4cb3d99c
JW
1766 /* Add a fake 'exit' subprog which could simplify subprog iteration
1767 * logic. 'subprog_cnt' should not be increased.
1768 */
1769 subprog[env->subprog_cnt].start = insn_cnt;
1770
06ee7115 1771 if (env->log.level & BPF_LOG_LEVEL2)
cc8b0b92 1772 for (i = 0; i < env->subprog_cnt; i++)
9c8105bd 1773 verbose(env, "func#%d @%d\n", i, subprog[i].start);
cc8b0b92 1774
e6ac2450
MKL
1775 return 0;
1776}
1777
1778static int check_subprogs(struct bpf_verifier_env *env)
1779{
1780 int i, subprog_start, subprog_end, off, cur_subprog = 0;
1781 struct bpf_subprog_info *subprog = env->subprog_info;
1782 struct bpf_insn *insn = env->prog->insnsi;
1783 int insn_cnt = env->prog->len;
1784
cc8b0b92 1785 /* now check that all jumps are within the same subprog */
4cb3d99c
JW
1786 subprog_start = subprog[cur_subprog].start;
1787 subprog_end = subprog[cur_subprog + 1].start;
cc8b0b92
AS
1788 for (i = 0; i < insn_cnt; i++) {
1789 u8 code = insn[i].code;
1790
7f6e4312
MF
1791 if (code == (BPF_JMP | BPF_CALL) &&
1792 insn[i].imm == BPF_FUNC_tail_call &&
1793 insn[i].src_reg != BPF_PSEUDO_CALL)
1794 subprog[cur_subprog].has_tail_call = true;
09b28d76
AS
1795 if (BPF_CLASS(code) == BPF_LD &&
1796 (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
1797 subprog[cur_subprog].has_ld_abs = true;
092ed096 1798 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
cc8b0b92
AS
1799 goto next;
1800 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
1801 goto next;
1802 off = i + insn[i].off + 1;
1803 if (off < subprog_start || off >= subprog_end) {
1804 verbose(env, "jump out of range from insn %d to %d\n", i, off);
1805 return -EINVAL;
1806 }
1807next:
1808 if (i == subprog_end - 1) {
1809 /* to avoid fall-through from one subprog into another
1810 * the last insn of the subprog should be either exit
1811 * or unconditional jump back
1812 */
1813 if (code != (BPF_JMP | BPF_EXIT) &&
1814 code != (BPF_JMP | BPF_JA)) {
1815 verbose(env, "last insn is not an exit or jmp\n");
1816 return -EINVAL;
1817 }
1818 subprog_start = subprog_end;
4cb3d99c
JW
1819 cur_subprog++;
1820 if (cur_subprog < env->subprog_cnt)
9c8105bd 1821 subprog_end = subprog[cur_subprog + 1].start;
cc8b0b92
AS
1822 }
1823 }
1824 return 0;
1825}
1826
679c782d
EC
1827/* Parentage chain of this register (or stack slot) should take care of all
1828 * issues like callee-saved registers, stack slot allocation time, etc.
1829 */
f4d7e40a 1830static int mark_reg_read(struct bpf_verifier_env *env,
679c782d 1831 const struct bpf_reg_state *state,
5327ed3d 1832 struct bpf_reg_state *parent, u8 flag)
f4d7e40a
AS
1833{
1834 bool writes = parent == state->parent; /* Observe write marks */
06ee7115 1835 int cnt = 0;
dc503a8a
EC
1836
1837 while (parent) {
1838 /* if read wasn't screened by an earlier write ... */
679c782d 1839 if (writes && state->live & REG_LIVE_WRITTEN)
dc503a8a 1840 break;
9242b5f5
AS
1841 if (parent->live & REG_LIVE_DONE) {
1842 verbose(env, "verifier BUG type %s var_off %lld off %d\n",
1843 reg_type_str[parent->type],
1844 parent->var_off.value, parent->off);
1845 return -EFAULT;
1846 }
5327ed3d
JW
1847 /* The first condition is more likely to be true than the
1848 * second, checked it first.
1849 */
1850 if ((parent->live & REG_LIVE_READ) == flag ||
1851 parent->live & REG_LIVE_READ64)
25af32da
AS
1852 /* The parentage chain never changes and
1853 * this parent was already marked as LIVE_READ.
1854 * There is no need to keep walking the chain again and
1855 * keep re-marking all parents as LIVE_READ.
1856 * This case happens when the same register is read
1857 * multiple times without writes into it in-between.
5327ed3d
JW
1858 * Also, if parent has the stronger REG_LIVE_READ64 set,
1859 * then no need to set the weak REG_LIVE_READ32.
25af32da
AS
1860 */
1861 break;
dc503a8a 1862 /* ... then we depend on parent's value */
5327ed3d
JW
1863 parent->live |= flag;
1864 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
1865 if (flag == REG_LIVE_READ64)
1866 parent->live &= ~REG_LIVE_READ32;
dc503a8a
EC
1867 state = parent;
1868 parent = state->parent;
f4d7e40a 1869 writes = true;
06ee7115 1870 cnt++;
dc503a8a 1871 }
06ee7115
AS
1872
1873 if (env->longest_mark_read_walk < cnt)
1874 env->longest_mark_read_walk = cnt;
f4d7e40a 1875 return 0;
dc503a8a
EC
1876}
1877
5327ed3d
JW
1878/* This function is supposed to be used by the following 32-bit optimization
1879 * code only. It returns TRUE if the source or destination register operates
1880 * on 64-bit, otherwise return FALSE.
1881 */
1882static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
1883 u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
1884{
1885 u8 code, class, op;
1886
1887 code = insn->code;
1888 class = BPF_CLASS(code);
1889 op = BPF_OP(code);
1890 if (class == BPF_JMP) {
1891 /* BPF_EXIT for "main" will reach here. Return TRUE
1892 * conservatively.
1893 */
1894 if (op == BPF_EXIT)
1895 return true;
1896 if (op == BPF_CALL) {
1897 /* BPF to BPF call will reach here because of marking
1898 * caller saved clobber with DST_OP_NO_MARK for which we
1899 * don't care the register def because they are anyway
1900 * marked as NOT_INIT already.
1901 */
1902 if (insn->src_reg == BPF_PSEUDO_CALL)
1903 return false;
1904 /* Helper call will reach here because of arg type
1905 * check, conservatively return TRUE.
1906 */
1907 if (t == SRC_OP)
1908 return true;
1909
1910 return false;
1911 }
1912 }
1913
1914 if (class == BPF_ALU64 || class == BPF_JMP ||
1915 /* BPF_END always use BPF_ALU class. */
1916 (class == BPF_ALU && op == BPF_END && insn->imm == 64))
1917 return true;
1918
1919 if (class == BPF_ALU || class == BPF_JMP32)
1920 return false;
1921
1922 if (class == BPF_LDX) {
1923 if (t != SRC_OP)
1924 return BPF_SIZE(code) == BPF_DW;
1925 /* LDX source must be ptr. */
1926 return true;
1927 }
1928
1929 if (class == BPF_STX) {
83a28819
IL
1930 /* BPF_STX (including atomic variants) has multiple source
1931 * operands, one of which is a ptr. Check whether the caller is
1932 * asking about it.
1933 */
1934 if (t == SRC_OP && reg->type != SCALAR_VALUE)
5327ed3d
JW
1935 return true;
1936 return BPF_SIZE(code) == BPF_DW;
1937 }
1938
1939 if (class == BPF_LD) {
1940 u8 mode = BPF_MODE(code);
1941
1942 /* LD_IMM64 */
1943 if (mode == BPF_IMM)
1944 return true;
1945
1946 /* Both LD_IND and LD_ABS return 32-bit data. */
1947 if (t != SRC_OP)
1948 return false;
1949
1950 /* Implicit ctx ptr. */
1951 if (regno == BPF_REG_6)
1952 return true;
1953
1954 /* Explicit source could be any width. */
1955 return true;
1956 }
1957
1958 if (class == BPF_ST)
1959 /* The only source register for BPF_ST is a ptr. */
1960 return true;
1961
1962 /* Conservatively return true at default. */
1963 return true;
1964}
1965
83a28819
IL
1966/* Return the regno defined by the insn, or -1. */
1967static int insn_def_regno(const struct bpf_insn *insn)
b325fbca 1968{
83a28819
IL
1969 switch (BPF_CLASS(insn->code)) {
1970 case BPF_JMP:
1971 case BPF_JMP32:
1972 case BPF_ST:
1973 return -1;
1974 case BPF_STX:
1975 if (BPF_MODE(insn->code) == BPF_ATOMIC &&
1976 (insn->imm & BPF_FETCH)) {
1977 if (insn->imm == BPF_CMPXCHG)
1978 return BPF_REG_0;
1979 else
1980 return insn->src_reg;
1981 } else {
1982 return -1;
1983 }
1984 default:
1985 return insn->dst_reg;
1986 }
b325fbca
JW
1987}
1988
1989/* Return TRUE if INSN has defined any 32-bit value explicitly. */
1990static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
1991{
83a28819
IL
1992 int dst_reg = insn_def_regno(insn);
1993
1994 if (dst_reg == -1)
b325fbca
JW
1995 return false;
1996
83a28819 1997 return !is_reg64(env, insn, dst_reg, NULL, DST_OP);
b325fbca
JW
1998}
1999
5327ed3d
JW
2000static void mark_insn_zext(struct bpf_verifier_env *env,
2001 struct bpf_reg_state *reg)
2002{
2003 s32 def_idx = reg->subreg_def;
2004
2005 if (def_idx == DEF_NOT_SUBREG)
2006 return;
2007
2008 env->insn_aux_data[def_idx - 1].zext_dst = true;
2009 /* The dst will be zero extended, so won't be sub-register anymore. */
2010 reg->subreg_def = DEF_NOT_SUBREG;
2011}
2012
dc503a8a 2013static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
17a52670
AS
2014 enum reg_arg_type t)
2015{
f4d7e40a
AS
2016 struct bpf_verifier_state *vstate = env->cur_state;
2017 struct bpf_func_state *state = vstate->frame[vstate->curframe];
5327ed3d 2018 struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
c342dc10 2019 struct bpf_reg_state *reg, *regs = state->regs;
5327ed3d 2020 bool rw64;
dc503a8a 2021
17a52670 2022 if (regno >= MAX_BPF_REG) {
61bd5218 2023 verbose(env, "R%d is invalid\n", regno);
17a52670
AS
2024 return -EINVAL;
2025 }
2026
c342dc10 2027 reg = &regs[regno];
5327ed3d 2028 rw64 = is_reg64(env, insn, regno, reg, t);
17a52670
AS
2029 if (t == SRC_OP) {
2030 /* check whether register used as source operand can be read */
c342dc10 2031 if (reg->type == NOT_INIT) {
61bd5218 2032 verbose(env, "R%d !read_ok\n", regno);
17a52670
AS
2033 return -EACCES;
2034 }
679c782d 2035 /* We don't need to worry about FP liveness because it's read-only */
c342dc10
JW
2036 if (regno == BPF_REG_FP)
2037 return 0;
2038
5327ed3d
JW
2039 if (rw64)
2040 mark_insn_zext(env, reg);
2041
2042 return mark_reg_read(env, reg, reg->parent,
2043 rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
17a52670
AS
2044 } else {
2045 /* check whether register used as dest operand can be written to */
2046 if (regno == BPF_REG_FP) {
61bd5218 2047 verbose(env, "frame pointer is read only\n");
17a52670
AS
2048 return -EACCES;
2049 }
c342dc10 2050 reg->live |= REG_LIVE_WRITTEN;
5327ed3d 2051 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
17a52670 2052 if (t == DST_OP)
61bd5218 2053 mark_reg_unknown(env, regs, regno);
17a52670
AS
2054 }
2055 return 0;
2056}
2057
b5dc0163
AS
2058/* for any branch, call, exit record the history of jmps in the given state */
2059static int push_jmp_history(struct bpf_verifier_env *env,
2060 struct bpf_verifier_state *cur)
2061{
2062 u32 cnt = cur->jmp_history_cnt;
2063 struct bpf_idx_pair *p;
2064
2065 cnt++;
2066 p = krealloc(cur->jmp_history, cnt * sizeof(*p), GFP_USER);
2067 if (!p)
2068 return -ENOMEM;
2069 p[cnt - 1].idx = env->insn_idx;
2070 p[cnt - 1].prev_idx = env->prev_insn_idx;
2071 cur->jmp_history = p;
2072 cur->jmp_history_cnt = cnt;
2073 return 0;
2074}
2075
2076/* Backtrack one insn at a time. If idx is not at the top of recorded
2077 * history then previous instruction came from straight line execution.
2078 */
2079static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
2080 u32 *history)
2081{
2082 u32 cnt = *history;
2083
2084 if (cnt && st->jmp_history[cnt - 1].idx == i) {
2085 i = st->jmp_history[cnt - 1].prev_idx;
2086 (*history)--;
2087 } else {
2088 i--;
2089 }
2090 return i;
2091}
2092
e6ac2450
MKL
2093static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
2094{
2095 const struct btf_type *func;
2096
2097 if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
2098 return NULL;
2099
2100 func = btf_type_by_id(btf_vmlinux, insn->imm);
2101 return btf_name_by_offset(btf_vmlinux, func->name_off);
2102}
2103
b5dc0163
AS
2104/* For given verifier state backtrack_insn() is called from the last insn to
2105 * the first insn. Its purpose is to compute a bitmask of registers and
2106 * stack slots that needs precision in the parent verifier state.
2107 */
2108static int backtrack_insn(struct bpf_verifier_env *env, int idx,
2109 u32 *reg_mask, u64 *stack_mask)
2110{
2111 const struct bpf_insn_cbs cbs = {
e6ac2450 2112 .cb_call = disasm_kfunc_name,
b5dc0163
AS
2113 .cb_print = verbose,
2114 .private_data = env,
2115 };
2116 struct bpf_insn *insn = env->prog->insnsi + idx;
2117 u8 class = BPF_CLASS(insn->code);
2118 u8 opcode = BPF_OP(insn->code);
2119 u8 mode = BPF_MODE(insn->code);
2120 u32 dreg = 1u << insn->dst_reg;
2121 u32 sreg = 1u << insn->src_reg;
2122 u32 spi;
2123
2124 if (insn->code == 0)
2125 return 0;
2126 if (env->log.level & BPF_LOG_LEVEL) {
2127 verbose(env, "regs=%x stack=%llx before ", *reg_mask, *stack_mask);
2128 verbose(env, "%d: ", idx);
2129 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
2130 }
2131
2132 if (class == BPF_ALU || class == BPF_ALU64) {
2133 if (!(*reg_mask & dreg))
2134 return 0;
2135 if (opcode == BPF_MOV) {
2136 if (BPF_SRC(insn->code) == BPF_X) {
2137 /* dreg = sreg
2138 * dreg needs precision after this insn
2139 * sreg needs precision before this insn
2140 */
2141 *reg_mask &= ~dreg;
2142 *reg_mask |= sreg;
2143 } else {
2144 /* dreg = K
2145 * dreg needs precision after this insn.
2146 * Corresponding register is already marked
2147 * as precise=true in this verifier state.
2148 * No further markings in parent are necessary
2149 */
2150 *reg_mask &= ~dreg;
2151 }
2152 } else {
2153 if (BPF_SRC(insn->code) == BPF_X) {
2154 /* dreg += sreg
2155 * both dreg and sreg need precision
2156 * before this insn
2157 */
2158 *reg_mask |= sreg;
2159 } /* else dreg += K
2160 * dreg still needs precision before this insn
2161 */
2162 }
2163 } else if (class == BPF_LDX) {
2164 if (!(*reg_mask & dreg))
2165 return 0;
2166 *reg_mask &= ~dreg;
2167
2168 /* scalars can only be spilled into stack w/o losing precision.
2169 * Load from any other memory can be zero extended.
2170 * The desire to keep that precision is already indicated
2171 * by 'precise' mark in corresponding register of this state.
2172 * No further tracking necessary.
2173 */
2174 if (insn->src_reg != BPF_REG_FP)
2175 return 0;
2176 if (BPF_SIZE(insn->code) != BPF_DW)
2177 return 0;
2178
2179 /* dreg = *(u64 *)[fp - off] was a fill from the stack.
2180 * that [fp - off] slot contains scalar that needs to be
2181 * tracked with precision
2182 */
2183 spi = (-insn->off - 1) / BPF_REG_SIZE;
2184 if (spi >= 64) {
2185 verbose(env, "BUG spi %d\n", spi);
2186 WARN_ONCE(1, "verifier backtracking bug");
2187 return -EFAULT;
2188 }
2189 *stack_mask |= 1ull << spi;
b3b50f05 2190 } else if (class == BPF_STX || class == BPF_ST) {
b5dc0163 2191 if (*reg_mask & dreg)
b3b50f05 2192 /* stx & st shouldn't be using _scalar_ dst_reg
b5dc0163
AS
2193 * to access memory. It means backtracking
2194 * encountered a case of pointer subtraction.
2195 */
2196 return -ENOTSUPP;
2197 /* scalars can only be spilled into stack */
2198 if (insn->dst_reg != BPF_REG_FP)
2199 return 0;
2200 if (BPF_SIZE(insn->code) != BPF_DW)
2201 return 0;
2202 spi = (-insn->off - 1) / BPF_REG_SIZE;
2203 if (spi >= 64) {
2204 verbose(env, "BUG spi %d\n", spi);
2205 WARN_ONCE(1, "verifier backtracking bug");
2206 return -EFAULT;
2207 }
2208 if (!(*stack_mask & (1ull << spi)))
2209 return 0;
2210 *stack_mask &= ~(1ull << spi);
b3b50f05
AN
2211 if (class == BPF_STX)
2212 *reg_mask |= sreg;
b5dc0163
AS
2213 } else if (class == BPF_JMP || class == BPF_JMP32) {
2214 if (opcode == BPF_CALL) {
2215 if (insn->src_reg == BPF_PSEUDO_CALL)
2216 return -ENOTSUPP;
2217 /* regular helper call sets R0 */
2218 *reg_mask &= ~1;
2219 if (*reg_mask & 0x3f) {
2220 /* if backtracing was looking for registers R1-R5
2221 * they should have been found already.
2222 */
2223 verbose(env, "BUG regs %x\n", *reg_mask);
2224 WARN_ONCE(1, "verifier backtracking bug");
2225 return -EFAULT;
2226 }
2227 } else if (opcode == BPF_EXIT) {
2228 return -ENOTSUPP;
2229 }
2230 } else if (class == BPF_LD) {
2231 if (!(*reg_mask & dreg))
2232 return 0;
2233 *reg_mask &= ~dreg;
2234 /* It's ld_imm64 or ld_abs or ld_ind.
2235 * For ld_imm64 no further tracking of precision
2236 * into parent is necessary
2237 */
2238 if (mode == BPF_IND || mode == BPF_ABS)
2239 /* to be analyzed */
2240 return -ENOTSUPP;
b5dc0163
AS
2241 }
2242 return 0;
2243}
2244
2245/* the scalar precision tracking algorithm:
2246 * . at the start all registers have precise=false.
2247 * . scalar ranges are tracked as normal through alu and jmp insns.
2248 * . once precise value of the scalar register is used in:
2249 * . ptr + scalar alu
2250 * . if (scalar cond K|scalar)
2251 * . helper_call(.., scalar, ...) where ARG_CONST is expected
2252 * backtrack through the verifier states and mark all registers and
2253 * stack slots with spilled constants that these scalar regisers
2254 * should be precise.
2255 * . during state pruning two registers (or spilled stack slots)
2256 * are equivalent if both are not precise.
2257 *
2258 * Note the verifier cannot simply walk register parentage chain,
2259 * since many different registers and stack slots could have been
2260 * used to compute single precise scalar.
2261 *
2262 * The approach of starting with precise=true for all registers and then
2263 * backtrack to mark a register as not precise when the verifier detects
2264 * that program doesn't care about specific value (e.g., when helper
2265 * takes register as ARG_ANYTHING parameter) is not safe.
2266 *
2267 * It's ok to walk single parentage chain of the verifier states.
2268 * It's possible that this backtracking will go all the way till 1st insn.
2269 * All other branches will be explored for needing precision later.
2270 *
2271 * The backtracking needs to deal with cases like:
2272 * 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)
2273 * r9 -= r8
2274 * r5 = r9
2275 * if r5 > 0x79f goto pc+7
2276 * R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
2277 * r5 += 1
2278 * ...
2279 * call bpf_perf_event_output#25
2280 * where .arg5_type = ARG_CONST_SIZE_OR_ZERO
2281 *
2282 * and this case:
2283 * r6 = 1
2284 * call foo // uses callee's r6 inside to compute r0
2285 * r0 += r6
2286 * if r0 == 0 goto
2287 *
2288 * to track above reg_mask/stack_mask needs to be independent for each frame.
2289 *
2290 * Also if parent's curframe > frame where backtracking started,
2291 * the verifier need to mark registers in both frames, otherwise callees
2292 * may incorrectly prune callers. This is similar to
2293 * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
2294 *
2295 * For now backtracking falls back into conservative marking.
2296 */
2297static void mark_all_scalars_precise(struct bpf_verifier_env *env,
2298 struct bpf_verifier_state *st)
2299{
2300 struct bpf_func_state *func;
2301 struct bpf_reg_state *reg;
2302 int i, j;
2303
2304 /* big hammer: mark all scalars precise in this path.
2305 * pop_stack may still get !precise scalars.
2306 */
2307 for (; st; st = st->parent)
2308 for (i = 0; i <= st->curframe; i++) {
2309 func = st->frame[i];
2310 for (j = 0; j < BPF_REG_FP; j++) {
2311 reg = &func->regs[j];
2312 if (reg->type != SCALAR_VALUE)
2313 continue;
2314 reg->precise = true;
2315 }
2316 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
2317 if (func->stack[j].slot_type[0] != STACK_SPILL)
2318 continue;
2319 reg = &func->stack[j].spilled_ptr;
2320 if (reg->type != SCALAR_VALUE)
2321 continue;
2322 reg->precise = true;
2323 }
2324 }
2325}
2326
a3ce685d
AS
2327static int __mark_chain_precision(struct bpf_verifier_env *env, int regno,
2328 int spi)
b5dc0163
AS
2329{
2330 struct bpf_verifier_state *st = env->cur_state;
2331 int first_idx = st->first_insn_idx;
2332 int last_idx = env->insn_idx;
2333 struct bpf_func_state *func;
2334 struct bpf_reg_state *reg;
a3ce685d
AS
2335 u32 reg_mask = regno >= 0 ? 1u << regno : 0;
2336 u64 stack_mask = spi >= 0 ? 1ull << spi : 0;
b5dc0163 2337 bool skip_first = true;
a3ce685d 2338 bool new_marks = false;
b5dc0163
AS
2339 int i, err;
2340
2c78ee89 2341 if (!env->bpf_capable)
b5dc0163
AS
2342 return 0;
2343
2344 func = st->frame[st->curframe];
a3ce685d
AS
2345 if (regno >= 0) {
2346 reg = &func->regs[regno];
2347 if (reg->type != SCALAR_VALUE) {
2348 WARN_ONCE(1, "backtracing misuse");
2349 return -EFAULT;
2350 }
2351 if (!reg->precise)
2352 new_marks = true;
2353 else
2354 reg_mask = 0;
2355 reg->precise = true;
b5dc0163 2356 }
b5dc0163 2357
a3ce685d
AS
2358 while (spi >= 0) {
2359 if (func->stack[spi].slot_type[0] != STACK_SPILL) {
2360 stack_mask = 0;
2361 break;
2362 }
2363 reg = &func->stack[spi].spilled_ptr;
2364 if (reg->type != SCALAR_VALUE) {
2365 stack_mask = 0;
2366 break;
2367 }
2368 if (!reg->precise)
2369 new_marks = true;
2370 else
2371 stack_mask = 0;
2372 reg->precise = true;
2373 break;
2374 }
2375
2376 if (!new_marks)
2377 return 0;
2378 if (!reg_mask && !stack_mask)
2379 return 0;
b5dc0163
AS
2380 for (;;) {
2381 DECLARE_BITMAP(mask, 64);
b5dc0163
AS
2382 u32 history = st->jmp_history_cnt;
2383
2384 if (env->log.level & BPF_LOG_LEVEL)
2385 verbose(env, "last_idx %d first_idx %d\n", last_idx, first_idx);
2386 for (i = last_idx;;) {
2387 if (skip_first) {
2388 err = 0;
2389 skip_first = false;
2390 } else {
2391 err = backtrack_insn(env, i, &reg_mask, &stack_mask);
2392 }
2393 if (err == -ENOTSUPP) {
2394 mark_all_scalars_precise(env, st);
2395 return 0;
2396 } else if (err) {
2397 return err;
2398 }
2399 if (!reg_mask && !stack_mask)
2400 /* Found assignment(s) into tracked register in this state.
2401 * Since this state is already marked, just return.
2402 * Nothing to be tracked further in the parent state.
2403 */
2404 return 0;
2405 if (i == first_idx)
2406 break;
2407 i = get_prev_insn_idx(st, i, &history);
2408 if (i >= env->prog->len) {
2409 /* This can happen if backtracking reached insn 0
2410 * and there are still reg_mask or stack_mask
2411 * to backtrack.
2412 * It means the backtracking missed the spot where
2413 * particular register was initialized with a constant.
2414 */
2415 verbose(env, "BUG backtracking idx %d\n", i);
2416 WARN_ONCE(1, "verifier backtracking bug");
2417 return -EFAULT;
2418 }
2419 }
2420 st = st->parent;
2421 if (!st)
2422 break;
2423
a3ce685d 2424 new_marks = false;
b5dc0163
AS
2425 func = st->frame[st->curframe];
2426 bitmap_from_u64(mask, reg_mask);
2427 for_each_set_bit(i, mask, 32) {
2428 reg = &func->regs[i];
a3ce685d
AS
2429 if (reg->type != SCALAR_VALUE) {
2430 reg_mask &= ~(1u << i);
b5dc0163 2431 continue;
a3ce685d 2432 }
b5dc0163
AS
2433 if (!reg->precise)
2434 new_marks = true;
2435 reg->precise = true;
2436 }
2437
2438 bitmap_from_u64(mask, stack_mask);
2439 for_each_set_bit(i, mask, 64) {
2440 if (i >= func->allocated_stack / BPF_REG_SIZE) {
2339cd6c
AS
2441 /* the sequence of instructions:
2442 * 2: (bf) r3 = r10
2443 * 3: (7b) *(u64 *)(r3 -8) = r0
2444 * 4: (79) r4 = *(u64 *)(r10 -8)
2445 * doesn't contain jmps. It's backtracked
2446 * as a single block.
2447 * During backtracking insn 3 is not recognized as
2448 * stack access, so at the end of backtracking
2449 * stack slot fp-8 is still marked in stack_mask.
2450 * However the parent state may not have accessed
2451 * fp-8 and it's "unallocated" stack space.
2452 * In such case fallback to conservative.
b5dc0163 2453 */
2339cd6c
AS
2454 mark_all_scalars_precise(env, st);
2455 return 0;
b5dc0163
AS
2456 }
2457
a3ce685d
AS
2458 if (func->stack[i].slot_type[0] != STACK_SPILL) {
2459 stack_mask &= ~(1ull << i);
b5dc0163 2460 continue;
a3ce685d 2461 }
b5dc0163 2462 reg = &func->stack[i].spilled_ptr;
a3ce685d
AS
2463 if (reg->type != SCALAR_VALUE) {
2464 stack_mask &= ~(1ull << i);
b5dc0163 2465 continue;
a3ce685d 2466 }
b5dc0163
AS
2467 if (!reg->precise)
2468 new_marks = true;
2469 reg->precise = true;
2470 }
2471 if (env->log.level & BPF_LOG_LEVEL) {
2472 print_verifier_state(env, func);
2473 verbose(env, "parent %s regs=%x stack=%llx marks\n",
2474 new_marks ? "didn't have" : "already had",
2475 reg_mask, stack_mask);
2476 }
2477
a3ce685d
AS
2478 if (!reg_mask && !stack_mask)
2479 break;
b5dc0163
AS
2480 if (!new_marks)
2481 break;
2482
2483 last_idx = st->last_insn_idx;
2484 first_idx = st->first_insn_idx;
2485 }
2486 return 0;
2487}
2488
a3ce685d
AS
2489static int mark_chain_precision(struct bpf_verifier_env *env, int regno)
2490{
2491 return __mark_chain_precision(env, regno, -1);
2492}
2493
2494static int mark_chain_precision_stack(struct bpf_verifier_env *env, int spi)
2495{
2496 return __mark_chain_precision(env, -1, spi);
2497}
b5dc0163 2498
1be7f75d
AS
2499static bool is_spillable_regtype(enum bpf_reg_type type)
2500{
2501 switch (type) {
2502 case PTR_TO_MAP_VALUE:
2503 case PTR_TO_MAP_VALUE_OR_NULL:
2504 case PTR_TO_STACK:
2505 case PTR_TO_CTX:
969bf05e 2506 case PTR_TO_PACKET:
de8f3a83 2507 case PTR_TO_PACKET_META:
969bf05e 2508 case PTR_TO_PACKET_END:
d58e468b 2509 case PTR_TO_FLOW_KEYS:
1be7f75d 2510 case CONST_PTR_TO_MAP:
c64b7983
JS
2511 case PTR_TO_SOCKET:
2512 case PTR_TO_SOCKET_OR_NULL:
46f8bc92
MKL
2513 case PTR_TO_SOCK_COMMON:
2514 case PTR_TO_SOCK_COMMON_OR_NULL:
655a51e5
MKL
2515 case PTR_TO_TCP_SOCK:
2516 case PTR_TO_TCP_SOCK_OR_NULL:
fada7fdc 2517 case PTR_TO_XDP_SOCK:
65726b5b 2518 case PTR_TO_BTF_ID:
b121b341 2519 case PTR_TO_BTF_ID_OR_NULL:
afbf21dc
YS
2520 case PTR_TO_RDONLY_BUF:
2521 case PTR_TO_RDONLY_BUF_OR_NULL:
2522 case PTR_TO_RDWR_BUF:
2523 case PTR_TO_RDWR_BUF_OR_NULL:
eaa6bcb7 2524 case PTR_TO_PERCPU_BTF_ID:
744ea4e3
GR
2525 case PTR_TO_MEM:
2526 case PTR_TO_MEM_OR_NULL:
69c087ba
YS
2527 case PTR_TO_FUNC:
2528 case PTR_TO_MAP_KEY:
1be7f75d
AS
2529 return true;
2530 default:
2531 return false;
2532 }
2533}
2534
cc2b14d5
AS
2535/* Does this register contain a constant zero? */
2536static bool register_is_null(struct bpf_reg_state *reg)
2537{
2538 return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
2539}
2540
f7cf25b2
AS
2541static bool register_is_const(struct bpf_reg_state *reg)
2542{
2543 return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
2544}
2545
5689d49b
YS
2546static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
2547{
2548 return tnum_is_unknown(reg->var_off) &&
2549 reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
2550 reg->umin_value == 0 && reg->umax_value == U64_MAX &&
2551 reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
2552 reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
2553}
2554
2555static bool register_is_bounded(struct bpf_reg_state *reg)
2556{
2557 return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
2558}
2559
6e7e63cb
JH
2560static bool __is_pointer_value(bool allow_ptr_leaks,
2561 const struct bpf_reg_state *reg)
2562{
2563 if (allow_ptr_leaks)
2564 return false;
2565
2566 return reg->type != SCALAR_VALUE;
2567}
2568
f7cf25b2
AS
2569static void save_register_state(struct bpf_func_state *state,
2570 int spi, struct bpf_reg_state *reg)
2571{
2572 int i;
2573
2574 state->stack[spi].spilled_ptr = *reg;
2575 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
2576
2577 for (i = 0; i < BPF_REG_SIZE; i++)
2578 state->stack[spi].slot_type[i] = STACK_SPILL;
2579}
2580
01f810ac 2581/* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
17a52670
AS
2582 * stack boundary and alignment are checked in check_mem_access()
2583 */
01f810ac
AM
2584static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
2585 /* stack frame we're writing to */
2586 struct bpf_func_state *state,
2587 int off, int size, int value_regno,
2588 int insn_idx)
17a52670 2589{
f4d7e40a 2590 struct bpf_func_state *cur; /* state of the current function */
638f5b90 2591 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
b5dc0163 2592 u32 dst_reg = env->prog->insnsi[insn_idx].dst_reg;
f7cf25b2 2593 struct bpf_reg_state *reg = NULL;
638f5b90 2594
f4d7e40a 2595 err = realloc_func_state(state, round_up(slot + 1, BPF_REG_SIZE),
fd978bf7 2596 state->acquired_refs, true);
638f5b90
AS
2597 if (err)
2598 return err;
9c399760
AS
2599 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
2600 * so it's aligned access and [off, off + size) are within stack limits
2601 */
638f5b90
AS
2602 if (!env->allow_ptr_leaks &&
2603 state->stack[spi].slot_type[0] == STACK_SPILL &&
2604 size != BPF_REG_SIZE) {
2605 verbose(env, "attempt to corrupt spilled pointer on stack\n");
2606 return -EACCES;
2607 }
17a52670 2608
f4d7e40a 2609 cur = env->cur_state->frame[env->cur_state->curframe];
f7cf25b2
AS
2610 if (value_regno >= 0)
2611 reg = &cur->regs[value_regno];
17a52670 2612
5689d49b 2613 if (reg && size == BPF_REG_SIZE && register_is_bounded(reg) &&
2c78ee89 2614 !register_is_null(reg) && env->bpf_capable) {
b5dc0163
AS
2615 if (dst_reg != BPF_REG_FP) {
2616 /* The backtracking logic can only recognize explicit
2617 * stack slot address like [fp - 8]. Other spill of
2618 * scalar via different register has to be conervative.
2619 * Backtrack from here and mark all registers as precise
2620 * that contributed into 'reg' being a constant.
2621 */
2622 err = mark_chain_precision(env, value_regno);
2623 if (err)
2624 return err;
2625 }
f7cf25b2
AS
2626 save_register_state(state, spi, reg);
2627 } else if (reg && is_spillable_regtype(reg->type)) {
17a52670 2628 /* register containing pointer is being spilled into stack */
9c399760 2629 if (size != BPF_REG_SIZE) {
f7cf25b2 2630 verbose_linfo(env, insn_idx, "; ");
61bd5218 2631 verbose(env, "invalid size of register spill\n");
17a52670
AS
2632 return -EACCES;
2633 }
2634
f7cf25b2 2635 if (state != cur && reg->type == PTR_TO_STACK) {
f4d7e40a
AS
2636 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
2637 return -EINVAL;
2638 }
2639
2c78ee89 2640 if (!env->bypass_spec_v4) {
f7cf25b2 2641 bool sanitize = false;
17a52670 2642
f7cf25b2
AS
2643 if (state->stack[spi].slot_type[0] == STACK_SPILL &&
2644 register_is_const(&state->stack[spi].spilled_ptr))
2645 sanitize = true;
2646 for (i = 0; i < BPF_REG_SIZE; i++)
2647 if (state->stack[spi].slot_type[i] == STACK_MISC) {
2648 sanitize = true;
2649 break;
2650 }
2651 if (sanitize) {
af86ca4e
AS
2652 int *poff = &env->insn_aux_data[insn_idx].sanitize_stack_off;
2653 int soff = (-spi - 1) * BPF_REG_SIZE;
2654
2655 /* detected reuse of integer stack slot with a pointer
2656 * which means either llvm is reusing stack slot or
2657 * an attacker is trying to exploit CVE-2018-3639
2658 * (speculative store bypass)
2659 * Have to sanitize that slot with preemptive
2660 * store of zero.
2661 */
2662 if (*poff && *poff != soff) {
2663 /* disallow programs where single insn stores
2664 * into two different stack slots, since verifier
2665 * cannot sanitize them
2666 */
2667 verbose(env,
2668 "insn %d cannot access two stack slots fp%d and fp%d",
2669 insn_idx, *poff, soff);
2670 return -EINVAL;
2671 }
2672 *poff = soff;
2673 }
af86ca4e 2674 }
f7cf25b2 2675 save_register_state(state, spi, reg);
9c399760 2676 } else {
cc2b14d5
AS
2677 u8 type = STACK_MISC;
2678
679c782d
EC
2679 /* regular write of data into stack destroys any spilled ptr */
2680 state->stack[spi].spilled_ptr.type = NOT_INIT;
0bae2d4d
JW
2681 /* Mark slots as STACK_MISC if they belonged to spilled ptr. */
2682 if (state->stack[spi].slot_type[0] == STACK_SPILL)
2683 for (i = 0; i < BPF_REG_SIZE; i++)
2684 state->stack[spi].slot_type[i] = STACK_MISC;
9c399760 2685
cc2b14d5
AS
2686 /* only mark the slot as written if all 8 bytes were written
2687 * otherwise read propagation may incorrectly stop too soon
2688 * when stack slots are partially written.
2689 * This heuristic means that read propagation will be
2690 * conservative, since it will add reg_live_read marks
2691 * to stack slots all the way to first state when programs
2692 * writes+reads less than 8 bytes
2693 */
2694 if (size == BPF_REG_SIZE)
2695 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
2696
2697 /* when we zero initialize stack slots mark them as such */
b5dc0163
AS
2698 if (reg && register_is_null(reg)) {
2699 /* backtracking doesn't work for STACK_ZERO yet. */
2700 err = mark_chain_precision(env, value_regno);
2701 if (err)
2702 return err;
cc2b14d5 2703 type = STACK_ZERO;
b5dc0163 2704 }
cc2b14d5 2705
0bae2d4d 2706 /* Mark slots affected by this stack write. */
9c399760 2707 for (i = 0; i < size; i++)
638f5b90 2708 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
cc2b14d5 2709 type;
17a52670
AS
2710 }
2711 return 0;
2712}
2713
01f810ac
AM
2714/* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
2715 * known to contain a variable offset.
2716 * This function checks whether the write is permitted and conservatively
2717 * tracks the effects of the write, considering that each stack slot in the
2718 * dynamic range is potentially written to.
2719 *
2720 * 'off' includes 'regno->off'.
2721 * 'value_regno' can be -1, meaning that an unknown value is being written to
2722 * the stack.
2723 *
2724 * Spilled pointers in range are not marked as written because we don't know
2725 * what's going to be actually written. This means that read propagation for
2726 * future reads cannot be terminated by this write.
2727 *
2728 * For privileged programs, uninitialized stack slots are considered
2729 * initialized by this write (even though we don't know exactly what offsets
2730 * are going to be written to). The idea is that we don't want the verifier to
2731 * reject future reads that access slots written to through variable offsets.
2732 */
2733static int check_stack_write_var_off(struct bpf_verifier_env *env,
2734 /* func where register points to */
2735 struct bpf_func_state *state,
2736 int ptr_regno, int off, int size,
2737 int value_regno, int insn_idx)
2738{
2739 struct bpf_func_state *cur; /* state of the current function */
2740 int min_off, max_off;
2741 int i, err;
2742 struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
2743 bool writing_zero = false;
2744 /* set if the fact that we're writing a zero is used to let any
2745 * stack slots remain STACK_ZERO
2746 */
2747 bool zero_used = false;
2748
2749 cur = env->cur_state->frame[env->cur_state->curframe];
2750 ptr_reg = &cur->regs[ptr_regno];
2751 min_off = ptr_reg->smin_value + off;
2752 max_off = ptr_reg->smax_value + off + size;
2753 if (value_regno >= 0)
2754 value_reg = &cur->regs[value_regno];
2755 if (value_reg && register_is_null(value_reg))
2756 writing_zero = true;
2757
2758 err = realloc_func_state(state, round_up(-min_off, BPF_REG_SIZE),
2759 state->acquired_refs, true);
2760 if (err)
2761 return err;
2762
2763
2764 /* Variable offset writes destroy any spilled pointers in range. */
2765 for (i = min_off; i < max_off; i++) {
2766 u8 new_type, *stype;
2767 int slot, spi;
2768
2769 slot = -i - 1;
2770 spi = slot / BPF_REG_SIZE;
2771 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
2772
2773 if (!env->allow_ptr_leaks
2774 && *stype != NOT_INIT
2775 && *stype != SCALAR_VALUE) {
2776 /* Reject the write if there's are spilled pointers in
2777 * range. If we didn't reject here, the ptr status
2778 * would be erased below (even though not all slots are
2779 * actually overwritten), possibly opening the door to
2780 * leaks.
2781 */
2782 verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
2783 insn_idx, i);
2784 return -EINVAL;
2785 }
2786
2787 /* Erase all spilled pointers. */
2788 state->stack[spi].spilled_ptr.type = NOT_INIT;
2789
2790 /* Update the slot type. */
2791 new_type = STACK_MISC;
2792 if (writing_zero && *stype == STACK_ZERO) {
2793 new_type = STACK_ZERO;
2794 zero_used = true;
2795 }
2796 /* If the slot is STACK_INVALID, we check whether it's OK to
2797 * pretend that it will be initialized by this write. The slot
2798 * might not actually be written to, and so if we mark it as
2799 * initialized future reads might leak uninitialized memory.
2800 * For privileged programs, we will accept such reads to slots
2801 * that may or may not be written because, if we're reject
2802 * them, the error would be too confusing.
2803 */
2804 if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
2805 verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
2806 insn_idx, i);
2807 return -EINVAL;
2808 }
2809 *stype = new_type;
2810 }
2811 if (zero_used) {
2812 /* backtracking doesn't work for STACK_ZERO yet. */
2813 err = mark_chain_precision(env, value_regno);
2814 if (err)
2815 return err;
2816 }
2817 return 0;
2818}
2819
2820/* When register 'dst_regno' is assigned some values from stack[min_off,
2821 * max_off), we set the register's type according to the types of the
2822 * respective stack slots. If all the stack values are known to be zeros, then
2823 * so is the destination reg. Otherwise, the register is considered to be
2824 * SCALAR. This function does not deal with register filling; the caller must
2825 * ensure that all spilled registers in the stack range have been marked as
2826 * read.
2827 */
2828static void mark_reg_stack_read(struct bpf_verifier_env *env,
2829 /* func where src register points to */
2830 struct bpf_func_state *ptr_state,
2831 int min_off, int max_off, int dst_regno)
2832{
2833 struct bpf_verifier_state *vstate = env->cur_state;
2834 struct bpf_func_state *state = vstate->frame[vstate->curframe];
2835 int i, slot, spi;
2836 u8 *stype;
2837 int zeros = 0;
2838
2839 for (i = min_off; i < max_off; i++) {
2840 slot = -i - 1;
2841 spi = slot / BPF_REG_SIZE;
2842 stype = ptr_state->stack[spi].slot_type;
2843 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
2844 break;
2845 zeros++;
2846 }
2847 if (zeros == max_off - min_off) {
2848 /* any access_size read into register is zero extended,
2849 * so the whole register == const_zero
2850 */
2851 __mark_reg_const_zero(&state->regs[dst_regno]);
2852 /* backtracking doesn't support STACK_ZERO yet,
2853 * so mark it precise here, so that later
2854 * backtracking can stop here.
2855 * Backtracking may not need this if this register
2856 * doesn't participate in pointer adjustment.
2857 * Forward propagation of precise flag is not
2858 * necessary either. This mark is only to stop
2859 * backtracking. Any register that contributed
2860 * to const 0 was marked precise before spill.
2861 */
2862 state->regs[dst_regno].precise = true;
2863 } else {
2864 /* have read misc data from the stack */
2865 mark_reg_unknown(env, state->regs, dst_regno);
2866 }
2867 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
2868}
2869
2870/* Read the stack at 'off' and put the results into the register indicated by
2871 * 'dst_regno'. It handles reg filling if the addressed stack slot is a
2872 * spilled reg.
2873 *
2874 * 'dst_regno' can be -1, meaning that the read value is not going to a
2875 * register.
2876 *
2877 * The access is assumed to be within the current stack bounds.
2878 */
2879static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
2880 /* func where src register points to */
2881 struct bpf_func_state *reg_state,
2882 int off, int size, int dst_regno)
17a52670 2883{
f4d7e40a
AS
2884 struct bpf_verifier_state *vstate = env->cur_state;
2885 struct bpf_func_state *state = vstate->frame[vstate->curframe];
638f5b90 2886 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
f7cf25b2 2887 struct bpf_reg_state *reg;
638f5b90 2888 u8 *stype;
17a52670 2889
f4d7e40a 2890 stype = reg_state->stack[spi].slot_type;
f7cf25b2 2891 reg = &reg_state->stack[spi].spilled_ptr;
17a52670 2892
638f5b90 2893 if (stype[0] == STACK_SPILL) {
9c399760 2894 if (size != BPF_REG_SIZE) {
f7cf25b2
AS
2895 if (reg->type != SCALAR_VALUE) {
2896 verbose_linfo(env, env->insn_idx, "; ");
2897 verbose(env, "invalid size of register fill\n");
2898 return -EACCES;
2899 }
01f810ac
AM
2900 if (dst_regno >= 0) {
2901 mark_reg_unknown(env, state->regs, dst_regno);
2902 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
f7cf25b2
AS
2903 }
2904 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
2905 return 0;
17a52670 2906 }
9c399760 2907 for (i = 1; i < BPF_REG_SIZE; i++) {
638f5b90 2908 if (stype[(slot - i) % BPF_REG_SIZE] != STACK_SPILL) {
61bd5218 2909 verbose(env, "corrupted spill memory\n");
17a52670
AS
2910 return -EACCES;
2911 }
2912 }
2913
01f810ac 2914 if (dst_regno >= 0) {
17a52670 2915 /* restore register state from stack */
01f810ac 2916 state->regs[dst_regno] = *reg;
2f18f62e
AS
2917 /* mark reg as written since spilled pointer state likely
2918 * has its liveness marks cleared by is_state_visited()
2919 * which resets stack/reg liveness for state transitions
2920 */
01f810ac 2921 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
6e7e63cb 2922 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
01f810ac 2923 /* If dst_regno==-1, the caller is asking us whether
6e7e63cb
JH
2924 * it is acceptable to use this value as a SCALAR_VALUE
2925 * (e.g. for XADD).
2926 * We must not allow unprivileged callers to do that
2927 * with spilled pointers.
2928 */
2929 verbose(env, "leaking pointer from stack off %d\n",
2930 off);
2931 return -EACCES;
dc503a8a 2932 }
f7cf25b2 2933 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
17a52670 2934 } else {
01f810ac 2935 u8 type;
cc2b14d5 2936
17a52670 2937 for (i = 0; i < size; i++) {
01f810ac
AM
2938 type = stype[(slot - i) % BPF_REG_SIZE];
2939 if (type == STACK_MISC)
cc2b14d5 2940 continue;
01f810ac 2941 if (type == STACK_ZERO)
cc2b14d5 2942 continue;
cc2b14d5
AS
2943 verbose(env, "invalid read from stack off %d+%d size %d\n",
2944 off, i, size);
2945 return -EACCES;
2946 }
f7cf25b2 2947 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
01f810ac
AM
2948 if (dst_regno >= 0)
2949 mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
17a52670 2950 }
f7cf25b2 2951 return 0;
17a52670
AS
2952}
2953
01f810ac
AM
2954enum stack_access_src {
2955 ACCESS_DIRECT = 1, /* the access is performed by an instruction */
2956 ACCESS_HELPER = 2, /* the access is performed by a helper */
2957};
2958
2959static int check_stack_range_initialized(struct bpf_verifier_env *env,
2960 int regno, int off, int access_size,
2961 bool zero_size_allowed,
2962 enum stack_access_src type,
2963 struct bpf_call_arg_meta *meta);
2964
2965static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
2966{
2967 return cur_regs(env) + regno;
2968}
2969
2970/* Read the stack at 'ptr_regno + off' and put the result into the register
2971 * 'dst_regno'.
2972 * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
2973 * but not its variable offset.
2974 * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
2975 *
2976 * As opposed to check_stack_read_fixed_off, this function doesn't deal with
2977 * filling registers (i.e. reads of spilled register cannot be detected when
2978 * the offset is not fixed). We conservatively mark 'dst_regno' as containing
2979 * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
2980 * offset; for a fixed offset check_stack_read_fixed_off should be used
2981 * instead.
2982 */
2983static int check_stack_read_var_off(struct bpf_verifier_env *env,
2984 int ptr_regno, int off, int size, int dst_regno)
e4298d25 2985{
01f810ac
AM
2986 /* The state of the source register. */
2987 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
2988 struct bpf_func_state *ptr_state = func(env, reg);
2989 int err;
2990 int min_off, max_off;
2991
2992 /* Note that we pass a NULL meta, so raw access will not be permitted.
e4298d25 2993 */
01f810ac
AM
2994 err = check_stack_range_initialized(env, ptr_regno, off, size,
2995 false, ACCESS_DIRECT, NULL);
2996 if (err)
2997 return err;
2998
2999 min_off = reg->smin_value + off;
3000 max_off = reg->smax_value + off;
3001 mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
3002 return 0;
3003}
3004
3005/* check_stack_read dispatches to check_stack_read_fixed_off or
3006 * check_stack_read_var_off.
3007 *
3008 * The caller must ensure that the offset falls within the allocated stack
3009 * bounds.
3010 *
3011 * 'dst_regno' is a register which will receive the value from the stack. It
3012 * can be -1, meaning that the read value is not going to a register.
3013 */
3014static int check_stack_read(struct bpf_verifier_env *env,
3015 int ptr_regno, int off, int size,
3016 int dst_regno)
3017{
3018 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3019 struct bpf_func_state *state = func(env, reg);
3020 int err;
3021 /* Some accesses are only permitted with a static offset. */
3022 bool var_off = !tnum_is_const(reg->var_off);
3023
3024 /* The offset is required to be static when reads don't go to a
3025 * register, in order to not leak pointers (see
3026 * check_stack_read_fixed_off).
3027 */
3028 if (dst_regno < 0 && var_off) {
e4298d25
DB
3029 char tn_buf[48];
3030
3031 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
01f810ac 3032 verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
e4298d25
DB
3033 tn_buf, off, size);
3034 return -EACCES;
3035 }
01f810ac
AM
3036 /* Variable offset is prohibited for unprivileged mode for simplicity
3037 * since it requires corresponding support in Spectre masking for stack
3038 * ALU. See also retrieve_ptr_limit().
3039 */
3040 if (!env->bypass_spec_v1 && var_off) {
3041 char tn_buf[48];
e4298d25 3042
01f810ac
AM
3043 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3044 verbose(env, "R%d variable offset stack access prohibited for !root, var_off=%s\n",
3045 ptr_regno, tn_buf);
e4298d25
DB
3046 return -EACCES;
3047 }
3048
01f810ac
AM
3049 if (!var_off) {
3050 off += reg->var_off.value;
3051 err = check_stack_read_fixed_off(env, state, off, size,
3052 dst_regno);
3053 } else {
3054 /* Variable offset stack reads need more conservative handling
3055 * than fixed offset ones. Note that dst_regno >= 0 on this
3056 * branch.
3057 */
3058 err = check_stack_read_var_off(env, ptr_regno, off, size,
3059 dst_regno);
3060 }
3061 return err;
3062}
3063
3064
3065/* check_stack_write dispatches to check_stack_write_fixed_off or
3066 * check_stack_write_var_off.
3067 *
3068 * 'ptr_regno' is the register used as a pointer into the stack.
3069 * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
3070 * 'value_regno' is the register whose value we're writing to the stack. It can
3071 * be -1, meaning that we're not writing from a register.
3072 *
3073 * The caller must ensure that the offset falls within the maximum stack size.
3074 */
3075static int check_stack_write(struct bpf_verifier_env *env,
3076 int ptr_regno, int off, int size,
3077 int value_regno, int insn_idx)
3078{
3079 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3080 struct bpf_func_state *state = func(env, reg);
3081 int err;
3082
3083 if (tnum_is_const(reg->var_off)) {
3084 off += reg->var_off.value;
3085 err = check_stack_write_fixed_off(env, state, off, size,
3086 value_regno, insn_idx);
3087 } else {
3088 /* Variable offset stack reads need more conservative handling
3089 * than fixed offset ones.
3090 */
3091 err = check_stack_write_var_off(env, state,
3092 ptr_regno, off, size,
3093 value_regno, insn_idx);
3094 }
3095 return err;
e4298d25
DB
3096}
3097
591fe988
DB
3098static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
3099 int off, int size, enum bpf_access_type type)
3100{
3101 struct bpf_reg_state *regs = cur_regs(env);
3102 struct bpf_map *map = regs[regno].map_ptr;
3103 u32 cap = bpf_map_flags_to_cap(map);
3104
3105 if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
3106 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
3107 map->value_size, off, size);
3108 return -EACCES;
3109 }
3110
3111 if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
3112 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
3113 map->value_size, off, size);
3114 return -EACCES;
3115 }
3116
3117 return 0;
3118}
3119
457f4436
AN
3120/* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
3121static int __check_mem_access(struct bpf_verifier_env *env, int regno,
3122 int off, int size, u32 mem_size,
3123 bool zero_size_allowed)
17a52670 3124{
457f4436
AN
3125 bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
3126 struct bpf_reg_state *reg;
3127
3128 if (off >= 0 && size_ok && (u64)off + size <= mem_size)
3129 return 0;
17a52670 3130
457f4436
AN
3131 reg = &cur_regs(env)[regno];
3132 switch (reg->type) {
69c087ba
YS
3133 case PTR_TO_MAP_KEY:
3134 verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
3135 mem_size, off, size);
3136 break;
457f4436 3137 case PTR_TO_MAP_VALUE:
61bd5218 3138 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
457f4436
AN
3139 mem_size, off, size);
3140 break;
3141 case PTR_TO_PACKET:
3142 case PTR_TO_PACKET_META:
3143 case PTR_TO_PACKET_END:
3144 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
3145 off, size, regno, reg->id, off, mem_size);
3146 break;
3147 case PTR_TO_MEM:
3148 default:
3149 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
3150 mem_size, off, size);
17a52670 3151 }
457f4436
AN
3152
3153 return -EACCES;
17a52670
AS
3154}
3155
457f4436
AN
3156/* check read/write into a memory region with possible variable offset */
3157static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
3158 int off, int size, u32 mem_size,
3159 bool zero_size_allowed)
dbcfe5f7 3160{
f4d7e40a
AS
3161 struct bpf_verifier_state *vstate = env->cur_state;
3162 struct bpf_func_state *state = vstate->frame[vstate->curframe];
dbcfe5f7
GB
3163 struct bpf_reg_state *reg = &state->regs[regno];
3164 int err;
3165
457f4436 3166 /* We may have adjusted the register pointing to memory region, so we
f1174f77
EC
3167 * need to try adding each of min_value and max_value to off
3168 * to make sure our theoretical access will be safe.
dbcfe5f7 3169 */
06ee7115 3170 if (env->log.level & BPF_LOG_LEVEL)
61bd5218 3171 print_verifier_state(env, state);
b7137c4e 3172
dbcfe5f7
GB
3173 /* The minimum value is only important with signed
3174 * comparisons where we can't assume the floor of a
3175 * value is 0. If we are using signed variables for our
3176 * index'es we need to make sure that whatever we use
3177 * will have a set floor within our range.
3178 */
b7137c4e
DB
3179 if (reg->smin_value < 0 &&
3180 (reg->smin_value == S64_MIN ||
3181 (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
3182 reg->smin_value + off < 0)) {
61bd5218 3183 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
dbcfe5f7
GB
3184 regno);
3185 return -EACCES;
3186 }
457f4436
AN
3187 err = __check_mem_access(env, regno, reg->smin_value + off, size,
3188 mem_size, zero_size_allowed);
dbcfe5f7 3189 if (err) {
457f4436 3190 verbose(env, "R%d min value is outside of the allowed memory range\n",
61bd5218 3191 regno);
dbcfe5f7
GB
3192 return err;
3193 }
3194
b03c9f9f
EC
3195 /* If we haven't set a max value then we need to bail since we can't be
3196 * sure we won't do bad things.
3197 * If reg->umax_value + off could overflow, treat that as unbounded too.
dbcfe5f7 3198 */
b03c9f9f 3199 if (reg->umax_value >= BPF_MAX_VAR_OFF) {
457f4436 3200 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
dbcfe5f7
GB
3201 regno);
3202 return -EACCES;
3203 }
457f4436
AN
3204 err = __check_mem_access(env, regno, reg->umax_value + off, size,
3205 mem_size, zero_size_allowed);
3206 if (err) {
3207 verbose(env, "R%d max value is outside of the allowed memory range\n",
61bd5218 3208 regno);
457f4436
AN
3209 return err;
3210 }
3211
3212 return 0;
3213}
d83525ca 3214
457f4436
AN
3215/* check read/write into a map element with possible variable offset */
3216static int check_map_access(struct bpf_verifier_env *env, u32 regno,
3217 int off, int size, bool zero_size_allowed)
3218{
3219 struct bpf_verifier_state *vstate = env->cur_state;
3220 struct bpf_func_state *state = vstate->frame[vstate->curframe];
3221 struct bpf_reg_state *reg = &state->regs[regno];
3222 struct bpf_map *map = reg->map_ptr;
3223 int err;
3224
3225 err = check_mem_region_access(env, regno, off, size, map->value_size,
3226 zero_size_allowed);
3227 if (err)
3228 return err;
3229
3230 if (map_value_has_spin_lock(map)) {
3231 u32 lock = map->spin_lock_off;
d83525ca
AS
3232
3233 /* if any part of struct bpf_spin_lock can be touched by
3234 * load/store reject this program.
3235 * To check that [x1, x2) overlaps with [y1, y2)
3236 * it is sufficient to check x1 < y2 && y1 < x2.
3237 */
3238 if (reg->smin_value + off < lock + sizeof(struct bpf_spin_lock) &&
3239 lock < reg->umax_value + off + size) {
3240 verbose(env, "bpf_spin_lock cannot be accessed directly by load/store\n");
3241 return -EACCES;
3242 }
3243 }
f1174f77 3244 return err;
dbcfe5f7
GB
3245}
3246
969bf05e
AS
3247#define MAX_PACKET_OFF 0xffff
3248
7e40781c
UP
3249static enum bpf_prog_type resolve_prog_type(struct bpf_prog *prog)
3250{
3aac1ead 3251 return prog->aux->dst_prog ? prog->aux->dst_prog->type : prog->type;
7e40781c
UP
3252}
3253
58e2af8b 3254static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
3a0af8fd
TG
3255 const struct bpf_call_arg_meta *meta,
3256 enum bpf_access_type t)
4acf6c0b 3257{
7e40781c
UP
3258 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
3259
3260 switch (prog_type) {
5d66fa7d 3261 /* Program types only with direct read access go here! */
3a0af8fd
TG
3262 case BPF_PROG_TYPE_LWT_IN:
3263 case BPF_PROG_TYPE_LWT_OUT:
004d4b27 3264 case BPF_PROG_TYPE_LWT_SEG6LOCAL:
2dbb9b9e 3265 case BPF_PROG_TYPE_SK_REUSEPORT:
5d66fa7d 3266 case BPF_PROG_TYPE_FLOW_DISSECTOR:
d5563d36 3267 case BPF_PROG_TYPE_CGROUP_SKB:
3a0af8fd
TG
3268 if (t == BPF_WRITE)
3269 return false;
8731745e 3270 fallthrough;
5d66fa7d
DB
3271
3272 /* Program types with direct read + write access go here! */
36bbef52
DB
3273 case BPF_PROG_TYPE_SCHED_CLS:
3274 case BPF_PROG_TYPE_SCHED_ACT:
4acf6c0b 3275 case BPF_PROG_TYPE_XDP:
3a0af8fd 3276 case BPF_PROG_TYPE_LWT_XMIT:
8a31db56 3277 case BPF_PROG_TYPE_SK_SKB:
4f738adb 3278 case BPF_PROG_TYPE_SK_MSG:
36bbef52
DB
3279 if (meta)
3280 return meta->pkt_access;
3281
3282 env->seen_direct_write = true;
4acf6c0b 3283 return true;
0d01da6a
SF
3284
3285 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
3286 if (t == BPF_WRITE)
3287 env->seen_direct_write = true;
3288
3289 return true;
3290
4acf6c0b
BB
3291 default:
3292 return false;
3293 }
3294}
3295
f1174f77 3296static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
9fd29c08 3297 int size, bool zero_size_allowed)
f1174f77 3298{
638f5b90 3299 struct bpf_reg_state *regs = cur_regs(env);
f1174f77
EC
3300 struct bpf_reg_state *reg = &regs[regno];
3301 int err;
3302
3303 /* We may have added a variable offset to the packet pointer; but any
3304 * reg->range we have comes after that. We are only checking the fixed
3305 * offset.
3306 */
3307
3308 /* We don't allow negative numbers, because we aren't tracking enough
3309 * detail to prove they're safe.
3310 */
b03c9f9f 3311 if (reg->smin_value < 0) {
61bd5218 3312 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
f1174f77
EC
3313 regno);
3314 return -EACCES;
3315 }
6d94e741
AS
3316
3317 err = reg->range < 0 ? -EINVAL :
3318 __check_mem_access(env, regno, off, size, reg->range,
457f4436 3319 zero_size_allowed);
f1174f77 3320 if (err) {
61bd5218 3321 verbose(env, "R%d offset is outside of the packet\n", regno);
f1174f77
EC
3322 return err;
3323 }
e647815a 3324
457f4436 3325 /* __check_mem_access has made sure "off + size - 1" is within u16.
e647815a
JW
3326 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
3327 * otherwise find_good_pkt_pointers would have refused to set range info
457f4436 3328 * that __check_mem_access would have rejected this pkt access.
e647815a
JW
3329 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
3330 */
3331 env->prog->aux->max_pkt_offset =
3332 max_t(u32, env->prog->aux->max_pkt_offset,
3333 off + reg->umax_value + size - 1);
3334
f1174f77
EC
3335 return err;
3336}
3337
3338/* check access to 'struct bpf_context' fields. Supports fixed offsets only */
31fd8581 3339static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
9e15db66 3340 enum bpf_access_type t, enum bpf_reg_type *reg_type,
22dc4a0f 3341 struct btf **btf, u32 *btf_id)
17a52670 3342{
f96da094
DB
3343 struct bpf_insn_access_aux info = {
3344 .reg_type = *reg_type,
9e15db66 3345 .log = &env->log,
f96da094 3346 };
31fd8581 3347
4f9218aa 3348 if (env->ops->is_valid_access &&
5e43f899 3349 env->ops->is_valid_access(off, size, t, env->prog, &info)) {
f96da094
DB
3350 /* A non zero info.ctx_field_size indicates that this field is a
3351 * candidate for later verifier transformation to load the whole
3352 * field and then apply a mask when accessed with a narrower
3353 * access than actual ctx access size. A zero info.ctx_field_size
3354 * will only allow for whole field access and rejects any other
3355 * type of narrower access.
31fd8581 3356 */
23994631 3357 *reg_type = info.reg_type;
31fd8581 3358
22dc4a0f
AN
3359 if (*reg_type == PTR_TO_BTF_ID || *reg_type == PTR_TO_BTF_ID_OR_NULL) {
3360 *btf = info.btf;
9e15db66 3361 *btf_id = info.btf_id;
22dc4a0f 3362 } else {
9e15db66 3363 env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
22dc4a0f 3364 }
32bbe007
AS
3365 /* remember the offset of last byte accessed in ctx */
3366 if (env->prog->aux->max_ctx_offset < off + size)
3367 env->prog->aux->max_ctx_offset = off + size;
17a52670 3368 return 0;
32bbe007 3369 }
17a52670 3370
61bd5218 3371 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
17a52670
AS
3372 return -EACCES;
3373}
3374
d58e468b
PP
3375static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
3376 int size)
3377{
3378 if (size < 0 || off < 0 ||
3379 (u64)off + size > sizeof(struct bpf_flow_keys)) {
3380 verbose(env, "invalid access to flow keys off=%d size=%d\n",
3381 off, size);
3382 return -EACCES;
3383 }
3384 return 0;
3385}
3386
5f456649
MKL
3387static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
3388 u32 regno, int off, int size,
3389 enum bpf_access_type t)
c64b7983
JS
3390{
3391 struct bpf_reg_state *regs = cur_regs(env);
3392 struct bpf_reg_state *reg = &regs[regno];
5f456649 3393 struct bpf_insn_access_aux info = {};
46f8bc92 3394 bool valid;
c64b7983
JS
3395
3396 if (reg->smin_value < 0) {
3397 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3398 regno);
3399 return -EACCES;
3400 }
3401
46f8bc92
MKL
3402 switch (reg->type) {
3403 case PTR_TO_SOCK_COMMON:
3404 valid = bpf_sock_common_is_valid_access(off, size, t, &info);
3405 break;
3406 case PTR_TO_SOCKET:
3407 valid = bpf_sock_is_valid_access(off, size, t, &info);
3408 break;
655a51e5
MKL
3409 case PTR_TO_TCP_SOCK:
3410 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
3411 break;
fada7fdc
JL
3412 case PTR_TO_XDP_SOCK:
3413 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
3414 break;
46f8bc92
MKL
3415 default:
3416 valid = false;
c64b7983
JS
3417 }
3418
5f456649 3419
46f8bc92
MKL
3420 if (valid) {
3421 env->insn_aux_data[insn_idx].ctx_field_size =
3422 info.ctx_field_size;
3423 return 0;
3424 }
3425
3426 verbose(env, "R%d invalid %s access off=%d size=%d\n",
3427 regno, reg_type_str[reg->type], off, size);
3428
3429 return -EACCES;
c64b7983
JS
3430}
3431
4cabc5b1
DB
3432static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
3433{
2a159c6f 3434 return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
4cabc5b1
DB
3435}
3436
f37a8cb8
DB
3437static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
3438{
2a159c6f 3439 const struct bpf_reg_state *reg = reg_state(env, regno);
f37a8cb8 3440
46f8bc92
MKL
3441 return reg->type == PTR_TO_CTX;
3442}
3443
3444static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
3445{
3446 const struct bpf_reg_state *reg = reg_state(env, regno);
3447
3448 return type_is_sk_pointer(reg->type);
f37a8cb8
DB
3449}
3450
ca369602
DB
3451static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
3452{
2a159c6f 3453 const struct bpf_reg_state *reg = reg_state(env, regno);
ca369602
DB
3454
3455 return type_is_pkt_pointer(reg->type);
3456}
3457
4b5defde
DB
3458static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
3459{
3460 const struct bpf_reg_state *reg = reg_state(env, regno);
3461
3462 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
3463 return reg->type == PTR_TO_FLOW_KEYS;
3464}
3465
61bd5218
JK
3466static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
3467 const struct bpf_reg_state *reg,
d1174416 3468 int off, int size, bool strict)
969bf05e 3469{
f1174f77 3470 struct tnum reg_off;
e07b98d9 3471 int ip_align;
d1174416
DM
3472
3473 /* Byte size accesses are always allowed. */
3474 if (!strict || size == 1)
3475 return 0;
3476
e4eda884
DM
3477 /* For platforms that do not have a Kconfig enabling
3478 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
3479 * NET_IP_ALIGN is universally set to '2'. And on platforms
3480 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
3481 * to this code only in strict mode where we want to emulate
3482 * the NET_IP_ALIGN==2 checking. Therefore use an
3483 * unconditional IP align value of '2'.
e07b98d9 3484 */
e4eda884 3485 ip_align = 2;
f1174f77
EC
3486
3487 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
3488 if (!tnum_is_aligned(reg_off, size)) {
3489 char tn_buf[48];
3490
3491 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
61bd5218
JK
3492 verbose(env,
3493 "misaligned packet access off %d+%s+%d+%d size %d\n",
f1174f77 3494 ip_align, tn_buf, reg->off, off, size);
969bf05e
AS
3495 return -EACCES;
3496 }
79adffcd 3497
969bf05e
AS
3498 return 0;
3499}
3500
61bd5218
JK
3501static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
3502 const struct bpf_reg_state *reg,
f1174f77
EC
3503 const char *pointer_desc,
3504 int off, int size, bool strict)
79adffcd 3505{
f1174f77
EC
3506 struct tnum reg_off;
3507
3508 /* Byte size accesses are always allowed. */
3509 if (!strict || size == 1)
3510 return 0;
3511
3512 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
3513 if (!tnum_is_aligned(reg_off, size)) {
3514 char tn_buf[48];
3515
3516 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
61bd5218 3517 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
f1174f77 3518 pointer_desc, tn_buf, reg->off, off, size);
79adffcd
DB
3519 return -EACCES;
3520 }
3521
969bf05e
AS
3522 return 0;
3523}
3524
e07b98d9 3525static int check_ptr_alignment(struct bpf_verifier_env *env,
ca369602
DB
3526 const struct bpf_reg_state *reg, int off,
3527 int size, bool strict_alignment_once)
79adffcd 3528{
ca369602 3529 bool strict = env->strict_alignment || strict_alignment_once;
f1174f77 3530 const char *pointer_desc = "";
d1174416 3531
79adffcd
DB
3532 switch (reg->type) {
3533 case PTR_TO_PACKET:
de8f3a83
DB
3534 case PTR_TO_PACKET_META:
3535 /* Special case, because of NET_IP_ALIGN. Given metadata sits
3536 * right in front, treat it the very same way.
3537 */
61bd5218 3538 return check_pkt_ptr_alignment(env, reg, off, size, strict);
d58e468b
PP
3539 case PTR_TO_FLOW_KEYS:
3540 pointer_desc = "flow keys ";
3541 break;
69c087ba
YS
3542 case PTR_TO_MAP_KEY:
3543 pointer_desc = "key ";
3544 break;
f1174f77
EC
3545 case PTR_TO_MAP_VALUE:
3546 pointer_desc = "value ";
3547 break;
3548 case PTR_TO_CTX:
3549 pointer_desc = "context ";
3550 break;
3551 case PTR_TO_STACK:
3552 pointer_desc = "stack ";
01f810ac
AM
3553 /* The stack spill tracking logic in check_stack_write_fixed_off()
3554 * and check_stack_read_fixed_off() relies on stack accesses being
a5ec6ae1
JH
3555 * aligned.
3556 */
3557 strict = true;
f1174f77 3558 break;
c64b7983
JS
3559 case PTR_TO_SOCKET:
3560 pointer_desc = "sock ";
3561 break;
46f8bc92
MKL
3562 case PTR_TO_SOCK_COMMON:
3563 pointer_desc = "sock_common ";
3564 break;
655a51e5
MKL
3565 case PTR_TO_TCP_SOCK:
3566 pointer_desc = "tcp_sock ";
3567 break;
fada7fdc
JL
3568 case PTR_TO_XDP_SOCK:
3569 pointer_desc = "xdp_sock ";
3570 break;
79adffcd 3571 default:
f1174f77 3572 break;
79adffcd 3573 }
61bd5218
JK
3574 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
3575 strict);
79adffcd
DB
3576}
3577
f4d7e40a
AS
3578static int update_stack_depth(struct bpf_verifier_env *env,
3579 const struct bpf_func_state *func,
3580 int off)
3581{
9c8105bd 3582 u16 stack = env->subprog_info[func->subprogno].stack_depth;
f4d7e40a
AS
3583
3584 if (stack >= -off)
3585 return 0;
3586
3587 /* update known max for given subprogram */
9c8105bd 3588 env->subprog_info[func->subprogno].stack_depth = -off;
70a87ffe
AS
3589 return 0;
3590}
f4d7e40a 3591
70a87ffe
AS
3592/* starting from main bpf function walk all instructions of the function
3593 * and recursively walk all callees that given function can call.
3594 * Ignore jump and exit insns.
3595 * Since recursion is prevented by check_cfg() this algorithm
3596 * only needs a local stack of MAX_CALL_FRAMES to remember callsites
3597 */
3598static int check_max_stack_depth(struct bpf_verifier_env *env)
3599{
9c8105bd
JW
3600 int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
3601 struct bpf_subprog_info *subprog = env->subprog_info;
70a87ffe 3602 struct bpf_insn *insn = env->prog->insnsi;
ebf7d1f5 3603 bool tail_call_reachable = false;
70a87ffe
AS
3604 int ret_insn[MAX_CALL_FRAMES];
3605 int ret_prog[MAX_CALL_FRAMES];
ebf7d1f5 3606 int j;
f4d7e40a 3607
70a87ffe 3608process_func:
7f6e4312
MF
3609 /* protect against potential stack overflow that might happen when
3610 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
3611 * depth for such case down to 256 so that the worst case scenario
3612 * would result in 8k stack size (32 which is tailcall limit * 256 =
3613 * 8k).
3614 *
3615 * To get the idea what might happen, see an example:
3616 * func1 -> sub rsp, 128
3617 * subfunc1 -> sub rsp, 256
3618 * tailcall1 -> add rsp, 256
3619 * func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
3620 * subfunc2 -> sub rsp, 64
3621 * subfunc22 -> sub rsp, 128
3622 * tailcall2 -> add rsp, 128
3623 * func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
3624 *
3625 * tailcall will unwind the current stack frame but it will not get rid
3626 * of caller's stack as shown on the example above.
3627 */
3628 if (idx && subprog[idx].has_tail_call && depth >= 256) {
3629 verbose(env,
3630 "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
3631 depth);
3632 return -EACCES;
3633 }
70a87ffe
AS
3634 /* round up to 32-bytes, since this is granularity
3635 * of interpreter stack size
3636 */
9c8105bd 3637 depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
70a87ffe 3638 if (depth > MAX_BPF_STACK) {
f4d7e40a 3639 verbose(env, "combined stack size of %d calls is %d. Too large\n",
70a87ffe 3640 frame + 1, depth);
f4d7e40a
AS
3641 return -EACCES;
3642 }
70a87ffe 3643continue_func:
4cb3d99c 3644 subprog_end = subprog[idx + 1].start;
70a87ffe 3645 for (; i < subprog_end; i++) {
69c087ba 3646 if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
70a87ffe
AS
3647 continue;
3648 /* remember insn and function to return to */
3649 ret_insn[frame] = i + 1;
9c8105bd 3650 ret_prog[frame] = idx;
70a87ffe
AS
3651
3652 /* find the callee */
3653 i = i + insn[i].imm + 1;
9c8105bd
JW
3654 idx = find_subprog(env, i);
3655 if (idx < 0) {
70a87ffe
AS
3656 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
3657 i);
3658 return -EFAULT;
3659 }
ebf7d1f5
MF
3660
3661 if (subprog[idx].has_tail_call)
3662 tail_call_reachable = true;
3663
70a87ffe
AS
3664 frame++;
3665 if (frame >= MAX_CALL_FRAMES) {
927cb781
PC
3666 verbose(env, "the call stack of %d frames is too deep !\n",
3667 frame);
3668 return -E2BIG;
70a87ffe
AS
3669 }
3670 goto process_func;
3671 }
ebf7d1f5
MF
3672 /* if tail call got detected across bpf2bpf calls then mark each of the
3673 * currently present subprog frames as tail call reachable subprogs;
3674 * this info will be utilized by JIT so that we will be preserving the
3675 * tail call counter throughout bpf2bpf calls combined with tailcalls
3676 */
3677 if (tail_call_reachable)
3678 for (j = 0; j < frame; j++)
3679 subprog[ret_prog[j]].tail_call_reachable = true;
3680
70a87ffe
AS
3681 /* end of for() loop means the last insn of the 'subprog'
3682 * was reached. Doesn't matter whether it was JA or EXIT
3683 */
3684 if (frame == 0)
3685 return 0;
9c8105bd 3686 depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
70a87ffe
AS
3687 frame--;
3688 i = ret_insn[frame];
9c8105bd 3689 idx = ret_prog[frame];
70a87ffe 3690 goto continue_func;
f4d7e40a
AS
3691}
3692
19d28fbd 3693#ifndef CONFIG_BPF_JIT_ALWAYS_ON
1ea47e01
AS
3694static int get_callee_stack_depth(struct bpf_verifier_env *env,
3695 const struct bpf_insn *insn, int idx)
3696{
3697 int start = idx + insn->imm + 1, subprog;
3698
3699 subprog = find_subprog(env, start);
3700 if (subprog < 0) {
3701 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
3702 start);
3703 return -EFAULT;
3704 }
9c8105bd 3705 return env->subprog_info[subprog].stack_depth;
1ea47e01 3706}
19d28fbd 3707#endif
1ea47e01 3708
51c39bb1
AS
3709int check_ctx_reg(struct bpf_verifier_env *env,
3710 const struct bpf_reg_state *reg, int regno)
58990d1f
DB
3711{
3712 /* Access to ctx or passing it to a helper is only allowed in
3713 * its original, unmodified form.
3714 */
3715
3716 if (reg->off) {
3717 verbose(env, "dereference of modified ctx ptr R%d off=%d disallowed\n",
3718 regno, reg->off);
3719 return -EACCES;
3720 }
3721
3722 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3723 char tn_buf[48];
3724
3725 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3726 verbose(env, "variable ctx access var_off=%s disallowed\n", tn_buf);
3727 return -EACCES;
3728 }
3729
3730 return 0;
3731}
3732
afbf21dc
YS
3733static int __check_buffer_access(struct bpf_verifier_env *env,
3734 const char *buf_info,
3735 const struct bpf_reg_state *reg,
3736 int regno, int off, int size)
9df1c28b
MM
3737{
3738 if (off < 0) {
3739 verbose(env,
4fc00b79 3740 "R%d invalid %s buffer access: off=%d, size=%d\n",
afbf21dc 3741 regno, buf_info, off, size);
9df1c28b
MM
3742 return -EACCES;
3743 }
3744 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3745 char tn_buf[48];
3746
3747 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3748 verbose(env,
4fc00b79 3749 "R%d invalid variable buffer offset: off=%d, var_off=%s\n",
9df1c28b
MM
3750 regno, off, tn_buf);
3751 return -EACCES;
3752 }
afbf21dc
YS
3753
3754 return 0;
3755}
3756
3757static int check_tp_buffer_access(struct bpf_verifier_env *env,
3758 const struct bpf_reg_state *reg,
3759 int regno, int off, int size)
3760{
3761 int err;
3762
3763 err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
3764 if (err)
3765 return err;
3766
9df1c28b
MM
3767 if (off + size > env->prog->aux->max_tp_access)
3768 env->prog->aux->max_tp_access = off + size;
3769
3770 return 0;
3771}
3772
afbf21dc
YS
3773static int check_buffer_access(struct bpf_verifier_env *env,
3774 const struct bpf_reg_state *reg,
3775 int regno, int off, int size,
3776 bool zero_size_allowed,
3777 const char *buf_info,
3778 u32 *max_access)
3779{
3780 int err;
3781
3782 err = __check_buffer_access(env, buf_info, reg, regno, off, size);
3783 if (err)
3784 return err;
3785
3786 if (off + size > *max_access)
3787 *max_access = off + size;
3788
3789 return 0;
3790}
3791
3f50f132
JF
3792/* BPF architecture zero extends alu32 ops into 64-bit registesr */
3793static void zext_32_to_64(struct bpf_reg_state *reg)
3794{
3795 reg->var_off = tnum_subreg(reg->var_off);
3796 __reg_assign_32_into_64(reg);
3797}
9df1c28b 3798
0c17d1d2
JH
3799/* truncate register to smaller size (in bytes)
3800 * must be called with size < BPF_REG_SIZE
3801 */
3802static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
3803{
3804 u64 mask;
3805
3806 /* clear high bits in bit representation */
3807 reg->var_off = tnum_cast(reg->var_off, size);
3808
3809 /* fix arithmetic bounds */
3810 mask = ((u64)1 << (size * 8)) - 1;
3811 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
3812 reg->umin_value &= mask;
3813 reg->umax_value &= mask;
3814 } else {
3815 reg->umin_value = 0;
3816 reg->umax_value = mask;
3817 }
3818 reg->smin_value = reg->umin_value;
3819 reg->smax_value = reg->umax_value;
3f50f132
JF
3820
3821 /* If size is smaller than 32bit register the 32bit register
3822 * values are also truncated so we push 64-bit bounds into
3823 * 32-bit bounds. Above were truncated < 32-bits already.
3824 */
3825 if (size >= 4)
3826 return;
3827 __reg_combine_64_into_32(reg);
0c17d1d2
JH
3828}
3829
a23740ec
AN
3830static bool bpf_map_is_rdonly(const struct bpf_map *map)
3831{
3832 return (map->map_flags & BPF_F_RDONLY_PROG) && map->frozen;
3833}
3834
3835static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val)
3836{
3837 void *ptr;
3838 u64 addr;
3839 int err;
3840
3841 err = map->ops->map_direct_value_addr(map, &addr, off);
3842 if (err)
3843 return err;
2dedd7d2 3844 ptr = (void *)(long)addr + off;
a23740ec
AN
3845
3846 switch (size) {
3847 case sizeof(u8):
3848 *val = (u64)*(u8 *)ptr;
3849 break;
3850 case sizeof(u16):
3851 *val = (u64)*(u16 *)ptr;
3852 break;
3853 case sizeof(u32):
3854 *val = (u64)*(u32 *)ptr;
3855 break;
3856 case sizeof(u64):
3857 *val = *(u64 *)ptr;
3858 break;
3859 default:
3860 return -EINVAL;
3861 }
3862 return 0;
3863}
3864
9e15db66
AS
3865static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
3866 struct bpf_reg_state *regs,
3867 int regno, int off, int size,
3868 enum bpf_access_type atype,
3869 int value_regno)
3870{
3871 struct bpf_reg_state *reg = regs + regno;
22dc4a0f
AN
3872 const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
3873 const char *tname = btf_name_by_offset(reg->btf, t->name_off);
9e15db66
AS
3874 u32 btf_id;
3875 int ret;
3876
9e15db66
AS
3877 if (off < 0) {
3878 verbose(env,
3879 "R%d is ptr_%s invalid negative access: off=%d\n",
3880 regno, tname, off);
3881 return -EACCES;
3882 }
3883 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3884 char tn_buf[48];
3885
3886 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3887 verbose(env,
3888 "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
3889 regno, tname, off, tn_buf);
3890 return -EACCES;
3891 }
3892
27ae7997 3893 if (env->ops->btf_struct_access) {
22dc4a0f
AN
3894 ret = env->ops->btf_struct_access(&env->log, reg->btf, t,
3895 off, size, atype, &btf_id);
27ae7997
MKL
3896 } else {
3897 if (atype != BPF_READ) {
3898 verbose(env, "only read is supported\n");
3899 return -EACCES;
3900 }
3901
22dc4a0f
AN
3902 ret = btf_struct_access(&env->log, reg->btf, t, off, size,
3903 atype, &btf_id);
27ae7997
MKL
3904 }
3905
9e15db66
AS
3906 if (ret < 0)
3907 return ret;
3908
41c48f3a 3909 if (atype == BPF_READ && value_regno >= 0)
22dc4a0f 3910 mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id);
41c48f3a
AI
3911
3912 return 0;
3913}
3914
3915static int check_ptr_to_map_access(struct bpf_verifier_env *env,
3916 struct bpf_reg_state *regs,
3917 int regno, int off, int size,
3918 enum bpf_access_type atype,
3919 int value_regno)
3920{
3921 struct bpf_reg_state *reg = regs + regno;
3922 struct bpf_map *map = reg->map_ptr;
3923 const struct btf_type *t;
3924 const char *tname;
3925 u32 btf_id;
3926 int ret;
3927
3928 if (!btf_vmlinux) {
3929 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
3930 return -ENOTSUPP;
3931 }
3932
3933 if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
3934 verbose(env, "map_ptr access not supported for map type %d\n",
3935 map->map_type);
3936 return -ENOTSUPP;
3937 }
3938
3939 t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
3940 tname = btf_name_by_offset(btf_vmlinux, t->name_off);
3941
3942 if (!env->allow_ptr_to_map_access) {
3943 verbose(env,
3944 "%s access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
3945 tname);
3946 return -EPERM;
9e15db66 3947 }
27ae7997 3948
41c48f3a
AI
3949 if (off < 0) {
3950 verbose(env, "R%d is %s invalid negative access: off=%d\n",
3951 regno, tname, off);
3952 return -EACCES;
3953 }
3954
3955 if (atype != BPF_READ) {
3956 verbose(env, "only read from %s is supported\n", tname);
3957 return -EACCES;
3958 }
3959
22dc4a0f 3960 ret = btf_struct_access(&env->log, btf_vmlinux, t, off, size, atype, &btf_id);
41c48f3a
AI
3961 if (ret < 0)
3962 return ret;
3963
3964 if (value_regno >= 0)
22dc4a0f 3965 mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id);
41c48f3a 3966
9e15db66
AS
3967 return 0;
3968}
3969
01f810ac
AM
3970/* Check that the stack access at the given offset is within bounds. The
3971 * maximum valid offset is -1.
3972 *
3973 * The minimum valid offset is -MAX_BPF_STACK for writes, and
3974 * -state->allocated_stack for reads.
3975 */
3976static int check_stack_slot_within_bounds(int off,
3977 struct bpf_func_state *state,
3978 enum bpf_access_type t)
3979{
3980 int min_valid_off;
3981
3982 if (t == BPF_WRITE)
3983 min_valid_off = -MAX_BPF_STACK;
3984 else
3985 min_valid_off = -state->allocated_stack;
3986
3987 if (off < min_valid_off || off > -1)
3988 return -EACCES;
3989 return 0;
3990}
3991
3992/* Check that the stack access at 'regno + off' falls within the maximum stack
3993 * bounds.
3994 *
3995 * 'off' includes `regno->offset`, but not its dynamic part (if any).
3996 */
3997static int check_stack_access_within_bounds(
3998 struct bpf_verifier_env *env,
3999 int regno, int off, int access_size,
4000 enum stack_access_src src, enum bpf_access_type type)
4001{
4002 struct bpf_reg_state *regs = cur_regs(env);
4003 struct bpf_reg_state *reg = regs + regno;
4004 struct bpf_func_state *state = func(env, reg);
4005 int min_off, max_off;
4006 int err;
4007 char *err_extra;
4008
4009 if (src == ACCESS_HELPER)
4010 /* We don't know if helpers are reading or writing (or both). */
4011 err_extra = " indirect access to";
4012 else if (type == BPF_READ)
4013 err_extra = " read from";
4014 else
4015 err_extra = " write to";
4016
4017 if (tnum_is_const(reg->var_off)) {
4018 min_off = reg->var_off.value + off;
4019 if (access_size > 0)
4020 max_off = min_off + access_size - 1;
4021 else
4022 max_off = min_off;
4023 } else {
4024 if (reg->smax_value >= BPF_MAX_VAR_OFF ||
4025 reg->smin_value <= -BPF_MAX_VAR_OFF) {
4026 verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
4027 err_extra, regno);
4028 return -EACCES;
4029 }
4030 min_off = reg->smin_value + off;
4031 if (access_size > 0)
4032 max_off = reg->smax_value + off + access_size - 1;
4033 else
4034 max_off = min_off;
4035 }
4036
4037 err = check_stack_slot_within_bounds(min_off, state, type);
4038 if (!err)
4039 err = check_stack_slot_within_bounds(max_off, state, type);
4040
4041 if (err) {
4042 if (tnum_is_const(reg->var_off)) {
4043 verbose(env, "invalid%s stack R%d off=%d size=%d\n",
4044 err_extra, regno, off, access_size);
4045 } else {
4046 char tn_buf[48];
4047
4048 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4049 verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
4050 err_extra, regno, tn_buf, access_size);
4051 }
4052 }
4053 return err;
4054}
41c48f3a 4055
17a52670
AS
4056/* check whether memory at (regno + off) is accessible for t = (read | write)
4057 * if t==write, value_regno is a register which value is stored into memory
4058 * if t==read, value_regno is a register which will receive the value from memory
4059 * if t==write && value_regno==-1, some unknown value is stored into memory
4060 * if t==read && value_regno==-1, don't care what we read from memory
4061 */
ca369602
DB
4062static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
4063 int off, int bpf_size, enum bpf_access_type t,
4064 int value_regno, bool strict_alignment_once)
17a52670 4065{
638f5b90
AS
4066 struct bpf_reg_state *regs = cur_regs(env);
4067 struct bpf_reg_state *reg = regs + regno;
f4d7e40a 4068 struct bpf_func_state *state;
17a52670
AS
4069 int size, err = 0;
4070
4071 size = bpf_size_to_bytes(bpf_size);
4072 if (size < 0)
4073 return size;
4074
f1174f77 4075 /* alignment checks will add in reg->off themselves */
ca369602 4076 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
969bf05e
AS
4077 if (err)
4078 return err;
17a52670 4079
f1174f77
EC
4080 /* for access checks, reg->off is just part of off */
4081 off += reg->off;
4082
69c087ba
YS
4083 if (reg->type == PTR_TO_MAP_KEY) {
4084 if (t == BPF_WRITE) {
4085 verbose(env, "write to change key R%d not allowed\n", regno);
4086 return -EACCES;
4087 }
4088
4089 err = check_mem_region_access(env, regno, off, size,
4090 reg->map_ptr->key_size, false);
4091 if (err)
4092 return err;
4093 if (value_regno >= 0)
4094 mark_reg_unknown(env, regs, value_regno);
4095 } else if (reg->type == PTR_TO_MAP_VALUE) {
1be7f75d
AS
4096 if (t == BPF_WRITE && value_regno >= 0 &&
4097 is_pointer_value(env, value_regno)) {
61bd5218 4098 verbose(env, "R%d leaks addr into map\n", value_regno);
1be7f75d
AS
4099 return -EACCES;
4100 }
591fe988
DB
4101 err = check_map_access_type(env, regno, off, size, t);
4102 if (err)
4103 return err;
9fd29c08 4104 err = check_map_access(env, regno, off, size, false);
a23740ec
AN
4105 if (!err && t == BPF_READ && value_regno >= 0) {
4106 struct bpf_map *map = reg->map_ptr;
4107
4108 /* if map is read-only, track its contents as scalars */
4109 if (tnum_is_const(reg->var_off) &&
4110 bpf_map_is_rdonly(map) &&
4111 map->ops->map_direct_value_addr) {
4112 int map_off = off + reg->var_off.value;
4113 u64 val = 0;
4114
4115 err = bpf_map_direct_read(map, map_off, size,
4116 &val);
4117 if (err)
4118 return err;
4119
4120 regs[value_regno].type = SCALAR_VALUE;
4121 __mark_reg_known(&regs[value_regno], val);
4122 } else {
4123 mark_reg_unknown(env, regs, value_regno);
4124 }
4125 }
457f4436
AN
4126 } else if (reg->type == PTR_TO_MEM) {
4127 if (t == BPF_WRITE && value_regno >= 0 &&
4128 is_pointer_value(env, value_regno)) {
4129 verbose(env, "R%d leaks addr into mem\n", value_regno);
4130 return -EACCES;
4131 }
4132 err = check_mem_region_access(env, regno, off, size,
4133 reg->mem_size, false);
4134 if (!err && t == BPF_READ && value_regno >= 0)
4135 mark_reg_unknown(env, regs, value_regno);
1a0dc1ac 4136 } else if (reg->type == PTR_TO_CTX) {
f1174f77 4137 enum bpf_reg_type reg_type = SCALAR_VALUE;
22dc4a0f 4138 struct btf *btf = NULL;
9e15db66 4139 u32 btf_id = 0;
19de99f7 4140
1be7f75d
AS
4141 if (t == BPF_WRITE && value_regno >= 0 &&
4142 is_pointer_value(env, value_regno)) {
61bd5218 4143 verbose(env, "R%d leaks addr into ctx\n", value_regno);
1be7f75d
AS
4144 return -EACCES;
4145 }
f1174f77 4146
58990d1f
DB
4147 err = check_ctx_reg(env, reg, regno);
4148 if (err < 0)
4149 return err;
4150
22dc4a0f 4151 err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf, &btf_id);
9e15db66
AS
4152 if (err)
4153 verbose_linfo(env, insn_idx, "; ");
969bf05e 4154 if (!err && t == BPF_READ && value_regno >= 0) {
f1174f77 4155 /* ctx access returns either a scalar, or a
de8f3a83
DB
4156 * PTR_TO_PACKET[_META,_END]. In the latter
4157 * case, we know the offset is zero.
f1174f77 4158 */
46f8bc92 4159 if (reg_type == SCALAR_VALUE) {
638f5b90 4160 mark_reg_unknown(env, regs, value_regno);
46f8bc92 4161 } else {
638f5b90 4162 mark_reg_known_zero(env, regs,
61bd5218 4163 value_regno);
46f8bc92
MKL
4164 if (reg_type_may_be_null(reg_type))
4165 regs[value_regno].id = ++env->id_gen;
5327ed3d
JW
4166 /* A load of ctx field could have different
4167 * actual load size with the one encoded in the
4168 * insn. When the dst is PTR, it is for sure not
4169 * a sub-register.
4170 */
4171 regs[value_regno].subreg_def = DEF_NOT_SUBREG;
b121b341 4172 if (reg_type == PTR_TO_BTF_ID ||
22dc4a0f
AN
4173 reg_type == PTR_TO_BTF_ID_OR_NULL) {
4174 regs[value_regno].btf = btf;
9e15db66 4175 regs[value_regno].btf_id = btf_id;
22dc4a0f 4176 }
46f8bc92 4177 }
638f5b90 4178 regs[value_regno].type = reg_type;
969bf05e 4179 }
17a52670 4180
f1174f77 4181 } else if (reg->type == PTR_TO_STACK) {
01f810ac
AM
4182 /* Basic bounds checks. */
4183 err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
e4298d25
DB
4184 if (err)
4185 return err;
8726679a 4186
f4d7e40a
AS
4187 state = func(env, reg);
4188 err = update_stack_depth(env, state, off);
4189 if (err)
4190 return err;
8726679a 4191
01f810ac
AM
4192 if (t == BPF_READ)
4193 err = check_stack_read(env, regno, off, size,
61bd5218 4194 value_regno);
01f810ac
AM
4195 else
4196 err = check_stack_write(env, regno, off, size,
4197 value_regno, insn_idx);
de8f3a83 4198 } else if (reg_is_pkt_pointer(reg)) {
3a0af8fd 4199 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
61bd5218 4200 verbose(env, "cannot write into packet\n");
969bf05e
AS
4201 return -EACCES;
4202 }
4acf6c0b
BB
4203 if (t == BPF_WRITE && value_regno >= 0 &&
4204 is_pointer_value(env, value_regno)) {
61bd5218
JK
4205 verbose(env, "R%d leaks addr into packet\n",
4206 value_regno);
4acf6c0b
BB
4207 return -EACCES;
4208 }
9fd29c08 4209 err = check_packet_access(env, regno, off, size, false);
969bf05e 4210 if (!err && t == BPF_READ && value_regno >= 0)
638f5b90 4211 mark_reg_unknown(env, regs, value_regno);
d58e468b
PP
4212 } else if (reg->type == PTR_TO_FLOW_KEYS) {
4213 if (t == BPF_WRITE && value_regno >= 0 &&
4214 is_pointer_value(env, value_regno)) {
4215 verbose(env, "R%d leaks addr into flow keys\n",
4216 value_regno);
4217 return -EACCES;
4218 }
4219
4220 err = check_flow_keys_access(env, off, size);
4221 if (!err && t == BPF_READ && value_regno >= 0)
4222 mark_reg_unknown(env, regs, value_regno);
46f8bc92 4223 } else if (type_is_sk_pointer(reg->type)) {
c64b7983 4224 if (t == BPF_WRITE) {
46f8bc92
MKL
4225 verbose(env, "R%d cannot write into %s\n",
4226 regno, reg_type_str[reg->type]);
c64b7983
JS
4227 return -EACCES;
4228 }
5f456649 4229 err = check_sock_access(env, insn_idx, regno, off, size, t);
c64b7983
JS
4230 if (!err && value_regno >= 0)
4231 mark_reg_unknown(env, regs, value_regno);
9df1c28b
MM
4232 } else if (reg->type == PTR_TO_TP_BUFFER) {
4233 err = check_tp_buffer_access(env, reg, regno, off, size);
4234 if (!err && t == BPF_READ && value_regno >= 0)
4235 mark_reg_unknown(env, regs, value_regno);
9e15db66
AS
4236 } else if (reg->type == PTR_TO_BTF_ID) {
4237 err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
4238 value_regno);
41c48f3a
AI
4239 } else if (reg->type == CONST_PTR_TO_MAP) {
4240 err = check_ptr_to_map_access(env, regs, regno, off, size, t,
4241 value_regno);
afbf21dc
YS
4242 } else if (reg->type == PTR_TO_RDONLY_BUF) {
4243 if (t == BPF_WRITE) {
4244 verbose(env, "R%d cannot write into %s\n",
4245 regno, reg_type_str[reg->type]);
4246 return -EACCES;
4247 }
f6dfbe31
CIK
4248 err = check_buffer_access(env, reg, regno, off, size, false,
4249 "rdonly",
afbf21dc
YS
4250 &env->prog->aux->max_rdonly_access);
4251 if (!err && value_regno >= 0)
4252 mark_reg_unknown(env, regs, value_regno);
4253 } else if (reg->type == PTR_TO_RDWR_BUF) {
f6dfbe31
CIK
4254 err = check_buffer_access(env, reg, regno, off, size, false,
4255 "rdwr",
afbf21dc
YS
4256 &env->prog->aux->max_rdwr_access);
4257 if (!err && t == BPF_READ && value_regno >= 0)
4258 mark_reg_unknown(env, regs, value_regno);
17a52670 4259 } else {
61bd5218
JK
4260 verbose(env, "R%d invalid mem access '%s'\n", regno,
4261 reg_type_str[reg->type]);
17a52670
AS
4262 return -EACCES;
4263 }
969bf05e 4264
f1174f77 4265 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
638f5b90 4266 regs[value_regno].type == SCALAR_VALUE) {
f1174f77 4267 /* b/h/w load zero-extends, mark upper bits as known 0 */
0c17d1d2 4268 coerce_reg_to_size(&regs[value_regno], size);
969bf05e 4269 }
17a52670
AS
4270 return err;
4271}
4272
91c960b0 4273static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
17a52670 4274{
5ffa2550 4275 int load_reg;
17a52670
AS
4276 int err;
4277
5ca419f2
BJ
4278 switch (insn->imm) {
4279 case BPF_ADD:
4280 case BPF_ADD | BPF_FETCH:
981f94c3
BJ
4281 case BPF_AND:
4282 case BPF_AND | BPF_FETCH:
4283 case BPF_OR:
4284 case BPF_OR | BPF_FETCH:
4285 case BPF_XOR:
4286 case BPF_XOR | BPF_FETCH:
5ffa2550
BJ
4287 case BPF_XCHG:
4288 case BPF_CMPXCHG:
5ca419f2
BJ
4289 break;
4290 default:
91c960b0
BJ
4291 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
4292 return -EINVAL;
4293 }
4294
4295 if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
4296 verbose(env, "invalid atomic operand size\n");
17a52670
AS
4297 return -EINVAL;
4298 }
4299
4300 /* check src1 operand */
dc503a8a 4301 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17a52670
AS
4302 if (err)
4303 return err;
4304
4305 /* check src2 operand */
dc503a8a 4306 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17a52670
AS
4307 if (err)
4308 return err;
4309
5ffa2550
BJ
4310 if (insn->imm == BPF_CMPXCHG) {
4311 /* Check comparison of R0 with memory location */
4312 err = check_reg_arg(env, BPF_REG_0, SRC_OP);
4313 if (err)
4314 return err;
4315 }
4316
6bdf6abc 4317 if (is_pointer_value(env, insn->src_reg)) {
61bd5218 4318 verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
6bdf6abc
DB
4319 return -EACCES;
4320 }
4321
ca369602 4322 if (is_ctx_reg(env, insn->dst_reg) ||
4b5defde 4323 is_pkt_reg(env, insn->dst_reg) ||
46f8bc92
MKL
4324 is_flow_key_reg(env, insn->dst_reg) ||
4325 is_sk_reg(env, insn->dst_reg)) {
91c960b0 4326 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
2a159c6f
DB
4327 insn->dst_reg,
4328 reg_type_str[reg_state(env, insn->dst_reg)->type]);
f37a8cb8
DB
4329 return -EACCES;
4330 }
4331
37086bfd
BJ
4332 if (insn->imm & BPF_FETCH) {
4333 if (insn->imm == BPF_CMPXCHG)
4334 load_reg = BPF_REG_0;
4335 else
4336 load_reg = insn->src_reg;
4337
4338 /* check and record load of old value */
4339 err = check_reg_arg(env, load_reg, DST_OP);
4340 if (err)
4341 return err;
4342 } else {
4343 /* This instruction accesses a memory location but doesn't
4344 * actually load it into a register.
4345 */
4346 load_reg = -1;
4347 }
4348
91c960b0 4349 /* check whether we can read the memory */
31fd8581 4350 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
37086bfd 4351 BPF_SIZE(insn->code), BPF_READ, load_reg, true);
17a52670
AS
4352 if (err)
4353 return err;
4354
91c960b0 4355 /* check whether we can write into the same memory */
5ca419f2
BJ
4356 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
4357 BPF_SIZE(insn->code), BPF_WRITE, -1, true);
4358 if (err)
4359 return err;
4360
5ca419f2 4361 return 0;
17a52670
AS
4362}
4363
01f810ac
AM
4364/* When register 'regno' is used to read the stack (either directly or through
4365 * a helper function) make sure that it's within stack boundary and, depending
4366 * on the access type, that all elements of the stack are initialized.
4367 *
4368 * 'off' includes 'regno->off', but not its dynamic part (if any).
4369 *
4370 * All registers that have been spilled on the stack in the slots within the
4371 * read offsets are marked as read.
4372 */
4373static int check_stack_range_initialized(
4374 struct bpf_verifier_env *env, int regno, int off,
4375 int access_size, bool zero_size_allowed,
4376 enum stack_access_src type, struct bpf_call_arg_meta *meta)
2011fccf
AI
4377{
4378 struct bpf_reg_state *reg = reg_state(env, regno);
01f810ac
AM
4379 struct bpf_func_state *state = func(env, reg);
4380 int err, min_off, max_off, i, j, slot, spi;
4381 char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
4382 enum bpf_access_type bounds_check_type;
4383 /* Some accesses can write anything into the stack, others are
4384 * read-only.
4385 */
4386 bool clobber = false;
2011fccf 4387
01f810ac
AM
4388 if (access_size == 0 && !zero_size_allowed) {
4389 verbose(env, "invalid zero-sized read\n");
2011fccf
AI
4390 return -EACCES;
4391 }
2011fccf 4392
01f810ac
AM
4393 if (type == ACCESS_HELPER) {
4394 /* The bounds checks for writes are more permissive than for
4395 * reads. However, if raw_mode is not set, we'll do extra
4396 * checks below.
4397 */
4398 bounds_check_type = BPF_WRITE;
4399 clobber = true;
4400 } else {
4401 bounds_check_type = BPF_READ;
4402 }
4403 err = check_stack_access_within_bounds(env, regno, off, access_size,
4404 type, bounds_check_type);
4405 if (err)
4406 return err;
4407
17a52670 4408
2011fccf 4409 if (tnum_is_const(reg->var_off)) {
01f810ac 4410 min_off = max_off = reg->var_off.value + off;
2011fccf 4411 } else {
088ec26d
AI
4412 /* Variable offset is prohibited for unprivileged mode for
4413 * simplicity since it requires corresponding support in
4414 * Spectre masking for stack ALU.
4415 * See also retrieve_ptr_limit().
4416 */
2c78ee89 4417 if (!env->bypass_spec_v1) {
088ec26d 4418 char tn_buf[48];
f1174f77 4419
088ec26d 4420 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
01f810ac
AM
4421 verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
4422 regno, err_extra, tn_buf);
088ec26d
AI
4423 return -EACCES;
4424 }
f2bcd05e
AI
4425 /* Only initialized buffer on stack is allowed to be accessed
4426 * with variable offset. With uninitialized buffer it's hard to
4427 * guarantee that whole memory is marked as initialized on
4428 * helper return since specific bounds are unknown what may
4429 * cause uninitialized stack leaking.
4430 */
4431 if (meta && meta->raw_mode)
4432 meta = NULL;
4433
01f810ac
AM
4434 min_off = reg->smin_value + off;
4435 max_off = reg->smax_value + off;
17a52670
AS
4436 }
4437
435faee1
DB
4438 if (meta && meta->raw_mode) {
4439 meta->access_size = access_size;
4440 meta->regno = regno;
4441 return 0;
4442 }
4443
2011fccf 4444 for (i = min_off; i < max_off + access_size; i++) {
cc2b14d5
AS
4445 u8 *stype;
4446
2011fccf 4447 slot = -i - 1;
638f5b90 4448 spi = slot / BPF_REG_SIZE;
cc2b14d5
AS
4449 if (state->allocated_stack <= slot)
4450 goto err;
4451 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
4452 if (*stype == STACK_MISC)
4453 goto mark;
4454 if (*stype == STACK_ZERO) {
01f810ac
AM
4455 if (clobber) {
4456 /* helper can write anything into the stack */
4457 *stype = STACK_MISC;
4458 }
cc2b14d5 4459 goto mark;
17a52670 4460 }
1d68f22b
YS
4461
4462 if (state->stack[spi].slot_type[0] == STACK_SPILL &&
4463 state->stack[spi].spilled_ptr.type == PTR_TO_BTF_ID)
4464 goto mark;
4465
f7cf25b2 4466 if (state->stack[spi].slot_type[0] == STACK_SPILL &&
cd17d38f
YS
4467 (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
4468 env->allow_ptr_leaks)) {
01f810ac
AM
4469 if (clobber) {
4470 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
4471 for (j = 0; j < BPF_REG_SIZE; j++)
4472 state->stack[spi].slot_type[j] = STACK_MISC;
4473 }
f7cf25b2
AS
4474 goto mark;
4475 }
4476
cc2b14d5 4477err:
2011fccf 4478 if (tnum_is_const(reg->var_off)) {
01f810ac
AM
4479 verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
4480 err_extra, regno, min_off, i - min_off, access_size);
2011fccf
AI
4481 } else {
4482 char tn_buf[48];
4483
4484 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
01f810ac
AM
4485 verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
4486 err_extra, regno, tn_buf, i - min_off, access_size);
2011fccf 4487 }
cc2b14d5
AS
4488 return -EACCES;
4489mark:
4490 /* reading any byte out of 8-byte 'spill_slot' will cause
4491 * the whole slot to be marked as 'read'
4492 */
679c782d 4493 mark_reg_read(env, &state->stack[spi].spilled_ptr,
5327ed3d
JW
4494 state->stack[spi].spilled_ptr.parent,
4495 REG_LIVE_READ64);
17a52670 4496 }
2011fccf 4497 return update_stack_depth(env, state, min_off);
17a52670
AS
4498}
4499
06c1c049
GB
4500static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
4501 int access_size, bool zero_size_allowed,
4502 struct bpf_call_arg_meta *meta)
4503{
638f5b90 4504 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
06c1c049 4505
f1174f77 4506 switch (reg->type) {
06c1c049 4507 case PTR_TO_PACKET:
de8f3a83 4508 case PTR_TO_PACKET_META:
9fd29c08
YS
4509 return check_packet_access(env, regno, reg->off, access_size,
4510 zero_size_allowed);
69c087ba
YS
4511 case PTR_TO_MAP_KEY:
4512 return check_mem_region_access(env, regno, reg->off, access_size,
4513 reg->map_ptr->key_size, false);
06c1c049 4514 case PTR_TO_MAP_VALUE:
591fe988
DB
4515 if (check_map_access_type(env, regno, reg->off, access_size,
4516 meta && meta->raw_mode ? BPF_WRITE :
4517 BPF_READ))
4518 return -EACCES;
9fd29c08
YS
4519 return check_map_access(env, regno, reg->off, access_size,
4520 zero_size_allowed);
457f4436
AN
4521 case PTR_TO_MEM:
4522 return check_mem_region_access(env, regno, reg->off,
4523 access_size, reg->mem_size,
4524 zero_size_allowed);
afbf21dc
YS
4525 case PTR_TO_RDONLY_BUF:
4526 if (meta && meta->raw_mode)
4527 return -EACCES;
4528 return check_buffer_access(env, reg, regno, reg->off,
4529 access_size, zero_size_allowed,
4530 "rdonly",
4531 &env->prog->aux->max_rdonly_access);
4532 case PTR_TO_RDWR_BUF:
4533 return check_buffer_access(env, reg, regno, reg->off,
4534 access_size, zero_size_allowed,
4535 "rdwr",
4536 &env->prog->aux->max_rdwr_access);
0d004c02 4537 case PTR_TO_STACK:
01f810ac
AM
4538 return check_stack_range_initialized(
4539 env,
4540 regno, reg->off, access_size,
4541 zero_size_allowed, ACCESS_HELPER, meta);
0d004c02
LB
4542 default: /* scalar_value or invalid ptr */
4543 /* Allow zero-byte read from NULL, regardless of pointer type */
4544 if (zero_size_allowed && access_size == 0 &&
4545 register_is_null(reg))
4546 return 0;
4547
4548 verbose(env, "R%d type=%s expected=%s\n", regno,
4549 reg_type_str[reg->type],
4550 reg_type_str[PTR_TO_STACK]);
4551 return -EACCES;
06c1c049
GB
4552 }
4553}
4554
e5069b9c
DB
4555int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
4556 u32 regno, u32 mem_size)
4557{
4558 if (register_is_null(reg))
4559 return 0;
4560
4561 if (reg_type_may_be_null(reg->type)) {
4562 /* Assuming that the register contains a value check if the memory
4563 * access is safe. Temporarily save and restore the register's state as
4564 * the conversion shouldn't be visible to a caller.
4565 */
4566 const struct bpf_reg_state saved_reg = *reg;
4567 int rv;
4568
4569 mark_ptr_not_null_reg(reg);
4570 rv = check_helper_mem_access(env, regno, mem_size, true, NULL);
4571 *reg = saved_reg;
4572 return rv;
4573 }
4574
4575 return check_helper_mem_access(env, regno, mem_size, true, NULL);
4576}
4577
d83525ca
AS
4578/* Implementation details:
4579 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL
4580 * Two bpf_map_lookups (even with the same key) will have different reg->id.
4581 * For traditional PTR_TO_MAP_VALUE the verifier clears reg->id after
4582 * value_or_null->value transition, since the verifier only cares about
4583 * the range of access to valid map value pointer and doesn't care about actual
4584 * address of the map element.
4585 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
4586 * reg->id > 0 after value_or_null->value transition. By doing so
4587 * two bpf_map_lookups will be considered two different pointers that
4588 * point to different bpf_spin_locks.
4589 * The verifier allows taking only one bpf_spin_lock at a time to avoid
4590 * dead-locks.
4591 * Since only one bpf_spin_lock is allowed the checks are simpler than
4592 * reg_is_refcounted() logic. The verifier needs to remember only
4593 * one spin_lock instead of array of acquired_refs.
4594 * cur_state->active_spin_lock remembers which map value element got locked
4595 * and clears it after bpf_spin_unlock.
4596 */
4597static int process_spin_lock(struct bpf_verifier_env *env, int regno,
4598 bool is_lock)
4599{
4600 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4601 struct bpf_verifier_state *cur = env->cur_state;
4602 bool is_const = tnum_is_const(reg->var_off);
4603 struct bpf_map *map = reg->map_ptr;
4604 u64 val = reg->var_off.value;
4605
d83525ca
AS
4606 if (!is_const) {
4607 verbose(env,
4608 "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
4609 regno);
4610 return -EINVAL;
4611 }
4612 if (!map->btf) {
4613 verbose(env,
4614 "map '%s' has to have BTF in order to use bpf_spin_lock\n",
4615 map->name);
4616 return -EINVAL;
4617 }
4618 if (!map_value_has_spin_lock(map)) {
4619 if (map->spin_lock_off == -E2BIG)
4620 verbose(env,
4621 "map '%s' has more than one 'struct bpf_spin_lock'\n",
4622 map->name);
4623 else if (map->spin_lock_off == -ENOENT)
4624 verbose(env,
4625 "map '%s' doesn't have 'struct bpf_spin_lock'\n",
4626 map->name);
4627 else
4628 verbose(env,
4629 "map '%s' is not a struct type or bpf_spin_lock is mangled\n",
4630 map->name);
4631 return -EINVAL;
4632 }
4633 if (map->spin_lock_off != val + reg->off) {
4634 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock'\n",
4635 val + reg->off);
4636 return -EINVAL;
4637 }
4638 if (is_lock) {
4639 if (cur->active_spin_lock) {
4640 verbose(env,
4641 "Locking two bpf_spin_locks are not allowed\n");
4642 return -EINVAL;
4643 }
4644 cur->active_spin_lock = reg->id;
4645 } else {
4646 if (!cur->active_spin_lock) {
4647 verbose(env, "bpf_spin_unlock without taking a lock\n");
4648 return -EINVAL;
4649 }
4650 if (cur->active_spin_lock != reg->id) {
4651 verbose(env, "bpf_spin_unlock of different lock\n");
4652 return -EINVAL;
4653 }
4654 cur->active_spin_lock = 0;
4655 }
4656 return 0;
4657}
4658
90133415
DB
4659static bool arg_type_is_mem_ptr(enum bpf_arg_type type)
4660{
4661 return type == ARG_PTR_TO_MEM ||
4662 type == ARG_PTR_TO_MEM_OR_NULL ||
4663 type == ARG_PTR_TO_UNINIT_MEM;
4664}
4665
4666static bool arg_type_is_mem_size(enum bpf_arg_type type)
4667{
4668 return type == ARG_CONST_SIZE ||
4669 type == ARG_CONST_SIZE_OR_ZERO;
4670}
4671
457f4436
AN
4672static bool arg_type_is_alloc_size(enum bpf_arg_type type)
4673{
4674 return type == ARG_CONST_ALLOC_SIZE_OR_ZERO;
4675}
4676
57c3bb72
AI
4677static bool arg_type_is_int_ptr(enum bpf_arg_type type)
4678{
4679 return type == ARG_PTR_TO_INT ||
4680 type == ARG_PTR_TO_LONG;
4681}
4682
4683static int int_ptr_type_to_size(enum bpf_arg_type type)
4684{
4685 if (type == ARG_PTR_TO_INT)
4686 return sizeof(u32);
4687 else if (type == ARG_PTR_TO_LONG)
4688 return sizeof(u64);
4689
4690 return -EINVAL;
4691}
4692
912f442c
LB
4693static int resolve_map_arg_type(struct bpf_verifier_env *env,
4694 const struct bpf_call_arg_meta *meta,
4695 enum bpf_arg_type *arg_type)
4696{
4697 if (!meta->map_ptr) {
4698 /* kernel subsystem misconfigured verifier */
4699 verbose(env, "invalid map_ptr to access map->type\n");
4700 return -EACCES;
4701 }
4702
4703 switch (meta->map_ptr->map_type) {
4704 case BPF_MAP_TYPE_SOCKMAP:
4705 case BPF_MAP_TYPE_SOCKHASH:
4706 if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
6550f2dd 4707 *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
912f442c
LB
4708 } else {
4709 verbose(env, "invalid arg_type for sockmap/sockhash\n");
4710 return -EINVAL;
4711 }
4712 break;
4713
4714 default:
4715 break;
4716 }
4717 return 0;
4718}
4719
f79e7ea5
LB
4720struct bpf_reg_types {
4721 const enum bpf_reg_type types[10];
1df8f55a 4722 u32 *btf_id;
f79e7ea5
LB
4723};
4724
4725static const struct bpf_reg_types map_key_value_types = {
4726 .types = {
4727 PTR_TO_STACK,
4728 PTR_TO_PACKET,
4729 PTR_TO_PACKET_META,
69c087ba 4730 PTR_TO_MAP_KEY,
f79e7ea5
LB
4731 PTR_TO_MAP_VALUE,
4732 },
4733};
4734
4735static const struct bpf_reg_types sock_types = {
4736 .types = {
4737 PTR_TO_SOCK_COMMON,
4738 PTR_TO_SOCKET,
4739 PTR_TO_TCP_SOCK,
4740 PTR_TO_XDP_SOCK,
4741 },
4742};
4743
49a2a4d4 4744#ifdef CONFIG_NET
1df8f55a
MKL
4745static const struct bpf_reg_types btf_id_sock_common_types = {
4746 .types = {
4747 PTR_TO_SOCK_COMMON,
4748 PTR_TO_SOCKET,
4749 PTR_TO_TCP_SOCK,
4750 PTR_TO_XDP_SOCK,
4751 PTR_TO_BTF_ID,
4752 },
4753 .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
4754};
49a2a4d4 4755#endif
1df8f55a 4756
f79e7ea5
LB
4757static const struct bpf_reg_types mem_types = {
4758 .types = {
4759 PTR_TO_STACK,
4760 PTR_TO_PACKET,
4761 PTR_TO_PACKET_META,
69c087ba 4762 PTR_TO_MAP_KEY,
f79e7ea5
LB
4763 PTR_TO_MAP_VALUE,
4764 PTR_TO_MEM,
4765 PTR_TO_RDONLY_BUF,
4766 PTR_TO_RDWR_BUF,
4767 },
4768};
4769
4770static const struct bpf_reg_types int_ptr_types = {
4771 .types = {
4772 PTR_TO_STACK,
4773 PTR_TO_PACKET,
4774 PTR_TO_PACKET_META,
69c087ba 4775 PTR_TO_MAP_KEY,
f79e7ea5
LB
4776 PTR_TO_MAP_VALUE,
4777 },
4778};
4779
4780static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
4781static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
4782static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
4783static const struct bpf_reg_types alloc_mem_types = { .types = { PTR_TO_MEM } };
4784static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
4785static const struct bpf_reg_types btf_ptr_types = { .types = { PTR_TO_BTF_ID } };
4786static const struct bpf_reg_types spin_lock_types = { .types = { PTR_TO_MAP_VALUE } };
eaa6bcb7 4787static const struct bpf_reg_types percpu_btf_ptr_types = { .types = { PTR_TO_PERCPU_BTF_ID } };
69c087ba
YS
4788static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
4789static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
fff13c4b 4790static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
f79e7ea5 4791
0789e13b 4792static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
f79e7ea5
LB
4793 [ARG_PTR_TO_MAP_KEY] = &map_key_value_types,
4794 [ARG_PTR_TO_MAP_VALUE] = &map_key_value_types,
4795 [ARG_PTR_TO_UNINIT_MAP_VALUE] = &map_key_value_types,
4796 [ARG_PTR_TO_MAP_VALUE_OR_NULL] = &map_key_value_types,
4797 [ARG_CONST_SIZE] = &scalar_types,
4798 [ARG_CONST_SIZE_OR_ZERO] = &scalar_types,
4799 [ARG_CONST_ALLOC_SIZE_OR_ZERO] = &scalar_types,
4800 [ARG_CONST_MAP_PTR] = &const_map_ptr_types,
4801 [ARG_PTR_TO_CTX] = &context_types,
4802 [ARG_PTR_TO_CTX_OR_NULL] = &context_types,
4803 [ARG_PTR_TO_SOCK_COMMON] = &sock_types,
49a2a4d4 4804#ifdef CONFIG_NET
1df8f55a 4805 [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types,
49a2a4d4 4806#endif
f79e7ea5
LB
4807 [ARG_PTR_TO_SOCKET] = &fullsock_types,
4808 [ARG_PTR_TO_SOCKET_OR_NULL] = &fullsock_types,
4809 [ARG_PTR_TO_BTF_ID] = &btf_ptr_types,
4810 [ARG_PTR_TO_SPIN_LOCK] = &spin_lock_types,
4811 [ARG_PTR_TO_MEM] = &mem_types,
4812 [ARG_PTR_TO_MEM_OR_NULL] = &mem_types,
4813 [ARG_PTR_TO_UNINIT_MEM] = &mem_types,
4814 [ARG_PTR_TO_ALLOC_MEM] = &alloc_mem_types,
4815 [ARG_PTR_TO_ALLOC_MEM_OR_NULL] = &alloc_mem_types,
4816 [ARG_PTR_TO_INT] = &int_ptr_types,
4817 [ARG_PTR_TO_LONG] = &int_ptr_types,
eaa6bcb7 4818 [ARG_PTR_TO_PERCPU_BTF_ID] = &percpu_btf_ptr_types,
69c087ba
YS
4819 [ARG_PTR_TO_FUNC] = &func_ptr_types,
4820 [ARG_PTR_TO_STACK_OR_NULL] = &stack_ptr_types,
fff13c4b 4821 [ARG_PTR_TO_CONST_STR] = &const_str_ptr_types,
f79e7ea5
LB
4822};
4823
4824static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
a968d5e2
MKL
4825 enum bpf_arg_type arg_type,
4826 const u32 *arg_btf_id)
f79e7ea5
LB
4827{
4828 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4829 enum bpf_reg_type expected, type = reg->type;
a968d5e2 4830 const struct bpf_reg_types *compatible;
f79e7ea5
LB
4831 int i, j;
4832
a968d5e2
MKL
4833 compatible = compatible_reg_types[arg_type];
4834 if (!compatible) {
4835 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
4836 return -EFAULT;
4837 }
4838
f79e7ea5
LB
4839 for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
4840 expected = compatible->types[i];
4841 if (expected == NOT_INIT)
4842 break;
4843
4844 if (type == expected)
a968d5e2 4845 goto found;
f79e7ea5
LB
4846 }
4847
4848 verbose(env, "R%d type=%s expected=", regno, reg_type_str[type]);
4849 for (j = 0; j + 1 < i; j++)
4850 verbose(env, "%s, ", reg_type_str[compatible->types[j]]);
4851 verbose(env, "%s\n", reg_type_str[compatible->types[j]]);
4852 return -EACCES;
a968d5e2
MKL
4853
4854found:
4855 if (type == PTR_TO_BTF_ID) {
1df8f55a
MKL
4856 if (!arg_btf_id) {
4857 if (!compatible->btf_id) {
4858 verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
4859 return -EFAULT;
4860 }
4861 arg_btf_id = compatible->btf_id;
4862 }
4863
22dc4a0f
AN
4864 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
4865 btf_vmlinux, *arg_btf_id)) {
a968d5e2 4866 verbose(env, "R%d is of type %s but %s is expected\n",
22dc4a0f
AN
4867 regno, kernel_type_name(reg->btf, reg->btf_id),
4868 kernel_type_name(btf_vmlinux, *arg_btf_id));
a968d5e2
MKL
4869 return -EACCES;
4870 }
4871
4872 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4873 verbose(env, "R%d is a pointer to in-kernel struct with non-zero offset\n",
4874 regno);
4875 return -EACCES;
4876 }
4877 }
4878
4879 return 0;
f79e7ea5
LB
4880}
4881
af7ec138
YS
4882static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
4883 struct bpf_call_arg_meta *meta,
4884 const struct bpf_func_proto *fn)
17a52670 4885{
af7ec138 4886 u32 regno = BPF_REG_1 + arg;
638f5b90 4887 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
af7ec138 4888 enum bpf_arg_type arg_type = fn->arg_type[arg];
f79e7ea5 4889 enum bpf_reg_type type = reg->type;
17a52670
AS
4890 int err = 0;
4891
80f1d68c 4892 if (arg_type == ARG_DONTCARE)
17a52670
AS
4893 return 0;
4894
dc503a8a
EC
4895 err = check_reg_arg(env, regno, SRC_OP);
4896 if (err)
4897 return err;
17a52670 4898
1be7f75d
AS
4899 if (arg_type == ARG_ANYTHING) {
4900 if (is_pointer_value(env, regno)) {
61bd5218
JK
4901 verbose(env, "R%d leaks addr into helper function\n",
4902 regno);
1be7f75d
AS
4903 return -EACCES;
4904 }
80f1d68c 4905 return 0;
1be7f75d 4906 }
80f1d68c 4907
de8f3a83 4908 if (type_is_pkt_pointer(type) &&
3a0af8fd 4909 !may_access_direct_pkt_data(env, meta, BPF_READ)) {
61bd5218 4910 verbose(env, "helper access to the packet is not allowed\n");
6841de8b
AS
4911 return -EACCES;
4912 }
4913
912f442c
LB
4914 if (arg_type == ARG_PTR_TO_MAP_VALUE ||
4915 arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE ||
4916 arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL) {
4917 err = resolve_map_arg_type(env, meta, &arg_type);
4918 if (err)
4919 return err;
4920 }
4921
fd1b0d60
LB
4922 if (register_is_null(reg) && arg_type_may_be_null(arg_type))
4923 /* A NULL register has a SCALAR_VALUE type, so skip
4924 * type checking.
4925 */
4926 goto skip_type_check;
4927
a968d5e2 4928 err = check_reg_type(env, regno, arg_type, fn->arg_btf_id[arg]);
f79e7ea5
LB
4929 if (err)
4930 return err;
4931
a968d5e2 4932 if (type == PTR_TO_CTX) {
feec7040
LB
4933 err = check_ctx_reg(env, reg, regno);
4934 if (err < 0)
4935 return err;
d7b9454a
LB
4936 }
4937
fd1b0d60 4938skip_type_check:
02f7c958 4939 if (reg->ref_obj_id) {
457f4436
AN
4940 if (meta->ref_obj_id) {
4941 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
4942 regno, reg->ref_obj_id,
4943 meta->ref_obj_id);
4944 return -EFAULT;
4945 }
4946 meta->ref_obj_id = reg->ref_obj_id;
17a52670
AS
4947 }
4948
17a52670
AS
4949 if (arg_type == ARG_CONST_MAP_PTR) {
4950 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
33ff9823 4951 meta->map_ptr = reg->map_ptr;
17a52670
AS
4952 } else if (arg_type == ARG_PTR_TO_MAP_KEY) {
4953 /* bpf_map_xxx(..., map_ptr, ..., key) call:
4954 * check that [key, key + map->key_size) are within
4955 * stack limits and initialized
4956 */
33ff9823 4957 if (!meta->map_ptr) {
17a52670
AS
4958 /* in function declaration map_ptr must come before
4959 * map_key, so that it's verified and known before
4960 * we have to check map_key here. Otherwise it means
4961 * that kernel subsystem misconfigured verifier
4962 */
61bd5218 4963 verbose(env, "invalid map_ptr to access map->key\n");
17a52670
AS
4964 return -EACCES;
4965 }
d71962f3
PC
4966 err = check_helper_mem_access(env, regno,
4967 meta->map_ptr->key_size, false,
4968 NULL);
2ea864c5 4969 } else if (arg_type == ARG_PTR_TO_MAP_VALUE ||
6ac99e8f
MKL
4970 (arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL &&
4971 !register_is_null(reg)) ||
2ea864c5 4972 arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE) {
17a52670
AS
4973 /* bpf_map_xxx(..., map_ptr, ..., value) call:
4974 * check [value, value + map->value_size) validity
4975 */
33ff9823 4976 if (!meta->map_ptr) {
17a52670 4977 /* kernel subsystem misconfigured verifier */
61bd5218 4978 verbose(env, "invalid map_ptr to access map->value\n");
17a52670
AS
4979 return -EACCES;
4980 }
2ea864c5 4981 meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE);
d71962f3
PC
4982 err = check_helper_mem_access(env, regno,
4983 meta->map_ptr->value_size, false,
2ea864c5 4984 meta);
eaa6bcb7
HL
4985 } else if (arg_type == ARG_PTR_TO_PERCPU_BTF_ID) {
4986 if (!reg->btf_id) {
4987 verbose(env, "Helper has invalid btf_id in R%d\n", regno);
4988 return -EACCES;
4989 }
22dc4a0f 4990 meta->ret_btf = reg->btf;
eaa6bcb7 4991 meta->ret_btf_id = reg->btf_id;
c18f0b6a
LB
4992 } else if (arg_type == ARG_PTR_TO_SPIN_LOCK) {
4993 if (meta->func_id == BPF_FUNC_spin_lock) {
4994 if (process_spin_lock(env, regno, true))
4995 return -EACCES;
4996 } else if (meta->func_id == BPF_FUNC_spin_unlock) {
4997 if (process_spin_lock(env, regno, false))
4998 return -EACCES;
4999 } else {
5000 verbose(env, "verifier internal error\n");
5001 return -EFAULT;
5002 }
69c087ba
YS
5003 } else if (arg_type == ARG_PTR_TO_FUNC) {
5004 meta->subprogno = reg->subprogno;
a2bbe7cc
LB
5005 } else if (arg_type_is_mem_ptr(arg_type)) {
5006 /* The access to this pointer is only checked when we hit the
5007 * next is_mem_size argument below.
5008 */
5009 meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MEM);
90133415 5010 } else if (arg_type_is_mem_size(arg_type)) {
39f19ebb 5011 bool zero_size_allowed = (arg_type == ARG_CONST_SIZE_OR_ZERO);
17a52670 5012
10060503
JF
5013 /* This is used to refine r0 return value bounds for helpers
5014 * that enforce this value as an upper bound on return values.
5015 * See do_refine_retval_range() for helpers that can refine
5016 * the return value. C type of helper is u32 so we pull register
5017 * bound from umax_value however, if negative verifier errors
5018 * out. Only upper bounds can be learned because retval is an
5019 * int type and negative retvals are allowed.
849fa506 5020 */
10060503 5021 meta->msize_max_value = reg->umax_value;
849fa506 5022
f1174f77
EC
5023 /* The register is SCALAR_VALUE; the access check
5024 * happens using its boundaries.
06c1c049 5025 */
f1174f77 5026 if (!tnum_is_const(reg->var_off))
06c1c049
GB
5027 /* For unprivileged variable accesses, disable raw
5028 * mode so that the program is required to
5029 * initialize all the memory that the helper could
5030 * just partially fill up.
5031 */
5032 meta = NULL;
5033
b03c9f9f 5034 if (reg->smin_value < 0) {
61bd5218 5035 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
f1174f77
EC
5036 regno);
5037 return -EACCES;
5038 }
06c1c049 5039
b03c9f9f 5040 if (reg->umin_value == 0) {
f1174f77
EC
5041 err = check_helper_mem_access(env, regno - 1, 0,
5042 zero_size_allowed,
5043 meta);
06c1c049
GB
5044 if (err)
5045 return err;
06c1c049 5046 }
f1174f77 5047
b03c9f9f 5048 if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
61bd5218 5049 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
f1174f77
EC
5050 regno);
5051 return -EACCES;
5052 }
5053 err = check_helper_mem_access(env, regno - 1,
b03c9f9f 5054 reg->umax_value,
f1174f77 5055 zero_size_allowed, meta);
b5dc0163
AS
5056 if (!err)
5057 err = mark_chain_precision(env, regno);
457f4436
AN
5058 } else if (arg_type_is_alloc_size(arg_type)) {
5059 if (!tnum_is_const(reg->var_off)) {
28a8add6 5060 verbose(env, "R%d is not a known constant'\n",
457f4436
AN
5061 regno);
5062 return -EACCES;
5063 }
5064 meta->mem_size = reg->var_off.value;
57c3bb72
AI
5065 } else if (arg_type_is_int_ptr(arg_type)) {
5066 int size = int_ptr_type_to_size(arg_type);
5067
5068 err = check_helper_mem_access(env, regno, size, false, meta);
5069 if (err)
5070 return err;
5071 err = check_ptr_alignment(env, reg, 0, size, true);
fff13c4b
FR
5072 } else if (arg_type == ARG_PTR_TO_CONST_STR) {
5073 struct bpf_map *map = reg->map_ptr;
5074 int map_off;
5075 u64 map_addr;
5076 char *str_ptr;
5077
5078 if (reg->type != PTR_TO_MAP_VALUE || !map ||
5079 !bpf_map_is_rdonly(map)) {
5080 verbose(env, "R%d does not point to a readonly map'\n", regno);
5081 return -EACCES;
5082 }
5083
5084 if (!tnum_is_const(reg->var_off)) {
5085 verbose(env, "R%d is not a constant address'\n", regno);
5086 return -EACCES;
5087 }
5088
5089 if (!map->ops->map_direct_value_addr) {
5090 verbose(env, "no direct value access support for this map type\n");
5091 return -EACCES;
5092 }
5093
5094 err = check_map_access(env, regno, reg->off,
5095 map->value_size - reg->off, false);
5096 if (err)
5097 return err;
5098
5099 map_off = reg->off + reg->var_off.value;
5100 err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
5101 if (err) {
5102 verbose(env, "direct value access on string failed\n");
5103 return err;
5104 }
5105
5106 str_ptr = (char *)(long)(map_addr);
5107 if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
5108 verbose(env, "string is not zero-terminated\n");
5109 return -EINVAL;
5110 }
17a52670
AS
5111 }
5112
5113 return err;
5114}
5115
0126240f
LB
5116static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
5117{
5118 enum bpf_attach_type eatype = env->prog->expected_attach_type;
7e40781c 5119 enum bpf_prog_type type = resolve_prog_type(env->prog);
0126240f
LB
5120
5121 if (func_id != BPF_FUNC_map_update_elem)
5122 return false;
5123
5124 /* It's not possible to get access to a locked struct sock in these
5125 * contexts, so updating is safe.
5126 */
5127 switch (type) {
5128 case BPF_PROG_TYPE_TRACING:
5129 if (eatype == BPF_TRACE_ITER)
5130 return true;
5131 break;
5132 case BPF_PROG_TYPE_SOCKET_FILTER:
5133 case BPF_PROG_TYPE_SCHED_CLS:
5134 case BPF_PROG_TYPE_SCHED_ACT:
5135 case BPF_PROG_TYPE_XDP:
5136 case BPF_PROG_TYPE_SK_REUSEPORT:
5137 case BPF_PROG_TYPE_FLOW_DISSECTOR:
5138 case BPF_PROG_TYPE_SK_LOOKUP:
5139 return true;
5140 default:
5141 break;
5142 }
5143
5144 verbose(env, "cannot update sockmap in this context\n");
5145 return false;
5146}
5147
e411901c
MF
5148static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
5149{
5150 return env->prog->jit_requested && IS_ENABLED(CONFIG_X86_64);
5151}
5152
61bd5218
JK
5153static int check_map_func_compatibility(struct bpf_verifier_env *env,
5154 struct bpf_map *map, int func_id)
35578d79 5155{
35578d79
KX
5156 if (!map)
5157 return 0;
5158
6aff67c8
AS
5159 /* We need a two way check, first is from map perspective ... */
5160 switch (map->map_type) {
5161 case BPF_MAP_TYPE_PROG_ARRAY:
5162 if (func_id != BPF_FUNC_tail_call)
5163 goto error;
5164 break;
5165 case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
5166 if (func_id != BPF_FUNC_perf_event_read &&
908432ca 5167 func_id != BPF_FUNC_perf_event_output &&
a7658e1a 5168 func_id != BPF_FUNC_skb_output &&
d831ee84
EC
5169 func_id != BPF_FUNC_perf_event_read_value &&
5170 func_id != BPF_FUNC_xdp_output)
6aff67c8
AS
5171 goto error;
5172 break;
457f4436
AN
5173 case BPF_MAP_TYPE_RINGBUF:
5174 if (func_id != BPF_FUNC_ringbuf_output &&
5175 func_id != BPF_FUNC_ringbuf_reserve &&
5176 func_id != BPF_FUNC_ringbuf_submit &&
5177 func_id != BPF_FUNC_ringbuf_discard &&
5178 func_id != BPF_FUNC_ringbuf_query)
5179 goto error;
5180 break;
6aff67c8
AS
5181 case BPF_MAP_TYPE_STACK_TRACE:
5182 if (func_id != BPF_FUNC_get_stackid)
5183 goto error;
5184 break;
4ed8ec52 5185 case BPF_MAP_TYPE_CGROUP_ARRAY:
60747ef4 5186 if (func_id != BPF_FUNC_skb_under_cgroup &&
60d20f91 5187 func_id != BPF_FUNC_current_task_under_cgroup)
4a482f34
MKL
5188 goto error;
5189 break;
cd339431 5190 case BPF_MAP_TYPE_CGROUP_STORAGE:
b741f163 5191 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
cd339431
RG
5192 if (func_id != BPF_FUNC_get_local_storage)
5193 goto error;
5194 break;
546ac1ff 5195 case BPF_MAP_TYPE_DEVMAP:
6f9d451a 5196 case BPF_MAP_TYPE_DEVMAP_HASH:
0cdbb4b0
THJ
5197 if (func_id != BPF_FUNC_redirect_map &&
5198 func_id != BPF_FUNC_map_lookup_elem)
546ac1ff
JF
5199 goto error;
5200 break;
fbfc504a
BT
5201 /* Restrict bpf side of cpumap and xskmap, open when use-cases
5202 * appear.
5203 */
6710e112
JDB
5204 case BPF_MAP_TYPE_CPUMAP:
5205 if (func_id != BPF_FUNC_redirect_map)
5206 goto error;
5207 break;
fada7fdc
JL
5208 case BPF_MAP_TYPE_XSKMAP:
5209 if (func_id != BPF_FUNC_redirect_map &&
5210 func_id != BPF_FUNC_map_lookup_elem)
5211 goto error;
5212 break;
56f668df 5213 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
bcc6b1b7 5214 case BPF_MAP_TYPE_HASH_OF_MAPS:
56f668df
MKL
5215 if (func_id != BPF_FUNC_map_lookup_elem)
5216 goto error;
16a43625 5217 break;
174a79ff
JF
5218 case BPF_MAP_TYPE_SOCKMAP:
5219 if (func_id != BPF_FUNC_sk_redirect_map &&
5220 func_id != BPF_FUNC_sock_map_update &&
4f738adb 5221 func_id != BPF_FUNC_map_delete_elem &&
9fed9000 5222 func_id != BPF_FUNC_msg_redirect_map &&
64d85290 5223 func_id != BPF_FUNC_sk_select_reuseport &&
0126240f
LB
5224 func_id != BPF_FUNC_map_lookup_elem &&
5225 !may_update_sockmap(env, func_id))
174a79ff
JF
5226 goto error;
5227 break;
81110384
JF
5228 case BPF_MAP_TYPE_SOCKHASH:
5229 if (func_id != BPF_FUNC_sk_redirect_hash &&
5230 func_id != BPF_FUNC_sock_hash_update &&
5231 func_id != BPF_FUNC_map_delete_elem &&
9fed9000 5232 func_id != BPF_FUNC_msg_redirect_hash &&
64d85290 5233 func_id != BPF_FUNC_sk_select_reuseport &&
0126240f
LB
5234 func_id != BPF_FUNC_map_lookup_elem &&
5235 !may_update_sockmap(env, func_id))
81110384
JF
5236 goto error;
5237 break;
2dbb9b9e
MKL
5238 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
5239 if (func_id != BPF_FUNC_sk_select_reuseport)
5240 goto error;
5241 break;
f1a2e44a
MV
5242 case BPF_MAP_TYPE_QUEUE:
5243 case BPF_MAP_TYPE_STACK:
5244 if (func_id != BPF_FUNC_map_peek_elem &&
5245 func_id != BPF_FUNC_map_pop_elem &&
5246 func_id != BPF_FUNC_map_push_elem)
5247 goto error;
5248 break;
6ac99e8f
MKL
5249 case BPF_MAP_TYPE_SK_STORAGE:
5250 if (func_id != BPF_FUNC_sk_storage_get &&
5251 func_id != BPF_FUNC_sk_storage_delete)
5252 goto error;
5253 break;
8ea63684
KS
5254 case BPF_MAP_TYPE_INODE_STORAGE:
5255 if (func_id != BPF_FUNC_inode_storage_get &&
5256 func_id != BPF_FUNC_inode_storage_delete)
5257 goto error;
5258 break;
4cf1bc1f
KS
5259 case BPF_MAP_TYPE_TASK_STORAGE:
5260 if (func_id != BPF_FUNC_task_storage_get &&
5261 func_id != BPF_FUNC_task_storage_delete)
5262 goto error;
5263 break;
6aff67c8
AS
5264 default:
5265 break;
5266 }
5267
5268 /* ... and second from the function itself. */
5269 switch (func_id) {
5270 case BPF_FUNC_tail_call:
5271 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
5272 goto error;
e411901c
MF
5273 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
5274 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
f4d7e40a
AS
5275 return -EINVAL;
5276 }
6aff67c8
AS
5277 break;
5278 case BPF_FUNC_perf_event_read:
5279 case BPF_FUNC_perf_event_output:
908432ca 5280 case BPF_FUNC_perf_event_read_value:
a7658e1a 5281 case BPF_FUNC_skb_output:
d831ee84 5282 case BPF_FUNC_xdp_output:
6aff67c8
AS
5283 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
5284 goto error;
5285 break;
5286 case BPF_FUNC_get_stackid:
5287 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
5288 goto error;
5289 break;
60d20f91 5290 case BPF_FUNC_current_task_under_cgroup:
747ea55e 5291 case BPF_FUNC_skb_under_cgroup:
4a482f34
MKL
5292 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
5293 goto error;
5294 break;
97f91a7c 5295 case BPF_FUNC_redirect_map:
9c270af3 5296 if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
6f9d451a 5297 map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
fbfc504a
BT
5298 map->map_type != BPF_MAP_TYPE_CPUMAP &&
5299 map->map_type != BPF_MAP_TYPE_XSKMAP)
97f91a7c
JF
5300 goto error;
5301 break;
174a79ff 5302 case BPF_FUNC_sk_redirect_map:
4f738adb 5303 case BPF_FUNC_msg_redirect_map:
81110384 5304 case BPF_FUNC_sock_map_update:
174a79ff
JF
5305 if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
5306 goto error;
5307 break;
81110384
JF
5308 case BPF_FUNC_sk_redirect_hash:
5309 case BPF_FUNC_msg_redirect_hash:
5310 case BPF_FUNC_sock_hash_update:
5311 if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
174a79ff
JF
5312 goto error;
5313 break;
cd339431 5314 case BPF_FUNC_get_local_storage:
b741f163
RG
5315 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
5316 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
cd339431
RG
5317 goto error;
5318 break;
2dbb9b9e 5319 case BPF_FUNC_sk_select_reuseport:
9fed9000
JS
5320 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
5321 map->map_type != BPF_MAP_TYPE_SOCKMAP &&
5322 map->map_type != BPF_MAP_TYPE_SOCKHASH)
2dbb9b9e
MKL
5323 goto error;
5324 break;
f1a2e44a
MV
5325 case BPF_FUNC_map_peek_elem:
5326 case BPF_FUNC_map_pop_elem:
5327 case BPF_FUNC_map_push_elem:
5328 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
5329 map->map_type != BPF_MAP_TYPE_STACK)
5330 goto error;
5331 break;
6ac99e8f
MKL
5332 case BPF_FUNC_sk_storage_get:
5333 case BPF_FUNC_sk_storage_delete:
5334 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
5335 goto error;
5336 break;
8ea63684
KS
5337 case BPF_FUNC_inode_storage_get:
5338 case BPF_FUNC_inode_storage_delete:
5339 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
5340 goto error;
5341 break;
4cf1bc1f
KS
5342 case BPF_FUNC_task_storage_get:
5343 case BPF_FUNC_task_storage_delete:
5344 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
5345 goto error;
5346 break;
6aff67c8
AS
5347 default:
5348 break;
35578d79
KX
5349 }
5350
5351 return 0;
6aff67c8 5352error:
61bd5218 5353 verbose(env, "cannot pass map_type %d into func %s#%d\n",
ebb676da 5354 map->map_type, func_id_name(func_id), func_id);
6aff67c8 5355 return -EINVAL;
35578d79
KX
5356}
5357
90133415 5358static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
435faee1
DB
5359{
5360 int count = 0;
5361
39f19ebb 5362 if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
435faee1 5363 count++;
39f19ebb 5364 if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
435faee1 5365 count++;
39f19ebb 5366 if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
435faee1 5367 count++;
39f19ebb 5368 if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
435faee1 5369 count++;
39f19ebb 5370 if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
435faee1
DB
5371 count++;
5372
90133415
DB
5373 /* We only support one arg being in raw mode at the moment,
5374 * which is sufficient for the helper functions we have
5375 * right now.
5376 */
5377 return count <= 1;
5378}
5379
5380static bool check_args_pair_invalid(enum bpf_arg_type arg_curr,
5381 enum bpf_arg_type arg_next)
5382{
5383 return (arg_type_is_mem_ptr(arg_curr) &&
5384 !arg_type_is_mem_size(arg_next)) ||
5385 (!arg_type_is_mem_ptr(arg_curr) &&
5386 arg_type_is_mem_size(arg_next));
5387}
5388
5389static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
5390{
5391 /* bpf_xxx(..., buf, len) call will access 'len'
5392 * bytes from memory 'buf'. Both arg types need
5393 * to be paired, so make sure there's no buggy
5394 * helper function specification.
5395 */
5396 if (arg_type_is_mem_size(fn->arg1_type) ||
5397 arg_type_is_mem_ptr(fn->arg5_type) ||
5398 check_args_pair_invalid(fn->arg1_type, fn->arg2_type) ||
5399 check_args_pair_invalid(fn->arg2_type, fn->arg3_type) ||
5400 check_args_pair_invalid(fn->arg3_type, fn->arg4_type) ||
5401 check_args_pair_invalid(fn->arg4_type, fn->arg5_type))
5402 return false;
5403
5404 return true;
5405}
5406
1b986589 5407static bool check_refcount_ok(const struct bpf_func_proto *fn, int func_id)
fd978bf7
JS
5408{
5409 int count = 0;
5410
1b986589 5411 if (arg_type_may_be_refcounted(fn->arg1_type))
fd978bf7 5412 count++;
1b986589 5413 if (arg_type_may_be_refcounted(fn->arg2_type))
fd978bf7 5414 count++;
1b986589 5415 if (arg_type_may_be_refcounted(fn->arg3_type))
fd978bf7 5416 count++;
1b986589 5417 if (arg_type_may_be_refcounted(fn->arg4_type))
fd978bf7 5418 count++;
1b986589 5419 if (arg_type_may_be_refcounted(fn->arg5_type))
fd978bf7
JS
5420 count++;
5421
1b986589
MKL
5422 /* A reference acquiring function cannot acquire
5423 * another refcounted ptr.
5424 */
64d85290 5425 if (may_be_acquire_function(func_id) && count)
1b986589
MKL
5426 return false;
5427
fd978bf7
JS
5428 /* We only support one arg being unreferenced at the moment,
5429 * which is sufficient for the helper functions we have right now.
5430 */
5431 return count <= 1;
5432}
5433
9436ef6e
LB
5434static bool check_btf_id_ok(const struct bpf_func_proto *fn)
5435{
5436 int i;
5437
1df8f55a 5438 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
9436ef6e
LB
5439 if (fn->arg_type[i] == ARG_PTR_TO_BTF_ID && !fn->arg_btf_id[i])
5440 return false;
5441
1df8f55a
MKL
5442 if (fn->arg_type[i] != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i])
5443 return false;
5444 }
5445
9436ef6e
LB
5446 return true;
5447}
5448
1b986589 5449static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
90133415
DB
5450{
5451 return check_raw_mode_ok(fn) &&
fd978bf7 5452 check_arg_pair_ok(fn) &&
9436ef6e 5453 check_btf_id_ok(fn) &&
1b986589 5454 check_refcount_ok(fn, func_id) ? 0 : -EINVAL;
435faee1
DB
5455}
5456
de8f3a83
DB
5457/* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
5458 * are now invalid, so turn them into unknown SCALAR_VALUE.
f1174f77 5459 */
f4d7e40a
AS
5460static void __clear_all_pkt_pointers(struct bpf_verifier_env *env,
5461 struct bpf_func_state *state)
969bf05e 5462{
58e2af8b 5463 struct bpf_reg_state *regs = state->regs, *reg;
969bf05e
AS
5464 int i;
5465
5466 for (i = 0; i < MAX_BPF_REG; i++)
de8f3a83 5467 if (reg_is_pkt_pointer_any(&regs[i]))
61bd5218 5468 mark_reg_unknown(env, regs, i);
969bf05e 5469
f3709f69
JS
5470 bpf_for_each_spilled_reg(i, state, reg) {
5471 if (!reg)
969bf05e 5472 continue;
de8f3a83 5473 if (reg_is_pkt_pointer_any(reg))
f54c7898 5474 __mark_reg_unknown(env, reg);
969bf05e
AS
5475 }
5476}
5477
f4d7e40a
AS
5478static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
5479{
5480 struct bpf_verifier_state *vstate = env->cur_state;
5481 int i;
5482
5483 for (i = 0; i <= vstate->curframe; i++)
5484 __clear_all_pkt_pointers(env, vstate->frame[i]);
5485}
5486
6d94e741
AS
5487enum {
5488 AT_PKT_END = -1,
5489 BEYOND_PKT_END = -2,
5490};
5491
5492static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
5493{
5494 struct bpf_func_state *state = vstate->frame[vstate->curframe];
5495 struct bpf_reg_state *reg = &state->regs[regn];
5496
5497 if (reg->type != PTR_TO_PACKET)
5498 /* PTR_TO_PACKET_META is not supported yet */
5499 return;
5500
5501 /* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
5502 * How far beyond pkt_end it goes is unknown.
5503 * if (!range_open) it's the case of pkt >= pkt_end
5504 * if (range_open) it's the case of pkt > pkt_end
5505 * hence this pointer is at least 1 byte bigger than pkt_end
5506 */
5507 if (range_open)
5508 reg->range = BEYOND_PKT_END;
5509 else
5510 reg->range = AT_PKT_END;
5511}
5512
fd978bf7 5513static void release_reg_references(struct bpf_verifier_env *env,
1b986589
MKL
5514 struct bpf_func_state *state,
5515 int ref_obj_id)
fd978bf7
JS
5516{
5517 struct bpf_reg_state *regs = state->regs, *reg;
5518 int i;
5519
5520 for (i = 0; i < MAX_BPF_REG; i++)
1b986589 5521 if (regs[i].ref_obj_id == ref_obj_id)
fd978bf7
JS
5522 mark_reg_unknown(env, regs, i);
5523
5524 bpf_for_each_spilled_reg(i, state, reg) {
5525 if (!reg)
5526 continue;
1b986589 5527 if (reg->ref_obj_id == ref_obj_id)
f54c7898 5528 __mark_reg_unknown(env, reg);
fd978bf7
JS
5529 }
5530}
5531
5532/* The pointer with the specified id has released its reference to kernel
5533 * resources. Identify all copies of the same pointer and clear the reference.
5534 */
5535static int release_reference(struct bpf_verifier_env *env,
1b986589 5536 int ref_obj_id)
fd978bf7
JS
5537{
5538 struct bpf_verifier_state *vstate = env->cur_state;
1b986589 5539 int err;
fd978bf7
JS
5540 int i;
5541
1b986589
MKL
5542 err = release_reference_state(cur_func(env), ref_obj_id);
5543 if (err)
5544 return err;
5545
fd978bf7 5546 for (i = 0; i <= vstate->curframe; i++)
1b986589 5547 release_reg_references(env, vstate->frame[i], ref_obj_id);
fd978bf7 5548
1b986589 5549 return 0;
fd978bf7
JS
5550}
5551
51c39bb1
AS
5552static void clear_caller_saved_regs(struct bpf_verifier_env *env,
5553 struct bpf_reg_state *regs)
5554{
5555 int i;
5556
5557 /* after the call registers r0 - r5 were scratched */
5558 for (i = 0; i < CALLER_SAVED_REGS; i++) {
5559 mark_reg_not_init(env, regs, caller_saved[i]);
5560 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
5561 }
5562}
5563
14351375
YS
5564typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
5565 struct bpf_func_state *caller,
5566 struct bpf_func_state *callee,
5567 int insn_idx);
5568
5569static int __check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
5570 int *insn_idx, int subprog,
5571 set_callee_state_fn set_callee_state_cb)
f4d7e40a
AS
5572{
5573 struct bpf_verifier_state *state = env->cur_state;
51c39bb1 5574 struct bpf_func_info_aux *func_info_aux;
f4d7e40a 5575 struct bpf_func_state *caller, *callee;
14351375 5576 int err;
51c39bb1 5577 bool is_global = false;
f4d7e40a 5578
aada9ce6 5579 if (state->curframe + 1 >= MAX_CALL_FRAMES) {
f4d7e40a 5580 verbose(env, "the call stack of %d frames is too deep\n",
aada9ce6 5581 state->curframe + 2);
f4d7e40a
AS
5582 return -E2BIG;
5583 }
5584
f4d7e40a
AS
5585 caller = state->frame[state->curframe];
5586 if (state->frame[state->curframe + 1]) {
5587 verbose(env, "verifier bug. Frame %d already allocated\n",
5588 state->curframe + 1);
5589 return -EFAULT;
5590 }
5591
51c39bb1
AS
5592 func_info_aux = env->prog->aux->func_info_aux;
5593 if (func_info_aux)
5594 is_global = func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
34747c41 5595 err = btf_check_subprog_arg_match(env, subprog, caller->regs);
51c39bb1
AS
5596 if (err == -EFAULT)
5597 return err;
5598 if (is_global) {
5599 if (err) {
5600 verbose(env, "Caller passes invalid args into func#%d\n",
5601 subprog);
5602 return err;
5603 } else {
5604 if (env->log.level & BPF_LOG_LEVEL)
5605 verbose(env,
5606 "Func#%d is global and valid. Skipping.\n",
5607 subprog);
5608 clear_caller_saved_regs(env, caller->regs);
5609
45159b27 5610 /* All global functions return a 64-bit SCALAR_VALUE */
51c39bb1 5611 mark_reg_unknown(env, caller->regs, BPF_REG_0);
45159b27 5612 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
51c39bb1
AS
5613
5614 /* continue with next insn after call */
5615 return 0;
5616 }
5617 }
5618
f4d7e40a
AS
5619 callee = kzalloc(sizeof(*callee), GFP_KERNEL);
5620 if (!callee)
5621 return -ENOMEM;
5622 state->frame[state->curframe + 1] = callee;
5623
5624 /* callee cannot access r0, r6 - r9 for reading and has to write
5625 * into its own stack before reading from it.
5626 * callee can read/write into caller's stack
5627 */
5628 init_func_state(env, callee,
5629 /* remember the callsite, it will be used by bpf_exit */
5630 *insn_idx /* callsite */,
5631 state->curframe + 1 /* frameno within this callchain */,
f910cefa 5632 subprog /* subprog number within this prog */);
f4d7e40a 5633
fd978bf7
JS
5634 /* Transfer references to the callee */
5635 err = transfer_reference_state(callee, caller);
5636 if (err)
5637 return err;
5638
14351375
YS
5639 err = set_callee_state_cb(env, caller, callee, *insn_idx);
5640 if (err)
5641 return err;
f4d7e40a 5642
51c39bb1 5643 clear_caller_saved_regs(env, caller->regs);
f4d7e40a
AS
5644
5645 /* only increment it after check_reg_arg() finished */
5646 state->curframe++;
5647
5648 /* and go analyze first insn of the callee */
14351375 5649 *insn_idx = env->subprog_info[subprog].start - 1;
f4d7e40a 5650
06ee7115 5651 if (env->log.level & BPF_LOG_LEVEL) {
f4d7e40a
AS
5652 verbose(env, "caller:\n");
5653 print_verifier_state(env, caller);
5654 verbose(env, "callee:\n");
5655 print_verifier_state(env, callee);
5656 }
5657 return 0;
5658}
5659
314ee05e
YS
5660int map_set_for_each_callback_args(struct bpf_verifier_env *env,
5661 struct bpf_func_state *caller,
5662 struct bpf_func_state *callee)
5663{
5664 /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
5665 * void *callback_ctx, u64 flags);
5666 * callback_fn(struct bpf_map *map, void *key, void *value,
5667 * void *callback_ctx);
5668 */
5669 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
5670
5671 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
5672 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
5673 callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
5674
5675 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
5676 __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
5677 callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
5678
5679 /* pointer to stack or null */
5680 callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
5681
5682 /* unused */
5683 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
5684 return 0;
5685}
5686
14351375
YS
5687static int set_callee_state(struct bpf_verifier_env *env,
5688 struct bpf_func_state *caller,
5689 struct bpf_func_state *callee, int insn_idx)
5690{
5691 int i;
5692
5693 /* copy r1 - r5 args that callee can access. The copy includes parent
5694 * pointers, which connects us up to the liveness chain
5695 */
5696 for (i = BPF_REG_1; i <= BPF_REG_5; i++)
5697 callee->regs[i] = caller->regs[i];
5698 return 0;
5699}
5700
5701static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
5702 int *insn_idx)
5703{
5704 int subprog, target_insn;
5705
5706 target_insn = *insn_idx + insn->imm + 1;
5707 subprog = find_subprog(env, target_insn);
5708 if (subprog < 0) {
5709 verbose(env, "verifier bug. No program starts at insn %d\n",
5710 target_insn);
5711 return -EFAULT;
5712 }
5713
5714 return __check_func_call(env, insn, insn_idx, subprog, set_callee_state);
5715}
5716
69c087ba
YS
5717static int set_map_elem_callback_state(struct bpf_verifier_env *env,
5718 struct bpf_func_state *caller,
5719 struct bpf_func_state *callee,
5720 int insn_idx)
5721{
5722 struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
5723 struct bpf_map *map;
5724 int err;
5725
5726 if (bpf_map_ptr_poisoned(insn_aux)) {
5727 verbose(env, "tail_call abusing map_ptr\n");
5728 return -EINVAL;
5729 }
5730
5731 map = BPF_MAP_PTR(insn_aux->map_ptr_state);
5732 if (!map->ops->map_set_for_each_callback_args ||
5733 !map->ops->map_for_each_callback) {
5734 verbose(env, "callback function not allowed for map\n");
5735 return -ENOTSUPP;
5736 }
5737
5738 err = map->ops->map_set_for_each_callback_args(env, caller, callee);
5739 if (err)
5740 return err;
5741
5742 callee->in_callback_fn = true;
5743 return 0;
5744}
5745
f4d7e40a
AS
5746static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
5747{
5748 struct bpf_verifier_state *state = env->cur_state;
5749 struct bpf_func_state *caller, *callee;
5750 struct bpf_reg_state *r0;
fd978bf7 5751 int err;
f4d7e40a
AS
5752
5753 callee = state->frame[state->curframe];
5754 r0 = &callee->regs[BPF_REG_0];
5755 if (r0->type == PTR_TO_STACK) {
5756 /* technically it's ok to return caller's stack pointer
5757 * (or caller's caller's pointer) back to the caller,
5758 * since these pointers are valid. Only current stack
5759 * pointer will be invalid as soon as function exits,
5760 * but let's be conservative
5761 */
5762 verbose(env, "cannot return stack pointer to the caller\n");
5763 return -EINVAL;
5764 }
5765
5766 state->curframe--;
5767 caller = state->frame[state->curframe];
69c087ba
YS
5768 if (callee->in_callback_fn) {
5769 /* enforce R0 return value range [0, 1]. */
5770 struct tnum range = tnum_range(0, 1);
5771
5772 if (r0->type != SCALAR_VALUE) {
5773 verbose(env, "R0 not a scalar value\n");
5774 return -EACCES;
5775 }
5776 if (!tnum_in(range, r0->var_off)) {
5777 verbose_invalid_scalar(env, r0, &range, "callback return", "R0");
5778 return -EINVAL;
5779 }
5780 } else {
5781 /* return to the caller whatever r0 had in the callee */
5782 caller->regs[BPF_REG_0] = *r0;
5783 }
f4d7e40a 5784
fd978bf7
JS
5785 /* Transfer references to the caller */
5786 err = transfer_reference_state(caller, callee);
5787 if (err)
5788 return err;
5789
f4d7e40a 5790 *insn_idx = callee->callsite + 1;
06ee7115 5791 if (env->log.level & BPF_LOG_LEVEL) {
f4d7e40a
AS
5792 verbose(env, "returning from callee:\n");
5793 print_verifier_state(env, callee);
5794 verbose(env, "to caller at %d:\n", *insn_idx);
5795 print_verifier_state(env, caller);
5796 }
5797 /* clear everything in the callee */
5798 free_func_state(callee);
5799 state->frame[state->curframe + 1] = NULL;
5800 return 0;
5801}
5802
849fa506
YS
5803static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
5804 int func_id,
5805 struct bpf_call_arg_meta *meta)
5806{
5807 struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
5808
5809 if (ret_type != RET_INTEGER ||
5810 (func_id != BPF_FUNC_get_stack &&
fd0b88f7 5811 func_id != BPF_FUNC_get_task_stack &&
47cc0ed5
DB
5812 func_id != BPF_FUNC_probe_read_str &&
5813 func_id != BPF_FUNC_probe_read_kernel_str &&
5814 func_id != BPF_FUNC_probe_read_user_str))
849fa506
YS
5815 return;
5816
10060503 5817 ret_reg->smax_value = meta->msize_max_value;
fa123ac0 5818 ret_reg->s32_max_value = meta->msize_max_value;
b0270958
AS
5819 ret_reg->smin_value = -MAX_ERRNO;
5820 ret_reg->s32_min_value = -MAX_ERRNO;
849fa506
YS
5821 __reg_deduce_bounds(ret_reg);
5822 __reg_bound_offset(ret_reg);
10060503 5823 __update_reg_bounds(ret_reg);
849fa506
YS
5824}
5825
c93552c4
DB
5826static int
5827record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
5828 int func_id, int insn_idx)
5829{
5830 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
591fe988 5831 struct bpf_map *map = meta->map_ptr;
c93552c4
DB
5832
5833 if (func_id != BPF_FUNC_tail_call &&
09772d92
DB
5834 func_id != BPF_FUNC_map_lookup_elem &&
5835 func_id != BPF_FUNC_map_update_elem &&
f1a2e44a
MV
5836 func_id != BPF_FUNC_map_delete_elem &&
5837 func_id != BPF_FUNC_map_push_elem &&
5838 func_id != BPF_FUNC_map_pop_elem &&
69c087ba 5839 func_id != BPF_FUNC_map_peek_elem &&
e6a4750f
BT
5840 func_id != BPF_FUNC_for_each_map_elem &&
5841 func_id != BPF_FUNC_redirect_map)
c93552c4 5842 return 0;
09772d92 5843
591fe988 5844 if (map == NULL) {
c93552c4
DB
5845 verbose(env, "kernel subsystem misconfigured verifier\n");
5846 return -EINVAL;
5847 }
5848
591fe988
DB
5849 /* In case of read-only, some additional restrictions
5850 * need to be applied in order to prevent altering the
5851 * state of the map from program side.
5852 */
5853 if ((map->map_flags & BPF_F_RDONLY_PROG) &&
5854 (func_id == BPF_FUNC_map_delete_elem ||
5855 func_id == BPF_FUNC_map_update_elem ||
5856 func_id == BPF_FUNC_map_push_elem ||
5857 func_id == BPF_FUNC_map_pop_elem)) {
5858 verbose(env, "write into map forbidden\n");
5859 return -EACCES;
5860 }
5861
d2e4c1e6 5862 if (!BPF_MAP_PTR(aux->map_ptr_state))
c93552c4 5863 bpf_map_ptr_store(aux, meta->map_ptr,
2c78ee89 5864 !meta->map_ptr->bypass_spec_v1);
d2e4c1e6 5865 else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
c93552c4 5866 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
2c78ee89 5867 !meta->map_ptr->bypass_spec_v1);
c93552c4
DB
5868 return 0;
5869}
5870
d2e4c1e6
DB
5871static int
5872record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
5873 int func_id, int insn_idx)
5874{
5875 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
5876 struct bpf_reg_state *regs = cur_regs(env), *reg;
5877 struct bpf_map *map = meta->map_ptr;
5878 struct tnum range;
5879 u64 val;
cc52d914 5880 int err;
d2e4c1e6
DB
5881
5882 if (func_id != BPF_FUNC_tail_call)
5883 return 0;
5884 if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
5885 verbose(env, "kernel subsystem misconfigured verifier\n");
5886 return -EINVAL;
5887 }
5888
5889 range = tnum_range(0, map->max_entries - 1);
5890 reg = &regs[BPF_REG_3];
5891
5892 if (!register_is_const(reg) || !tnum_in(range, reg->var_off)) {
5893 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
5894 return 0;
5895 }
5896
cc52d914
DB
5897 err = mark_chain_precision(env, BPF_REG_3);
5898 if (err)
5899 return err;
5900
d2e4c1e6
DB
5901 val = reg->var_off.value;
5902 if (bpf_map_key_unseen(aux))
5903 bpf_map_key_store(aux, val);
5904 else if (!bpf_map_key_poisoned(aux) &&
5905 bpf_map_key_immediate(aux) != val)
5906 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
5907 return 0;
5908}
5909
fd978bf7
JS
5910static int check_reference_leak(struct bpf_verifier_env *env)
5911{
5912 struct bpf_func_state *state = cur_func(env);
5913 int i;
5914
5915 for (i = 0; i < state->acquired_refs; i++) {
5916 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
5917 state->refs[i].id, state->refs[i].insn_idx);
5918 }
5919 return state->acquired_refs ? -EINVAL : 0;
5920}
5921
7b15523a
FR
5922static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
5923 struct bpf_reg_state *regs)
5924{
5925 struct bpf_reg_state *fmt_reg = &regs[BPF_REG_3];
5926 struct bpf_reg_state *data_len_reg = &regs[BPF_REG_5];
5927 struct bpf_map *fmt_map = fmt_reg->map_ptr;
5928 int err, fmt_map_off, num_args;
5929 u64 fmt_addr;
5930 char *fmt;
5931
5932 /* data must be an array of u64 */
5933 if (data_len_reg->var_off.value % 8)
5934 return -EINVAL;
5935 num_args = data_len_reg->var_off.value / 8;
5936
5937 /* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
5938 * and map_direct_value_addr is set.
5939 */
5940 fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
5941 err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
5942 fmt_map_off);
8e8ee109
FR
5943 if (err) {
5944 verbose(env, "verifier bug\n");
5945 return -EFAULT;
5946 }
7b15523a
FR
5947 fmt = (char *)(long)fmt_addr + fmt_map_off;
5948
5949 /* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
5950 * can focus on validating the format specifiers.
5951 */
5952 err = bpf_printf_prepare(fmt, UINT_MAX, NULL, NULL, NULL, num_args);
5953 if (err < 0)
5954 verbose(env, "Invalid format string\n");
5955
5956 return err;
5957}
5958
69c087ba
YS
5959static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
5960 int *insn_idx_p)
17a52670 5961{
17a52670 5962 const struct bpf_func_proto *fn = NULL;
638f5b90 5963 struct bpf_reg_state *regs;
33ff9823 5964 struct bpf_call_arg_meta meta;
69c087ba 5965 int insn_idx = *insn_idx_p;
969bf05e 5966 bool changes_data;
69c087ba 5967 int i, err, func_id;
17a52670
AS
5968
5969 /* find function prototype */
69c087ba 5970 func_id = insn->imm;
17a52670 5971 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
61bd5218
JK
5972 verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
5973 func_id);
17a52670
AS
5974 return -EINVAL;
5975 }
5976
00176a34 5977 if (env->ops->get_func_proto)
5e43f899 5978 fn = env->ops->get_func_proto(func_id, env->prog);
17a52670 5979 if (!fn) {
61bd5218
JK
5980 verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
5981 func_id);
17a52670
AS
5982 return -EINVAL;
5983 }
5984
5985 /* eBPF programs must be GPL compatible to use GPL-ed functions */
24701ece 5986 if (!env->prog->gpl_compatible && fn->gpl_only) {
3fe2867c 5987 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
17a52670
AS
5988 return -EINVAL;
5989 }
5990
eae2e83e
JO
5991 if (fn->allowed && !fn->allowed(env->prog)) {
5992 verbose(env, "helper call is not allowed in probe\n");
5993 return -EINVAL;
5994 }
5995
04514d13 5996 /* With LD_ABS/IND some JITs save/restore skb from r1. */
17bedab2 5997 changes_data = bpf_helper_changes_pkt_data(fn->func);
04514d13
DB
5998 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
5999 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
6000 func_id_name(func_id), func_id);
6001 return -EINVAL;
6002 }
969bf05e 6003
33ff9823 6004 memset(&meta, 0, sizeof(meta));
36bbef52 6005 meta.pkt_access = fn->pkt_access;
33ff9823 6006
1b986589 6007 err = check_func_proto(fn, func_id);
435faee1 6008 if (err) {
61bd5218 6009 verbose(env, "kernel subsystem misconfigured func %s#%d\n",
ebb676da 6010 func_id_name(func_id), func_id);
435faee1
DB
6011 return err;
6012 }
6013
d83525ca 6014 meta.func_id = func_id;
17a52670 6015 /* check args */
523a4cf4 6016 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
af7ec138 6017 err = check_func_arg(env, i, &meta, fn);
a7658e1a
AS
6018 if (err)
6019 return err;
6020 }
17a52670 6021
c93552c4
DB
6022 err = record_func_map(env, &meta, func_id, insn_idx);
6023 if (err)
6024 return err;
6025
d2e4c1e6
DB
6026 err = record_func_key(env, &meta, func_id, insn_idx);
6027 if (err)
6028 return err;
6029
435faee1
DB
6030 /* Mark slots with STACK_MISC in case of raw mode, stack offset
6031 * is inferred from register state.
6032 */
6033 for (i = 0; i < meta.access_size; i++) {
ca369602
DB
6034 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
6035 BPF_WRITE, -1, false);
435faee1
DB
6036 if (err)
6037 return err;
6038 }
6039
fd978bf7
JS
6040 if (func_id == BPF_FUNC_tail_call) {
6041 err = check_reference_leak(env);
6042 if (err) {
6043 verbose(env, "tail_call would lead to reference leak\n");
6044 return err;
6045 }
6046 } else if (is_release_function(func_id)) {
1b986589 6047 err = release_reference(env, meta.ref_obj_id);
46f8bc92
MKL
6048 if (err) {
6049 verbose(env, "func %s#%d reference has not been acquired before\n",
6050 func_id_name(func_id), func_id);
fd978bf7 6051 return err;
46f8bc92 6052 }
fd978bf7
JS
6053 }
6054
638f5b90 6055 regs = cur_regs(env);
cd339431
RG
6056
6057 /* check that flags argument in get_local_storage(map, flags) is 0,
6058 * this is required because get_local_storage() can't return an error.
6059 */
6060 if (func_id == BPF_FUNC_get_local_storage &&
6061 !register_is_null(&regs[BPF_REG_2])) {
6062 verbose(env, "get_local_storage() doesn't support non-zero flags\n");
6063 return -EINVAL;
6064 }
6065
69c087ba
YS
6066 if (func_id == BPF_FUNC_for_each_map_elem) {
6067 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
6068 set_map_elem_callback_state);
6069 if (err < 0)
6070 return -EINVAL;
6071 }
6072
7b15523a
FR
6073 if (func_id == BPF_FUNC_snprintf) {
6074 err = check_bpf_snprintf_call(env, regs);
6075 if (err < 0)
6076 return err;
6077 }
6078
17a52670 6079 /* reset caller saved regs */
dc503a8a 6080 for (i = 0; i < CALLER_SAVED_REGS; i++) {
61bd5218 6081 mark_reg_not_init(env, regs, caller_saved[i]);
dc503a8a
EC
6082 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
6083 }
17a52670 6084
5327ed3d
JW
6085 /* helper call returns 64-bit value. */
6086 regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
6087
dc503a8a 6088 /* update return register (already marked as written above) */
17a52670 6089 if (fn->ret_type == RET_INTEGER) {
f1174f77 6090 /* sets type to SCALAR_VALUE */
61bd5218 6091 mark_reg_unknown(env, regs, BPF_REG_0);
17a52670
AS
6092 } else if (fn->ret_type == RET_VOID) {
6093 regs[BPF_REG_0].type = NOT_INIT;
3e6a4b3e
RG
6094 } else if (fn->ret_type == RET_PTR_TO_MAP_VALUE_OR_NULL ||
6095 fn->ret_type == RET_PTR_TO_MAP_VALUE) {
f1174f77 6096 /* There is no offset yet applied, variable or fixed */
61bd5218 6097 mark_reg_known_zero(env, regs, BPF_REG_0);
17a52670
AS
6098 /* remember map_ptr, so that check_map_access()
6099 * can check 'value_size' boundary of memory access
6100 * to map element returned from bpf_map_lookup_elem()
6101 */
33ff9823 6102 if (meta.map_ptr == NULL) {
61bd5218
JK
6103 verbose(env,
6104 "kernel subsystem misconfigured verifier\n");
17a52670
AS
6105 return -EINVAL;
6106 }
33ff9823 6107 regs[BPF_REG_0].map_ptr = meta.map_ptr;
4d31f301
DB
6108 if (fn->ret_type == RET_PTR_TO_MAP_VALUE) {
6109 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE;
e16d2f1a
AS
6110 if (map_value_has_spin_lock(meta.map_ptr))
6111 regs[BPF_REG_0].id = ++env->id_gen;
4d31f301
DB
6112 } else {
6113 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE_OR_NULL;
4d31f301 6114 }
c64b7983
JS
6115 } else if (fn->ret_type == RET_PTR_TO_SOCKET_OR_NULL) {
6116 mark_reg_known_zero(env, regs, BPF_REG_0);
6117 regs[BPF_REG_0].type = PTR_TO_SOCKET_OR_NULL;
85a51f8c
LB
6118 } else if (fn->ret_type == RET_PTR_TO_SOCK_COMMON_OR_NULL) {
6119 mark_reg_known_zero(env, regs, BPF_REG_0);
6120 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON_OR_NULL;
655a51e5
MKL
6121 } else if (fn->ret_type == RET_PTR_TO_TCP_SOCK_OR_NULL) {
6122 mark_reg_known_zero(env, regs, BPF_REG_0);
6123 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK_OR_NULL;
457f4436
AN
6124 } else if (fn->ret_type == RET_PTR_TO_ALLOC_MEM_OR_NULL) {
6125 mark_reg_known_zero(env, regs, BPF_REG_0);
6126 regs[BPF_REG_0].type = PTR_TO_MEM_OR_NULL;
457f4436 6127 regs[BPF_REG_0].mem_size = meta.mem_size;
63d9b80d
HL
6128 } else if (fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID_OR_NULL ||
6129 fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID) {
eaa6bcb7
HL
6130 const struct btf_type *t;
6131
6132 mark_reg_known_zero(env, regs, BPF_REG_0);
22dc4a0f 6133 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
eaa6bcb7
HL
6134 if (!btf_type_is_struct(t)) {
6135 u32 tsize;
6136 const struct btf_type *ret;
6137 const char *tname;
6138
6139 /* resolve the type size of ksym. */
22dc4a0f 6140 ret = btf_resolve_size(meta.ret_btf, t, &tsize);
eaa6bcb7 6141 if (IS_ERR(ret)) {
22dc4a0f 6142 tname = btf_name_by_offset(meta.ret_btf, t->name_off);
eaa6bcb7
HL
6143 verbose(env, "unable to resolve the size of type '%s': %ld\n",
6144 tname, PTR_ERR(ret));
6145 return -EINVAL;
6146 }
63d9b80d
HL
6147 regs[BPF_REG_0].type =
6148 fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID ?
6149 PTR_TO_MEM : PTR_TO_MEM_OR_NULL;
eaa6bcb7
HL
6150 regs[BPF_REG_0].mem_size = tsize;
6151 } else {
63d9b80d
HL
6152 regs[BPF_REG_0].type =
6153 fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID ?
6154 PTR_TO_BTF_ID : PTR_TO_BTF_ID_OR_NULL;
22dc4a0f 6155 regs[BPF_REG_0].btf = meta.ret_btf;
eaa6bcb7
HL
6156 regs[BPF_REG_0].btf_id = meta.ret_btf_id;
6157 }
3ca1032a
KS
6158 } else if (fn->ret_type == RET_PTR_TO_BTF_ID_OR_NULL ||
6159 fn->ret_type == RET_PTR_TO_BTF_ID) {
af7ec138
YS
6160 int ret_btf_id;
6161
6162 mark_reg_known_zero(env, regs, BPF_REG_0);
3ca1032a
KS
6163 regs[BPF_REG_0].type = fn->ret_type == RET_PTR_TO_BTF_ID ?
6164 PTR_TO_BTF_ID :
6165 PTR_TO_BTF_ID_OR_NULL;
af7ec138
YS
6166 ret_btf_id = *fn->ret_btf_id;
6167 if (ret_btf_id == 0) {
6168 verbose(env, "invalid return type %d of func %s#%d\n",
6169 fn->ret_type, func_id_name(func_id), func_id);
6170 return -EINVAL;
6171 }
22dc4a0f
AN
6172 /* current BPF helper definitions are only coming from
6173 * built-in code with type IDs from vmlinux BTF
6174 */
6175 regs[BPF_REG_0].btf = btf_vmlinux;
af7ec138 6176 regs[BPF_REG_0].btf_id = ret_btf_id;
17a52670 6177 } else {
61bd5218 6178 verbose(env, "unknown return type %d of func %s#%d\n",
ebb676da 6179 fn->ret_type, func_id_name(func_id), func_id);
17a52670
AS
6180 return -EINVAL;
6181 }
04fd61ab 6182
93c230e3
MKL
6183 if (reg_type_may_be_null(regs[BPF_REG_0].type))
6184 regs[BPF_REG_0].id = ++env->id_gen;
6185
0f3adc28 6186 if (is_ptr_cast_function(func_id)) {
1b986589
MKL
6187 /* For release_reference() */
6188 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
64d85290 6189 } else if (is_acquire_function(func_id, meta.map_ptr)) {
0f3adc28
LB
6190 int id = acquire_reference_state(env, insn_idx);
6191
6192 if (id < 0)
6193 return id;
6194 /* For mark_ptr_or_null_reg() */
6195 regs[BPF_REG_0].id = id;
6196 /* For release_reference() */
6197 regs[BPF_REG_0].ref_obj_id = id;
6198 }
1b986589 6199
849fa506
YS
6200 do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
6201
61bd5218 6202 err = check_map_func_compatibility(env, meta.map_ptr, func_id);
35578d79
KX
6203 if (err)
6204 return err;
04fd61ab 6205
fa28dcb8
SL
6206 if ((func_id == BPF_FUNC_get_stack ||
6207 func_id == BPF_FUNC_get_task_stack) &&
6208 !env->prog->has_callchain_buf) {
c195651e
YS
6209 const char *err_str;
6210
6211#ifdef CONFIG_PERF_EVENTS
6212 err = get_callchain_buffers(sysctl_perf_event_max_stack);
6213 err_str = "cannot get callchain buffer for func %s#%d\n";
6214#else
6215 err = -ENOTSUPP;
6216 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
6217#endif
6218 if (err) {
6219 verbose(env, err_str, func_id_name(func_id), func_id);
6220 return err;
6221 }
6222
6223 env->prog->has_callchain_buf = true;
6224 }
6225
5d99cb2c
SL
6226 if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
6227 env->prog->call_get_stack = true;
6228
969bf05e
AS
6229 if (changes_data)
6230 clear_all_pkt_pointers(env);
6231 return 0;
6232}
6233
e6ac2450
MKL
6234/* mark_btf_func_reg_size() is used when the reg size is determined by
6235 * the BTF func_proto's return value size and argument.
6236 */
6237static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
6238 size_t reg_size)
6239{
6240 struct bpf_reg_state *reg = &cur_regs(env)[regno];
6241
6242 if (regno == BPF_REG_0) {
6243 /* Function return value */
6244 reg->live |= REG_LIVE_WRITTEN;
6245 reg->subreg_def = reg_size == sizeof(u64) ?
6246 DEF_NOT_SUBREG : env->insn_idx + 1;
6247 } else {
6248 /* Function argument */
6249 if (reg_size == sizeof(u64)) {
6250 mark_insn_zext(env, reg);
6251 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
6252 } else {
6253 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
6254 }
6255 }
6256}
6257
6258static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn)
6259{
6260 const struct btf_type *t, *func, *func_proto, *ptr_type;
6261 struct bpf_reg_state *regs = cur_regs(env);
6262 const char *func_name, *ptr_type_name;
6263 u32 i, nargs, func_id, ptr_type_id;
6264 const struct btf_param *args;
6265 int err;
6266
6267 func_id = insn->imm;
6268 func = btf_type_by_id(btf_vmlinux, func_id);
6269 func_name = btf_name_by_offset(btf_vmlinux, func->name_off);
6270 func_proto = btf_type_by_id(btf_vmlinux, func->type);
6271
6272 if (!env->ops->check_kfunc_call ||
6273 !env->ops->check_kfunc_call(func_id)) {
6274 verbose(env, "calling kernel function %s is not allowed\n",
6275 func_name);
6276 return -EACCES;
6277 }
6278
6279 /* Check the arguments */
6280 err = btf_check_kfunc_arg_match(env, btf_vmlinux, func_id, regs);
6281 if (err)
6282 return err;
6283
6284 for (i = 0; i < CALLER_SAVED_REGS; i++)
6285 mark_reg_not_init(env, regs, caller_saved[i]);
6286
6287 /* Check return type */
6288 t = btf_type_skip_modifiers(btf_vmlinux, func_proto->type, NULL);
6289 if (btf_type_is_scalar(t)) {
6290 mark_reg_unknown(env, regs, BPF_REG_0);
6291 mark_btf_func_reg_size(env, BPF_REG_0, t->size);
6292 } else if (btf_type_is_ptr(t)) {
6293 ptr_type = btf_type_skip_modifiers(btf_vmlinux, t->type,
6294 &ptr_type_id);
6295 if (!btf_type_is_struct(ptr_type)) {
6296 ptr_type_name = btf_name_by_offset(btf_vmlinux,
6297 ptr_type->name_off);
6298 verbose(env, "kernel function %s returns pointer type %s %s is not supported\n",
6299 func_name, btf_type_str(ptr_type),
6300 ptr_type_name);
6301 return -EINVAL;
6302 }
6303 mark_reg_known_zero(env, regs, BPF_REG_0);
6304 regs[BPF_REG_0].btf = btf_vmlinux;
6305 regs[BPF_REG_0].type = PTR_TO_BTF_ID;
6306 regs[BPF_REG_0].btf_id = ptr_type_id;
6307 mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
6308 } /* else { add_kfunc_call() ensures it is btf_type_is_void(t) } */
6309
6310 nargs = btf_type_vlen(func_proto);
6311 args = (const struct btf_param *)(func_proto + 1);
6312 for (i = 0; i < nargs; i++) {
6313 u32 regno = i + 1;
6314
6315 t = btf_type_skip_modifiers(btf_vmlinux, args[i].type, NULL);
6316 if (btf_type_is_ptr(t))
6317 mark_btf_func_reg_size(env, regno, sizeof(void *));
6318 else
6319 /* scalar. ensured by btf_check_kfunc_arg_match() */
6320 mark_btf_func_reg_size(env, regno, t->size);
6321 }
6322
6323 return 0;
6324}
6325
b03c9f9f
EC
6326static bool signed_add_overflows(s64 a, s64 b)
6327{
6328 /* Do the add in u64, where overflow is well-defined */
6329 s64 res = (s64)((u64)a + (u64)b);
6330
6331 if (b < 0)
6332 return res > a;
6333 return res < a;
6334}
6335
bc895e8b 6336static bool signed_add32_overflows(s32 a, s32 b)
3f50f132
JF
6337{
6338 /* Do the add in u32, where overflow is well-defined */
6339 s32 res = (s32)((u32)a + (u32)b);
6340
6341 if (b < 0)
6342 return res > a;
6343 return res < a;
6344}
6345
bc895e8b 6346static bool signed_sub_overflows(s64 a, s64 b)
b03c9f9f
EC
6347{
6348 /* Do the sub in u64, where overflow is well-defined */
6349 s64 res = (s64)((u64)a - (u64)b);
6350
6351 if (b < 0)
6352 return res < a;
6353 return res > a;
969bf05e
AS
6354}
6355
3f50f132
JF
6356static bool signed_sub32_overflows(s32 a, s32 b)
6357{
bc895e8b 6358 /* Do the sub in u32, where overflow is well-defined */
3f50f132
JF
6359 s32 res = (s32)((u32)a - (u32)b);
6360
6361 if (b < 0)
6362 return res < a;
6363 return res > a;
6364}
6365
bb7f0f98
AS
6366static bool check_reg_sane_offset(struct bpf_verifier_env *env,
6367 const struct bpf_reg_state *reg,
6368 enum bpf_reg_type type)
6369{
6370 bool known = tnum_is_const(reg->var_off);
6371 s64 val = reg->var_off.value;
6372 s64 smin = reg->smin_value;
6373
6374 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
6375 verbose(env, "math between %s pointer and %lld is not allowed\n",
6376 reg_type_str[type], val);
6377 return false;
6378 }
6379
6380 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
6381 verbose(env, "%s pointer offset %d is not allowed\n",
6382 reg_type_str[type], reg->off);
6383 return false;
6384 }
6385
6386 if (smin == S64_MIN) {
6387 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
6388 reg_type_str[type]);
6389 return false;
6390 }
6391
6392 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
6393 verbose(env, "value %lld makes %s pointer be out of bounds\n",
6394 smin, reg_type_str[type]);
6395 return false;
6396 }
6397
6398 return true;
6399}
6400
979d63d5
DB
6401static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
6402{
6403 return &env->insn_aux_data[env->insn_idx];
6404}
6405
6406static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
6407 u32 *ptr_limit, u8 opcode, bool off_is_neg)
6408{
6409 bool mask_to_left = (opcode == BPF_ADD && off_is_neg) ||
6410 (opcode == BPF_SUB && !off_is_neg);
1b1597e6 6411 u32 off, max;
979d63d5
DB
6412
6413 switch (ptr_reg->type) {
6414 case PTR_TO_STACK:
1b1597e6
PK
6415 /* Offset 0 is out-of-bounds, but acceptable start for the
6416 * left direction, see BPF_REG_FP.
6417 */
6418 max = MAX_BPF_STACK + mask_to_left;
088ec26d
AI
6419 /* Indirect variable offset stack access is prohibited in
6420 * unprivileged mode so it's not handled here.
6421 */
979d63d5
DB
6422 off = ptr_reg->off + ptr_reg->var_off.value;
6423 if (mask_to_left)
6424 *ptr_limit = MAX_BPF_STACK + off;
6425 else
b5871dca 6426 *ptr_limit = -off - 1;
1b1597e6 6427 return *ptr_limit >= max ? -ERANGE : 0;
979d63d5 6428 case PTR_TO_MAP_VALUE:
1b1597e6 6429 max = ptr_reg->map_ptr->value_size;
979d63d5
DB
6430 if (mask_to_left) {
6431 *ptr_limit = ptr_reg->umax_value + ptr_reg->off;
6432 } else {
6433 off = ptr_reg->smin_value + ptr_reg->off;
b5871dca 6434 *ptr_limit = ptr_reg->map_ptr->value_size - off - 1;
979d63d5 6435 }
1b1597e6 6436 return *ptr_limit >= max ? -ERANGE : 0;
979d63d5
DB
6437 default:
6438 return -EINVAL;
6439 }
6440}
6441
d3bd7413
DB
6442static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
6443 const struct bpf_insn *insn)
6444{
2c78ee89 6445 return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
d3bd7413
DB
6446}
6447
6448static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
6449 u32 alu_state, u32 alu_limit)
6450{
6451 /* If we arrived here from different branches with different
6452 * state or limits to sanitize, then this won't work.
6453 */
6454 if (aux->alu_state &&
6455 (aux->alu_state != alu_state ||
6456 aux->alu_limit != alu_limit))
6457 return -EACCES;
6458
e6ac5933 6459 /* Corresponding fixup done in do_misc_fixups(). */
d3bd7413
DB
6460 aux->alu_state = alu_state;
6461 aux->alu_limit = alu_limit;
6462 return 0;
6463}
6464
6465static int sanitize_val_alu(struct bpf_verifier_env *env,
6466 struct bpf_insn *insn)
6467{
6468 struct bpf_insn_aux_data *aux = cur_aux(env);
6469
6470 if (can_skip_alu_sanitation(env, insn))
6471 return 0;
6472
6473 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
6474}
6475
979d63d5
DB
6476static int sanitize_ptr_alu(struct bpf_verifier_env *env,
6477 struct bpf_insn *insn,
6478 const struct bpf_reg_state *ptr_reg,
6479 struct bpf_reg_state *dst_reg,
6480 bool off_is_neg)
6481{
6482 struct bpf_verifier_state *vstate = env->cur_state;
6483 struct bpf_insn_aux_data *aux = cur_aux(env);
6484 bool ptr_is_dst_reg = ptr_reg == dst_reg;
6485 u8 opcode = BPF_OP(insn->code);
6486 u32 alu_state, alu_limit;
6487 struct bpf_reg_state tmp;
6488 bool ret;
f232326f 6489 int err;
979d63d5 6490
d3bd7413 6491 if (can_skip_alu_sanitation(env, insn))
979d63d5
DB
6492 return 0;
6493
6494 /* We already marked aux for masking from non-speculative
6495 * paths, thus we got here in the first place. We only care
6496 * to explore bad access from here.
6497 */
6498 if (vstate->speculative)
6499 goto do_sim;
6500
6501 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
6502 alu_state |= ptr_is_dst_reg ?
6503 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
6504
f232326f
PK
6505 err = retrieve_ptr_limit(ptr_reg, &alu_limit, opcode, off_is_neg);
6506 if (err < 0)
6507 return err;
6508
6509 err = update_alu_sanitation_state(aux, alu_state, alu_limit);
6510 if (err < 0)
6511 return err;
979d63d5
DB
6512do_sim:
6513 /* Simulate and find potential out-of-bounds access under
6514 * speculative execution from truncation as a result of
6515 * masking when off was not within expected range. If off
6516 * sits in dst, then we temporarily need to move ptr there
6517 * to simulate dst (== 0) +/-= ptr. Needed, for example,
6518 * for cases where we use K-based arithmetic in one direction
6519 * and truncated reg-based in the other in order to explore
6520 * bad access.
6521 */
6522 if (!ptr_is_dst_reg) {
6523 tmp = *dst_reg;
6524 *dst_reg = *ptr_reg;
6525 }
6526 ret = push_stack(env, env->insn_idx + 1, env->insn_idx, true);
0803278b 6527 if (!ptr_is_dst_reg && ret)
979d63d5
DB
6528 *dst_reg = tmp;
6529 return !ret ? -EFAULT : 0;
6530}
6531
01f810ac
AM
6532/* check that stack access falls within stack limits and that 'reg' doesn't
6533 * have a variable offset.
6534 *
6535 * Variable offset is prohibited for unprivileged mode for simplicity since it
6536 * requires corresponding support in Spectre masking for stack ALU. See also
6537 * retrieve_ptr_limit().
6538 *
6539 *
6540 * 'off' includes 'reg->off'.
6541 */
6542static int check_stack_access_for_ptr_arithmetic(
6543 struct bpf_verifier_env *env,
6544 int regno,
6545 const struct bpf_reg_state *reg,
6546 int off)
6547{
6548 if (!tnum_is_const(reg->var_off)) {
6549 char tn_buf[48];
6550
6551 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6552 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
6553 regno, tn_buf, off);
6554 return -EACCES;
6555 }
6556
6557 if (off >= 0 || off < -MAX_BPF_STACK) {
6558 verbose(env, "R%d stack pointer arithmetic goes out of range, "
6559 "prohibited for !root; off=%d\n", regno, off);
6560 return -EACCES;
6561 }
6562
6563 return 0;
6564}
6565
6566
f1174f77 6567/* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
f1174f77
EC
6568 * Caller should also handle BPF_MOV case separately.
6569 * If we return -EACCES, caller may want to try again treating pointer as a
6570 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks.
6571 */
6572static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
6573 struct bpf_insn *insn,
6574 const struct bpf_reg_state *ptr_reg,
6575 const struct bpf_reg_state *off_reg)
969bf05e 6576{
f4d7e40a
AS
6577 struct bpf_verifier_state *vstate = env->cur_state;
6578 struct bpf_func_state *state = vstate->frame[vstate->curframe];
6579 struct bpf_reg_state *regs = state->regs, *dst_reg;
f1174f77 6580 bool known = tnum_is_const(off_reg->var_off);
b03c9f9f
EC
6581 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
6582 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
6583 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
6584 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
9d7eceed 6585 u32 dst = insn->dst_reg, src = insn->src_reg;
969bf05e 6586 u8 opcode = BPF_OP(insn->code);
979d63d5 6587 int ret;
969bf05e 6588
f1174f77 6589 dst_reg = &regs[dst];
969bf05e 6590
6f16101e
DB
6591 if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
6592 smin_val > smax_val || umin_val > umax_val) {
6593 /* Taint dst register if offset had invalid bounds derived from
6594 * e.g. dead branches.
6595 */
f54c7898 6596 __mark_reg_unknown(env, dst_reg);
6f16101e 6597 return 0;
f1174f77
EC
6598 }
6599
6600 if (BPF_CLASS(insn->code) != BPF_ALU64) {
6601 /* 32-bit ALU ops on pointers produce (meaningless) scalars */
6c693541
YS
6602 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
6603 __mark_reg_unknown(env, dst_reg);
6604 return 0;
6605 }
6606
82abbf8d
AS
6607 verbose(env,
6608 "R%d 32-bit pointer arithmetic prohibited\n",
6609 dst);
f1174f77 6610 return -EACCES;
969bf05e
AS
6611 }
6612
aad2eeaf
JS
6613 switch (ptr_reg->type) {
6614 case PTR_TO_MAP_VALUE_OR_NULL:
6615 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
6616 dst, reg_type_str[ptr_reg->type]);
f1174f77 6617 return -EACCES;
aad2eeaf 6618 case CONST_PTR_TO_MAP:
7c696732
YS
6619 /* smin_val represents the known value */
6620 if (known && smin_val == 0 && opcode == BPF_ADD)
6621 break;
8731745e 6622 fallthrough;
aad2eeaf 6623 case PTR_TO_PACKET_END:
c64b7983
JS
6624 case PTR_TO_SOCKET:
6625 case PTR_TO_SOCKET_OR_NULL:
46f8bc92
MKL
6626 case PTR_TO_SOCK_COMMON:
6627 case PTR_TO_SOCK_COMMON_OR_NULL:
655a51e5
MKL
6628 case PTR_TO_TCP_SOCK:
6629 case PTR_TO_TCP_SOCK_OR_NULL:
fada7fdc 6630 case PTR_TO_XDP_SOCK:
aad2eeaf
JS
6631 verbose(env, "R%d pointer arithmetic on %s prohibited\n",
6632 dst, reg_type_str[ptr_reg->type]);
f1174f77 6633 return -EACCES;
9d7eceed
DB
6634 case PTR_TO_MAP_VALUE:
6635 if (!env->allow_ptr_leaks && !known && (smin_val < 0) != (smax_val < 0)) {
6636 verbose(env, "R%d has unknown scalar with mixed signed bounds, pointer arithmetic with it prohibited for !root\n",
6637 off_reg == dst_reg ? dst : src);
6638 return -EACCES;
6639 }
df561f66 6640 fallthrough;
aad2eeaf
JS
6641 default:
6642 break;
f1174f77
EC
6643 }
6644
6645 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
6646 * The id may be overwritten later if we create a new variable offset.
969bf05e 6647 */
f1174f77
EC
6648 dst_reg->type = ptr_reg->type;
6649 dst_reg->id = ptr_reg->id;
969bf05e 6650
bb7f0f98
AS
6651 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
6652 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
6653 return -EINVAL;
6654
3f50f132
JF
6655 /* pointer types do not carry 32-bit bounds at the moment. */
6656 __mark_reg32_unbounded(dst_reg);
6657
f1174f77
EC
6658 switch (opcode) {
6659 case BPF_ADD:
979d63d5
DB
6660 ret = sanitize_ptr_alu(env, insn, ptr_reg, dst_reg, smin_val < 0);
6661 if (ret < 0) {
f232326f 6662 verbose(env, "R%d tried to add from different maps, paths, or prohibited types\n", dst);
979d63d5
DB
6663 return ret;
6664 }
f1174f77
EC
6665 /* We can take a fixed offset as long as it doesn't overflow
6666 * the s32 'off' field
969bf05e 6667 */
b03c9f9f
EC
6668 if (known && (ptr_reg->off + smin_val ==
6669 (s64)(s32)(ptr_reg->off + smin_val))) {
f1174f77 6670 /* pointer += K. Accumulate it into fixed offset */
b03c9f9f
EC
6671 dst_reg->smin_value = smin_ptr;
6672 dst_reg->smax_value = smax_ptr;
6673 dst_reg->umin_value = umin_ptr;
6674 dst_reg->umax_value = umax_ptr;
f1174f77 6675 dst_reg->var_off = ptr_reg->var_off;
b03c9f9f 6676 dst_reg->off = ptr_reg->off + smin_val;
0962590e 6677 dst_reg->raw = ptr_reg->raw;
f1174f77
EC
6678 break;
6679 }
f1174f77
EC
6680 /* A new variable offset is created. Note that off_reg->off
6681 * == 0, since it's a scalar.
6682 * dst_reg gets the pointer type and since some positive
6683 * integer value was added to the pointer, give it a new 'id'
6684 * if it's a PTR_TO_PACKET.
6685 * this creates a new 'base' pointer, off_reg (variable) gets
6686 * added into the variable offset, and we copy the fixed offset
6687 * from ptr_reg.
969bf05e 6688 */
b03c9f9f
EC
6689 if (signed_add_overflows(smin_ptr, smin_val) ||
6690 signed_add_overflows(smax_ptr, smax_val)) {
6691 dst_reg->smin_value = S64_MIN;
6692 dst_reg->smax_value = S64_MAX;
6693 } else {
6694 dst_reg->smin_value = smin_ptr + smin_val;
6695 dst_reg->smax_value = smax_ptr + smax_val;
6696 }
6697 if (umin_ptr + umin_val < umin_ptr ||
6698 umax_ptr + umax_val < umax_ptr) {
6699 dst_reg->umin_value = 0;
6700 dst_reg->umax_value = U64_MAX;
6701 } else {
6702 dst_reg->umin_value = umin_ptr + umin_val;
6703 dst_reg->umax_value = umax_ptr + umax_val;
6704 }
f1174f77
EC
6705 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
6706 dst_reg->off = ptr_reg->off;
0962590e 6707 dst_reg->raw = ptr_reg->raw;
de8f3a83 6708 if (reg_is_pkt_pointer(ptr_reg)) {
f1174f77
EC
6709 dst_reg->id = ++env->id_gen;
6710 /* something was added to pkt_ptr, set range to zero */
22dc4a0f 6711 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
f1174f77
EC
6712 }
6713 break;
6714 case BPF_SUB:
979d63d5
DB
6715 ret = sanitize_ptr_alu(env, insn, ptr_reg, dst_reg, smin_val < 0);
6716 if (ret < 0) {
f232326f 6717 verbose(env, "R%d tried to sub from different maps, paths, or prohibited types\n", dst);
979d63d5
DB
6718 return ret;
6719 }
f1174f77
EC
6720 if (dst_reg == off_reg) {
6721 /* scalar -= pointer. Creates an unknown scalar */
82abbf8d
AS
6722 verbose(env, "R%d tried to subtract pointer from scalar\n",
6723 dst);
f1174f77
EC
6724 return -EACCES;
6725 }
6726 /* We don't allow subtraction from FP, because (according to
6727 * test_verifier.c test "invalid fp arithmetic", JITs might not
6728 * be able to deal with it.
969bf05e 6729 */
f1174f77 6730 if (ptr_reg->type == PTR_TO_STACK) {
82abbf8d
AS
6731 verbose(env, "R%d subtraction from stack pointer prohibited\n",
6732 dst);
f1174f77
EC
6733 return -EACCES;
6734 }
b03c9f9f
EC
6735 if (known && (ptr_reg->off - smin_val ==
6736 (s64)(s32)(ptr_reg->off - smin_val))) {
f1174f77 6737 /* pointer -= K. Subtract it from fixed offset */
b03c9f9f
EC
6738 dst_reg->smin_value = smin_ptr;
6739 dst_reg->smax_value = smax_ptr;
6740 dst_reg->umin_value = umin_ptr;
6741 dst_reg->umax_value = umax_ptr;
f1174f77
EC
6742 dst_reg->var_off = ptr_reg->var_off;
6743 dst_reg->id = ptr_reg->id;
b03c9f9f 6744 dst_reg->off = ptr_reg->off - smin_val;
0962590e 6745 dst_reg->raw = ptr_reg->raw;
f1174f77
EC
6746 break;
6747 }
f1174f77
EC
6748 /* A new variable offset is created. If the subtrahend is known
6749 * nonnegative, then any reg->range we had before is still good.
969bf05e 6750 */
b03c9f9f
EC
6751 if (signed_sub_overflows(smin_ptr, smax_val) ||
6752 signed_sub_overflows(smax_ptr, smin_val)) {
6753 /* Overflow possible, we know nothing */
6754 dst_reg->smin_value = S64_MIN;
6755 dst_reg->smax_value = S64_MAX;
6756 } else {
6757 dst_reg->smin_value = smin_ptr - smax_val;
6758 dst_reg->smax_value = smax_ptr - smin_val;
6759 }
6760 if (umin_ptr < umax_val) {
6761 /* Overflow possible, we know nothing */
6762 dst_reg->umin_value = 0;
6763 dst_reg->umax_value = U64_MAX;
6764 } else {
6765 /* Cannot overflow (as long as bounds are consistent) */
6766 dst_reg->umin_value = umin_ptr - umax_val;
6767 dst_reg->umax_value = umax_ptr - umin_val;
6768 }
f1174f77
EC
6769 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
6770 dst_reg->off = ptr_reg->off;
0962590e 6771 dst_reg->raw = ptr_reg->raw;
de8f3a83 6772 if (reg_is_pkt_pointer(ptr_reg)) {
f1174f77
EC
6773 dst_reg->id = ++env->id_gen;
6774 /* something was added to pkt_ptr, set range to zero */
b03c9f9f 6775 if (smin_val < 0)
22dc4a0f 6776 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
43188702 6777 }
f1174f77
EC
6778 break;
6779 case BPF_AND:
6780 case BPF_OR:
6781 case BPF_XOR:
82abbf8d
AS
6782 /* bitwise ops on pointers are troublesome, prohibit. */
6783 verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
6784 dst, bpf_alu_string[opcode >> 4]);
f1174f77
EC
6785 return -EACCES;
6786 default:
6787 /* other operators (e.g. MUL,LSH) produce non-pointer results */
82abbf8d
AS
6788 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
6789 dst, bpf_alu_string[opcode >> 4]);
f1174f77 6790 return -EACCES;
43188702
JF
6791 }
6792
bb7f0f98
AS
6793 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
6794 return -EINVAL;
6795
b03c9f9f
EC
6796 __update_reg_bounds(dst_reg);
6797 __reg_deduce_bounds(dst_reg);
6798 __reg_bound_offset(dst_reg);
0d6303db
DB
6799
6800 /* For unprivileged we require that resulting offset must be in bounds
6801 * in order to be able to sanitize access later on.
6802 */
2c78ee89 6803 if (!env->bypass_spec_v1) {
e4298d25
DB
6804 if (dst_reg->type == PTR_TO_MAP_VALUE &&
6805 check_map_access(env, dst, dst_reg->off, 1, false)) {
6806 verbose(env, "R%d pointer arithmetic of map value goes out of range, "
6807 "prohibited for !root\n", dst);
6808 return -EACCES;
6809 } else if (dst_reg->type == PTR_TO_STACK &&
01f810ac
AM
6810 check_stack_access_for_ptr_arithmetic(
6811 env, dst, dst_reg, dst_reg->off +
6812 dst_reg->var_off.value)) {
e4298d25
DB
6813 return -EACCES;
6814 }
0d6303db
DB
6815 }
6816
43188702
JF
6817 return 0;
6818}
6819
3f50f132
JF
6820static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
6821 struct bpf_reg_state *src_reg)
6822{
6823 s32 smin_val = src_reg->s32_min_value;
6824 s32 smax_val = src_reg->s32_max_value;
6825 u32 umin_val = src_reg->u32_min_value;
6826 u32 umax_val = src_reg->u32_max_value;
6827
6828 if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
6829 signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
6830 dst_reg->s32_min_value = S32_MIN;
6831 dst_reg->s32_max_value = S32_MAX;
6832 } else {
6833 dst_reg->s32_min_value += smin_val;
6834 dst_reg->s32_max_value += smax_val;
6835 }
6836 if (dst_reg->u32_min_value + umin_val < umin_val ||
6837 dst_reg->u32_max_value + umax_val < umax_val) {
6838 dst_reg->u32_min_value = 0;
6839 dst_reg->u32_max_value = U32_MAX;
6840 } else {
6841 dst_reg->u32_min_value += umin_val;
6842 dst_reg->u32_max_value += umax_val;
6843 }
6844}
6845
07cd2631
JF
6846static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
6847 struct bpf_reg_state *src_reg)
6848{
6849 s64 smin_val = src_reg->smin_value;
6850 s64 smax_val = src_reg->smax_value;
6851 u64 umin_val = src_reg->umin_value;
6852 u64 umax_val = src_reg->umax_value;
6853
6854 if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
6855 signed_add_overflows(dst_reg->smax_value, smax_val)) {
6856 dst_reg->smin_value = S64_MIN;
6857 dst_reg->smax_value = S64_MAX;
6858 } else {
6859 dst_reg->smin_value += smin_val;
6860 dst_reg->smax_value += smax_val;
6861 }
6862 if (dst_reg->umin_value + umin_val < umin_val ||
6863 dst_reg->umax_value + umax_val < umax_val) {
6864 dst_reg->umin_value = 0;
6865 dst_reg->umax_value = U64_MAX;
6866 } else {
6867 dst_reg->umin_value += umin_val;
6868 dst_reg->umax_value += umax_val;
6869 }
3f50f132
JF
6870}
6871
6872static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
6873 struct bpf_reg_state *src_reg)
6874{
6875 s32 smin_val = src_reg->s32_min_value;
6876 s32 smax_val = src_reg->s32_max_value;
6877 u32 umin_val = src_reg->u32_min_value;
6878 u32 umax_val = src_reg->u32_max_value;
6879
6880 if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
6881 signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
6882 /* Overflow possible, we know nothing */
6883 dst_reg->s32_min_value = S32_MIN;
6884 dst_reg->s32_max_value = S32_MAX;
6885 } else {
6886 dst_reg->s32_min_value -= smax_val;
6887 dst_reg->s32_max_value -= smin_val;
6888 }
6889 if (dst_reg->u32_min_value < umax_val) {
6890 /* Overflow possible, we know nothing */
6891 dst_reg->u32_min_value = 0;
6892 dst_reg->u32_max_value = U32_MAX;
6893 } else {
6894 /* Cannot overflow (as long as bounds are consistent) */
6895 dst_reg->u32_min_value -= umax_val;
6896 dst_reg->u32_max_value -= umin_val;
6897 }
07cd2631
JF
6898}
6899
6900static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
6901 struct bpf_reg_state *src_reg)
6902{
6903 s64 smin_val = src_reg->smin_value;
6904 s64 smax_val = src_reg->smax_value;
6905 u64 umin_val = src_reg->umin_value;
6906 u64 umax_val = src_reg->umax_value;
6907
6908 if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
6909 signed_sub_overflows(dst_reg->smax_value, smin_val)) {
6910 /* Overflow possible, we know nothing */
6911 dst_reg->smin_value = S64_MIN;
6912 dst_reg->smax_value = S64_MAX;
6913 } else {
6914 dst_reg->smin_value -= smax_val;
6915 dst_reg->smax_value -= smin_val;
6916 }
6917 if (dst_reg->umin_value < umax_val) {
6918 /* Overflow possible, we know nothing */
6919 dst_reg->umin_value = 0;
6920 dst_reg->umax_value = U64_MAX;
6921 } else {
6922 /* Cannot overflow (as long as bounds are consistent) */
6923 dst_reg->umin_value -= umax_val;
6924 dst_reg->umax_value -= umin_val;
6925 }
3f50f132
JF
6926}
6927
6928static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
6929 struct bpf_reg_state *src_reg)
6930{
6931 s32 smin_val = src_reg->s32_min_value;
6932 u32 umin_val = src_reg->u32_min_value;
6933 u32 umax_val = src_reg->u32_max_value;
6934
6935 if (smin_val < 0 || dst_reg->s32_min_value < 0) {
6936 /* Ain't nobody got time to multiply that sign */
6937 __mark_reg32_unbounded(dst_reg);
6938 return;
6939 }
6940 /* Both values are positive, so we can work with unsigned and
6941 * copy the result to signed (unless it exceeds S32_MAX).
6942 */
6943 if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
6944 /* Potential overflow, we know nothing */
6945 __mark_reg32_unbounded(dst_reg);
6946 return;
6947 }
6948 dst_reg->u32_min_value *= umin_val;
6949 dst_reg->u32_max_value *= umax_val;
6950 if (dst_reg->u32_max_value > S32_MAX) {
6951 /* Overflow possible, we know nothing */
6952 dst_reg->s32_min_value = S32_MIN;
6953 dst_reg->s32_max_value = S32_MAX;
6954 } else {
6955 dst_reg->s32_min_value = dst_reg->u32_min_value;
6956 dst_reg->s32_max_value = dst_reg->u32_max_value;
6957 }
07cd2631
JF
6958}
6959
6960static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
6961 struct bpf_reg_state *src_reg)
6962{
6963 s64 smin_val = src_reg->smin_value;
6964 u64 umin_val = src_reg->umin_value;
6965 u64 umax_val = src_reg->umax_value;
6966
07cd2631
JF
6967 if (smin_val < 0 || dst_reg->smin_value < 0) {
6968 /* Ain't nobody got time to multiply that sign */
3f50f132 6969 __mark_reg64_unbounded(dst_reg);
07cd2631
JF
6970 return;
6971 }
6972 /* Both values are positive, so we can work with unsigned and
6973 * copy the result to signed (unless it exceeds S64_MAX).
6974 */
6975 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
6976 /* Potential overflow, we know nothing */
3f50f132 6977 __mark_reg64_unbounded(dst_reg);
07cd2631
JF
6978 return;
6979 }
6980 dst_reg->umin_value *= umin_val;
6981 dst_reg->umax_value *= umax_val;
6982 if (dst_reg->umax_value > S64_MAX) {
6983 /* Overflow possible, we know nothing */
6984 dst_reg->smin_value = S64_MIN;
6985 dst_reg->smax_value = S64_MAX;
6986 } else {
6987 dst_reg->smin_value = dst_reg->umin_value;
6988 dst_reg->smax_value = dst_reg->umax_value;
6989 }
6990}
6991
3f50f132
JF
6992static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
6993 struct bpf_reg_state *src_reg)
6994{
6995 bool src_known = tnum_subreg_is_const(src_reg->var_off);
6996 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
6997 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
6998 s32 smin_val = src_reg->s32_min_value;
6999 u32 umax_val = src_reg->u32_max_value;
7000
7001 /* Assuming scalar64_min_max_and will be called so its safe
7002 * to skip updating register for known 32-bit case.
7003 */
7004 if (src_known && dst_known)
7005 return;
7006
7007 /* We get our minimum from the var_off, since that's inherently
7008 * bitwise. Our maximum is the minimum of the operands' maxima.
7009 */
7010 dst_reg->u32_min_value = var32_off.value;
7011 dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
7012 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
7013 /* Lose signed bounds when ANDing negative numbers,
7014 * ain't nobody got time for that.
7015 */
7016 dst_reg->s32_min_value = S32_MIN;
7017 dst_reg->s32_max_value = S32_MAX;
7018 } else {
7019 /* ANDing two positives gives a positive, so safe to
7020 * cast result into s64.
7021 */
7022 dst_reg->s32_min_value = dst_reg->u32_min_value;
7023 dst_reg->s32_max_value = dst_reg->u32_max_value;
7024 }
7025
7026}
7027
07cd2631
JF
7028static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
7029 struct bpf_reg_state *src_reg)
7030{
3f50f132
JF
7031 bool src_known = tnum_is_const(src_reg->var_off);
7032 bool dst_known = tnum_is_const(dst_reg->var_off);
07cd2631
JF
7033 s64 smin_val = src_reg->smin_value;
7034 u64 umax_val = src_reg->umax_value;
7035
3f50f132 7036 if (src_known && dst_known) {
4fbb38a3 7037 __mark_reg_known(dst_reg, dst_reg->var_off.value);
3f50f132
JF
7038 return;
7039 }
7040
07cd2631
JF
7041 /* We get our minimum from the var_off, since that's inherently
7042 * bitwise. Our maximum is the minimum of the operands' maxima.
7043 */
07cd2631
JF
7044 dst_reg->umin_value = dst_reg->var_off.value;
7045 dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
7046 if (dst_reg->smin_value < 0 || smin_val < 0) {
7047 /* Lose signed bounds when ANDing negative numbers,
7048 * ain't nobody got time for that.
7049 */
7050 dst_reg->smin_value = S64_MIN;
7051 dst_reg->smax_value = S64_MAX;
7052 } else {
7053 /* ANDing two positives gives a positive, so safe to
7054 * cast result into s64.
7055 */
7056 dst_reg->smin_value = dst_reg->umin_value;
7057 dst_reg->smax_value = dst_reg->umax_value;
7058 }
7059 /* We may learn something more from the var_off */
7060 __update_reg_bounds(dst_reg);
7061}
7062
3f50f132
JF
7063static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
7064 struct bpf_reg_state *src_reg)
7065{
7066 bool src_known = tnum_subreg_is_const(src_reg->var_off);
7067 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
7068 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
5b9fbeb7
DB
7069 s32 smin_val = src_reg->s32_min_value;
7070 u32 umin_val = src_reg->u32_min_value;
3f50f132
JF
7071
7072 /* Assuming scalar64_min_max_or will be called so it is safe
7073 * to skip updating register for known case.
7074 */
7075 if (src_known && dst_known)
7076 return;
7077
7078 /* We get our maximum from the var_off, and our minimum is the
7079 * maximum of the operands' minima
7080 */
7081 dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
7082 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
7083 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
7084 /* Lose signed bounds when ORing negative numbers,
7085 * ain't nobody got time for that.
7086 */
7087 dst_reg->s32_min_value = S32_MIN;
7088 dst_reg->s32_max_value = S32_MAX;
7089 } else {
7090 /* ORing two positives gives a positive, so safe to
7091 * cast result into s64.
7092 */
5b9fbeb7
DB
7093 dst_reg->s32_min_value = dst_reg->u32_min_value;
7094 dst_reg->s32_max_value = dst_reg->u32_max_value;
3f50f132
JF
7095 }
7096}
7097
07cd2631
JF
7098static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
7099 struct bpf_reg_state *src_reg)
7100{
3f50f132
JF
7101 bool src_known = tnum_is_const(src_reg->var_off);
7102 bool dst_known = tnum_is_const(dst_reg->var_off);
07cd2631
JF
7103 s64 smin_val = src_reg->smin_value;
7104 u64 umin_val = src_reg->umin_value;
7105
3f50f132 7106 if (src_known && dst_known) {
4fbb38a3 7107 __mark_reg_known(dst_reg, dst_reg->var_off.value);
3f50f132
JF
7108 return;
7109 }
7110
07cd2631
JF
7111 /* We get our maximum from the var_off, and our minimum is the
7112 * maximum of the operands' minima
7113 */
07cd2631
JF
7114 dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
7115 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
7116 if (dst_reg->smin_value < 0 || smin_val < 0) {
7117 /* Lose signed bounds when ORing negative numbers,
7118 * ain't nobody got time for that.
7119 */
7120 dst_reg->smin_value = S64_MIN;
7121 dst_reg->smax_value = S64_MAX;
7122 } else {
7123 /* ORing two positives gives a positive, so safe to
7124 * cast result into s64.
7125 */
7126 dst_reg->smin_value = dst_reg->umin_value;
7127 dst_reg->smax_value = dst_reg->umax_value;
7128 }
7129 /* We may learn something more from the var_off */
7130 __update_reg_bounds(dst_reg);
7131}
7132
2921c90d
YS
7133static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
7134 struct bpf_reg_state *src_reg)
7135{
7136 bool src_known = tnum_subreg_is_const(src_reg->var_off);
7137 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
7138 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
7139 s32 smin_val = src_reg->s32_min_value;
7140
7141 /* Assuming scalar64_min_max_xor will be called so it is safe
7142 * to skip updating register for known case.
7143 */
7144 if (src_known && dst_known)
7145 return;
7146
7147 /* We get both minimum and maximum from the var32_off. */
7148 dst_reg->u32_min_value = var32_off.value;
7149 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
7150
7151 if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
7152 /* XORing two positive sign numbers gives a positive,
7153 * so safe to cast u32 result into s32.
7154 */
7155 dst_reg->s32_min_value = dst_reg->u32_min_value;
7156 dst_reg->s32_max_value = dst_reg->u32_max_value;
7157 } else {
7158 dst_reg->s32_min_value = S32_MIN;
7159 dst_reg->s32_max_value = S32_MAX;
7160 }
7161}
7162
7163static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
7164 struct bpf_reg_state *src_reg)
7165{
7166 bool src_known = tnum_is_const(src_reg->var_off);
7167 bool dst_known = tnum_is_const(dst_reg->var_off);
7168 s64 smin_val = src_reg->smin_value;
7169
7170 if (src_known && dst_known) {
7171 /* dst_reg->var_off.value has been updated earlier */
7172 __mark_reg_known(dst_reg, dst_reg->var_off.value);
7173 return;
7174 }
7175
7176 /* We get both minimum and maximum from the var_off. */
7177 dst_reg->umin_value = dst_reg->var_off.value;
7178 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
7179
7180 if (dst_reg->smin_value >= 0 && smin_val >= 0) {
7181 /* XORing two positive sign numbers gives a positive,
7182 * so safe to cast u64 result into s64.
7183 */
7184 dst_reg->smin_value = dst_reg->umin_value;
7185 dst_reg->smax_value = dst_reg->umax_value;
7186 } else {
7187 dst_reg->smin_value = S64_MIN;
7188 dst_reg->smax_value = S64_MAX;
7189 }
7190
7191 __update_reg_bounds(dst_reg);
7192}
7193
3f50f132
JF
7194static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
7195 u64 umin_val, u64 umax_val)
07cd2631 7196{
07cd2631
JF
7197 /* We lose all sign bit information (except what we can pick
7198 * up from var_off)
7199 */
3f50f132
JF
7200 dst_reg->s32_min_value = S32_MIN;
7201 dst_reg->s32_max_value = S32_MAX;
7202 /* If we might shift our top bit out, then we know nothing */
7203 if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
7204 dst_reg->u32_min_value = 0;
7205 dst_reg->u32_max_value = U32_MAX;
7206 } else {
7207 dst_reg->u32_min_value <<= umin_val;
7208 dst_reg->u32_max_value <<= umax_val;
7209 }
7210}
7211
7212static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
7213 struct bpf_reg_state *src_reg)
7214{
7215 u32 umax_val = src_reg->u32_max_value;
7216 u32 umin_val = src_reg->u32_min_value;
7217 /* u32 alu operation will zext upper bits */
7218 struct tnum subreg = tnum_subreg(dst_reg->var_off);
7219
7220 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
7221 dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
7222 /* Not required but being careful mark reg64 bounds as unknown so
7223 * that we are forced to pick them up from tnum and zext later and
7224 * if some path skips this step we are still safe.
7225 */
7226 __mark_reg64_unbounded(dst_reg);
7227 __update_reg32_bounds(dst_reg);
7228}
7229
7230static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
7231 u64 umin_val, u64 umax_val)
7232{
7233 /* Special case <<32 because it is a common compiler pattern to sign
7234 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
7235 * positive we know this shift will also be positive so we can track
7236 * bounds correctly. Otherwise we lose all sign bit information except
7237 * what we can pick up from var_off. Perhaps we can generalize this
7238 * later to shifts of any length.
7239 */
7240 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
7241 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
7242 else
7243 dst_reg->smax_value = S64_MAX;
7244
7245 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
7246 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
7247 else
7248 dst_reg->smin_value = S64_MIN;
7249
07cd2631
JF
7250 /* If we might shift our top bit out, then we know nothing */
7251 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
7252 dst_reg->umin_value = 0;
7253 dst_reg->umax_value = U64_MAX;
7254 } else {
7255 dst_reg->umin_value <<= umin_val;
7256 dst_reg->umax_value <<= umax_val;
7257 }
3f50f132
JF
7258}
7259
7260static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
7261 struct bpf_reg_state *src_reg)
7262{
7263 u64 umax_val = src_reg->umax_value;
7264 u64 umin_val = src_reg->umin_value;
7265
7266 /* scalar64 calc uses 32bit unshifted bounds so must be called first */
7267 __scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
7268 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
7269
07cd2631
JF
7270 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
7271 /* We may learn something more from the var_off */
7272 __update_reg_bounds(dst_reg);
7273}
7274
3f50f132
JF
7275static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
7276 struct bpf_reg_state *src_reg)
7277{
7278 struct tnum subreg = tnum_subreg(dst_reg->var_off);
7279 u32 umax_val = src_reg->u32_max_value;
7280 u32 umin_val = src_reg->u32_min_value;
7281
7282 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
7283 * be negative, then either:
7284 * 1) src_reg might be zero, so the sign bit of the result is
7285 * unknown, so we lose our signed bounds
7286 * 2) it's known negative, thus the unsigned bounds capture the
7287 * signed bounds
7288 * 3) the signed bounds cross zero, so they tell us nothing
7289 * about the result
7290 * If the value in dst_reg is known nonnegative, then again the
18b24d78 7291 * unsigned bounds capture the signed bounds.
3f50f132
JF
7292 * Thus, in all cases it suffices to blow away our signed bounds
7293 * and rely on inferring new ones from the unsigned bounds and
7294 * var_off of the result.
7295 */
7296 dst_reg->s32_min_value = S32_MIN;
7297 dst_reg->s32_max_value = S32_MAX;
7298
7299 dst_reg->var_off = tnum_rshift(subreg, umin_val);
7300 dst_reg->u32_min_value >>= umax_val;
7301 dst_reg->u32_max_value >>= umin_val;
7302
7303 __mark_reg64_unbounded(dst_reg);
7304 __update_reg32_bounds(dst_reg);
7305}
7306
07cd2631
JF
7307static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
7308 struct bpf_reg_state *src_reg)
7309{
7310 u64 umax_val = src_reg->umax_value;
7311 u64 umin_val = src_reg->umin_value;
7312
7313 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
7314 * be negative, then either:
7315 * 1) src_reg might be zero, so the sign bit of the result is
7316 * unknown, so we lose our signed bounds
7317 * 2) it's known negative, thus the unsigned bounds capture the
7318 * signed bounds
7319 * 3) the signed bounds cross zero, so they tell us nothing
7320 * about the result
7321 * If the value in dst_reg is known nonnegative, then again the
18b24d78 7322 * unsigned bounds capture the signed bounds.
07cd2631
JF
7323 * Thus, in all cases it suffices to blow away our signed bounds
7324 * and rely on inferring new ones from the unsigned bounds and
7325 * var_off of the result.
7326 */
7327 dst_reg->smin_value = S64_MIN;
7328 dst_reg->smax_value = S64_MAX;
7329 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
7330 dst_reg->umin_value >>= umax_val;
7331 dst_reg->umax_value >>= umin_val;
3f50f132
JF
7332
7333 /* Its not easy to operate on alu32 bounds here because it depends
7334 * on bits being shifted in. Take easy way out and mark unbounded
7335 * so we can recalculate later from tnum.
7336 */
7337 __mark_reg32_unbounded(dst_reg);
07cd2631
JF
7338 __update_reg_bounds(dst_reg);
7339}
7340
3f50f132
JF
7341static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
7342 struct bpf_reg_state *src_reg)
07cd2631 7343{
3f50f132 7344 u64 umin_val = src_reg->u32_min_value;
07cd2631
JF
7345
7346 /* Upon reaching here, src_known is true and
7347 * umax_val is equal to umin_val.
7348 */
3f50f132
JF
7349 dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
7350 dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
07cd2631 7351
3f50f132
JF
7352 dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
7353
7354 /* blow away the dst_reg umin_value/umax_value and rely on
7355 * dst_reg var_off to refine the result.
7356 */
7357 dst_reg->u32_min_value = 0;
7358 dst_reg->u32_max_value = U32_MAX;
7359
7360 __mark_reg64_unbounded(dst_reg);
7361 __update_reg32_bounds(dst_reg);
7362}
7363
7364static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
7365 struct bpf_reg_state *src_reg)
7366{
7367 u64 umin_val = src_reg->umin_value;
7368
7369 /* Upon reaching here, src_known is true and umax_val is equal
7370 * to umin_val.
7371 */
7372 dst_reg->smin_value >>= umin_val;
7373 dst_reg->smax_value >>= umin_val;
7374
7375 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
07cd2631
JF
7376
7377 /* blow away the dst_reg umin_value/umax_value and rely on
7378 * dst_reg var_off to refine the result.
7379 */
7380 dst_reg->umin_value = 0;
7381 dst_reg->umax_value = U64_MAX;
3f50f132
JF
7382
7383 /* Its not easy to operate on alu32 bounds here because it depends
7384 * on bits being shifted in from upper 32-bits. Take easy way out
7385 * and mark unbounded so we can recalculate later from tnum.
7386 */
7387 __mark_reg32_unbounded(dst_reg);
07cd2631
JF
7388 __update_reg_bounds(dst_reg);
7389}
7390
468f6eaf
JH
7391/* WARNING: This function does calculations on 64-bit values, but the actual
7392 * execution may occur on 32-bit values. Therefore, things like bitshifts
7393 * need extra checks in the 32-bit case.
7394 */
f1174f77
EC
7395static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
7396 struct bpf_insn *insn,
7397 struct bpf_reg_state *dst_reg,
7398 struct bpf_reg_state src_reg)
969bf05e 7399{
638f5b90 7400 struct bpf_reg_state *regs = cur_regs(env);
48461135 7401 u8 opcode = BPF_OP(insn->code);
b0b3fb67 7402 bool src_known;
b03c9f9f
EC
7403 s64 smin_val, smax_val;
7404 u64 umin_val, umax_val;
3f50f132
JF
7405 s32 s32_min_val, s32_max_val;
7406 u32 u32_min_val, u32_max_val;
468f6eaf 7407 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
d3bd7413
DB
7408 u32 dst = insn->dst_reg;
7409 int ret;
3f50f132 7410 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
b799207e 7411
b03c9f9f
EC
7412 smin_val = src_reg.smin_value;
7413 smax_val = src_reg.smax_value;
7414 umin_val = src_reg.umin_value;
7415 umax_val = src_reg.umax_value;
f23cc643 7416
3f50f132
JF
7417 s32_min_val = src_reg.s32_min_value;
7418 s32_max_val = src_reg.s32_max_value;
7419 u32_min_val = src_reg.u32_min_value;
7420 u32_max_val = src_reg.u32_max_value;
7421
7422 if (alu32) {
7423 src_known = tnum_subreg_is_const(src_reg.var_off);
3f50f132
JF
7424 if ((src_known &&
7425 (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
7426 s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
7427 /* Taint dst register if offset had invalid bounds
7428 * derived from e.g. dead branches.
7429 */
7430 __mark_reg_unknown(env, dst_reg);
7431 return 0;
7432 }
7433 } else {
7434 src_known = tnum_is_const(src_reg.var_off);
3f50f132
JF
7435 if ((src_known &&
7436 (smin_val != smax_val || umin_val != umax_val)) ||
7437 smin_val > smax_val || umin_val > umax_val) {
7438 /* Taint dst register if offset had invalid bounds
7439 * derived from e.g. dead branches.
7440 */
7441 __mark_reg_unknown(env, dst_reg);
7442 return 0;
7443 }
6f16101e
DB
7444 }
7445
bb7f0f98
AS
7446 if (!src_known &&
7447 opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
f54c7898 7448 __mark_reg_unknown(env, dst_reg);
bb7f0f98
AS
7449 return 0;
7450 }
7451
3f50f132
JF
7452 /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
7453 * There are two classes of instructions: The first class we track both
7454 * alu32 and alu64 sign/unsigned bounds independently this provides the
7455 * greatest amount of precision when alu operations are mixed with jmp32
7456 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
7457 * and BPF_OR. This is possible because these ops have fairly easy to
7458 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
7459 * See alu32 verifier tests for examples. The second class of
7460 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
7461 * with regards to tracking sign/unsigned bounds because the bits may
7462 * cross subreg boundaries in the alu64 case. When this happens we mark
7463 * the reg unbounded in the subreg bound space and use the resulting
7464 * tnum to calculate an approximation of the sign/unsigned bounds.
7465 */
48461135
JB
7466 switch (opcode) {
7467 case BPF_ADD:
d3bd7413
DB
7468 ret = sanitize_val_alu(env, insn);
7469 if (ret < 0) {
7470 verbose(env, "R%d tried to add from different pointers or scalars\n", dst);
7471 return ret;
7472 }
3f50f132 7473 scalar32_min_max_add(dst_reg, &src_reg);
07cd2631 7474 scalar_min_max_add(dst_reg, &src_reg);
3f50f132 7475 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
48461135
JB
7476 break;
7477 case BPF_SUB:
d3bd7413
DB
7478 ret = sanitize_val_alu(env, insn);
7479 if (ret < 0) {
7480 verbose(env, "R%d tried to sub from different pointers or scalars\n", dst);
7481 return ret;
7482 }
3f50f132 7483 scalar32_min_max_sub(dst_reg, &src_reg);
07cd2631 7484 scalar_min_max_sub(dst_reg, &src_reg);
3f50f132 7485 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
48461135
JB
7486 break;
7487 case BPF_MUL:
3f50f132
JF
7488 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
7489 scalar32_min_max_mul(dst_reg, &src_reg);
07cd2631 7490 scalar_min_max_mul(dst_reg, &src_reg);
48461135
JB
7491 break;
7492 case BPF_AND:
3f50f132
JF
7493 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
7494 scalar32_min_max_and(dst_reg, &src_reg);
07cd2631 7495 scalar_min_max_and(dst_reg, &src_reg);
f1174f77
EC
7496 break;
7497 case BPF_OR:
3f50f132
JF
7498 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
7499 scalar32_min_max_or(dst_reg, &src_reg);
07cd2631 7500 scalar_min_max_or(dst_reg, &src_reg);
48461135 7501 break;
2921c90d
YS
7502 case BPF_XOR:
7503 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
7504 scalar32_min_max_xor(dst_reg, &src_reg);
7505 scalar_min_max_xor(dst_reg, &src_reg);
7506 break;
48461135 7507 case BPF_LSH:
468f6eaf
JH
7508 if (umax_val >= insn_bitness) {
7509 /* Shifts greater than 31 or 63 are undefined.
7510 * This includes shifts by a negative number.
b03c9f9f 7511 */
61bd5218 7512 mark_reg_unknown(env, regs, insn->dst_reg);
f1174f77
EC
7513 break;
7514 }
3f50f132
JF
7515 if (alu32)
7516 scalar32_min_max_lsh(dst_reg, &src_reg);
7517 else
7518 scalar_min_max_lsh(dst_reg, &src_reg);
48461135
JB
7519 break;
7520 case BPF_RSH:
468f6eaf
JH
7521 if (umax_val >= insn_bitness) {
7522 /* Shifts greater than 31 or 63 are undefined.
7523 * This includes shifts by a negative number.
b03c9f9f 7524 */
61bd5218 7525 mark_reg_unknown(env, regs, insn->dst_reg);
f1174f77
EC
7526 break;
7527 }
3f50f132
JF
7528 if (alu32)
7529 scalar32_min_max_rsh(dst_reg, &src_reg);
7530 else
7531 scalar_min_max_rsh(dst_reg, &src_reg);
48461135 7532 break;
9cbe1f5a
YS
7533 case BPF_ARSH:
7534 if (umax_val >= insn_bitness) {
7535 /* Shifts greater than 31 or 63 are undefined.
7536 * This includes shifts by a negative number.
7537 */
7538 mark_reg_unknown(env, regs, insn->dst_reg);
7539 break;
7540 }
3f50f132
JF
7541 if (alu32)
7542 scalar32_min_max_arsh(dst_reg, &src_reg);
7543 else
7544 scalar_min_max_arsh(dst_reg, &src_reg);
9cbe1f5a 7545 break;
48461135 7546 default:
61bd5218 7547 mark_reg_unknown(env, regs, insn->dst_reg);
48461135
JB
7548 break;
7549 }
7550
3f50f132
JF
7551 /* ALU32 ops are zero extended into 64bit register */
7552 if (alu32)
7553 zext_32_to_64(dst_reg);
468f6eaf 7554
294f2fc6 7555 __update_reg_bounds(dst_reg);
b03c9f9f
EC
7556 __reg_deduce_bounds(dst_reg);
7557 __reg_bound_offset(dst_reg);
f1174f77
EC
7558 return 0;
7559}
7560
7561/* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
7562 * and var_off.
7563 */
7564static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
7565 struct bpf_insn *insn)
7566{
f4d7e40a
AS
7567 struct bpf_verifier_state *vstate = env->cur_state;
7568 struct bpf_func_state *state = vstate->frame[vstate->curframe];
7569 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
f1174f77
EC
7570 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
7571 u8 opcode = BPF_OP(insn->code);
b5dc0163 7572 int err;
f1174f77
EC
7573
7574 dst_reg = &regs[insn->dst_reg];
f1174f77
EC
7575 src_reg = NULL;
7576 if (dst_reg->type != SCALAR_VALUE)
7577 ptr_reg = dst_reg;
75748837
AS
7578 else
7579 /* Make sure ID is cleared otherwise dst_reg min/max could be
7580 * incorrectly propagated into other registers by find_equal_scalars()
7581 */
7582 dst_reg->id = 0;
f1174f77
EC
7583 if (BPF_SRC(insn->code) == BPF_X) {
7584 src_reg = &regs[insn->src_reg];
f1174f77
EC
7585 if (src_reg->type != SCALAR_VALUE) {
7586 if (dst_reg->type != SCALAR_VALUE) {
7587 /* Combining two pointers by any ALU op yields
82abbf8d
AS
7588 * an arbitrary scalar. Disallow all math except
7589 * pointer subtraction
f1174f77 7590 */
dd066823 7591 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
82abbf8d
AS
7592 mark_reg_unknown(env, regs, insn->dst_reg);
7593 return 0;
f1174f77 7594 }
82abbf8d
AS
7595 verbose(env, "R%d pointer %s pointer prohibited\n",
7596 insn->dst_reg,
7597 bpf_alu_string[opcode >> 4]);
7598 return -EACCES;
f1174f77
EC
7599 } else {
7600 /* scalar += pointer
7601 * This is legal, but we have to reverse our
7602 * src/dest handling in computing the range
7603 */
b5dc0163
AS
7604 err = mark_chain_precision(env, insn->dst_reg);
7605 if (err)
7606 return err;
82abbf8d
AS
7607 return adjust_ptr_min_max_vals(env, insn,
7608 src_reg, dst_reg);
f1174f77
EC
7609 }
7610 } else if (ptr_reg) {
7611 /* pointer += scalar */
b5dc0163
AS
7612 err = mark_chain_precision(env, insn->src_reg);
7613 if (err)
7614 return err;
82abbf8d
AS
7615 return adjust_ptr_min_max_vals(env, insn,
7616 dst_reg, src_reg);
f1174f77
EC
7617 }
7618 } else {
7619 /* Pretend the src is a reg with a known value, since we only
7620 * need to be able to read from this state.
7621 */
7622 off_reg.type = SCALAR_VALUE;
b03c9f9f 7623 __mark_reg_known(&off_reg, insn->imm);
f1174f77 7624 src_reg = &off_reg;
82abbf8d
AS
7625 if (ptr_reg) /* pointer += K */
7626 return adjust_ptr_min_max_vals(env, insn,
7627 ptr_reg, src_reg);
f1174f77
EC
7628 }
7629
7630 /* Got here implies adding two SCALAR_VALUEs */
7631 if (WARN_ON_ONCE(ptr_reg)) {
f4d7e40a 7632 print_verifier_state(env, state);
61bd5218 7633 verbose(env, "verifier internal error: unexpected ptr_reg\n");
f1174f77
EC
7634 return -EINVAL;
7635 }
7636 if (WARN_ON(!src_reg)) {
f4d7e40a 7637 print_verifier_state(env, state);
61bd5218 7638 verbose(env, "verifier internal error: no src_reg\n");
f1174f77
EC
7639 return -EINVAL;
7640 }
7641 return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
48461135
JB
7642}
7643
17a52670 7644/* check validity of 32-bit and 64-bit arithmetic operations */
58e2af8b 7645static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
17a52670 7646{
638f5b90 7647 struct bpf_reg_state *regs = cur_regs(env);
17a52670
AS
7648 u8 opcode = BPF_OP(insn->code);
7649 int err;
7650
7651 if (opcode == BPF_END || opcode == BPF_NEG) {
7652 if (opcode == BPF_NEG) {
7653 if (BPF_SRC(insn->code) != 0 ||
7654 insn->src_reg != BPF_REG_0 ||
7655 insn->off != 0 || insn->imm != 0) {
61bd5218 7656 verbose(env, "BPF_NEG uses reserved fields\n");
17a52670
AS
7657 return -EINVAL;
7658 }
7659 } else {
7660 if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
e67b8a68
EC
7661 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
7662 BPF_CLASS(insn->code) == BPF_ALU64) {
61bd5218 7663 verbose(env, "BPF_END uses reserved fields\n");
17a52670
AS
7664 return -EINVAL;
7665 }
7666 }
7667
7668 /* check src operand */
dc503a8a 7669 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17a52670
AS
7670 if (err)
7671 return err;
7672
1be7f75d 7673 if (is_pointer_value(env, insn->dst_reg)) {
61bd5218 7674 verbose(env, "R%d pointer arithmetic prohibited\n",
1be7f75d
AS
7675 insn->dst_reg);
7676 return -EACCES;
7677 }
7678
17a52670 7679 /* check dest operand */
dc503a8a 7680 err = check_reg_arg(env, insn->dst_reg, DST_OP);
17a52670
AS
7681 if (err)
7682 return err;
7683
7684 } else if (opcode == BPF_MOV) {
7685
7686 if (BPF_SRC(insn->code) == BPF_X) {
7687 if (insn->imm != 0 || insn->off != 0) {
61bd5218 7688 verbose(env, "BPF_MOV uses reserved fields\n");
17a52670
AS
7689 return -EINVAL;
7690 }
7691
7692 /* check src operand */
dc503a8a 7693 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17a52670
AS
7694 if (err)
7695 return err;
7696 } else {
7697 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
61bd5218 7698 verbose(env, "BPF_MOV uses reserved fields\n");
17a52670
AS
7699 return -EINVAL;
7700 }
7701 }
7702
fbeb1603
AF
7703 /* check dest operand, mark as required later */
7704 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
17a52670
AS
7705 if (err)
7706 return err;
7707
7708 if (BPF_SRC(insn->code) == BPF_X) {
e434b8cd
JW
7709 struct bpf_reg_state *src_reg = regs + insn->src_reg;
7710 struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
7711
17a52670
AS
7712 if (BPF_CLASS(insn->code) == BPF_ALU64) {
7713 /* case: R1 = R2
7714 * copy register state to dest reg
7715 */
75748837
AS
7716 if (src_reg->type == SCALAR_VALUE && !src_reg->id)
7717 /* Assign src and dst registers the same ID
7718 * that will be used by find_equal_scalars()
7719 * to propagate min/max range.
7720 */
7721 src_reg->id = ++env->id_gen;
e434b8cd
JW
7722 *dst_reg = *src_reg;
7723 dst_reg->live |= REG_LIVE_WRITTEN;
5327ed3d 7724 dst_reg->subreg_def = DEF_NOT_SUBREG;
17a52670 7725 } else {
f1174f77 7726 /* R1 = (u32) R2 */
1be7f75d 7727 if (is_pointer_value(env, insn->src_reg)) {
61bd5218
JK
7728 verbose(env,
7729 "R%d partial copy of pointer\n",
1be7f75d
AS
7730 insn->src_reg);
7731 return -EACCES;
e434b8cd
JW
7732 } else if (src_reg->type == SCALAR_VALUE) {
7733 *dst_reg = *src_reg;
75748837
AS
7734 /* Make sure ID is cleared otherwise
7735 * dst_reg min/max could be incorrectly
7736 * propagated into src_reg by find_equal_scalars()
7737 */
7738 dst_reg->id = 0;
e434b8cd 7739 dst_reg->live |= REG_LIVE_WRITTEN;
5327ed3d 7740 dst_reg->subreg_def = env->insn_idx + 1;
e434b8cd
JW
7741 } else {
7742 mark_reg_unknown(env, regs,
7743 insn->dst_reg);
1be7f75d 7744 }
3f50f132 7745 zext_32_to_64(dst_reg);
17a52670
AS
7746 }
7747 } else {
7748 /* case: R = imm
7749 * remember the value we stored into this reg
7750 */
fbeb1603
AF
7751 /* clear any state __mark_reg_known doesn't set */
7752 mark_reg_unknown(env, regs, insn->dst_reg);
f1174f77 7753 regs[insn->dst_reg].type = SCALAR_VALUE;
95a762e2
JH
7754 if (BPF_CLASS(insn->code) == BPF_ALU64) {
7755 __mark_reg_known(regs + insn->dst_reg,
7756 insn->imm);
7757 } else {
7758 __mark_reg_known(regs + insn->dst_reg,
7759 (u32)insn->imm);
7760 }
17a52670
AS
7761 }
7762
7763 } else if (opcode > BPF_END) {
61bd5218 7764 verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
17a52670
AS
7765 return -EINVAL;
7766
7767 } else { /* all other ALU ops: and, sub, xor, add, ... */
7768
17a52670
AS
7769 if (BPF_SRC(insn->code) == BPF_X) {
7770 if (insn->imm != 0 || insn->off != 0) {
61bd5218 7771 verbose(env, "BPF_ALU uses reserved fields\n");
17a52670
AS
7772 return -EINVAL;
7773 }
7774 /* check src1 operand */
dc503a8a 7775 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17a52670
AS
7776 if (err)
7777 return err;
7778 } else {
7779 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
61bd5218 7780 verbose(env, "BPF_ALU uses reserved fields\n");
17a52670
AS
7781 return -EINVAL;
7782 }
7783 }
7784
7785 /* check src2 operand */
dc503a8a 7786 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17a52670
AS
7787 if (err)
7788 return err;
7789
7790 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
7791 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
61bd5218 7792 verbose(env, "div by zero\n");
17a52670
AS
7793 return -EINVAL;
7794 }
7795
229394e8
RV
7796 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
7797 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
7798 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
7799
7800 if (insn->imm < 0 || insn->imm >= size) {
61bd5218 7801 verbose(env, "invalid shift %d\n", insn->imm);
229394e8
RV
7802 return -EINVAL;
7803 }
7804 }
7805
1a0dc1ac 7806 /* check dest operand */
dc503a8a 7807 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
1a0dc1ac
AS
7808 if (err)
7809 return err;
7810
f1174f77 7811 return adjust_reg_min_max_vals(env, insn);
17a52670
AS
7812 }
7813
7814 return 0;
7815}
7816
c6a9efa1
PC
7817static void __find_good_pkt_pointers(struct bpf_func_state *state,
7818 struct bpf_reg_state *dst_reg,
6d94e741 7819 enum bpf_reg_type type, int new_range)
c6a9efa1
PC
7820{
7821 struct bpf_reg_state *reg;
7822 int i;
7823
7824 for (i = 0; i < MAX_BPF_REG; i++) {
7825 reg = &state->regs[i];
7826 if (reg->type == type && reg->id == dst_reg->id)
7827 /* keep the maximum range already checked */
7828 reg->range = max(reg->range, new_range);
7829 }
7830
7831 bpf_for_each_spilled_reg(i, state, reg) {
7832 if (!reg)
7833 continue;
7834 if (reg->type == type && reg->id == dst_reg->id)
7835 reg->range = max(reg->range, new_range);
7836 }
7837}
7838
f4d7e40a 7839static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
de8f3a83 7840 struct bpf_reg_state *dst_reg,
f8ddadc4 7841 enum bpf_reg_type type,
fb2a311a 7842 bool range_right_open)
969bf05e 7843{
6d94e741 7844 int new_range, i;
2d2be8ca 7845
fb2a311a
DB
7846 if (dst_reg->off < 0 ||
7847 (dst_reg->off == 0 && range_right_open))
f1174f77
EC
7848 /* This doesn't give us any range */
7849 return;
7850
b03c9f9f
EC
7851 if (dst_reg->umax_value > MAX_PACKET_OFF ||
7852 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
f1174f77
EC
7853 /* Risk of overflow. For instance, ptr + (1<<63) may be less
7854 * than pkt_end, but that's because it's also less than pkt.
7855 */
7856 return;
7857
fb2a311a
DB
7858 new_range = dst_reg->off;
7859 if (range_right_open)
7860 new_range--;
7861
7862 /* Examples for register markings:
2d2be8ca 7863 *
fb2a311a 7864 * pkt_data in dst register:
2d2be8ca
DB
7865 *
7866 * r2 = r3;
7867 * r2 += 8;
7868 * if (r2 > pkt_end) goto <handle exception>
7869 * <access okay>
7870 *
b4e432f1
DB
7871 * r2 = r3;
7872 * r2 += 8;
7873 * if (r2 < pkt_end) goto <access okay>
7874 * <handle exception>
7875 *
2d2be8ca
DB
7876 * Where:
7877 * r2 == dst_reg, pkt_end == src_reg
7878 * r2=pkt(id=n,off=8,r=0)
7879 * r3=pkt(id=n,off=0,r=0)
7880 *
fb2a311a 7881 * pkt_data in src register:
2d2be8ca
DB
7882 *
7883 * r2 = r3;
7884 * r2 += 8;
7885 * if (pkt_end >= r2) goto <access okay>
7886 * <handle exception>
7887 *
b4e432f1
DB
7888 * r2 = r3;
7889 * r2 += 8;
7890 * if (pkt_end <= r2) goto <handle exception>
7891 * <access okay>
7892 *
2d2be8ca
DB
7893 * Where:
7894 * pkt_end == dst_reg, r2 == src_reg
7895 * r2=pkt(id=n,off=8,r=0)
7896 * r3=pkt(id=n,off=0,r=0)
7897 *
7898 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
fb2a311a
DB
7899 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
7900 * and [r3, r3 + 8-1) respectively is safe to access depending on
7901 * the check.
969bf05e 7902 */
2d2be8ca 7903
f1174f77
EC
7904 /* If our ids match, then we must have the same max_value. And we
7905 * don't care about the other reg's fixed offset, since if it's too big
7906 * the range won't allow anything.
7907 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
7908 */
c6a9efa1
PC
7909 for (i = 0; i <= vstate->curframe; i++)
7910 __find_good_pkt_pointers(vstate->frame[i], dst_reg, type,
7911 new_range);
969bf05e
AS
7912}
7913
3f50f132 7914static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
4f7b3e82 7915{
3f50f132
JF
7916 struct tnum subreg = tnum_subreg(reg->var_off);
7917 s32 sval = (s32)val;
a72dafaf 7918
3f50f132
JF
7919 switch (opcode) {
7920 case BPF_JEQ:
7921 if (tnum_is_const(subreg))
7922 return !!tnum_equals_const(subreg, val);
7923 break;
7924 case BPF_JNE:
7925 if (tnum_is_const(subreg))
7926 return !tnum_equals_const(subreg, val);
7927 break;
7928 case BPF_JSET:
7929 if ((~subreg.mask & subreg.value) & val)
7930 return 1;
7931 if (!((subreg.mask | subreg.value) & val))
7932 return 0;
7933 break;
7934 case BPF_JGT:
7935 if (reg->u32_min_value > val)
7936 return 1;
7937 else if (reg->u32_max_value <= val)
7938 return 0;
7939 break;
7940 case BPF_JSGT:
7941 if (reg->s32_min_value > sval)
7942 return 1;
ee114dd6 7943 else if (reg->s32_max_value <= sval)
3f50f132
JF
7944 return 0;
7945 break;
7946 case BPF_JLT:
7947 if (reg->u32_max_value < val)
7948 return 1;
7949 else if (reg->u32_min_value >= val)
7950 return 0;
7951 break;
7952 case BPF_JSLT:
7953 if (reg->s32_max_value < sval)
7954 return 1;
7955 else if (reg->s32_min_value >= sval)
7956 return 0;
7957 break;
7958 case BPF_JGE:
7959 if (reg->u32_min_value >= val)
7960 return 1;
7961 else if (reg->u32_max_value < val)
7962 return 0;
7963 break;
7964 case BPF_JSGE:
7965 if (reg->s32_min_value >= sval)
7966 return 1;
7967 else if (reg->s32_max_value < sval)
7968 return 0;
7969 break;
7970 case BPF_JLE:
7971 if (reg->u32_max_value <= val)
7972 return 1;
7973 else if (reg->u32_min_value > val)
7974 return 0;
7975 break;
7976 case BPF_JSLE:
7977 if (reg->s32_max_value <= sval)
7978 return 1;
7979 else if (reg->s32_min_value > sval)
7980 return 0;
7981 break;
7982 }
4f7b3e82 7983
3f50f132
JF
7984 return -1;
7985}
092ed096 7986
3f50f132
JF
7987
7988static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
7989{
7990 s64 sval = (s64)val;
a72dafaf 7991
4f7b3e82
AS
7992 switch (opcode) {
7993 case BPF_JEQ:
7994 if (tnum_is_const(reg->var_off))
7995 return !!tnum_equals_const(reg->var_off, val);
7996 break;
7997 case BPF_JNE:
7998 if (tnum_is_const(reg->var_off))
7999 return !tnum_equals_const(reg->var_off, val);
8000 break;
960ea056
JK
8001 case BPF_JSET:
8002 if ((~reg->var_off.mask & reg->var_off.value) & val)
8003 return 1;
8004 if (!((reg->var_off.mask | reg->var_off.value) & val))
8005 return 0;
8006 break;
4f7b3e82
AS
8007 case BPF_JGT:
8008 if (reg->umin_value > val)
8009 return 1;
8010 else if (reg->umax_value <= val)
8011 return 0;
8012 break;
8013 case BPF_JSGT:
a72dafaf 8014 if (reg->smin_value > sval)
4f7b3e82 8015 return 1;
ee114dd6 8016 else if (reg->smax_value <= sval)
4f7b3e82
AS
8017 return 0;
8018 break;
8019 case BPF_JLT:
8020 if (reg->umax_value < val)
8021 return 1;
8022 else if (reg->umin_value >= val)
8023 return 0;
8024 break;
8025 case BPF_JSLT:
a72dafaf 8026 if (reg->smax_value < sval)
4f7b3e82 8027 return 1;
a72dafaf 8028 else if (reg->smin_value >= sval)
4f7b3e82
AS
8029 return 0;
8030 break;
8031 case BPF_JGE:
8032 if (reg->umin_value >= val)
8033 return 1;
8034 else if (reg->umax_value < val)
8035 return 0;
8036 break;
8037 case BPF_JSGE:
a72dafaf 8038 if (reg->smin_value >= sval)
4f7b3e82 8039 return 1;
a72dafaf 8040 else if (reg->smax_value < sval)
4f7b3e82
AS
8041 return 0;
8042 break;
8043 case BPF_JLE:
8044 if (reg->umax_value <= val)
8045 return 1;
8046 else if (reg->umin_value > val)
8047 return 0;
8048 break;
8049 case BPF_JSLE:
a72dafaf 8050 if (reg->smax_value <= sval)
4f7b3e82 8051 return 1;
a72dafaf 8052 else if (reg->smin_value > sval)
4f7b3e82
AS
8053 return 0;
8054 break;
8055 }
8056
8057 return -1;
8058}
8059
3f50f132
JF
8060/* compute branch direction of the expression "if (reg opcode val) goto target;"
8061 * and return:
8062 * 1 - branch will be taken and "goto target" will be executed
8063 * 0 - branch will not be taken and fall-through to next insn
8064 * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
8065 * range [0,10]
604dca5e 8066 */
3f50f132
JF
8067static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
8068 bool is_jmp32)
604dca5e 8069{
cac616db
JF
8070 if (__is_pointer_value(false, reg)) {
8071 if (!reg_type_not_null(reg->type))
8072 return -1;
8073
8074 /* If pointer is valid tests against zero will fail so we can
8075 * use this to direct branch taken.
8076 */
8077 if (val != 0)
8078 return -1;
8079
8080 switch (opcode) {
8081 case BPF_JEQ:
8082 return 0;
8083 case BPF_JNE:
8084 return 1;
8085 default:
8086 return -1;
8087 }
8088 }
604dca5e 8089
3f50f132
JF
8090 if (is_jmp32)
8091 return is_branch32_taken(reg, val, opcode);
8092 return is_branch64_taken(reg, val, opcode);
604dca5e
JH
8093}
8094
6d94e741
AS
8095static int flip_opcode(u32 opcode)
8096{
8097 /* How can we transform "a <op> b" into "b <op> a"? */
8098 static const u8 opcode_flip[16] = {
8099 /* these stay the same */
8100 [BPF_JEQ >> 4] = BPF_JEQ,
8101 [BPF_JNE >> 4] = BPF_JNE,
8102 [BPF_JSET >> 4] = BPF_JSET,
8103 /* these swap "lesser" and "greater" (L and G in the opcodes) */
8104 [BPF_JGE >> 4] = BPF_JLE,
8105 [BPF_JGT >> 4] = BPF_JLT,
8106 [BPF_JLE >> 4] = BPF_JGE,
8107 [BPF_JLT >> 4] = BPF_JGT,
8108 [BPF_JSGE >> 4] = BPF_JSLE,
8109 [BPF_JSGT >> 4] = BPF_JSLT,
8110 [BPF_JSLE >> 4] = BPF_JSGE,
8111 [BPF_JSLT >> 4] = BPF_JSGT
8112 };
8113 return opcode_flip[opcode >> 4];
8114}
8115
8116static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
8117 struct bpf_reg_state *src_reg,
8118 u8 opcode)
8119{
8120 struct bpf_reg_state *pkt;
8121
8122 if (src_reg->type == PTR_TO_PACKET_END) {
8123 pkt = dst_reg;
8124 } else if (dst_reg->type == PTR_TO_PACKET_END) {
8125 pkt = src_reg;
8126 opcode = flip_opcode(opcode);
8127 } else {
8128 return -1;
8129 }
8130
8131 if (pkt->range >= 0)
8132 return -1;
8133
8134 switch (opcode) {
8135 case BPF_JLE:
8136 /* pkt <= pkt_end */
8137 fallthrough;
8138 case BPF_JGT:
8139 /* pkt > pkt_end */
8140 if (pkt->range == BEYOND_PKT_END)
8141 /* pkt has at last one extra byte beyond pkt_end */
8142 return opcode == BPF_JGT;
8143 break;
8144 case BPF_JLT:
8145 /* pkt < pkt_end */
8146 fallthrough;
8147 case BPF_JGE:
8148 /* pkt >= pkt_end */
8149 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
8150 return opcode == BPF_JGE;
8151 break;
8152 }
8153 return -1;
8154}
8155
48461135
JB
8156/* Adjusts the register min/max values in the case that the dst_reg is the
8157 * variable register that we are working on, and src_reg is a constant or we're
8158 * simply doing a BPF_K check.
f1174f77 8159 * In JEQ/JNE cases we also adjust the var_off values.
48461135
JB
8160 */
8161static void reg_set_min_max(struct bpf_reg_state *true_reg,
3f50f132
JF
8162 struct bpf_reg_state *false_reg,
8163 u64 val, u32 val32,
092ed096 8164 u8 opcode, bool is_jmp32)
48461135 8165{
3f50f132
JF
8166 struct tnum false_32off = tnum_subreg(false_reg->var_off);
8167 struct tnum false_64off = false_reg->var_off;
8168 struct tnum true_32off = tnum_subreg(true_reg->var_off);
8169 struct tnum true_64off = true_reg->var_off;
8170 s64 sval = (s64)val;
8171 s32 sval32 = (s32)val32;
a72dafaf 8172
f1174f77
EC
8173 /* If the dst_reg is a pointer, we can't learn anything about its
8174 * variable offset from the compare (unless src_reg were a pointer into
8175 * the same object, but we don't bother with that.
8176 * Since false_reg and true_reg have the same type by construction, we
8177 * only need to check one of them for pointerness.
8178 */
8179 if (__is_pointer_value(false, false_reg))
8180 return;
4cabc5b1 8181
48461135
JB
8182 switch (opcode) {
8183 case BPF_JEQ:
48461135 8184 case BPF_JNE:
a72dafaf
JW
8185 {
8186 struct bpf_reg_state *reg =
8187 opcode == BPF_JEQ ? true_reg : false_reg;
8188
e688c3db
AS
8189 /* JEQ/JNE comparison doesn't change the register equivalence.
8190 * r1 = r2;
8191 * if (r1 == 42) goto label;
8192 * ...
8193 * label: // here both r1 and r2 are known to be 42.
8194 *
8195 * Hence when marking register as known preserve it's ID.
48461135 8196 */
3f50f132
JF
8197 if (is_jmp32)
8198 __mark_reg32_known(reg, val32);
8199 else
e688c3db 8200 ___mark_reg_known(reg, val);
48461135 8201 break;
a72dafaf 8202 }
960ea056 8203 case BPF_JSET:
3f50f132
JF
8204 if (is_jmp32) {
8205 false_32off = tnum_and(false_32off, tnum_const(~val32));
8206 if (is_power_of_2(val32))
8207 true_32off = tnum_or(true_32off,
8208 tnum_const(val32));
8209 } else {
8210 false_64off = tnum_and(false_64off, tnum_const(~val));
8211 if (is_power_of_2(val))
8212 true_64off = tnum_or(true_64off,
8213 tnum_const(val));
8214 }
960ea056 8215 break;
48461135 8216 case BPF_JGE:
a72dafaf
JW
8217 case BPF_JGT:
8218 {
3f50f132
JF
8219 if (is_jmp32) {
8220 u32 false_umax = opcode == BPF_JGT ? val32 : val32 - 1;
8221 u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
8222
8223 false_reg->u32_max_value = min(false_reg->u32_max_value,
8224 false_umax);
8225 true_reg->u32_min_value = max(true_reg->u32_min_value,
8226 true_umin);
8227 } else {
8228 u64 false_umax = opcode == BPF_JGT ? val : val - 1;
8229 u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
8230
8231 false_reg->umax_value = min(false_reg->umax_value, false_umax);
8232 true_reg->umin_value = max(true_reg->umin_value, true_umin);
8233 }
b03c9f9f 8234 break;
a72dafaf 8235 }
48461135 8236 case BPF_JSGE:
a72dafaf
JW
8237 case BPF_JSGT:
8238 {
3f50f132
JF
8239 if (is_jmp32) {
8240 s32 false_smax = opcode == BPF_JSGT ? sval32 : sval32 - 1;
8241 s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
a72dafaf 8242
3f50f132
JF
8243 false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
8244 true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
8245 } else {
8246 s64 false_smax = opcode == BPF_JSGT ? sval : sval - 1;
8247 s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
8248
8249 false_reg->smax_value = min(false_reg->smax_value, false_smax);
8250 true_reg->smin_value = max(true_reg->smin_value, true_smin);
8251 }
48461135 8252 break;
a72dafaf 8253 }
b4e432f1 8254 case BPF_JLE:
a72dafaf
JW
8255 case BPF_JLT:
8256 {
3f50f132
JF
8257 if (is_jmp32) {
8258 u32 false_umin = opcode == BPF_JLT ? val32 : val32 + 1;
8259 u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
8260
8261 false_reg->u32_min_value = max(false_reg->u32_min_value,
8262 false_umin);
8263 true_reg->u32_max_value = min(true_reg->u32_max_value,
8264 true_umax);
8265 } else {
8266 u64 false_umin = opcode == BPF_JLT ? val : val + 1;
8267 u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
8268
8269 false_reg->umin_value = max(false_reg->umin_value, false_umin);
8270 true_reg->umax_value = min(true_reg->umax_value, true_umax);
8271 }
b4e432f1 8272 break;
a72dafaf 8273 }
b4e432f1 8274 case BPF_JSLE:
a72dafaf
JW
8275 case BPF_JSLT:
8276 {
3f50f132
JF
8277 if (is_jmp32) {
8278 s32 false_smin = opcode == BPF_JSLT ? sval32 : sval32 + 1;
8279 s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
a72dafaf 8280
3f50f132
JF
8281 false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
8282 true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
8283 } else {
8284 s64 false_smin = opcode == BPF_JSLT ? sval : sval + 1;
8285 s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
8286
8287 false_reg->smin_value = max(false_reg->smin_value, false_smin);
8288 true_reg->smax_value = min(true_reg->smax_value, true_smax);
8289 }
b4e432f1 8290 break;
a72dafaf 8291 }
48461135 8292 default:
0fc31b10 8293 return;
48461135
JB
8294 }
8295
3f50f132
JF
8296 if (is_jmp32) {
8297 false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
8298 tnum_subreg(false_32off));
8299 true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
8300 tnum_subreg(true_32off));
8301 __reg_combine_32_into_64(false_reg);
8302 __reg_combine_32_into_64(true_reg);
8303 } else {
8304 false_reg->var_off = false_64off;
8305 true_reg->var_off = true_64off;
8306 __reg_combine_64_into_32(false_reg);
8307 __reg_combine_64_into_32(true_reg);
8308 }
48461135
JB
8309}
8310
f1174f77
EC
8311/* Same as above, but for the case that dst_reg holds a constant and src_reg is
8312 * the variable reg.
48461135
JB
8313 */
8314static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
3f50f132
JF
8315 struct bpf_reg_state *false_reg,
8316 u64 val, u32 val32,
092ed096 8317 u8 opcode, bool is_jmp32)
48461135 8318{
6d94e741 8319 opcode = flip_opcode(opcode);
0fc31b10
JH
8320 /* This uses zero as "not present in table"; luckily the zero opcode,
8321 * BPF_JA, can't get here.
b03c9f9f 8322 */
0fc31b10 8323 if (opcode)
3f50f132 8324 reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
f1174f77
EC
8325}
8326
8327/* Regs are known to be equal, so intersect their min/max/var_off */
8328static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
8329 struct bpf_reg_state *dst_reg)
8330{
b03c9f9f
EC
8331 src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
8332 dst_reg->umin_value);
8333 src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
8334 dst_reg->umax_value);
8335 src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
8336 dst_reg->smin_value);
8337 src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
8338 dst_reg->smax_value);
f1174f77
EC
8339 src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
8340 dst_reg->var_off);
b03c9f9f
EC
8341 /* We might have learned new bounds from the var_off. */
8342 __update_reg_bounds(src_reg);
8343 __update_reg_bounds(dst_reg);
8344 /* We might have learned something about the sign bit. */
8345 __reg_deduce_bounds(src_reg);
8346 __reg_deduce_bounds(dst_reg);
8347 /* We might have learned some bits from the bounds. */
8348 __reg_bound_offset(src_reg);
8349 __reg_bound_offset(dst_reg);
8350 /* Intersecting with the old var_off might have improved our bounds
8351 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
8352 * then new var_off is (0; 0x7f...fc) which improves our umax.
8353 */
8354 __update_reg_bounds(src_reg);
8355 __update_reg_bounds(dst_reg);
f1174f77
EC
8356}
8357
8358static void reg_combine_min_max(struct bpf_reg_state *true_src,
8359 struct bpf_reg_state *true_dst,
8360 struct bpf_reg_state *false_src,
8361 struct bpf_reg_state *false_dst,
8362 u8 opcode)
8363{
8364 switch (opcode) {
8365 case BPF_JEQ:
8366 __reg_combine_min_max(true_src, true_dst);
8367 break;
8368 case BPF_JNE:
8369 __reg_combine_min_max(false_src, false_dst);
b03c9f9f 8370 break;
4cabc5b1 8371 }
48461135
JB
8372}
8373
fd978bf7
JS
8374static void mark_ptr_or_null_reg(struct bpf_func_state *state,
8375 struct bpf_reg_state *reg, u32 id,
840b9615 8376 bool is_null)
57a09bf0 8377{
93c230e3
MKL
8378 if (reg_type_may_be_null(reg->type) && reg->id == id &&
8379 !WARN_ON_ONCE(!reg->id)) {
f1174f77
EC
8380 /* Old offset (both fixed and variable parts) should
8381 * have been known-zero, because we don't allow pointer
8382 * arithmetic on pointers that might be NULL.
8383 */
b03c9f9f
EC
8384 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value ||
8385 !tnum_equals_const(reg->var_off, 0) ||
f1174f77 8386 reg->off)) {
b03c9f9f
EC
8387 __mark_reg_known_zero(reg);
8388 reg->off = 0;
f1174f77
EC
8389 }
8390 if (is_null) {
8391 reg->type = SCALAR_VALUE;
1b986589
MKL
8392 /* We don't need id and ref_obj_id from this point
8393 * onwards anymore, thus we should better reset it,
8394 * so that state pruning has chances to take effect.
8395 */
8396 reg->id = 0;
8397 reg->ref_obj_id = 0;
4ddb7416
DB
8398
8399 return;
8400 }
8401
8402 mark_ptr_not_null_reg(reg);
8403
8404 if (!reg_may_point_to_spin_lock(reg)) {
1b986589
MKL
8405 /* For not-NULL ptr, reg->ref_obj_id will be reset
8406 * in release_reg_references().
8407 *
8408 * reg->id is still used by spin_lock ptr. Other
8409 * than spin_lock ptr type, reg->id can be reset.
fd978bf7
JS
8410 */
8411 reg->id = 0;
56f668df 8412 }
57a09bf0
TG
8413 }
8414}
8415
c6a9efa1
PC
8416static void __mark_ptr_or_null_regs(struct bpf_func_state *state, u32 id,
8417 bool is_null)
8418{
8419 struct bpf_reg_state *reg;
8420 int i;
8421
8422 for (i = 0; i < MAX_BPF_REG; i++)
8423 mark_ptr_or_null_reg(state, &state->regs[i], id, is_null);
8424
8425 bpf_for_each_spilled_reg(i, state, reg) {
8426 if (!reg)
8427 continue;
8428 mark_ptr_or_null_reg(state, reg, id, is_null);
8429 }
8430}
8431
57a09bf0
TG
8432/* The logic is similar to find_good_pkt_pointers(), both could eventually
8433 * be folded together at some point.
8434 */
840b9615
JS
8435static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
8436 bool is_null)
57a09bf0 8437{
f4d7e40a 8438 struct bpf_func_state *state = vstate->frame[vstate->curframe];
c6a9efa1 8439 struct bpf_reg_state *regs = state->regs;
1b986589 8440 u32 ref_obj_id = regs[regno].ref_obj_id;
a08dd0da 8441 u32 id = regs[regno].id;
c6a9efa1 8442 int i;
57a09bf0 8443
1b986589
MKL
8444 if (ref_obj_id && ref_obj_id == id && is_null)
8445 /* regs[regno] is in the " == NULL" branch.
8446 * No one could have freed the reference state before
8447 * doing the NULL check.
8448 */
8449 WARN_ON_ONCE(release_reference_state(state, id));
fd978bf7 8450
c6a9efa1
PC
8451 for (i = 0; i <= vstate->curframe; i++)
8452 __mark_ptr_or_null_regs(vstate->frame[i], id, is_null);
57a09bf0
TG
8453}
8454
5beca081
DB
8455static bool try_match_pkt_pointers(const struct bpf_insn *insn,
8456 struct bpf_reg_state *dst_reg,
8457 struct bpf_reg_state *src_reg,
8458 struct bpf_verifier_state *this_branch,
8459 struct bpf_verifier_state *other_branch)
8460{
8461 if (BPF_SRC(insn->code) != BPF_X)
8462 return false;
8463
092ed096
JW
8464 /* Pointers are always 64-bit. */
8465 if (BPF_CLASS(insn->code) == BPF_JMP32)
8466 return false;
8467
5beca081
DB
8468 switch (BPF_OP(insn->code)) {
8469 case BPF_JGT:
8470 if ((dst_reg->type == PTR_TO_PACKET &&
8471 src_reg->type == PTR_TO_PACKET_END) ||
8472 (dst_reg->type == PTR_TO_PACKET_META &&
8473 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
8474 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
8475 find_good_pkt_pointers(this_branch, dst_reg,
8476 dst_reg->type, false);
6d94e741 8477 mark_pkt_end(other_branch, insn->dst_reg, true);
5beca081
DB
8478 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
8479 src_reg->type == PTR_TO_PACKET) ||
8480 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
8481 src_reg->type == PTR_TO_PACKET_META)) {
8482 /* pkt_end > pkt_data', pkt_data > pkt_meta' */
8483 find_good_pkt_pointers(other_branch, src_reg,
8484 src_reg->type, true);
6d94e741 8485 mark_pkt_end(this_branch, insn->src_reg, false);
5beca081
DB
8486 } else {
8487 return false;
8488 }
8489 break;
8490 case BPF_JLT:
8491 if ((dst_reg->type == PTR_TO_PACKET &&
8492 src_reg->type == PTR_TO_PACKET_END) ||
8493 (dst_reg->type == PTR_TO_PACKET_META &&
8494 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
8495 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
8496 find_good_pkt_pointers(other_branch, dst_reg,
8497 dst_reg->type, true);
6d94e741 8498 mark_pkt_end(this_branch, insn->dst_reg, false);
5beca081
DB
8499 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
8500 src_reg->type == PTR_TO_PACKET) ||
8501 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
8502 src_reg->type == PTR_TO_PACKET_META)) {
8503 /* pkt_end < pkt_data', pkt_data > pkt_meta' */
8504 find_good_pkt_pointers(this_branch, src_reg,
8505 src_reg->type, false);
6d94e741 8506 mark_pkt_end(other_branch, insn->src_reg, true);
5beca081
DB
8507 } else {
8508 return false;
8509 }
8510 break;
8511 case BPF_JGE:
8512 if ((dst_reg->type == PTR_TO_PACKET &&
8513 src_reg->type == PTR_TO_PACKET_END) ||
8514 (dst_reg->type == PTR_TO_PACKET_META &&
8515 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
8516 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
8517 find_good_pkt_pointers(this_branch, dst_reg,
8518 dst_reg->type, true);
6d94e741 8519 mark_pkt_end(other_branch, insn->dst_reg, false);
5beca081
DB
8520 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
8521 src_reg->type == PTR_TO_PACKET) ||
8522 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
8523 src_reg->type == PTR_TO_PACKET_META)) {
8524 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
8525 find_good_pkt_pointers(other_branch, src_reg,
8526 src_reg->type, false);
6d94e741 8527 mark_pkt_end(this_branch, insn->src_reg, true);
5beca081
DB
8528 } else {
8529 return false;
8530 }
8531 break;
8532 case BPF_JLE:
8533 if ((dst_reg->type == PTR_TO_PACKET &&
8534 src_reg->type == PTR_TO_PACKET_END) ||
8535 (dst_reg->type == PTR_TO_PACKET_META &&
8536 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
8537 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
8538 find_good_pkt_pointers(other_branch, dst_reg,
8539 dst_reg->type, false);
6d94e741 8540 mark_pkt_end(this_branch, insn->dst_reg, true);
5beca081
DB
8541 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
8542 src_reg->type == PTR_TO_PACKET) ||
8543 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
8544 src_reg->type == PTR_TO_PACKET_META)) {
8545 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
8546 find_good_pkt_pointers(this_branch, src_reg,
8547 src_reg->type, true);
6d94e741 8548 mark_pkt_end(other_branch, insn->src_reg, false);
5beca081
DB
8549 } else {
8550 return false;
8551 }
8552 break;
8553 default:
8554 return false;
8555 }
8556
8557 return true;
8558}
8559
75748837
AS
8560static void find_equal_scalars(struct bpf_verifier_state *vstate,
8561 struct bpf_reg_state *known_reg)
8562{
8563 struct bpf_func_state *state;
8564 struct bpf_reg_state *reg;
8565 int i, j;
8566
8567 for (i = 0; i <= vstate->curframe; i++) {
8568 state = vstate->frame[i];
8569 for (j = 0; j < MAX_BPF_REG; j++) {
8570 reg = &state->regs[j];
8571 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
8572 *reg = *known_reg;
8573 }
8574
8575 bpf_for_each_spilled_reg(j, state, reg) {
8576 if (!reg)
8577 continue;
8578 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
8579 *reg = *known_reg;
8580 }
8581 }
8582}
8583
58e2af8b 8584static int check_cond_jmp_op(struct bpf_verifier_env *env,
17a52670
AS
8585 struct bpf_insn *insn, int *insn_idx)
8586{
f4d7e40a
AS
8587 struct bpf_verifier_state *this_branch = env->cur_state;
8588 struct bpf_verifier_state *other_branch;
8589 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
fb8d251e 8590 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
17a52670 8591 u8 opcode = BPF_OP(insn->code);
092ed096 8592 bool is_jmp32;
fb8d251e 8593 int pred = -1;
17a52670
AS
8594 int err;
8595
092ed096
JW
8596 /* Only conditional jumps are expected to reach here. */
8597 if (opcode == BPF_JA || opcode > BPF_JSLE) {
8598 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
17a52670
AS
8599 return -EINVAL;
8600 }
8601
8602 if (BPF_SRC(insn->code) == BPF_X) {
8603 if (insn->imm != 0) {
092ed096 8604 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
17a52670
AS
8605 return -EINVAL;
8606 }
8607
8608 /* check src1 operand */
dc503a8a 8609 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17a52670
AS
8610 if (err)
8611 return err;
1be7f75d
AS
8612
8613 if (is_pointer_value(env, insn->src_reg)) {
61bd5218 8614 verbose(env, "R%d pointer comparison prohibited\n",
1be7f75d
AS
8615 insn->src_reg);
8616 return -EACCES;
8617 }
fb8d251e 8618 src_reg = &regs[insn->src_reg];
17a52670
AS
8619 } else {
8620 if (insn->src_reg != BPF_REG_0) {
092ed096 8621 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
17a52670
AS
8622 return -EINVAL;
8623 }
8624 }
8625
8626 /* check src2 operand */
dc503a8a 8627 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17a52670
AS
8628 if (err)
8629 return err;
8630
1a0dc1ac 8631 dst_reg = &regs[insn->dst_reg];
092ed096 8632 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
1a0dc1ac 8633
3f50f132
JF
8634 if (BPF_SRC(insn->code) == BPF_K) {
8635 pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
8636 } else if (src_reg->type == SCALAR_VALUE &&
8637 is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
8638 pred = is_branch_taken(dst_reg,
8639 tnum_subreg(src_reg->var_off).value,
8640 opcode,
8641 is_jmp32);
8642 } else if (src_reg->type == SCALAR_VALUE &&
8643 !is_jmp32 && tnum_is_const(src_reg->var_off)) {
8644 pred = is_branch_taken(dst_reg,
8645 src_reg->var_off.value,
8646 opcode,
8647 is_jmp32);
6d94e741
AS
8648 } else if (reg_is_pkt_pointer_any(dst_reg) &&
8649 reg_is_pkt_pointer_any(src_reg) &&
8650 !is_jmp32) {
8651 pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
3f50f132
JF
8652 }
8653
b5dc0163 8654 if (pred >= 0) {
cac616db
JF
8655 /* If we get here with a dst_reg pointer type it is because
8656 * above is_branch_taken() special cased the 0 comparison.
8657 */
8658 if (!__is_pointer_value(false, dst_reg))
8659 err = mark_chain_precision(env, insn->dst_reg);
6d94e741
AS
8660 if (BPF_SRC(insn->code) == BPF_X && !err &&
8661 !__is_pointer_value(false, src_reg))
b5dc0163
AS
8662 err = mark_chain_precision(env, insn->src_reg);
8663 if (err)
8664 return err;
8665 }
fb8d251e
AS
8666 if (pred == 1) {
8667 /* only follow the goto, ignore fall-through */
8668 *insn_idx += insn->off;
8669 return 0;
8670 } else if (pred == 0) {
8671 /* only follow fall-through branch, since
8672 * that's where the program will go
8673 */
8674 return 0;
17a52670
AS
8675 }
8676
979d63d5
DB
8677 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
8678 false);
17a52670
AS
8679 if (!other_branch)
8680 return -EFAULT;
f4d7e40a 8681 other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
17a52670 8682
48461135
JB
8683 /* detect if we are comparing against a constant value so we can adjust
8684 * our min/max values for our dst register.
f1174f77
EC
8685 * this is only legit if both are scalars (or pointers to the same
8686 * object, I suppose, but we don't support that right now), because
8687 * otherwise the different base pointers mean the offsets aren't
8688 * comparable.
48461135
JB
8689 */
8690 if (BPF_SRC(insn->code) == BPF_X) {
092ed096 8691 struct bpf_reg_state *src_reg = &regs[insn->src_reg];
092ed096 8692
f1174f77 8693 if (dst_reg->type == SCALAR_VALUE &&
092ed096
JW
8694 src_reg->type == SCALAR_VALUE) {
8695 if (tnum_is_const(src_reg->var_off) ||
3f50f132
JF
8696 (is_jmp32 &&
8697 tnum_is_const(tnum_subreg(src_reg->var_off))))
f4d7e40a 8698 reg_set_min_max(&other_branch_regs[insn->dst_reg],
092ed096 8699 dst_reg,
3f50f132
JF
8700 src_reg->var_off.value,
8701 tnum_subreg(src_reg->var_off).value,
092ed096
JW
8702 opcode, is_jmp32);
8703 else if (tnum_is_const(dst_reg->var_off) ||
3f50f132
JF
8704 (is_jmp32 &&
8705 tnum_is_const(tnum_subreg(dst_reg->var_off))))
f4d7e40a 8706 reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
092ed096 8707 src_reg,
3f50f132
JF
8708 dst_reg->var_off.value,
8709 tnum_subreg(dst_reg->var_off).value,
092ed096
JW
8710 opcode, is_jmp32);
8711 else if (!is_jmp32 &&
8712 (opcode == BPF_JEQ || opcode == BPF_JNE))
f1174f77 8713 /* Comparing for equality, we can combine knowledge */
f4d7e40a
AS
8714 reg_combine_min_max(&other_branch_regs[insn->src_reg],
8715 &other_branch_regs[insn->dst_reg],
092ed096 8716 src_reg, dst_reg, opcode);
e688c3db
AS
8717 if (src_reg->id &&
8718 !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
75748837
AS
8719 find_equal_scalars(this_branch, src_reg);
8720 find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
8721 }
8722
f1174f77
EC
8723 }
8724 } else if (dst_reg->type == SCALAR_VALUE) {
f4d7e40a 8725 reg_set_min_max(&other_branch_regs[insn->dst_reg],
3f50f132
JF
8726 dst_reg, insn->imm, (u32)insn->imm,
8727 opcode, is_jmp32);
48461135
JB
8728 }
8729
e688c3db
AS
8730 if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
8731 !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
75748837
AS
8732 find_equal_scalars(this_branch, dst_reg);
8733 find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
8734 }
8735
092ed096
JW
8736 /* detect if R == 0 where R is returned from bpf_map_lookup_elem().
8737 * NOTE: these optimizations below are related with pointer comparison
8738 * which will never be JMP32.
8739 */
8740 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
1a0dc1ac 8741 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
840b9615
JS
8742 reg_type_may_be_null(dst_reg->type)) {
8743 /* Mark all identical registers in each branch as either
57a09bf0
TG
8744 * safe or unknown depending R == 0 or R != 0 conditional.
8745 */
840b9615
JS
8746 mark_ptr_or_null_regs(this_branch, insn->dst_reg,
8747 opcode == BPF_JNE);
8748 mark_ptr_or_null_regs(other_branch, insn->dst_reg,
8749 opcode == BPF_JEQ);
5beca081
DB
8750 } else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
8751 this_branch, other_branch) &&
8752 is_pointer_value(env, insn->dst_reg)) {
61bd5218
JK
8753 verbose(env, "R%d pointer comparison prohibited\n",
8754 insn->dst_reg);
1be7f75d 8755 return -EACCES;
17a52670 8756 }
06ee7115 8757 if (env->log.level & BPF_LOG_LEVEL)
f4d7e40a 8758 print_verifier_state(env, this_branch->frame[this_branch->curframe]);
17a52670
AS
8759 return 0;
8760}
8761
17a52670 8762/* verify BPF_LD_IMM64 instruction */
58e2af8b 8763static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
17a52670 8764{
d8eca5bb 8765 struct bpf_insn_aux_data *aux = cur_aux(env);
638f5b90 8766 struct bpf_reg_state *regs = cur_regs(env);
4976b718 8767 struct bpf_reg_state *dst_reg;
d8eca5bb 8768 struct bpf_map *map;
17a52670
AS
8769 int err;
8770
8771 if (BPF_SIZE(insn->code) != BPF_DW) {
61bd5218 8772 verbose(env, "invalid BPF_LD_IMM insn\n");
17a52670
AS
8773 return -EINVAL;
8774 }
8775 if (insn->off != 0) {
61bd5218 8776 verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
17a52670
AS
8777 return -EINVAL;
8778 }
8779
dc503a8a 8780 err = check_reg_arg(env, insn->dst_reg, DST_OP);
17a52670
AS
8781 if (err)
8782 return err;
8783
4976b718 8784 dst_reg = &regs[insn->dst_reg];
6b173873 8785 if (insn->src_reg == 0) {
6b173873
JK
8786 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
8787
4976b718 8788 dst_reg->type = SCALAR_VALUE;
b03c9f9f 8789 __mark_reg_known(&regs[insn->dst_reg], imm);
17a52670 8790 return 0;
6b173873 8791 }
17a52670 8792
4976b718
HL
8793 if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
8794 mark_reg_known_zero(env, regs, insn->dst_reg);
8795
8796 dst_reg->type = aux->btf_var.reg_type;
8797 switch (dst_reg->type) {
8798 case PTR_TO_MEM:
8799 dst_reg->mem_size = aux->btf_var.mem_size;
8800 break;
8801 case PTR_TO_BTF_ID:
eaa6bcb7 8802 case PTR_TO_PERCPU_BTF_ID:
22dc4a0f 8803 dst_reg->btf = aux->btf_var.btf;
4976b718
HL
8804 dst_reg->btf_id = aux->btf_var.btf_id;
8805 break;
8806 default:
8807 verbose(env, "bpf verifier is misconfigured\n");
8808 return -EFAULT;
8809 }
8810 return 0;
8811 }
8812
69c087ba
YS
8813 if (insn->src_reg == BPF_PSEUDO_FUNC) {
8814 struct bpf_prog_aux *aux = env->prog->aux;
8815 u32 subprogno = insn[1].imm;
8816
8817 if (!aux->func_info) {
8818 verbose(env, "missing btf func_info\n");
8819 return -EINVAL;
8820 }
8821 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
8822 verbose(env, "callback function not static\n");
8823 return -EINVAL;
8824 }
8825
8826 dst_reg->type = PTR_TO_FUNC;
8827 dst_reg->subprogno = subprogno;
8828 return 0;
8829 }
8830
d8eca5bb
DB
8831 map = env->used_maps[aux->map_index];
8832 mark_reg_known_zero(env, regs, insn->dst_reg);
4976b718 8833 dst_reg->map_ptr = map;
d8eca5bb
DB
8834
8835 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE) {
4976b718
HL
8836 dst_reg->type = PTR_TO_MAP_VALUE;
8837 dst_reg->off = aux->map_off;
d8eca5bb 8838 if (map_value_has_spin_lock(map))
4976b718 8839 dst_reg->id = ++env->id_gen;
d8eca5bb 8840 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD) {
4976b718 8841 dst_reg->type = CONST_PTR_TO_MAP;
d8eca5bb
DB
8842 } else {
8843 verbose(env, "bpf verifier is misconfigured\n");
8844 return -EINVAL;
8845 }
17a52670 8846
17a52670
AS
8847 return 0;
8848}
8849
96be4325
DB
8850static bool may_access_skb(enum bpf_prog_type type)
8851{
8852 switch (type) {
8853 case BPF_PROG_TYPE_SOCKET_FILTER:
8854 case BPF_PROG_TYPE_SCHED_CLS:
94caee8c 8855 case BPF_PROG_TYPE_SCHED_ACT:
96be4325
DB
8856 return true;
8857 default:
8858 return false;
8859 }
8860}
8861
ddd872bc
AS
8862/* verify safety of LD_ABS|LD_IND instructions:
8863 * - they can only appear in the programs where ctx == skb
8864 * - since they are wrappers of function calls, they scratch R1-R5 registers,
8865 * preserve R6-R9, and store return value into R0
8866 *
8867 * Implicit input:
8868 * ctx == skb == R6 == CTX
8869 *
8870 * Explicit input:
8871 * SRC == any register
8872 * IMM == 32-bit immediate
8873 *
8874 * Output:
8875 * R0 - 8/16/32-bit skb data converted to cpu endianness
8876 */
58e2af8b 8877static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
ddd872bc 8878{
638f5b90 8879 struct bpf_reg_state *regs = cur_regs(env);
6d4f151a 8880 static const int ctx_reg = BPF_REG_6;
ddd872bc 8881 u8 mode = BPF_MODE(insn->code);
ddd872bc
AS
8882 int i, err;
8883
7e40781c 8884 if (!may_access_skb(resolve_prog_type(env->prog))) {
61bd5218 8885 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
ddd872bc
AS
8886 return -EINVAL;
8887 }
8888
e0cea7ce
DB
8889 if (!env->ops->gen_ld_abs) {
8890 verbose(env, "bpf verifier is misconfigured\n");
8891 return -EINVAL;
8892 }
8893
ddd872bc 8894 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
d82bccc6 8895 BPF_SIZE(insn->code) == BPF_DW ||
ddd872bc 8896 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
61bd5218 8897 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
ddd872bc
AS
8898 return -EINVAL;
8899 }
8900
8901 /* check whether implicit source operand (register R6) is readable */
6d4f151a 8902 err = check_reg_arg(env, ctx_reg, SRC_OP);
ddd872bc
AS
8903 if (err)
8904 return err;
8905
fd978bf7
JS
8906 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
8907 * gen_ld_abs() may terminate the program at runtime, leading to
8908 * reference leak.
8909 */
8910 err = check_reference_leak(env);
8911 if (err) {
8912 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
8913 return err;
8914 }
8915
d83525ca
AS
8916 if (env->cur_state->active_spin_lock) {
8917 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
8918 return -EINVAL;
8919 }
8920
6d4f151a 8921 if (regs[ctx_reg].type != PTR_TO_CTX) {
61bd5218
JK
8922 verbose(env,
8923 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
ddd872bc
AS
8924 return -EINVAL;
8925 }
8926
8927 if (mode == BPF_IND) {
8928 /* check explicit source operand */
dc503a8a 8929 err = check_reg_arg(env, insn->src_reg, SRC_OP);
ddd872bc
AS
8930 if (err)
8931 return err;
8932 }
8933
6d4f151a
DB
8934 err = check_ctx_reg(env, &regs[ctx_reg], ctx_reg);
8935 if (err < 0)
8936 return err;
8937
ddd872bc 8938 /* reset caller saved regs to unreadable */
dc503a8a 8939 for (i = 0; i < CALLER_SAVED_REGS; i++) {
61bd5218 8940 mark_reg_not_init(env, regs, caller_saved[i]);
dc503a8a
EC
8941 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
8942 }
ddd872bc
AS
8943
8944 /* mark destination R0 register as readable, since it contains
dc503a8a
EC
8945 * the value fetched from the packet.
8946 * Already marked as written above.
ddd872bc 8947 */
61bd5218 8948 mark_reg_unknown(env, regs, BPF_REG_0);
5327ed3d
JW
8949 /* ld_abs load up to 32-bit skb data. */
8950 regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
ddd872bc
AS
8951 return 0;
8952}
8953
390ee7e2
AS
8954static int check_return_code(struct bpf_verifier_env *env)
8955{
5cf1e914 8956 struct tnum enforce_attach_type_range = tnum_unknown;
27ae7997 8957 const struct bpf_prog *prog = env->prog;
390ee7e2
AS
8958 struct bpf_reg_state *reg;
8959 struct tnum range = tnum_range(0, 1);
7e40781c 8960 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
27ae7997 8961 int err;
f782e2c3 8962 const bool is_subprog = env->cur_state->frame[0]->subprogno;
27ae7997 8963
9e4e01df 8964 /* LSM and struct_ops func-ptr's return type could be "void" */
f782e2c3
DB
8965 if (!is_subprog &&
8966 (prog_type == BPF_PROG_TYPE_STRUCT_OPS ||
7e40781c 8967 prog_type == BPF_PROG_TYPE_LSM) &&
27ae7997
MKL
8968 !prog->aux->attach_func_proto->type)
8969 return 0;
8970
8971 /* eBPF calling convetion is such that R0 is used
8972 * to return the value from eBPF program.
8973 * Make sure that it's readable at this time
8974 * of bpf_exit, which means that program wrote
8975 * something into it earlier
8976 */
8977 err = check_reg_arg(env, BPF_REG_0, SRC_OP);
8978 if (err)
8979 return err;
8980
8981 if (is_pointer_value(env, BPF_REG_0)) {
8982 verbose(env, "R0 leaks addr as return value\n");
8983 return -EACCES;
8984 }
390ee7e2 8985
f782e2c3
DB
8986 reg = cur_regs(env) + BPF_REG_0;
8987 if (is_subprog) {
8988 if (reg->type != SCALAR_VALUE) {
8989 verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
8990 reg_type_str[reg->type]);
8991 return -EINVAL;
8992 }
8993 return 0;
8994 }
8995
7e40781c 8996 switch (prog_type) {
983695fa
DB
8997 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
8998 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
1b66d253
DB
8999 env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
9000 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
9001 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
9002 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
9003 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
983695fa 9004 range = tnum_range(1, 1);
77241217
SF
9005 if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
9006 env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
9007 range = tnum_range(0, 3);
ed4ed404 9008 break;
390ee7e2 9009 case BPF_PROG_TYPE_CGROUP_SKB:
5cf1e914 9010 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
9011 range = tnum_range(0, 3);
9012 enforce_attach_type_range = tnum_range(2, 3);
9013 }
ed4ed404 9014 break;
390ee7e2
AS
9015 case BPF_PROG_TYPE_CGROUP_SOCK:
9016 case BPF_PROG_TYPE_SOCK_OPS:
ebc614f6 9017 case BPF_PROG_TYPE_CGROUP_DEVICE:
7b146ceb 9018 case BPF_PROG_TYPE_CGROUP_SYSCTL:
0d01da6a 9019 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
390ee7e2 9020 break;
15ab09bd
AS
9021 case BPF_PROG_TYPE_RAW_TRACEPOINT:
9022 if (!env->prog->aux->attach_btf_id)
9023 return 0;
9024 range = tnum_const(0);
9025 break;
15d83c4d 9026 case BPF_PROG_TYPE_TRACING:
e92888c7
YS
9027 switch (env->prog->expected_attach_type) {
9028 case BPF_TRACE_FENTRY:
9029 case BPF_TRACE_FEXIT:
9030 range = tnum_const(0);
9031 break;
9032 case BPF_TRACE_RAW_TP:
9033 case BPF_MODIFY_RETURN:
15d83c4d 9034 return 0;
2ec0616e
DB
9035 case BPF_TRACE_ITER:
9036 break;
e92888c7
YS
9037 default:
9038 return -ENOTSUPP;
9039 }
15d83c4d 9040 break;
e9ddbb77
JS
9041 case BPF_PROG_TYPE_SK_LOOKUP:
9042 range = tnum_range(SK_DROP, SK_PASS);
9043 break;
e92888c7
YS
9044 case BPF_PROG_TYPE_EXT:
9045 /* freplace program can return anything as its return value
9046 * depends on the to-be-replaced kernel func or bpf program.
9047 */
390ee7e2
AS
9048 default:
9049 return 0;
9050 }
9051
390ee7e2 9052 if (reg->type != SCALAR_VALUE) {
61bd5218 9053 verbose(env, "At program exit the register R0 is not a known value (%s)\n",
390ee7e2
AS
9054 reg_type_str[reg->type]);
9055 return -EINVAL;
9056 }
9057
9058 if (!tnum_in(range, reg->var_off)) {
bc2591d6 9059 verbose_invalid_scalar(env, reg, &range, "program exit", "R0");
390ee7e2
AS
9060 return -EINVAL;
9061 }
5cf1e914 9062
9063 if (!tnum_is_unknown(enforce_attach_type_range) &&
9064 tnum_in(enforce_attach_type_range, reg->var_off))
9065 env->prog->enforce_expected_attach_type = 1;
390ee7e2
AS
9066 return 0;
9067}
9068
475fb78f
AS
9069/* non-recursive DFS pseudo code
9070 * 1 procedure DFS-iterative(G,v):
9071 * 2 label v as discovered
9072 * 3 let S be a stack
9073 * 4 S.push(v)
9074 * 5 while S is not empty
9075 * 6 t <- S.pop()
9076 * 7 if t is what we're looking for:
9077 * 8 return t
9078 * 9 for all edges e in G.adjacentEdges(t) do
9079 * 10 if edge e is already labelled
9080 * 11 continue with the next edge
9081 * 12 w <- G.adjacentVertex(t,e)
9082 * 13 if vertex w is not discovered and not explored
9083 * 14 label e as tree-edge
9084 * 15 label w as discovered
9085 * 16 S.push(w)
9086 * 17 continue at 5
9087 * 18 else if vertex w is discovered
9088 * 19 label e as back-edge
9089 * 20 else
9090 * 21 // vertex w is explored
9091 * 22 label e as forward- or cross-edge
9092 * 23 label t as explored
9093 * 24 S.pop()
9094 *
9095 * convention:
9096 * 0x10 - discovered
9097 * 0x11 - discovered and fall-through edge labelled
9098 * 0x12 - discovered and fall-through and branch edges labelled
9099 * 0x20 - explored
9100 */
9101
9102enum {
9103 DISCOVERED = 0x10,
9104 EXPLORED = 0x20,
9105 FALLTHROUGH = 1,
9106 BRANCH = 2,
9107};
9108
dc2a4ebc
AS
9109static u32 state_htab_size(struct bpf_verifier_env *env)
9110{
9111 return env->prog->len;
9112}
9113
5d839021
AS
9114static struct bpf_verifier_state_list **explored_state(
9115 struct bpf_verifier_env *env,
9116 int idx)
9117{
dc2a4ebc
AS
9118 struct bpf_verifier_state *cur = env->cur_state;
9119 struct bpf_func_state *state = cur->frame[cur->curframe];
9120
9121 return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
5d839021
AS
9122}
9123
9124static void init_explored_state(struct bpf_verifier_env *env, int idx)
9125{
a8f500af 9126 env->insn_aux_data[idx].prune_point = true;
5d839021 9127}
f1bca824 9128
59e2e27d
WAF
9129enum {
9130 DONE_EXPLORING = 0,
9131 KEEP_EXPLORING = 1,
9132};
9133
475fb78f
AS
9134/* t, w, e - match pseudo-code above:
9135 * t - index of current instruction
9136 * w - next instruction
9137 * e - edge
9138 */
2589726d
AS
9139static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
9140 bool loop_ok)
475fb78f 9141{
7df737e9
AS
9142 int *insn_stack = env->cfg.insn_stack;
9143 int *insn_state = env->cfg.insn_state;
9144
475fb78f 9145 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
59e2e27d 9146 return DONE_EXPLORING;
475fb78f
AS
9147
9148 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
59e2e27d 9149 return DONE_EXPLORING;
475fb78f
AS
9150
9151 if (w < 0 || w >= env->prog->len) {
d9762e84 9152 verbose_linfo(env, t, "%d: ", t);
61bd5218 9153 verbose(env, "jump out of range from insn %d to %d\n", t, w);
475fb78f
AS
9154 return -EINVAL;
9155 }
9156
f1bca824
AS
9157 if (e == BRANCH)
9158 /* mark branch target for state pruning */
5d839021 9159 init_explored_state(env, w);
f1bca824 9160
475fb78f
AS
9161 if (insn_state[w] == 0) {
9162 /* tree-edge */
9163 insn_state[t] = DISCOVERED | e;
9164 insn_state[w] = DISCOVERED;
7df737e9 9165 if (env->cfg.cur_stack >= env->prog->len)
475fb78f 9166 return -E2BIG;
7df737e9 9167 insn_stack[env->cfg.cur_stack++] = w;
59e2e27d 9168 return KEEP_EXPLORING;
475fb78f 9169 } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
2c78ee89 9170 if (loop_ok && env->bpf_capable)
59e2e27d 9171 return DONE_EXPLORING;
d9762e84
MKL
9172 verbose_linfo(env, t, "%d: ", t);
9173 verbose_linfo(env, w, "%d: ", w);
61bd5218 9174 verbose(env, "back-edge from insn %d to %d\n", t, w);
475fb78f
AS
9175 return -EINVAL;
9176 } else if (insn_state[w] == EXPLORED) {
9177 /* forward- or cross-edge */
9178 insn_state[t] = DISCOVERED | e;
9179 } else {
61bd5218 9180 verbose(env, "insn state internal bug\n");
475fb78f
AS
9181 return -EFAULT;
9182 }
59e2e27d
WAF
9183 return DONE_EXPLORING;
9184}
9185
efdb22de
YS
9186static int visit_func_call_insn(int t, int insn_cnt,
9187 struct bpf_insn *insns,
9188 struct bpf_verifier_env *env,
9189 bool visit_callee)
9190{
9191 int ret;
9192
9193 ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
9194 if (ret)
9195 return ret;
9196
9197 if (t + 1 < insn_cnt)
9198 init_explored_state(env, t + 1);
9199 if (visit_callee) {
9200 init_explored_state(env, t);
9201 ret = push_insn(t, t + insns[t].imm + 1, BRANCH,
9202 env, false);
9203 }
9204 return ret;
9205}
9206
59e2e27d
WAF
9207/* Visits the instruction at index t and returns one of the following:
9208 * < 0 - an error occurred
9209 * DONE_EXPLORING - the instruction was fully explored
9210 * KEEP_EXPLORING - there is still work to be done before it is fully explored
9211 */
9212static int visit_insn(int t, int insn_cnt, struct bpf_verifier_env *env)
9213{
9214 struct bpf_insn *insns = env->prog->insnsi;
9215 int ret;
9216
69c087ba
YS
9217 if (bpf_pseudo_func(insns + t))
9218 return visit_func_call_insn(t, insn_cnt, insns, env, true);
9219
59e2e27d
WAF
9220 /* All non-branch instructions have a single fall-through edge. */
9221 if (BPF_CLASS(insns[t].code) != BPF_JMP &&
9222 BPF_CLASS(insns[t].code) != BPF_JMP32)
9223 return push_insn(t, t + 1, FALLTHROUGH, env, false);
9224
9225 switch (BPF_OP(insns[t].code)) {
9226 case BPF_EXIT:
9227 return DONE_EXPLORING;
9228
9229 case BPF_CALL:
efdb22de
YS
9230 return visit_func_call_insn(t, insn_cnt, insns, env,
9231 insns[t].src_reg == BPF_PSEUDO_CALL);
59e2e27d
WAF
9232
9233 case BPF_JA:
9234 if (BPF_SRC(insns[t].code) != BPF_K)
9235 return -EINVAL;
9236
9237 /* unconditional jump with single edge */
9238 ret = push_insn(t, t + insns[t].off + 1, FALLTHROUGH, env,
9239 true);
9240 if (ret)
9241 return ret;
9242
9243 /* unconditional jmp is not a good pruning point,
9244 * but it's marked, since backtracking needs
9245 * to record jmp history in is_state_visited().
9246 */
9247 init_explored_state(env, t + insns[t].off + 1);
9248 /* tell verifier to check for equivalent states
9249 * after every call and jump
9250 */
9251 if (t + 1 < insn_cnt)
9252 init_explored_state(env, t + 1);
9253
9254 return ret;
9255
9256 default:
9257 /* conditional jump with two edges */
9258 init_explored_state(env, t);
9259 ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
9260 if (ret)
9261 return ret;
9262
9263 return push_insn(t, t + insns[t].off + 1, BRANCH, env, true);
9264 }
475fb78f
AS
9265}
9266
9267/* non-recursive depth-first-search to detect loops in BPF program
9268 * loop == back-edge in directed graph
9269 */
58e2af8b 9270static int check_cfg(struct bpf_verifier_env *env)
475fb78f 9271{
475fb78f 9272 int insn_cnt = env->prog->len;
7df737e9 9273 int *insn_stack, *insn_state;
475fb78f 9274 int ret = 0;
59e2e27d 9275 int i;
475fb78f 9276
7df737e9 9277 insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
475fb78f
AS
9278 if (!insn_state)
9279 return -ENOMEM;
9280
7df737e9 9281 insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
475fb78f 9282 if (!insn_stack) {
71dde681 9283 kvfree(insn_state);
475fb78f
AS
9284 return -ENOMEM;
9285 }
9286
9287 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
9288 insn_stack[0] = 0; /* 0 is the first instruction */
7df737e9 9289 env->cfg.cur_stack = 1;
475fb78f 9290
59e2e27d
WAF
9291 while (env->cfg.cur_stack > 0) {
9292 int t = insn_stack[env->cfg.cur_stack - 1];
475fb78f 9293
59e2e27d
WAF
9294 ret = visit_insn(t, insn_cnt, env);
9295 switch (ret) {
9296 case DONE_EXPLORING:
9297 insn_state[t] = EXPLORED;
9298 env->cfg.cur_stack--;
9299 break;
9300 case KEEP_EXPLORING:
9301 break;
9302 default:
9303 if (ret > 0) {
9304 verbose(env, "visit_insn internal bug\n");
9305 ret = -EFAULT;
475fb78f 9306 }
475fb78f 9307 goto err_free;
59e2e27d 9308 }
475fb78f
AS
9309 }
9310
59e2e27d 9311 if (env->cfg.cur_stack < 0) {
61bd5218 9312 verbose(env, "pop stack internal bug\n");
475fb78f
AS
9313 ret = -EFAULT;
9314 goto err_free;
9315 }
475fb78f 9316
475fb78f
AS
9317 for (i = 0; i < insn_cnt; i++) {
9318 if (insn_state[i] != EXPLORED) {
61bd5218 9319 verbose(env, "unreachable insn %d\n", i);
475fb78f
AS
9320 ret = -EINVAL;
9321 goto err_free;
9322 }
9323 }
9324 ret = 0; /* cfg looks good */
9325
9326err_free:
71dde681
AS
9327 kvfree(insn_state);
9328 kvfree(insn_stack);
7df737e9 9329 env->cfg.insn_state = env->cfg.insn_stack = NULL;
475fb78f
AS
9330 return ret;
9331}
9332
09b28d76
AS
9333static int check_abnormal_return(struct bpf_verifier_env *env)
9334{
9335 int i;
9336
9337 for (i = 1; i < env->subprog_cnt; i++) {
9338 if (env->subprog_info[i].has_ld_abs) {
9339 verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
9340 return -EINVAL;
9341 }
9342 if (env->subprog_info[i].has_tail_call) {
9343 verbose(env, "tail_call is not allowed in subprogs without BTF\n");
9344 return -EINVAL;
9345 }
9346 }
9347 return 0;
9348}
9349
838e9690
YS
9350/* The minimum supported BTF func info size */
9351#define MIN_BPF_FUNCINFO_SIZE 8
9352#define MAX_FUNCINFO_REC_SIZE 252
9353
c454a46b
MKL
9354static int check_btf_func(struct bpf_verifier_env *env,
9355 const union bpf_attr *attr,
9356 union bpf_attr __user *uattr)
838e9690 9357{
09b28d76 9358 const struct btf_type *type, *func_proto, *ret_type;
d0b2818e 9359 u32 i, nfuncs, urec_size, min_size;
838e9690 9360 u32 krec_size = sizeof(struct bpf_func_info);
c454a46b 9361 struct bpf_func_info *krecord;
8c1b6e69 9362 struct bpf_func_info_aux *info_aux = NULL;
c454a46b
MKL
9363 struct bpf_prog *prog;
9364 const struct btf *btf;
838e9690 9365 void __user *urecord;
d0b2818e 9366 u32 prev_offset = 0;
09b28d76 9367 bool scalar_return;
e7ed83d6 9368 int ret = -ENOMEM;
838e9690
YS
9369
9370 nfuncs = attr->func_info_cnt;
09b28d76
AS
9371 if (!nfuncs) {
9372 if (check_abnormal_return(env))
9373 return -EINVAL;
838e9690 9374 return 0;
09b28d76 9375 }
838e9690
YS
9376
9377 if (nfuncs != env->subprog_cnt) {
9378 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
9379 return -EINVAL;
9380 }
9381
9382 urec_size = attr->func_info_rec_size;
9383 if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
9384 urec_size > MAX_FUNCINFO_REC_SIZE ||
9385 urec_size % sizeof(u32)) {
9386 verbose(env, "invalid func info rec size %u\n", urec_size);
9387 return -EINVAL;
9388 }
9389
c454a46b
MKL
9390 prog = env->prog;
9391 btf = prog->aux->btf;
838e9690
YS
9392
9393 urecord = u64_to_user_ptr(attr->func_info);
9394 min_size = min_t(u32, krec_size, urec_size);
9395
ba64e7d8 9396 krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
c454a46b
MKL
9397 if (!krecord)
9398 return -ENOMEM;
8c1b6e69
AS
9399 info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
9400 if (!info_aux)
9401 goto err_free;
ba64e7d8 9402
838e9690
YS
9403 for (i = 0; i < nfuncs; i++) {
9404 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
9405 if (ret) {
9406 if (ret == -E2BIG) {
9407 verbose(env, "nonzero tailing record in func info");
9408 /* set the size kernel expects so loader can zero
9409 * out the rest of the record.
9410 */
9411 if (put_user(min_size, &uattr->func_info_rec_size))
9412 ret = -EFAULT;
9413 }
c454a46b 9414 goto err_free;
838e9690
YS
9415 }
9416
ba64e7d8 9417 if (copy_from_user(&krecord[i], urecord, min_size)) {
838e9690 9418 ret = -EFAULT;
c454a46b 9419 goto err_free;
838e9690
YS
9420 }
9421
d30d42e0 9422 /* check insn_off */
09b28d76 9423 ret = -EINVAL;
838e9690 9424 if (i == 0) {
d30d42e0 9425 if (krecord[i].insn_off) {
838e9690 9426 verbose(env,
d30d42e0
MKL
9427 "nonzero insn_off %u for the first func info record",
9428 krecord[i].insn_off);
c454a46b 9429 goto err_free;
838e9690 9430 }
d30d42e0 9431 } else if (krecord[i].insn_off <= prev_offset) {
838e9690
YS
9432 verbose(env,
9433 "same or smaller insn offset (%u) than previous func info record (%u)",
d30d42e0 9434 krecord[i].insn_off, prev_offset);
c454a46b 9435 goto err_free;
838e9690
YS
9436 }
9437
d30d42e0 9438 if (env->subprog_info[i].start != krecord[i].insn_off) {
838e9690 9439 verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
c454a46b 9440 goto err_free;
838e9690
YS
9441 }
9442
9443 /* check type_id */
ba64e7d8 9444 type = btf_type_by_id(btf, krecord[i].type_id);
51c39bb1 9445 if (!type || !btf_type_is_func(type)) {
838e9690 9446 verbose(env, "invalid type id %d in func info",
ba64e7d8 9447 krecord[i].type_id);
c454a46b 9448 goto err_free;
838e9690 9449 }
51c39bb1 9450 info_aux[i].linkage = BTF_INFO_VLEN(type->info);
09b28d76
AS
9451
9452 func_proto = btf_type_by_id(btf, type->type);
9453 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
9454 /* btf_func_check() already verified it during BTF load */
9455 goto err_free;
9456 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
9457 scalar_return =
9458 btf_type_is_small_int(ret_type) || btf_type_is_enum(ret_type);
9459 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
9460 verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
9461 goto err_free;
9462 }
9463 if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
9464 verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
9465 goto err_free;
9466 }
9467
d30d42e0 9468 prev_offset = krecord[i].insn_off;
838e9690
YS
9469 urecord += urec_size;
9470 }
9471
ba64e7d8
YS
9472 prog->aux->func_info = krecord;
9473 prog->aux->func_info_cnt = nfuncs;
8c1b6e69 9474 prog->aux->func_info_aux = info_aux;
838e9690
YS
9475 return 0;
9476
c454a46b 9477err_free:
ba64e7d8 9478 kvfree(krecord);
8c1b6e69 9479 kfree(info_aux);
838e9690
YS
9480 return ret;
9481}
9482
ba64e7d8
YS
9483static void adjust_btf_func(struct bpf_verifier_env *env)
9484{
8c1b6e69 9485 struct bpf_prog_aux *aux = env->prog->aux;
ba64e7d8
YS
9486 int i;
9487
8c1b6e69 9488 if (!aux->func_info)
ba64e7d8
YS
9489 return;
9490
9491 for (i = 0; i < env->subprog_cnt; i++)
8c1b6e69 9492 aux->func_info[i].insn_off = env->subprog_info[i].start;
ba64e7d8
YS
9493}
9494
c454a46b
MKL
9495#define MIN_BPF_LINEINFO_SIZE (offsetof(struct bpf_line_info, line_col) + \
9496 sizeof(((struct bpf_line_info *)(0))->line_col))
9497#define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE
9498
9499static int check_btf_line(struct bpf_verifier_env *env,
9500 const union bpf_attr *attr,
9501 union bpf_attr __user *uattr)
9502{
9503 u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
9504 struct bpf_subprog_info *sub;
9505 struct bpf_line_info *linfo;
9506 struct bpf_prog *prog;
9507 const struct btf *btf;
9508 void __user *ulinfo;
9509 int err;
9510
9511 nr_linfo = attr->line_info_cnt;
9512 if (!nr_linfo)
9513 return 0;
9514
9515 rec_size = attr->line_info_rec_size;
9516 if (rec_size < MIN_BPF_LINEINFO_SIZE ||
9517 rec_size > MAX_LINEINFO_REC_SIZE ||
9518 rec_size & (sizeof(u32) - 1))
9519 return -EINVAL;
9520
9521 /* Need to zero it in case the userspace may
9522 * pass in a smaller bpf_line_info object.
9523 */
9524 linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
9525 GFP_KERNEL | __GFP_NOWARN);
9526 if (!linfo)
9527 return -ENOMEM;
9528
9529 prog = env->prog;
9530 btf = prog->aux->btf;
9531
9532 s = 0;
9533 sub = env->subprog_info;
9534 ulinfo = u64_to_user_ptr(attr->line_info);
9535 expected_size = sizeof(struct bpf_line_info);
9536 ncopy = min_t(u32, expected_size, rec_size);
9537 for (i = 0; i < nr_linfo; i++) {
9538 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
9539 if (err) {
9540 if (err == -E2BIG) {
9541 verbose(env, "nonzero tailing record in line_info");
9542 if (put_user(expected_size,
9543 &uattr->line_info_rec_size))
9544 err = -EFAULT;
9545 }
9546 goto err_free;
9547 }
9548
9549 if (copy_from_user(&linfo[i], ulinfo, ncopy)) {
9550 err = -EFAULT;
9551 goto err_free;
9552 }
9553
9554 /*
9555 * Check insn_off to ensure
9556 * 1) strictly increasing AND
9557 * 2) bounded by prog->len
9558 *
9559 * The linfo[0].insn_off == 0 check logically falls into
9560 * the later "missing bpf_line_info for func..." case
9561 * because the first linfo[0].insn_off must be the
9562 * first sub also and the first sub must have
9563 * subprog_info[0].start == 0.
9564 */
9565 if ((i && linfo[i].insn_off <= prev_offset) ||
9566 linfo[i].insn_off >= prog->len) {
9567 verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
9568 i, linfo[i].insn_off, prev_offset,
9569 prog->len);
9570 err = -EINVAL;
9571 goto err_free;
9572 }
9573
fdbaa0be
MKL
9574 if (!prog->insnsi[linfo[i].insn_off].code) {
9575 verbose(env,
9576 "Invalid insn code at line_info[%u].insn_off\n",
9577 i);
9578 err = -EINVAL;
9579 goto err_free;
9580 }
9581
23127b33
MKL
9582 if (!btf_name_by_offset(btf, linfo[i].line_off) ||
9583 !btf_name_by_offset(btf, linfo[i].file_name_off)) {
c454a46b
MKL
9584 verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
9585 err = -EINVAL;
9586 goto err_free;
9587 }
9588
9589 if (s != env->subprog_cnt) {
9590 if (linfo[i].insn_off == sub[s].start) {
9591 sub[s].linfo_idx = i;
9592 s++;
9593 } else if (sub[s].start < linfo[i].insn_off) {
9594 verbose(env, "missing bpf_line_info for func#%u\n", s);
9595 err = -EINVAL;
9596 goto err_free;
9597 }
9598 }
9599
9600 prev_offset = linfo[i].insn_off;
9601 ulinfo += rec_size;
9602 }
9603
9604 if (s != env->subprog_cnt) {
9605 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
9606 env->subprog_cnt - s, s);
9607 err = -EINVAL;
9608 goto err_free;
9609 }
9610
9611 prog->aux->linfo = linfo;
9612 prog->aux->nr_linfo = nr_linfo;
9613
9614 return 0;
9615
9616err_free:
9617 kvfree(linfo);
9618 return err;
9619}
9620
9621static int check_btf_info(struct bpf_verifier_env *env,
9622 const union bpf_attr *attr,
9623 union bpf_attr __user *uattr)
9624{
9625 struct btf *btf;
9626 int err;
9627
09b28d76
AS
9628 if (!attr->func_info_cnt && !attr->line_info_cnt) {
9629 if (check_abnormal_return(env))
9630 return -EINVAL;
c454a46b 9631 return 0;
09b28d76 9632 }
c454a46b
MKL
9633
9634 btf = btf_get_by_fd(attr->prog_btf_fd);
9635 if (IS_ERR(btf))
9636 return PTR_ERR(btf);
350a5c4d
AS
9637 if (btf_is_kernel(btf)) {
9638 btf_put(btf);
9639 return -EACCES;
9640 }
c454a46b
MKL
9641 env->prog->aux->btf = btf;
9642
9643 err = check_btf_func(env, attr, uattr);
9644 if (err)
9645 return err;
9646
9647 err = check_btf_line(env, attr, uattr);
9648 if (err)
9649 return err;
9650
9651 return 0;
ba64e7d8
YS
9652}
9653
f1174f77
EC
9654/* check %cur's range satisfies %old's */
9655static bool range_within(struct bpf_reg_state *old,
9656 struct bpf_reg_state *cur)
9657{
b03c9f9f
EC
9658 return old->umin_value <= cur->umin_value &&
9659 old->umax_value >= cur->umax_value &&
9660 old->smin_value <= cur->smin_value &&
fd675184
DB
9661 old->smax_value >= cur->smax_value &&
9662 old->u32_min_value <= cur->u32_min_value &&
9663 old->u32_max_value >= cur->u32_max_value &&
9664 old->s32_min_value <= cur->s32_min_value &&
9665 old->s32_max_value >= cur->s32_max_value;
f1174f77
EC
9666}
9667
9668/* Maximum number of register states that can exist at once */
9669#define ID_MAP_SIZE (MAX_BPF_REG + MAX_BPF_STACK / BPF_REG_SIZE)
9670struct idpair {
9671 u32 old;
9672 u32 cur;
9673};
9674
9675/* If in the old state two registers had the same id, then they need to have
9676 * the same id in the new state as well. But that id could be different from
9677 * the old state, so we need to track the mapping from old to new ids.
9678 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
9679 * regs with old id 5 must also have new id 9 for the new state to be safe. But
9680 * regs with a different old id could still have new id 9, we don't care about
9681 * that.
9682 * So we look through our idmap to see if this old id has been seen before. If
9683 * so, we require the new id to match; otherwise, we add the id pair to the map.
969bf05e 9684 */
f1174f77 9685static bool check_ids(u32 old_id, u32 cur_id, struct idpair *idmap)
969bf05e 9686{
f1174f77 9687 unsigned int i;
969bf05e 9688
f1174f77
EC
9689 for (i = 0; i < ID_MAP_SIZE; i++) {
9690 if (!idmap[i].old) {
9691 /* Reached an empty slot; haven't seen this id before */
9692 idmap[i].old = old_id;
9693 idmap[i].cur = cur_id;
9694 return true;
9695 }
9696 if (idmap[i].old == old_id)
9697 return idmap[i].cur == cur_id;
9698 }
9699 /* We ran out of idmap slots, which should be impossible */
9700 WARN_ON_ONCE(1);
9701 return false;
9702}
9703
9242b5f5
AS
9704static void clean_func_state(struct bpf_verifier_env *env,
9705 struct bpf_func_state *st)
9706{
9707 enum bpf_reg_liveness live;
9708 int i, j;
9709
9710 for (i = 0; i < BPF_REG_FP; i++) {
9711 live = st->regs[i].live;
9712 /* liveness must not touch this register anymore */
9713 st->regs[i].live |= REG_LIVE_DONE;
9714 if (!(live & REG_LIVE_READ))
9715 /* since the register is unused, clear its state
9716 * to make further comparison simpler
9717 */
f54c7898 9718 __mark_reg_not_init(env, &st->regs[i]);
9242b5f5
AS
9719 }
9720
9721 for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
9722 live = st->stack[i].spilled_ptr.live;
9723 /* liveness must not touch this stack slot anymore */
9724 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
9725 if (!(live & REG_LIVE_READ)) {
f54c7898 9726 __mark_reg_not_init(env, &st->stack[i].spilled_ptr);
9242b5f5
AS
9727 for (j = 0; j < BPF_REG_SIZE; j++)
9728 st->stack[i].slot_type[j] = STACK_INVALID;
9729 }
9730 }
9731}
9732
9733static void clean_verifier_state(struct bpf_verifier_env *env,
9734 struct bpf_verifier_state *st)
9735{
9736 int i;
9737
9738 if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
9739 /* all regs in this state in all frames were already marked */
9740 return;
9741
9742 for (i = 0; i <= st->curframe; i++)
9743 clean_func_state(env, st->frame[i]);
9744}
9745
9746/* the parentage chains form a tree.
9747 * the verifier states are added to state lists at given insn and
9748 * pushed into state stack for future exploration.
9749 * when the verifier reaches bpf_exit insn some of the verifer states
9750 * stored in the state lists have their final liveness state already,
9751 * but a lot of states will get revised from liveness point of view when
9752 * the verifier explores other branches.
9753 * Example:
9754 * 1: r0 = 1
9755 * 2: if r1 == 100 goto pc+1
9756 * 3: r0 = 2
9757 * 4: exit
9758 * when the verifier reaches exit insn the register r0 in the state list of
9759 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
9760 * of insn 2 and goes exploring further. At the insn 4 it will walk the
9761 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
9762 *
9763 * Since the verifier pushes the branch states as it sees them while exploring
9764 * the program the condition of walking the branch instruction for the second
9765 * time means that all states below this branch were already explored and
9766 * their final liveness markes are already propagated.
9767 * Hence when the verifier completes the search of state list in is_state_visited()
9768 * we can call this clean_live_states() function to mark all liveness states
9769 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
9770 * will not be used.
9771 * This function also clears the registers and stack for states that !READ
9772 * to simplify state merging.
9773 *
9774 * Important note here that walking the same branch instruction in the callee
9775 * doesn't meant that the states are DONE. The verifier has to compare
9776 * the callsites
9777 */
9778static void clean_live_states(struct bpf_verifier_env *env, int insn,
9779 struct bpf_verifier_state *cur)
9780{
9781 struct bpf_verifier_state_list *sl;
9782 int i;
9783
5d839021 9784 sl = *explored_state(env, insn);
a8f500af 9785 while (sl) {
2589726d
AS
9786 if (sl->state.branches)
9787 goto next;
dc2a4ebc
AS
9788 if (sl->state.insn_idx != insn ||
9789 sl->state.curframe != cur->curframe)
9242b5f5
AS
9790 goto next;
9791 for (i = 0; i <= cur->curframe; i++)
9792 if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
9793 goto next;
9794 clean_verifier_state(env, &sl->state);
9795next:
9796 sl = sl->next;
9797 }
9798}
9799
f1174f77 9800/* Returns true if (rold safe implies rcur safe) */
1b688a19
EC
9801static bool regsafe(struct bpf_reg_state *rold, struct bpf_reg_state *rcur,
9802 struct idpair *idmap)
f1174f77 9803{
f4d7e40a
AS
9804 bool equal;
9805
dc503a8a
EC
9806 if (!(rold->live & REG_LIVE_READ))
9807 /* explored state didn't use this */
9808 return true;
9809
679c782d 9810 equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, parent)) == 0;
f4d7e40a
AS
9811
9812 if (rold->type == PTR_TO_STACK)
9813 /* two stack pointers are equal only if they're pointing to
9814 * the same stack frame, since fp-8 in foo != fp-8 in bar
9815 */
9816 return equal && rold->frameno == rcur->frameno;
9817
9818 if (equal)
969bf05e
AS
9819 return true;
9820
f1174f77
EC
9821 if (rold->type == NOT_INIT)
9822 /* explored state can't have used this */
969bf05e 9823 return true;
f1174f77
EC
9824 if (rcur->type == NOT_INIT)
9825 return false;
9826 switch (rold->type) {
9827 case SCALAR_VALUE:
9828 if (rcur->type == SCALAR_VALUE) {
b5dc0163
AS
9829 if (!rold->precise && !rcur->precise)
9830 return true;
f1174f77
EC
9831 /* new val must satisfy old val knowledge */
9832 return range_within(rold, rcur) &&
9833 tnum_in(rold->var_off, rcur->var_off);
9834 } else {
179d1c56
JH
9835 /* We're trying to use a pointer in place of a scalar.
9836 * Even if the scalar was unbounded, this could lead to
9837 * pointer leaks because scalars are allowed to leak
9838 * while pointers are not. We could make this safe in
9839 * special cases if root is calling us, but it's
9840 * probably not worth the hassle.
f1174f77 9841 */
179d1c56 9842 return false;
f1174f77 9843 }
69c087ba 9844 case PTR_TO_MAP_KEY:
f1174f77 9845 case PTR_TO_MAP_VALUE:
1b688a19
EC
9846 /* If the new min/max/var_off satisfy the old ones and
9847 * everything else matches, we are OK.
d83525ca
AS
9848 * 'id' is not compared, since it's only used for maps with
9849 * bpf_spin_lock inside map element and in such cases if
9850 * the rest of the prog is valid for one map element then
9851 * it's valid for all map elements regardless of the key
9852 * used in bpf_map_lookup()
1b688a19
EC
9853 */
9854 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
9855 range_within(rold, rcur) &&
9856 tnum_in(rold->var_off, rcur->var_off);
f1174f77
EC
9857 case PTR_TO_MAP_VALUE_OR_NULL:
9858 /* a PTR_TO_MAP_VALUE could be safe to use as a
9859 * PTR_TO_MAP_VALUE_OR_NULL into the same map.
9860 * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
9861 * checked, doing so could have affected others with the same
9862 * id, and we can't check for that because we lost the id when
9863 * we converted to a PTR_TO_MAP_VALUE.
9864 */
9865 if (rcur->type != PTR_TO_MAP_VALUE_OR_NULL)
9866 return false;
9867 if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
9868 return false;
9869 /* Check our ids match any regs they're supposed to */
9870 return check_ids(rold->id, rcur->id, idmap);
de8f3a83 9871 case PTR_TO_PACKET_META:
f1174f77 9872 case PTR_TO_PACKET:
de8f3a83 9873 if (rcur->type != rold->type)
f1174f77
EC
9874 return false;
9875 /* We must have at least as much range as the old ptr
9876 * did, so that any accesses which were safe before are
9877 * still safe. This is true even if old range < old off,
9878 * since someone could have accessed through (ptr - k), or
9879 * even done ptr -= k in a register, to get a safe access.
9880 */
9881 if (rold->range > rcur->range)
9882 return false;
9883 /* If the offsets don't match, we can't trust our alignment;
9884 * nor can we be sure that we won't fall out of range.
9885 */
9886 if (rold->off != rcur->off)
9887 return false;
9888 /* id relations must be preserved */
9889 if (rold->id && !check_ids(rold->id, rcur->id, idmap))
9890 return false;
9891 /* new val must satisfy old val knowledge */
9892 return range_within(rold, rcur) &&
9893 tnum_in(rold->var_off, rcur->var_off);
9894 case PTR_TO_CTX:
9895 case CONST_PTR_TO_MAP:
f1174f77 9896 case PTR_TO_PACKET_END:
d58e468b 9897 case PTR_TO_FLOW_KEYS:
c64b7983
JS
9898 case PTR_TO_SOCKET:
9899 case PTR_TO_SOCKET_OR_NULL:
46f8bc92
MKL
9900 case PTR_TO_SOCK_COMMON:
9901 case PTR_TO_SOCK_COMMON_OR_NULL:
655a51e5
MKL
9902 case PTR_TO_TCP_SOCK:
9903 case PTR_TO_TCP_SOCK_OR_NULL:
fada7fdc 9904 case PTR_TO_XDP_SOCK:
f1174f77
EC
9905 /* Only valid matches are exact, which memcmp() above
9906 * would have accepted
9907 */
9908 default:
9909 /* Don't know what's going on, just say it's not safe */
9910 return false;
9911 }
969bf05e 9912
f1174f77
EC
9913 /* Shouldn't get here; if we do, say it's not safe */
9914 WARN_ON_ONCE(1);
969bf05e
AS
9915 return false;
9916}
9917
f4d7e40a
AS
9918static bool stacksafe(struct bpf_func_state *old,
9919 struct bpf_func_state *cur,
638f5b90
AS
9920 struct idpair *idmap)
9921{
9922 int i, spi;
9923
638f5b90
AS
9924 /* walk slots of the explored stack and ignore any additional
9925 * slots in the current stack, since explored(safe) state
9926 * didn't use them
9927 */
9928 for (i = 0; i < old->allocated_stack; i++) {
9929 spi = i / BPF_REG_SIZE;
9930
b233920c
AS
9931 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
9932 i += BPF_REG_SIZE - 1;
cc2b14d5 9933 /* explored state didn't use this */
fd05e57b 9934 continue;
b233920c 9935 }
cc2b14d5 9936
638f5b90
AS
9937 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
9938 continue;
19e2dbb7
AS
9939
9940 /* explored stack has more populated slots than current stack
9941 * and these slots were used
9942 */
9943 if (i >= cur->allocated_stack)
9944 return false;
9945
cc2b14d5
AS
9946 /* if old state was safe with misc data in the stack
9947 * it will be safe with zero-initialized stack.
9948 * The opposite is not true
9949 */
9950 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
9951 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
9952 continue;
638f5b90
AS
9953 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
9954 cur->stack[spi].slot_type[i % BPF_REG_SIZE])
9955 /* Ex: old explored (safe) state has STACK_SPILL in
b8c1a309 9956 * this stack slot, but current has STACK_MISC ->
638f5b90
AS
9957 * this verifier states are not equivalent,
9958 * return false to continue verification of this path
9959 */
9960 return false;
9961 if (i % BPF_REG_SIZE)
9962 continue;
9963 if (old->stack[spi].slot_type[0] != STACK_SPILL)
9964 continue;
9965 if (!regsafe(&old->stack[spi].spilled_ptr,
9966 &cur->stack[spi].spilled_ptr,
9967 idmap))
9968 /* when explored and current stack slot are both storing
9969 * spilled registers, check that stored pointers types
9970 * are the same as well.
9971 * Ex: explored safe path could have stored
9972 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
9973 * but current path has stored:
9974 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
9975 * such verifier states are not equivalent.
9976 * return false to continue verification of this path
9977 */
9978 return false;
9979 }
9980 return true;
9981}
9982
fd978bf7
JS
9983static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur)
9984{
9985 if (old->acquired_refs != cur->acquired_refs)
9986 return false;
9987 return !memcmp(old->refs, cur->refs,
9988 sizeof(*old->refs) * old->acquired_refs);
9989}
9990
f1bca824
AS
9991/* compare two verifier states
9992 *
9993 * all states stored in state_list are known to be valid, since
9994 * verifier reached 'bpf_exit' instruction through them
9995 *
9996 * this function is called when verifier exploring different branches of
9997 * execution popped from the state stack. If it sees an old state that has
9998 * more strict register state and more strict stack state then this execution
9999 * branch doesn't need to be explored further, since verifier already
10000 * concluded that more strict state leads to valid finish.
10001 *
10002 * Therefore two states are equivalent if register state is more conservative
10003 * and explored stack state is more conservative than the current one.
10004 * Example:
10005 * explored current
10006 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
10007 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
10008 *
10009 * In other words if current stack state (one being explored) has more
10010 * valid slots than old one that already passed validation, it means
10011 * the verifier can stop exploring and conclude that current state is valid too
10012 *
10013 * Similarly with registers. If explored state has register type as invalid
10014 * whereas register type in current state is meaningful, it means that
10015 * the current state will reach 'bpf_exit' instruction safely
10016 */
f4d7e40a
AS
10017static bool func_states_equal(struct bpf_func_state *old,
10018 struct bpf_func_state *cur)
f1bca824 10019{
f1174f77
EC
10020 struct idpair *idmap;
10021 bool ret = false;
f1bca824
AS
10022 int i;
10023
f1174f77
EC
10024 idmap = kcalloc(ID_MAP_SIZE, sizeof(struct idpair), GFP_KERNEL);
10025 /* If we failed to allocate the idmap, just say it's not safe */
10026 if (!idmap)
1a0dc1ac 10027 return false;
f1174f77
EC
10028
10029 for (i = 0; i < MAX_BPF_REG; i++) {
1b688a19 10030 if (!regsafe(&old->regs[i], &cur->regs[i], idmap))
f1174f77 10031 goto out_free;
f1bca824
AS
10032 }
10033
638f5b90
AS
10034 if (!stacksafe(old, cur, idmap))
10035 goto out_free;
fd978bf7
JS
10036
10037 if (!refsafe(old, cur))
10038 goto out_free;
f1174f77
EC
10039 ret = true;
10040out_free:
10041 kfree(idmap);
10042 return ret;
f1bca824
AS
10043}
10044
f4d7e40a
AS
10045static bool states_equal(struct bpf_verifier_env *env,
10046 struct bpf_verifier_state *old,
10047 struct bpf_verifier_state *cur)
10048{
10049 int i;
10050
10051 if (old->curframe != cur->curframe)
10052 return false;
10053
979d63d5
DB
10054 /* Verification state from speculative execution simulation
10055 * must never prune a non-speculative execution one.
10056 */
10057 if (old->speculative && !cur->speculative)
10058 return false;
10059
d83525ca
AS
10060 if (old->active_spin_lock != cur->active_spin_lock)
10061 return false;
10062
f4d7e40a
AS
10063 /* for states to be equal callsites have to be the same
10064 * and all frame states need to be equivalent
10065 */
10066 for (i = 0; i <= old->curframe; i++) {
10067 if (old->frame[i]->callsite != cur->frame[i]->callsite)
10068 return false;
10069 if (!func_states_equal(old->frame[i], cur->frame[i]))
10070 return false;
10071 }
10072 return true;
10073}
10074
5327ed3d
JW
10075/* Return 0 if no propagation happened. Return negative error code if error
10076 * happened. Otherwise, return the propagated bit.
10077 */
55e7f3b5
JW
10078static int propagate_liveness_reg(struct bpf_verifier_env *env,
10079 struct bpf_reg_state *reg,
10080 struct bpf_reg_state *parent_reg)
10081{
5327ed3d
JW
10082 u8 parent_flag = parent_reg->live & REG_LIVE_READ;
10083 u8 flag = reg->live & REG_LIVE_READ;
55e7f3b5
JW
10084 int err;
10085
5327ed3d
JW
10086 /* When comes here, read flags of PARENT_REG or REG could be any of
10087 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
10088 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
10089 */
10090 if (parent_flag == REG_LIVE_READ64 ||
10091 /* Or if there is no read flag from REG. */
10092 !flag ||
10093 /* Or if the read flag from REG is the same as PARENT_REG. */
10094 parent_flag == flag)
55e7f3b5
JW
10095 return 0;
10096
5327ed3d 10097 err = mark_reg_read(env, reg, parent_reg, flag);
55e7f3b5
JW
10098 if (err)
10099 return err;
10100
5327ed3d 10101 return flag;
55e7f3b5
JW
10102}
10103
8e9cd9ce 10104/* A write screens off any subsequent reads; but write marks come from the
f4d7e40a
AS
10105 * straight-line code between a state and its parent. When we arrive at an
10106 * equivalent state (jump target or such) we didn't arrive by the straight-line
10107 * code, so read marks in the state must propagate to the parent regardless
10108 * of the state's write marks. That's what 'parent == state->parent' comparison
679c782d 10109 * in mark_reg_read() is for.
8e9cd9ce 10110 */
f4d7e40a
AS
10111static int propagate_liveness(struct bpf_verifier_env *env,
10112 const struct bpf_verifier_state *vstate,
10113 struct bpf_verifier_state *vparent)
dc503a8a 10114{
3f8cafa4 10115 struct bpf_reg_state *state_reg, *parent_reg;
f4d7e40a 10116 struct bpf_func_state *state, *parent;
3f8cafa4 10117 int i, frame, err = 0;
dc503a8a 10118
f4d7e40a
AS
10119 if (vparent->curframe != vstate->curframe) {
10120 WARN(1, "propagate_live: parent frame %d current frame %d\n",
10121 vparent->curframe, vstate->curframe);
10122 return -EFAULT;
10123 }
dc503a8a
EC
10124 /* Propagate read liveness of registers... */
10125 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
83d16312 10126 for (frame = 0; frame <= vstate->curframe; frame++) {
3f8cafa4
JW
10127 parent = vparent->frame[frame];
10128 state = vstate->frame[frame];
10129 parent_reg = parent->regs;
10130 state_reg = state->regs;
83d16312
JK
10131 /* We don't need to worry about FP liveness, it's read-only */
10132 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
55e7f3b5
JW
10133 err = propagate_liveness_reg(env, &state_reg[i],
10134 &parent_reg[i]);
5327ed3d 10135 if (err < 0)
3f8cafa4 10136 return err;
5327ed3d
JW
10137 if (err == REG_LIVE_READ64)
10138 mark_insn_zext(env, &parent_reg[i]);
dc503a8a 10139 }
f4d7e40a 10140
1b04aee7 10141 /* Propagate stack slots. */
f4d7e40a
AS
10142 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
10143 i < parent->allocated_stack / BPF_REG_SIZE; i++) {
3f8cafa4
JW
10144 parent_reg = &parent->stack[i].spilled_ptr;
10145 state_reg = &state->stack[i].spilled_ptr;
55e7f3b5
JW
10146 err = propagate_liveness_reg(env, state_reg,
10147 parent_reg);
5327ed3d 10148 if (err < 0)
3f8cafa4 10149 return err;
dc503a8a
EC
10150 }
10151 }
5327ed3d 10152 return 0;
dc503a8a
EC
10153}
10154
a3ce685d
AS
10155/* find precise scalars in the previous equivalent state and
10156 * propagate them into the current state
10157 */
10158static int propagate_precision(struct bpf_verifier_env *env,
10159 const struct bpf_verifier_state *old)
10160{
10161 struct bpf_reg_state *state_reg;
10162 struct bpf_func_state *state;
10163 int i, err = 0;
10164
10165 state = old->frame[old->curframe];
10166 state_reg = state->regs;
10167 for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
10168 if (state_reg->type != SCALAR_VALUE ||
10169 !state_reg->precise)
10170 continue;
10171 if (env->log.level & BPF_LOG_LEVEL2)
10172 verbose(env, "propagating r%d\n", i);
10173 err = mark_chain_precision(env, i);
10174 if (err < 0)
10175 return err;
10176 }
10177
10178 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
10179 if (state->stack[i].slot_type[0] != STACK_SPILL)
10180 continue;
10181 state_reg = &state->stack[i].spilled_ptr;
10182 if (state_reg->type != SCALAR_VALUE ||
10183 !state_reg->precise)
10184 continue;
10185 if (env->log.level & BPF_LOG_LEVEL2)
10186 verbose(env, "propagating fp%d\n",
10187 (-i - 1) * BPF_REG_SIZE);
10188 err = mark_chain_precision_stack(env, i);
10189 if (err < 0)
10190 return err;
10191 }
10192 return 0;
10193}
10194
2589726d
AS
10195static bool states_maybe_looping(struct bpf_verifier_state *old,
10196 struct bpf_verifier_state *cur)
10197{
10198 struct bpf_func_state *fold, *fcur;
10199 int i, fr = cur->curframe;
10200
10201 if (old->curframe != fr)
10202 return false;
10203
10204 fold = old->frame[fr];
10205 fcur = cur->frame[fr];
10206 for (i = 0; i < MAX_BPF_REG; i++)
10207 if (memcmp(&fold->regs[i], &fcur->regs[i],
10208 offsetof(struct bpf_reg_state, parent)))
10209 return false;
10210 return true;
10211}
10212
10213
58e2af8b 10214static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
f1bca824 10215{
58e2af8b 10216 struct bpf_verifier_state_list *new_sl;
9f4686c4 10217 struct bpf_verifier_state_list *sl, **pprev;
679c782d 10218 struct bpf_verifier_state *cur = env->cur_state, *new;
ceefbc96 10219 int i, j, err, states_cnt = 0;
10d274e8 10220 bool add_new_state = env->test_state_freq ? true : false;
f1bca824 10221
b5dc0163 10222 cur->last_insn_idx = env->prev_insn_idx;
a8f500af 10223 if (!env->insn_aux_data[insn_idx].prune_point)
f1bca824
AS
10224 /* this 'insn_idx' instruction wasn't marked, so we will not
10225 * be doing state search here
10226 */
10227 return 0;
10228
2589726d
AS
10229 /* bpf progs typically have pruning point every 4 instructions
10230 * http://vger.kernel.org/bpfconf2019.html#session-1
10231 * Do not add new state for future pruning if the verifier hasn't seen
10232 * at least 2 jumps and at least 8 instructions.
10233 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
10234 * In tests that amounts to up to 50% reduction into total verifier
10235 * memory consumption and 20% verifier time speedup.
10236 */
10237 if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
10238 env->insn_processed - env->prev_insn_processed >= 8)
10239 add_new_state = true;
10240
a8f500af
AS
10241 pprev = explored_state(env, insn_idx);
10242 sl = *pprev;
10243
9242b5f5
AS
10244 clean_live_states(env, insn_idx, cur);
10245
a8f500af 10246 while (sl) {
dc2a4ebc
AS
10247 states_cnt++;
10248 if (sl->state.insn_idx != insn_idx)
10249 goto next;
2589726d
AS
10250 if (sl->state.branches) {
10251 if (states_maybe_looping(&sl->state, cur) &&
10252 states_equal(env, &sl->state, cur)) {
10253 verbose_linfo(env, insn_idx, "; ");
10254 verbose(env, "infinite loop detected at insn %d\n", insn_idx);
10255 return -EINVAL;
10256 }
10257 /* if the verifier is processing a loop, avoid adding new state
10258 * too often, since different loop iterations have distinct
10259 * states and may not help future pruning.
10260 * This threshold shouldn't be too low to make sure that
10261 * a loop with large bound will be rejected quickly.
10262 * The most abusive loop will be:
10263 * r1 += 1
10264 * if r1 < 1000000 goto pc-2
10265 * 1M insn_procssed limit / 100 == 10k peak states.
10266 * This threshold shouldn't be too high either, since states
10267 * at the end of the loop are likely to be useful in pruning.
10268 */
10269 if (env->jmps_processed - env->prev_jmps_processed < 20 &&
10270 env->insn_processed - env->prev_insn_processed < 100)
10271 add_new_state = false;
10272 goto miss;
10273 }
638f5b90 10274 if (states_equal(env, &sl->state, cur)) {
9f4686c4 10275 sl->hit_cnt++;
f1bca824 10276 /* reached equivalent register/stack state,
dc503a8a
EC
10277 * prune the search.
10278 * Registers read by the continuation are read by us.
8e9cd9ce
EC
10279 * If we have any write marks in env->cur_state, they
10280 * will prevent corresponding reads in the continuation
10281 * from reaching our parent (an explored_state). Our
10282 * own state will get the read marks recorded, but
10283 * they'll be immediately forgotten as we're pruning
10284 * this state and will pop a new one.
f1bca824 10285 */
f4d7e40a 10286 err = propagate_liveness(env, &sl->state, cur);
a3ce685d
AS
10287
10288 /* if previous state reached the exit with precision and
10289 * current state is equivalent to it (except precsion marks)
10290 * the precision needs to be propagated back in
10291 * the current state.
10292 */
10293 err = err ? : push_jmp_history(env, cur);
10294 err = err ? : propagate_precision(env, &sl->state);
f4d7e40a
AS
10295 if (err)
10296 return err;
f1bca824 10297 return 1;
dc503a8a 10298 }
2589726d
AS
10299miss:
10300 /* when new state is not going to be added do not increase miss count.
10301 * Otherwise several loop iterations will remove the state
10302 * recorded earlier. The goal of these heuristics is to have
10303 * states from some iterations of the loop (some in the beginning
10304 * and some at the end) to help pruning.
10305 */
10306 if (add_new_state)
10307 sl->miss_cnt++;
9f4686c4
AS
10308 /* heuristic to determine whether this state is beneficial
10309 * to keep checking from state equivalence point of view.
10310 * Higher numbers increase max_states_per_insn and verification time,
10311 * but do not meaningfully decrease insn_processed.
10312 */
10313 if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
10314 /* the state is unlikely to be useful. Remove it to
10315 * speed up verification
10316 */
10317 *pprev = sl->next;
10318 if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
2589726d
AS
10319 u32 br = sl->state.branches;
10320
10321 WARN_ONCE(br,
10322 "BUG live_done but branches_to_explore %d\n",
10323 br);
9f4686c4
AS
10324 free_verifier_state(&sl->state, false);
10325 kfree(sl);
10326 env->peak_states--;
10327 } else {
10328 /* cannot free this state, since parentage chain may
10329 * walk it later. Add it for free_list instead to
10330 * be freed at the end of verification
10331 */
10332 sl->next = env->free_list;
10333 env->free_list = sl;
10334 }
10335 sl = *pprev;
10336 continue;
10337 }
dc2a4ebc 10338next:
9f4686c4
AS
10339 pprev = &sl->next;
10340 sl = *pprev;
f1bca824
AS
10341 }
10342
06ee7115
AS
10343 if (env->max_states_per_insn < states_cnt)
10344 env->max_states_per_insn = states_cnt;
10345
2c78ee89 10346 if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
b5dc0163 10347 return push_jmp_history(env, cur);
ceefbc96 10348
2589726d 10349 if (!add_new_state)
b5dc0163 10350 return push_jmp_history(env, cur);
ceefbc96 10351
2589726d
AS
10352 /* There were no equivalent states, remember the current one.
10353 * Technically the current state is not proven to be safe yet,
f4d7e40a 10354 * but it will either reach outer most bpf_exit (which means it's safe)
2589726d 10355 * or it will be rejected. When there are no loops the verifier won't be
f4d7e40a 10356 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
2589726d
AS
10357 * again on the way to bpf_exit.
10358 * When looping the sl->state.branches will be > 0 and this state
10359 * will not be considered for equivalence until branches == 0.
f1bca824 10360 */
638f5b90 10361 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
f1bca824
AS
10362 if (!new_sl)
10363 return -ENOMEM;
06ee7115
AS
10364 env->total_states++;
10365 env->peak_states++;
2589726d
AS
10366 env->prev_jmps_processed = env->jmps_processed;
10367 env->prev_insn_processed = env->insn_processed;
f1bca824
AS
10368
10369 /* add new state to the head of linked list */
679c782d
EC
10370 new = &new_sl->state;
10371 err = copy_verifier_state(new, cur);
1969db47 10372 if (err) {
679c782d 10373 free_verifier_state(new, false);
1969db47
AS
10374 kfree(new_sl);
10375 return err;
10376 }
dc2a4ebc 10377 new->insn_idx = insn_idx;
2589726d
AS
10378 WARN_ONCE(new->branches != 1,
10379 "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
b5dc0163 10380
2589726d 10381 cur->parent = new;
b5dc0163
AS
10382 cur->first_insn_idx = insn_idx;
10383 clear_jmp_history(cur);
5d839021
AS
10384 new_sl->next = *explored_state(env, insn_idx);
10385 *explored_state(env, insn_idx) = new_sl;
7640ead9
JK
10386 /* connect new state to parentage chain. Current frame needs all
10387 * registers connected. Only r6 - r9 of the callers are alive (pushed
10388 * to the stack implicitly by JITs) so in callers' frames connect just
10389 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
10390 * the state of the call instruction (with WRITTEN set), and r0 comes
10391 * from callee with its full parentage chain, anyway.
10392 */
8e9cd9ce
EC
10393 /* clear write marks in current state: the writes we did are not writes
10394 * our child did, so they don't screen off its reads from us.
10395 * (There are no read marks in current state, because reads always mark
10396 * their parent and current state never has children yet. Only
10397 * explored_states can get read marks.)
10398 */
eea1c227
AS
10399 for (j = 0; j <= cur->curframe; j++) {
10400 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
10401 cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
10402 for (i = 0; i < BPF_REG_FP; i++)
10403 cur->frame[j]->regs[i].live = REG_LIVE_NONE;
10404 }
f4d7e40a
AS
10405
10406 /* all stack frames are accessible from callee, clear them all */
10407 for (j = 0; j <= cur->curframe; j++) {
10408 struct bpf_func_state *frame = cur->frame[j];
679c782d 10409 struct bpf_func_state *newframe = new->frame[j];
f4d7e40a 10410
679c782d 10411 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
cc2b14d5 10412 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
679c782d
EC
10413 frame->stack[i].spilled_ptr.parent =
10414 &newframe->stack[i].spilled_ptr;
10415 }
f4d7e40a 10416 }
f1bca824
AS
10417 return 0;
10418}
10419
c64b7983
JS
10420/* Return true if it's OK to have the same insn return a different type. */
10421static bool reg_type_mismatch_ok(enum bpf_reg_type type)
10422{
10423 switch (type) {
10424 case PTR_TO_CTX:
10425 case PTR_TO_SOCKET:
10426 case PTR_TO_SOCKET_OR_NULL:
46f8bc92
MKL
10427 case PTR_TO_SOCK_COMMON:
10428 case PTR_TO_SOCK_COMMON_OR_NULL:
655a51e5
MKL
10429 case PTR_TO_TCP_SOCK:
10430 case PTR_TO_TCP_SOCK_OR_NULL:
fada7fdc 10431 case PTR_TO_XDP_SOCK:
2a02759e 10432 case PTR_TO_BTF_ID:
b121b341 10433 case PTR_TO_BTF_ID_OR_NULL:
c64b7983
JS
10434 return false;
10435 default:
10436 return true;
10437 }
10438}
10439
10440/* If an instruction was previously used with particular pointer types, then we
10441 * need to be careful to avoid cases such as the below, where it may be ok
10442 * for one branch accessing the pointer, but not ok for the other branch:
10443 *
10444 * R1 = sock_ptr
10445 * goto X;
10446 * ...
10447 * R1 = some_other_valid_ptr;
10448 * goto X;
10449 * ...
10450 * R2 = *(u32 *)(R1 + 0);
10451 */
10452static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
10453{
10454 return src != prev && (!reg_type_mismatch_ok(src) ||
10455 !reg_type_mismatch_ok(prev));
10456}
10457
58e2af8b 10458static int do_check(struct bpf_verifier_env *env)
17a52670 10459{
6f8a57cc 10460 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
51c39bb1 10461 struct bpf_verifier_state *state = env->cur_state;
17a52670 10462 struct bpf_insn *insns = env->prog->insnsi;
638f5b90 10463 struct bpf_reg_state *regs;
06ee7115 10464 int insn_cnt = env->prog->len;
17a52670 10465 bool do_print_state = false;
b5dc0163 10466 int prev_insn_idx = -1;
17a52670 10467
17a52670
AS
10468 for (;;) {
10469 struct bpf_insn *insn;
10470 u8 class;
10471 int err;
10472
b5dc0163 10473 env->prev_insn_idx = prev_insn_idx;
c08435ec 10474 if (env->insn_idx >= insn_cnt) {
61bd5218 10475 verbose(env, "invalid insn idx %d insn_cnt %d\n",
c08435ec 10476 env->insn_idx, insn_cnt);
17a52670
AS
10477 return -EFAULT;
10478 }
10479
c08435ec 10480 insn = &insns[env->insn_idx];
17a52670
AS
10481 class = BPF_CLASS(insn->code);
10482
06ee7115 10483 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
61bd5218
JK
10484 verbose(env,
10485 "BPF program is too large. Processed %d insn\n",
06ee7115 10486 env->insn_processed);
17a52670
AS
10487 return -E2BIG;
10488 }
10489
c08435ec 10490 err = is_state_visited(env, env->insn_idx);
f1bca824
AS
10491 if (err < 0)
10492 return err;
10493 if (err == 1) {
10494 /* found equivalent state, can prune the search */
06ee7115 10495 if (env->log.level & BPF_LOG_LEVEL) {
f1bca824 10496 if (do_print_state)
979d63d5
DB
10497 verbose(env, "\nfrom %d to %d%s: safe\n",
10498 env->prev_insn_idx, env->insn_idx,
10499 env->cur_state->speculative ?
10500 " (speculative execution)" : "");
f1bca824 10501 else
c08435ec 10502 verbose(env, "%d: safe\n", env->insn_idx);
f1bca824
AS
10503 }
10504 goto process_bpf_exit;
10505 }
10506
c3494801
AS
10507 if (signal_pending(current))
10508 return -EAGAIN;
10509
3c2ce60b
DB
10510 if (need_resched())
10511 cond_resched();
10512
06ee7115
AS
10513 if (env->log.level & BPF_LOG_LEVEL2 ||
10514 (env->log.level & BPF_LOG_LEVEL && do_print_state)) {
10515 if (env->log.level & BPF_LOG_LEVEL2)
c08435ec 10516 verbose(env, "%d:", env->insn_idx);
c5fc9692 10517 else
979d63d5
DB
10518 verbose(env, "\nfrom %d to %d%s:",
10519 env->prev_insn_idx, env->insn_idx,
10520 env->cur_state->speculative ?
10521 " (speculative execution)" : "");
f4d7e40a 10522 print_verifier_state(env, state->frame[state->curframe]);
17a52670
AS
10523 do_print_state = false;
10524 }
10525
06ee7115 10526 if (env->log.level & BPF_LOG_LEVEL) {
7105e828 10527 const struct bpf_insn_cbs cbs = {
e6ac2450 10528 .cb_call = disasm_kfunc_name,
7105e828 10529 .cb_print = verbose,
abe08840 10530 .private_data = env,
7105e828
DB
10531 };
10532
c08435ec
DB
10533 verbose_linfo(env, env->insn_idx, "; ");
10534 verbose(env, "%d: ", env->insn_idx);
abe08840 10535 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
17a52670
AS
10536 }
10537
cae1927c 10538 if (bpf_prog_is_dev_bound(env->prog->aux)) {
c08435ec
DB
10539 err = bpf_prog_offload_verify_insn(env, env->insn_idx,
10540 env->prev_insn_idx);
cae1927c
JK
10541 if (err)
10542 return err;
10543 }
13a27dfc 10544
638f5b90 10545 regs = cur_regs(env);
51c39bb1 10546 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
b5dc0163 10547 prev_insn_idx = env->insn_idx;
fd978bf7 10548
17a52670 10549 if (class == BPF_ALU || class == BPF_ALU64) {
1be7f75d 10550 err = check_alu_op(env, insn);
17a52670
AS
10551 if (err)
10552 return err;
10553
10554 } else if (class == BPF_LDX) {
3df126f3 10555 enum bpf_reg_type *prev_src_type, src_reg_type;
9bac3d6d
AS
10556
10557 /* check for reserved fields is already done */
10558
17a52670 10559 /* check src operand */
dc503a8a 10560 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17a52670
AS
10561 if (err)
10562 return err;
10563
dc503a8a 10564 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
17a52670
AS
10565 if (err)
10566 return err;
10567
725f9dcd
AS
10568 src_reg_type = regs[insn->src_reg].type;
10569
17a52670
AS
10570 /* check that memory (src_reg + off) is readable,
10571 * the state of dst_reg will be updated by this func
10572 */
c08435ec
DB
10573 err = check_mem_access(env, env->insn_idx, insn->src_reg,
10574 insn->off, BPF_SIZE(insn->code),
10575 BPF_READ, insn->dst_reg, false);
17a52670
AS
10576 if (err)
10577 return err;
10578
c08435ec 10579 prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type;
3df126f3
JK
10580
10581 if (*prev_src_type == NOT_INIT) {
9bac3d6d
AS
10582 /* saw a valid insn
10583 * dst_reg = *(u32 *)(src_reg + off)
3df126f3 10584 * save type to validate intersecting paths
9bac3d6d 10585 */
3df126f3 10586 *prev_src_type = src_reg_type;
9bac3d6d 10587
c64b7983 10588 } else if (reg_type_mismatch(src_reg_type, *prev_src_type)) {
9bac3d6d
AS
10589 /* ABuser program is trying to use the same insn
10590 * dst_reg = *(u32*) (src_reg + off)
10591 * with different pointer types:
10592 * src_reg == ctx in one branch and
10593 * src_reg == stack|map in some other branch.
10594 * Reject it.
10595 */
61bd5218 10596 verbose(env, "same insn cannot be used with different pointers\n");
9bac3d6d
AS
10597 return -EINVAL;
10598 }
10599
17a52670 10600 } else if (class == BPF_STX) {
3df126f3 10601 enum bpf_reg_type *prev_dst_type, dst_reg_type;
d691f9e8 10602
91c960b0
BJ
10603 if (BPF_MODE(insn->code) == BPF_ATOMIC) {
10604 err = check_atomic(env, env->insn_idx, insn);
17a52670
AS
10605 if (err)
10606 return err;
c08435ec 10607 env->insn_idx++;
17a52670
AS
10608 continue;
10609 }
10610
5ca419f2
BJ
10611 if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
10612 verbose(env, "BPF_STX uses reserved fields\n");
10613 return -EINVAL;
10614 }
10615
17a52670 10616 /* check src1 operand */
dc503a8a 10617 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17a52670
AS
10618 if (err)
10619 return err;
10620 /* check src2 operand */
dc503a8a 10621 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17a52670
AS
10622 if (err)
10623 return err;
10624
d691f9e8
AS
10625 dst_reg_type = regs[insn->dst_reg].type;
10626
17a52670 10627 /* check that memory (dst_reg + off) is writeable */
c08435ec
DB
10628 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
10629 insn->off, BPF_SIZE(insn->code),
10630 BPF_WRITE, insn->src_reg, false);
17a52670
AS
10631 if (err)
10632 return err;
10633
c08435ec 10634 prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type;
3df126f3
JK
10635
10636 if (*prev_dst_type == NOT_INIT) {
10637 *prev_dst_type = dst_reg_type;
c64b7983 10638 } else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) {
61bd5218 10639 verbose(env, "same insn cannot be used with different pointers\n");
d691f9e8
AS
10640 return -EINVAL;
10641 }
10642
17a52670
AS
10643 } else if (class == BPF_ST) {
10644 if (BPF_MODE(insn->code) != BPF_MEM ||
10645 insn->src_reg != BPF_REG_0) {
61bd5218 10646 verbose(env, "BPF_ST uses reserved fields\n");
17a52670
AS
10647 return -EINVAL;
10648 }
10649 /* check src operand */
dc503a8a 10650 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17a52670
AS
10651 if (err)
10652 return err;
10653
f37a8cb8 10654 if (is_ctx_reg(env, insn->dst_reg)) {
9d2be44a 10655 verbose(env, "BPF_ST stores into R%d %s is not allowed\n",
2a159c6f
DB
10656 insn->dst_reg,
10657 reg_type_str[reg_state(env, insn->dst_reg)->type]);
f37a8cb8
DB
10658 return -EACCES;
10659 }
10660
17a52670 10661 /* check that memory (dst_reg + off) is writeable */
c08435ec
DB
10662 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
10663 insn->off, BPF_SIZE(insn->code),
10664 BPF_WRITE, -1, false);
17a52670
AS
10665 if (err)
10666 return err;
10667
092ed096 10668 } else if (class == BPF_JMP || class == BPF_JMP32) {
17a52670
AS
10669 u8 opcode = BPF_OP(insn->code);
10670
2589726d 10671 env->jmps_processed++;
17a52670
AS
10672 if (opcode == BPF_CALL) {
10673 if (BPF_SRC(insn->code) != BPF_K ||
10674 insn->off != 0 ||
f4d7e40a 10675 (insn->src_reg != BPF_REG_0 &&
e6ac2450
MKL
10676 insn->src_reg != BPF_PSEUDO_CALL &&
10677 insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
092ed096
JW
10678 insn->dst_reg != BPF_REG_0 ||
10679 class == BPF_JMP32) {
61bd5218 10680 verbose(env, "BPF_CALL uses reserved fields\n");
17a52670
AS
10681 return -EINVAL;
10682 }
10683
d83525ca
AS
10684 if (env->cur_state->active_spin_lock &&
10685 (insn->src_reg == BPF_PSEUDO_CALL ||
10686 insn->imm != BPF_FUNC_spin_unlock)) {
10687 verbose(env, "function calls are not allowed while holding a lock\n");
10688 return -EINVAL;
10689 }
f4d7e40a 10690 if (insn->src_reg == BPF_PSEUDO_CALL)
c08435ec 10691 err = check_func_call(env, insn, &env->insn_idx);
e6ac2450
MKL
10692 else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL)
10693 err = check_kfunc_call(env, insn);
f4d7e40a 10694 else
69c087ba 10695 err = check_helper_call(env, insn, &env->insn_idx);
17a52670
AS
10696 if (err)
10697 return err;
17a52670
AS
10698 } else if (opcode == BPF_JA) {
10699 if (BPF_SRC(insn->code) != BPF_K ||
10700 insn->imm != 0 ||
10701 insn->src_reg != BPF_REG_0 ||
092ed096
JW
10702 insn->dst_reg != BPF_REG_0 ||
10703 class == BPF_JMP32) {
61bd5218 10704 verbose(env, "BPF_JA uses reserved fields\n");
17a52670
AS
10705 return -EINVAL;
10706 }
10707
c08435ec 10708 env->insn_idx += insn->off + 1;
17a52670
AS
10709 continue;
10710
10711 } else if (opcode == BPF_EXIT) {
10712 if (BPF_SRC(insn->code) != BPF_K ||
10713 insn->imm != 0 ||
10714 insn->src_reg != BPF_REG_0 ||
092ed096
JW
10715 insn->dst_reg != BPF_REG_0 ||
10716 class == BPF_JMP32) {
61bd5218 10717 verbose(env, "BPF_EXIT uses reserved fields\n");
17a52670
AS
10718 return -EINVAL;
10719 }
10720
d83525ca
AS
10721 if (env->cur_state->active_spin_lock) {
10722 verbose(env, "bpf_spin_unlock is missing\n");
10723 return -EINVAL;
10724 }
10725
f4d7e40a
AS
10726 if (state->curframe) {
10727 /* exit from nested function */
c08435ec 10728 err = prepare_func_exit(env, &env->insn_idx);
f4d7e40a
AS
10729 if (err)
10730 return err;
10731 do_print_state = true;
10732 continue;
10733 }
10734
fd978bf7
JS
10735 err = check_reference_leak(env);
10736 if (err)
10737 return err;
10738
390ee7e2
AS
10739 err = check_return_code(env);
10740 if (err)
10741 return err;
f1bca824 10742process_bpf_exit:
2589726d 10743 update_branch_counts(env, env->cur_state);
b5dc0163 10744 err = pop_stack(env, &prev_insn_idx,
6f8a57cc 10745 &env->insn_idx, pop_log);
638f5b90
AS
10746 if (err < 0) {
10747 if (err != -ENOENT)
10748 return err;
17a52670
AS
10749 break;
10750 } else {
10751 do_print_state = true;
10752 continue;
10753 }
10754 } else {
c08435ec 10755 err = check_cond_jmp_op(env, insn, &env->insn_idx);
17a52670
AS
10756 if (err)
10757 return err;
10758 }
10759 } else if (class == BPF_LD) {
10760 u8 mode = BPF_MODE(insn->code);
10761
10762 if (mode == BPF_ABS || mode == BPF_IND) {
ddd872bc
AS
10763 err = check_ld_abs(env, insn);
10764 if (err)
10765 return err;
10766
17a52670
AS
10767 } else if (mode == BPF_IMM) {
10768 err = check_ld_imm(env, insn);
10769 if (err)
10770 return err;
10771
c08435ec 10772 env->insn_idx++;
51c39bb1 10773 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
17a52670 10774 } else {
61bd5218 10775 verbose(env, "invalid BPF_LD mode\n");
17a52670
AS
10776 return -EINVAL;
10777 }
10778 } else {
61bd5218 10779 verbose(env, "unknown insn class %d\n", class);
17a52670
AS
10780 return -EINVAL;
10781 }
10782
c08435ec 10783 env->insn_idx++;
17a52670
AS
10784 }
10785
10786 return 0;
10787}
10788
541c3bad
AN
10789static int find_btf_percpu_datasec(struct btf *btf)
10790{
10791 const struct btf_type *t;
10792 const char *tname;
10793 int i, n;
10794
10795 /*
10796 * Both vmlinux and module each have their own ".data..percpu"
10797 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
10798 * types to look at only module's own BTF types.
10799 */
10800 n = btf_nr_types(btf);
10801 if (btf_is_module(btf))
10802 i = btf_nr_types(btf_vmlinux);
10803 else
10804 i = 1;
10805
10806 for(; i < n; i++) {
10807 t = btf_type_by_id(btf, i);
10808 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
10809 continue;
10810
10811 tname = btf_name_by_offset(btf, t->name_off);
10812 if (!strcmp(tname, ".data..percpu"))
10813 return i;
10814 }
10815
10816 return -ENOENT;
10817}
10818
4976b718
HL
10819/* replace pseudo btf_id with kernel symbol address */
10820static int check_pseudo_btf_id(struct bpf_verifier_env *env,
10821 struct bpf_insn *insn,
10822 struct bpf_insn_aux_data *aux)
10823{
eaa6bcb7
HL
10824 const struct btf_var_secinfo *vsi;
10825 const struct btf_type *datasec;
541c3bad 10826 struct btf_mod_pair *btf_mod;
4976b718
HL
10827 const struct btf_type *t;
10828 const char *sym_name;
eaa6bcb7 10829 bool percpu = false;
f16e6313 10830 u32 type, id = insn->imm;
541c3bad 10831 struct btf *btf;
f16e6313 10832 s32 datasec_id;
4976b718 10833 u64 addr;
541c3bad 10834 int i, btf_fd, err;
4976b718 10835
541c3bad
AN
10836 btf_fd = insn[1].imm;
10837 if (btf_fd) {
10838 btf = btf_get_by_fd(btf_fd);
10839 if (IS_ERR(btf)) {
10840 verbose(env, "invalid module BTF object FD specified.\n");
10841 return -EINVAL;
10842 }
10843 } else {
10844 if (!btf_vmlinux) {
10845 verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
10846 return -EINVAL;
10847 }
10848 btf = btf_vmlinux;
10849 btf_get(btf);
4976b718
HL
10850 }
10851
541c3bad 10852 t = btf_type_by_id(btf, id);
4976b718
HL
10853 if (!t) {
10854 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
541c3bad
AN
10855 err = -ENOENT;
10856 goto err_put;
4976b718
HL
10857 }
10858
10859 if (!btf_type_is_var(t)) {
541c3bad
AN
10860 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR.\n", id);
10861 err = -EINVAL;
10862 goto err_put;
4976b718
HL
10863 }
10864
541c3bad 10865 sym_name = btf_name_by_offset(btf, t->name_off);
4976b718
HL
10866 addr = kallsyms_lookup_name(sym_name);
10867 if (!addr) {
10868 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
10869 sym_name);
541c3bad
AN
10870 err = -ENOENT;
10871 goto err_put;
4976b718
HL
10872 }
10873
541c3bad 10874 datasec_id = find_btf_percpu_datasec(btf);
eaa6bcb7 10875 if (datasec_id > 0) {
541c3bad 10876 datasec = btf_type_by_id(btf, datasec_id);
eaa6bcb7
HL
10877 for_each_vsi(i, datasec, vsi) {
10878 if (vsi->type == id) {
10879 percpu = true;
10880 break;
10881 }
10882 }
10883 }
10884
4976b718
HL
10885 insn[0].imm = (u32)addr;
10886 insn[1].imm = addr >> 32;
10887
10888 type = t->type;
541c3bad 10889 t = btf_type_skip_modifiers(btf, type, NULL);
eaa6bcb7
HL
10890 if (percpu) {
10891 aux->btf_var.reg_type = PTR_TO_PERCPU_BTF_ID;
541c3bad 10892 aux->btf_var.btf = btf;
eaa6bcb7
HL
10893 aux->btf_var.btf_id = type;
10894 } else if (!btf_type_is_struct(t)) {
4976b718
HL
10895 const struct btf_type *ret;
10896 const char *tname;
10897 u32 tsize;
10898
10899 /* resolve the type size of ksym. */
541c3bad 10900 ret = btf_resolve_size(btf, t, &tsize);
4976b718 10901 if (IS_ERR(ret)) {
541c3bad 10902 tname = btf_name_by_offset(btf, t->name_off);
4976b718
HL
10903 verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
10904 tname, PTR_ERR(ret));
541c3bad
AN
10905 err = -EINVAL;
10906 goto err_put;
4976b718
HL
10907 }
10908 aux->btf_var.reg_type = PTR_TO_MEM;
10909 aux->btf_var.mem_size = tsize;
10910 } else {
10911 aux->btf_var.reg_type = PTR_TO_BTF_ID;
541c3bad 10912 aux->btf_var.btf = btf;
4976b718
HL
10913 aux->btf_var.btf_id = type;
10914 }
541c3bad
AN
10915
10916 /* check whether we recorded this BTF (and maybe module) already */
10917 for (i = 0; i < env->used_btf_cnt; i++) {
10918 if (env->used_btfs[i].btf == btf) {
10919 btf_put(btf);
10920 return 0;
10921 }
10922 }
10923
10924 if (env->used_btf_cnt >= MAX_USED_BTFS) {
10925 err = -E2BIG;
10926 goto err_put;
10927 }
10928
10929 btf_mod = &env->used_btfs[env->used_btf_cnt];
10930 btf_mod->btf = btf;
10931 btf_mod->module = NULL;
10932
10933 /* if we reference variables from kernel module, bump its refcount */
10934 if (btf_is_module(btf)) {
10935 btf_mod->module = btf_try_get_module(btf);
10936 if (!btf_mod->module) {
10937 err = -ENXIO;
10938 goto err_put;
10939 }
10940 }
10941
10942 env->used_btf_cnt++;
10943
4976b718 10944 return 0;
541c3bad
AN
10945err_put:
10946 btf_put(btf);
10947 return err;
4976b718
HL
10948}
10949
56f668df
MKL
10950static int check_map_prealloc(struct bpf_map *map)
10951{
10952 return (map->map_type != BPF_MAP_TYPE_HASH &&
bcc6b1b7
MKL
10953 map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
10954 map->map_type != BPF_MAP_TYPE_HASH_OF_MAPS) ||
56f668df
MKL
10955 !(map->map_flags & BPF_F_NO_PREALLOC);
10956}
10957
d83525ca
AS
10958static bool is_tracing_prog_type(enum bpf_prog_type type)
10959{
10960 switch (type) {
10961 case BPF_PROG_TYPE_KPROBE:
10962 case BPF_PROG_TYPE_TRACEPOINT:
10963 case BPF_PROG_TYPE_PERF_EVENT:
10964 case BPF_PROG_TYPE_RAW_TRACEPOINT:
10965 return true;
10966 default:
10967 return false;
10968 }
10969}
10970
94dacdbd
TG
10971static bool is_preallocated_map(struct bpf_map *map)
10972{
10973 if (!check_map_prealloc(map))
10974 return false;
10975 if (map->inner_map_meta && !check_map_prealloc(map->inner_map_meta))
10976 return false;
10977 return true;
10978}
10979
61bd5218
JK
10980static int check_map_prog_compatibility(struct bpf_verifier_env *env,
10981 struct bpf_map *map,
fdc15d38
AS
10982 struct bpf_prog *prog)
10983
10984{
7e40781c 10985 enum bpf_prog_type prog_type = resolve_prog_type(prog);
94dacdbd
TG
10986 /*
10987 * Validate that trace type programs use preallocated hash maps.
10988 *
10989 * For programs attached to PERF events this is mandatory as the
10990 * perf NMI can hit any arbitrary code sequence.
10991 *
10992 * All other trace types using preallocated hash maps are unsafe as
10993 * well because tracepoint or kprobes can be inside locked regions
10994 * of the memory allocator or at a place where a recursion into the
10995 * memory allocator would see inconsistent state.
10996 *
2ed905c5
TG
10997 * On RT enabled kernels run-time allocation of all trace type
10998 * programs is strictly prohibited due to lock type constraints. On
10999 * !RT kernels it is allowed for backwards compatibility reasons for
11000 * now, but warnings are emitted so developers are made aware of
11001 * the unsafety and can fix their programs before this is enforced.
56f668df 11002 */
7e40781c
UP
11003 if (is_tracing_prog_type(prog_type) && !is_preallocated_map(map)) {
11004 if (prog_type == BPF_PROG_TYPE_PERF_EVENT) {
61bd5218 11005 verbose(env, "perf_event programs can only use preallocated hash map\n");
56f668df
MKL
11006 return -EINVAL;
11007 }
2ed905c5
TG
11008 if (IS_ENABLED(CONFIG_PREEMPT_RT)) {
11009 verbose(env, "trace type programs can only use preallocated hash map\n");
11010 return -EINVAL;
11011 }
94dacdbd
TG
11012 WARN_ONCE(1, "trace type BPF program uses run-time allocation\n");
11013 verbose(env, "trace type programs with run-time allocated hash maps are unsafe. Switch to preallocated hash maps.\n");
fdc15d38 11014 }
a3884572 11015
9e7a4d98
KS
11016 if (map_value_has_spin_lock(map)) {
11017 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
11018 verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
11019 return -EINVAL;
11020 }
11021
11022 if (is_tracing_prog_type(prog_type)) {
11023 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
11024 return -EINVAL;
11025 }
11026
11027 if (prog->aux->sleepable) {
11028 verbose(env, "sleepable progs cannot use bpf_spin_lock yet\n");
11029 return -EINVAL;
11030 }
d83525ca
AS
11031 }
11032
a3884572 11033 if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) &&
09728266 11034 !bpf_offload_prog_map_match(prog, map)) {
a3884572
JK
11035 verbose(env, "offload device mismatch between prog and map\n");
11036 return -EINVAL;
11037 }
11038
85d33df3
MKL
11039 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
11040 verbose(env, "bpf_struct_ops map cannot be used in prog\n");
11041 return -EINVAL;
11042 }
11043
1e6c62a8
AS
11044 if (prog->aux->sleepable)
11045 switch (map->map_type) {
11046 case BPF_MAP_TYPE_HASH:
11047 case BPF_MAP_TYPE_LRU_HASH:
11048 case BPF_MAP_TYPE_ARRAY:
638e4b82
AS
11049 case BPF_MAP_TYPE_PERCPU_HASH:
11050 case BPF_MAP_TYPE_PERCPU_ARRAY:
11051 case BPF_MAP_TYPE_LRU_PERCPU_HASH:
11052 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
11053 case BPF_MAP_TYPE_HASH_OF_MAPS:
1e6c62a8
AS
11054 if (!is_preallocated_map(map)) {
11055 verbose(env,
638e4b82 11056 "Sleepable programs can only use preallocated maps\n");
1e6c62a8
AS
11057 return -EINVAL;
11058 }
11059 break;
ba90c2cc
KS
11060 case BPF_MAP_TYPE_RINGBUF:
11061 break;
1e6c62a8
AS
11062 default:
11063 verbose(env,
ba90c2cc 11064 "Sleepable programs can only use array, hash, and ringbuf maps\n");
1e6c62a8
AS
11065 return -EINVAL;
11066 }
11067
fdc15d38
AS
11068 return 0;
11069}
11070
b741f163
RG
11071static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
11072{
11073 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
11074 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
11075}
11076
4976b718
HL
11077/* find and rewrite pseudo imm in ld_imm64 instructions:
11078 *
11079 * 1. if it accesses map FD, replace it with actual map pointer.
11080 * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
11081 *
11082 * NOTE: btf_vmlinux is required for converting pseudo btf_id.
0246e64d 11083 */
4976b718 11084static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
0246e64d
AS
11085{
11086 struct bpf_insn *insn = env->prog->insnsi;
11087 int insn_cnt = env->prog->len;
fdc15d38 11088 int i, j, err;
0246e64d 11089
f1f7714e 11090 err = bpf_prog_calc_tag(env->prog);
aafe6ae9
DB
11091 if (err)
11092 return err;
11093
0246e64d 11094 for (i = 0; i < insn_cnt; i++, insn++) {
9bac3d6d 11095 if (BPF_CLASS(insn->code) == BPF_LDX &&
d691f9e8 11096 (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
61bd5218 11097 verbose(env, "BPF_LDX uses reserved fields\n");
d691f9e8
AS
11098 return -EINVAL;
11099 }
11100
0246e64d 11101 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
d8eca5bb 11102 struct bpf_insn_aux_data *aux;
0246e64d
AS
11103 struct bpf_map *map;
11104 struct fd f;
d8eca5bb 11105 u64 addr;
0246e64d
AS
11106
11107 if (i == insn_cnt - 1 || insn[1].code != 0 ||
11108 insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
11109 insn[1].off != 0) {
61bd5218 11110 verbose(env, "invalid bpf_ld_imm64 insn\n");
0246e64d
AS
11111 return -EINVAL;
11112 }
11113
d8eca5bb 11114 if (insn[0].src_reg == 0)
0246e64d
AS
11115 /* valid generic load 64-bit imm */
11116 goto next_insn;
11117
4976b718
HL
11118 if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
11119 aux = &env->insn_aux_data[i];
11120 err = check_pseudo_btf_id(env, insn, aux);
11121 if (err)
11122 return err;
11123 goto next_insn;
11124 }
11125
69c087ba
YS
11126 if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
11127 aux = &env->insn_aux_data[i];
11128 aux->ptr_type = PTR_TO_FUNC;
11129 goto next_insn;
11130 }
11131
d8eca5bb
DB
11132 /* In final convert_pseudo_ld_imm64() step, this is
11133 * converted into regular 64-bit imm load insn.
11134 */
11135 if ((insn[0].src_reg != BPF_PSEUDO_MAP_FD &&
11136 insn[0].src_reg != BPF_PSEUDO_MAP_VALUE) ||
11137 (insn[0].src_reg == BPF_PSEUDO_MAP_FD &&
11138 insn[1].imm != 0)) {
11139 verbose(env,
11140 "unrecognized bpf_ld_imm64 insn\n");
0246e64d
AS
11141 return -EINVAL;
11142 }
11143
20182390 11144 f = fdget(insn[0].imm);
c2101297 11145 map = __bpf_map_get(f);
0246e64d 11146 if (IS_ERR(map)) {
61bd5218 11147 verbose(env, "fd %d is not pointing to valid bpf_map\n",
20182390 11148 insn[0].imm);
0246e64d
AS
11149 return PTR_ERR(map);
11150 }
11151
61bd5218 11152 err = check_map_prog_compatibility(env, map, env->prog);
fdc15d38
AS
11153 if (err) {
11154 fdput(f);
11155 return err;
11156 }
11157
d8eca5bb
DB
11158 aux = &env->insn_aux_data[i];
11159 if (insn->src_reg == BPF_PSEUDO_MAP_FD) {
11160 addr = (unsigned long)map;
11161 } else {
11162 u32 off = insn[1].imm;
11163
11164 if (off >= BPF_MAX_VAR_OFF) {
11165 verbose(env, "direct value offset of %u is not allowed\n", off);
11166 fdput(f);
11167 return -EINVAL;
11168 }
11169
11170 if (!map->ops->map_direct_value_addr) {
11171 verbose(env, "no direct value access support for this map type\n");
11172 fdput(f);
11173 return -EINVAL;
11174 }
11175
11176 err = map->ops->map_direct_value_addr(map, &addr, off);
11177 if (err) {
11178 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
11179 map->value_size, off);
11180 fdput(f);
11181 return err;
11182 }
11183
11184 aux->map_off = off;
11185 addr += off;
11186 }
11187
11188 insn[0].imm = (u32)addr;
11189 insn[1].imm = addr >> 32;
0246e64d
AS
11190
11191 /* check whether we recorded this map already */
d8eca5bb 11192 for (j = 0; j < env->used_map_cnt; j++) {
0246e64d 11193 if (env->used_maps[j] == map) {
d8eca5bb 11194 aux->map_index = j;
0246e64d
AS
11195 fdput(f);
11196 goto next_insn;
11197 }
d8eca5bb 11198 }
0246e64d
AS
11199
11200 if (env->used_map_cnt >= MAX_USED_MAPS) {
11201 fdput(f);
11202 return -E2BIG;
11203 }
11204
0246e64d
AS
11205 /* hold the map. If the program is rejected by verifier,
11206 * the map will be released by release_maps() or it
11207 * will be used by the valid program until it's unloaded
ab7f5bf0 11208 * and all maps are released in free_used_maps()
0246e64d 11209 */
1e0bd5a0 11210 bpf_map_inc(map);
d8eca5bb
DB
11211
11212 aux->map_index = env->used_map_cnt;
92117d84
AS
11213 env->used_maps[env->used_map_cnt++] = map;
11214
b741f163 11215 if (bpf_map_is_cgroup_storage(map) &&
e4730423 11216 bpf_cgroup_storage_assign(env->prog->aux, map)) {
b741f163 11217 verbose(env, "only one cgroup storage of each type is allowed\n");
de9cbbaa
RG
11218 fdput(f);
11219 return -EBUSY;
11220 }
11221
0246e64d
AS
11222 fdput(f);
11223next_insn:
11224 insn++;
11225 i++;
5e581dad
DB
11226 continue;
11227 }
11228
11229 /* Basic sanity check before we invest more work here. */
11230 if (!bpf_opcode_in_insntable(insn->code)) {
11231 verbose(env, "unknown opcode %02x\n", insn->code);
11232 return -EINVAL;
0246e64d
AS
11233 }
11234 }
11235
11236 /* now all pseudo BPF_LD_IMM64 instructions load valid
11237 * 'struct bpf_map *' into a register instead of user map_fd.
11238 * These pointers will be used later by verifier to validate map access.
11239 */
11240 return 0;
11241}
11242
11243/* drop refcnt of maps used by the rejected program */
58e2af8b 11244static void release_maps(struct bpf_verifier_env *env)
0246e64d 11245{
a2ea0746
DB
11246 __bpf_free_used_maps(env->prog->aux, env->used_maps,
11247 env->used_map_cnt);
0246e64d
AS
11248}
11249
541c3bad
AN
11250/* drop refcnt of maps used by the rejected program */
11251static void release_btfs(struct bpf_verifier_env *env)
11252{
11253 __bpf_free_used_btfs(env->prog->aux, env->used_btfs,
11254 env->used_btf_cnt);
11255}
11256
0246e64d 11257/* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
58e2af8b 11258static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
0246e64d
AS
11259{
11260 struct bpf_insn *insn = env->prog->insnsi;
11261 int insn_cnt = env->prog->len;
11262 int i;
11263
69c087ba
YS
11264 for (i = 0; i < insn_cnt; i++, insn++) {
11265 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
11266 continue;
11267 if (insn->src_reg == BPF_PSEUDO_FUNC)
11268 continue;
11269 insn->src_reg = 0;
11270 }
0246e64d
AS
11271}
11272
8041902d
AS
11273/* single env->prog->insni[off] instruction was replaced with the range
11274 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying
11275 * [0, off) and [off, end) to new locations, so the patched range stays zero
11276 */
b325fbca
JW
11277static int adjust_insn_aux_data(struct bpf_verifier_env *env,
11278 struct bpf_prog *new_prog, u32 off, u32 cnt)
8041902d
AS
11279{
11280 struct bpf_insn_aux_data *new_data, *old_data = env->insn_aux_data;
b325fbca
JW
11281 struct bpf_insn *insn = new_prog->insnsi;
11282 u32 prog_len;
c131187d 11283 int i;
8041902d 11284
b325fbca
JW
11285 /* aux info at OFF always needs adjustment, no matter fast path
11286 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
11287 * original insn at old prog.
11288 */
11289 old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
11290
8041902d
AS
11291 if (cnt == 1)
11292 return 0;
b325fbca 11293 prog_len = new_prog->len;
fad953ce
KC
11294 new_data = vzalloc(array_size(prog_len,
11295 sizeof(struct bpf_insn_aux_data)));
8041902d
AS
11296 if (!new_data)
11297 return -ENOMEM;
11298 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
11299 memcpy(new_data + off + cnt - 1, old_data + off,
11300 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
b325fbca 11301 for (i = off; i < off + cnt - 1; i++) {
51c39bb1 11302 new_data[i].seen = env->pass_cnt;
b325fbca
JW
11303 new_data[i].zext_dst = insn_has_def32(env, insn + i);
11304 }
8041902d
AS
11305 env->insn_aux_data = new_data;
11306 vfree(old_data);
11307 return 0;
11308}
11309
cc8b0b92
AS
11310static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
11311{
11312 int i;
11313
11314 if (len == 1)
11315 return;
4cb3d99c
JW
11316 /* NOTE: fake 'exit' subprog should be updated as well. */
11317 for (i = 0; i <= env->subprog_cnt; i++) {
afd59424 11318 if (env->subprog_info[i].start <= off)
cc8b0b92 11319 continue;
9c8105bd 11320 env->subprog_info[i].start += len - 1;
cc8b0b92
AS
11321 }
11322}
11323
a748c697
MF
11324static void adjust_poke_descs(struct bpf_prog *prog, u32 len)
11325{
11326 struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
11327 int i, sz = prog->aux->size_poke_tab;
11328 struct bpf_jit_poke_descriptor *desc;
11329
11330 for (i = 0; i < sz; i++) {
11331 desc = &tab[i];
11332 desc->insn_idx += len - 1;
11333 }
11334}
11335
8041902d
AS
11336static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
11337 const struct bpf_insn *patch, u32 len)
11338{
11339 struct bpf_prog *new_prog;
11340
11341 new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
4f73379e
AS
11342 if (IS_ERR(new_prog)) {
11343 if (PTR_ERR(new_prog) == -ERANGE)
11344 verbose(env,
11345 "insn %d cannot be patched due to 16-bit range\n",
11346 env->insn_aux_data[off].orig_idx);
8041902d 11347 return NULL;
4f73379e 11348 }
b325fbca 11349 if (adjust_insn_aux_data(env, new_prog, off, len))
8041902d 11350 return NULL;
cc8b0b92 11351 adjust_subprog_starts(env, off, len);
a748c697 11352 adjust_poke_descs(new_prog, len);
8041902d
AS
11353 return new_prog;
11354}
11355
52875a04
JK
11356static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
11357 u32 off, u32 cnt)
11358{
11359 int i, j;
11360
11361 /* find first prog starting at or after off (first to remove) */
11362 for (i = 0; i < env->subprog_cnt; i++)
11363 if (env->subprog_info[i].start >= off)
11364 break;
11365 /* find first prog starting at or after off + cnt (first to stay) */
11366 for (j = i; j < env->subprog_cnt; j++)
11367 if (env->subprog_info[j].start >= off + cnt)
11368 break;
11369 /* if j doesn't start exactly at off + cnt, we are just removing
11370 * the front of previous prog
11371 */
11372 if (env->subprog_info[j].start != off + cnt)
11373 j--;
11374
11375 if (j > i) {
11376 struct bpf_prog_aux *aux = env->prog->aux;
11377 int move;
11378
11379 /* move fake 'exit' subprog as well */
11380 move = env->subprog_cnt + 1 - j;
11381
11382 memmove(env->subprog_info + i,
11383 env->subprog_info + j,
11384 sizeof(*env->subprog_info) * move);
11385 env->subprog_cnt -= j - i;
11386
11387 /* remove func_info */
11388 if (aux->func_info) {
11389 move = aux->func_info_cnt - j;
11390
11391 memmove(aux->func_info + i,
11392 aux->func_info + j,
11393 sizeof(*aux->func_info) * move);
11394 aux->func_info_cnt -= j - i;
11395 /* func_info->insn_off is set after all code rewrites,
11396 * in adjust_btf_func() - no need to adjust
11397 */
11398 }
11399 } else {
11400 /* convert i from "first prog to remove" to "first to adjust" */
11401 if (env->subprog_info[i].start == off)
11402 i++;
11403 }
11404
11405 /* update fake 'exit' subprog as well */
11406 for (; i <= env->subprog_cnt; i++)
11407 env->subprog_info[i].start -= cnt;
11408
11409 return 0;
11410}
11411
11412static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
11413 u32 cnt)
11414{
11415 struct bpf_prog *prog = env->prog;
11416 u32 i, l_off, l_cnt, nr_linfo;
11417 struct bpf_line_info *linfo;
11418
11419 nr_linfo = prog->aux->nr_linfo;
11420 if (!nr_linfo)
11421 return 0;
11422
11423 linfo = prog->aux->linfo;
11424
11425 /* find first line info to remove, count lines to be removed */
11426 for (i = 0; i < nr_linfo; i++)
11427 if (linfo[i].insn_off >= off)
11428 break;
11429
11430 l_off = i;
11431 l_cnt = 0;
11432 for (; i < nr_linfo; i++)
11433 if (linfo[i].insn_off < off + cnt)
11434 l_cnt++;
11435 else
11436 break;
11437
11438 /* First live insn doesn't match first live linfo, it needs to "inherit"
11439 * last removed linfo. prog is already modified, so prog->len == off
11440 * means no live instructions after (tail of the program was removed).
11441 */
11442 if (prog->len != off && l_cnt &&
11443 (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
11444 l_cnt--;
11445 linfo[--i].insn_off = off + cnt;
11446 }
11447
11448 /* remove the line info which refer to the removed instructions */
11449 if (l_cnt) {
11450 memmove(linfo + l_off, linfo + i,
11451 sizeof(*linfo) * (nr_linfo - i));
11452
11453 prog->aux->nr_linfo -= l_cnt;
11454 nr_linfo = prog->aux->nr_linfo;
11455 }
11456
11457 /* pull all linfo[i].insn_off >= off + cnt in by cnt */
11458 for (i = l_off; i < nr_linfo; i++)
11459 linfo[i].insn_off -= cnt;
11460
11461 /* fix up all subprogs (incl. 'exit') which start >= off */
11462 for (i = 0; i <= env->subprog_cnt; i++)
11463 if (env->subprog_info[i].linfo_idx > l_off) {
11464 /* program may have started in the removed region but
11465 * may not be fully removed
11466 */
11467 if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
11468 env->subprog_info[i].linfo_idx -= l_cnt;
11469 else
11470 env->subprog_info[i].linfo_idx = l_off;
11471 }
11472
11473 return 0;
11474}
11475
11476static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
11477{
11478 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
11479 unsigned int orig_prog_len = env->prog->len;
11480 int err;
11481
08ca90af
JK
11482 if (bpf_prog_is_dev_bound(env->prog->aux))
11483 bpf_prog_offload_remove_insns(env, off, cnt);
11484
52875a04
JK
11485 err = bpf_remove_insns(env->prog, off, cnt);
11486 if (err)
11487 return err;
11488
11489 err = adjust_subprog_starts_after_remove(env, off, cnt);
11490 if (err)
11491 return err;
11492
11493 err = bpf_adj_linfo_after_remove(env, off, cnt);
11494 if (err)
11495 return err;
11496
11497 memmove(aux_data + off, aux_data + off + cnt,
11498 sizeof(*aux_data) * (orig_prog_len - off - cnt));
11499
11500 return 0;
11501}
11502
2a5418a1
DB
11503/* The verifier does more data flow analysis than llvm and will not
11504 * explore branches that are dead at run time. Malicious programs can
11505 * have dead code too. Therefore replace all dead at-run-time code
11506 * with 'ja -1'.
11507 *
11508 * Just nops are not optimal, e.g. if they would sit at the end of the
11509 * program and through another bug we would manage to jump there, then
11510 * we'd execute beyond program memory otherwise. Returning exception
11511 * code also wouldn't work since we can have subprogs where the dead
11512 * code could be located.
c131187d
AS
11513 */
11514static void sanitize_dead_code(struct bpf_verifier_env *env)
11515{
11516 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
2a5418a1 11517 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
c131187d
AS
11518 struct bpf_insn *insn = env->prog->insnsi;
11519 const int insn_cnt = env->prog->len;
11520 int i;
11521
11522 for (i = 0; i < insn_cnt; i++) {
11523 if (aux_data[i].seen)
11524 continue;
2a5418a1 11525 memcpy(insn + i, &trap, sizeof(trap));
c131187d
AS
11526 }
11527}
11528
e2ae4ca2
JK
11529static bool insn_is_cond_jump(u8 code)
11530{
11531 u8 op;
11532
092ed096
JW
11533 if (BPF_CLASS(code) == BPF_JMP32)
11534 return true;
11535
e2ae4ca2
JK
11536 if (BPF_CLASS(code) != BPF_JMP)
11537 return false;
11538
11539 op = BPF_OP(code);
11540 return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
11541}
11542
11543static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
11544{
11545 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
11546 struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
11547 struct bpf_insn *insn = env->prog->insnsi;
11548 const int insn_cnt = env->prog->len;
11549 int i;
11550
11551 for (i = 0; i < insn_cnt; i++, insn++) {
11552 if (!insn_is_cond_jump(insn->code))
11553 continue;
11554
11555 if (!aux_data[i + 1].seen)
11556 ja.off = insn->off;
11557 else if (!aux_data[i + 1 + insn->off].seen)
11558 ja.off = 0;
11559 else
11560 continue;
11561
08ca90af
JK
11562 if (bpf_prog_is_dev_bound(env->prog->aux))
11563 bpf_prog_offload_replace_insn(env, i, &ja);
11564
e2ae4ca2
JK
11565 memcpy(insn, &ja, sizeof(ja));
11566 }
11567}
11568
52875a04
JK
11569static int opt_remove_dead_code(struct bpf_verifier_env *env)
11570{
11571 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
11572 int insn_cnt = env->prog->len;
11573 int i, err;
11574
11575 for (i = 0; i < insn_cnt; i++) {
11576 int j;
11577
11578 j = 0;
11579 while (i + j < insn_cnt && !aux_data[i + j].seen)
11580 j++;
11581 if (!j)
11582 continue;
11583
11584 err = verifier_remove_insns(env, i, j);
11585 if (err)
11586 return err;
11587 insn_cnt = env->prog->len;
11588 }
11589
11590 return 0;
11591}
11592
a1b14abc
JK
11593static int opt_remove_nops(struct bpf_verifier_env *env)
11594{
11595 const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
11596 struct bpf_insn *insn = env->prog->insnsi;
11597 int insn_cnt = env->prog->len;
11598 int i, err;
11599
11600 for (i = 0; i < insn_cnt; i++) {
11601 if (memcmp(&insn[i], &ja, sizeof(ja)))
11602 continue;
11603
11604 err = verifier_remove_insns(env, i, 1);
11605 if (err)
11606 return err;
11607 insn_cnt--;
11608 i--;
11609 }
11610
11611 return 0;
11612}
11613
d6c2308c
JW
11614static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
11615 const union bpf_attr *attr)
a4b1d3c1 11616{
d6c2308c 11617 struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
a4b1d3c1 11618 struct bpf_insn_aux_data *aux = env->insn_aux_data;
d6c2308c 11619 int i, patch_len, delta = 0, len = env->prog->len;
a4b1d3c1 11620 struct bpf_insn *insns = env->prog->insnsi;
a4b1d3c1 11621 struct bpf_prog *new_prog;
d6c2308c 11622 bool rnd_hi32;
a4b1d3c1 11623
d6c2308c 11624 rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
a4b1d3c1 11625 zext_patch[1] = BPF_ZEXT_REG(0);
d6c2308c
JW
11626 rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
11627 rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
11628 rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
a4b1d3c1
JW
11629 for (i = 0; i < len; i++) {
11630 int adj_idx = i + delta;
11631 struct bpf_insn insn;
83a28819 11632 int load_reg;
a4b1d3c1 11633
d6c2308c 11634 insn = insns[adj_idx];
83a28819 11635 load_reg = insn_def_regno(&insn);
d6c2308c
JW
11636 if (!aux[adj_idx].zext_dst) {
11637 u8 code, class;
11638 u32 imm_rnd;
11639
11640 if (!rnd_hi32)
11641 continue;
11642
11643 code = insn.code;
11644 class = BPF_CLASS(code);
83a28819 11645 if (load_reg == -1)
d6c2308c
JW
11646 continue;
11647
11648 /* NOTE: arg "reg" (the fourth one) is only used for
83a28819
IL
11649 * BPF_STX + SRC_OP, so it is safe to pass NULL
11650 * here.
d6c2308c 11651 */
83a28819 11652 if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
d6c2308c
JW
11653 if (class == BPF_LD &&
11654 BPF_MODE(code) == BPF_IMM)
11655 i++;
11656 continue;
11657 }
11658
11659 /* ctx load could be transformed into wider load. */
11660 if (class == BPF_LDX &&
11661 aux[adj_idx].ptr_type == PTR_TO_CTX)
11662 continue;
11663
11664 imm_rnd = get_random_int();
11665 rnd_hi32_patch[0] = insn;
11666 rnd_hi32_patch[1].imm = imm_rnd;
83a28819 11667 rnd_hi32_patch[3].dst_reg = load_reg;
d6c2308c
JW
11668 patch = rnd_hi32_patch;
11669 patch_len = 4;
11670 goto apply_patch_buffer;
11671 }
11672
39491867
BJ
11673 /* Add in an zero-extend instruction if a) the JIT has requested
11674 * it or b) it's a CMPXCHG.
11675 *
11676 * The latter is because: BPF_CMPXCHG always loads a value into
11677 * R0, therefore always zero-extends. However some archs'
11678 * equivalent instruction only does this load when the
11679 * comparison is successful. This detail of CMPXCHG is
11680 * orthogonal to the general zero-extension behaviour of the
11681 * CPU, so it's treated independently of bpf_jit_needs_zext.
11682 */
11683 if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
a4b1d3c1
JW
11684 continue;
11685
83a28819
IL
11686 if (WARN_ON(load_reg == -1)) {
11687 verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
11688 return -EFAULT;
b2e37a71
IL
11689 }
11690
a4b1d3c1 11691 zext_patch[0] = insn;
b2e37a71
IL
11692 zext_patch[1].dst_reg = load_reg;
11693 zext_patch[1].src_reg = load_reg;
d6c2308c
JW
11694 patch = zext_patch;
11695 patch_len = 2;
11696apply_patch_buffer:
11697 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
a4b1d3c1
JW
11698 if (!new_prog)
11699 return -ENOMEM;
11700 env->prog = new_prog;
11701 insns = new_prog->insnsi;
11702 aux = env->insn_aux_data;
d6c2308c 11703 delta += patch_len - 1;
a4b1d3c1
JW
11704 }
11705
11706 return 0;
11707}
11708
c64b7983
JS
11709/* convert load instructions that access fields of a context type into a
11710 * sequence of instructions that access fields of the underlying structure:
11711 * struct __sk_buff -> struct sk_buff
11712 * struct bpf_sock_ops -> struct sock
9bac3d6d 11713 */
58e2af8b 11714static int convert_ctx_accesses(struct bpf_verifier_env *env)
9bac3d6d 11715{
00176a34 11716 const struct bpf_verifier_ops *ops = env->ops;
f96da094 11717 int i, cnt, size, ctx_field_size, delta = 0;
3df126f3 11718 const int insn_cnt = env->prog->len;
36bbef52 11719 struct bpf_insn insn_buf[16], *insn;
46f53a65 11720 u32 target_size, size_default, off;
9bac3d6d 11721 struct bpf_prog *new_prog;
d691f9e8 11722 enum bpf_access_type type;
f96da094 11723 bool is_narrower_load;
9bac3d6d 11724
b09928b9
DB
11725 if (ops->gen_prologue || env->seen_direct_write) {
11726 if (!ops->gen_prologue) {
11727 verbose(env, "bpf verifier is misconfigured\n");
11728 return -EINVAL;
11729 }
36bbef52
DB
11730 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
11731 env->prog);
11732 if (cnt >= ARRAY_SIZE(insn_buf)) {
61bd5218 11733 verbose(env, "bpf verifier is misconfigured\n");
36bbef52
DB
11734 return -EINVAL;
11735 } else if (cnt) {
8041902d 11736 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
36bbef52
DB
11737 if (!new_prog)
11738 return -ENOMEM;
8041902d 11739
36bbef52 11740 env->prog = new_prog;
3df126f3 11741 delta += cnt - 1;
36bbef52
DB
11742 }
11743 }
11744
c64b7983 11745 if (bpf_prog_is_dev_bound(env->prog->aux))
9bac3d6d
AS
11746 return 0;
11747
3df126f3 11748 insn = env->prog->insnsi + delta;
36bbef52 11749
9bac3d6d 11750 for (i = 0; i < insn_cnt; i++, insn++) {
c64b7983
JS
11751 bpf_convert_ctx_access_t convert_ctx_access;
11752
62c7989b
DB
11753 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
11754 insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
11755 insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
ea2e7ce5 11756 insn->code == (BPF_LDX | BPF_MEM | BPF_DW))
d691f9e8 11757 type = BPF_READ;
62c7989b
DB
11758 else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
11759 insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
11760 insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
ea2e7ce5 11761 insn->code == (BPF_STX | BPF_MEM | BPF_DW))
d691f9e8
AS
11762 type = BPF_WRITE;
11763 else
9bac3d6d
AS
11764 continue;
11765
af86ca4e
AS
11766 if (type == BPF_WRITE &&
11767 env->insn_aux_data[i + delta].sanitize_stack_off) {
11768 struct bpf_insn patch[] = {
11769 /* Sanitize suspicious stack slot with zero.
11770 * There are no memory dependencies for this store,
11771 * since it's only using frame pointer and immediate
11772 * constant of zero
11773 */
11774 BPF_ST_MEM(BPF_DW, BPF_REG_FP,
11775 env->insn_aux_data[i + delta].sanitize_stack_off,
11776 0),
11777 /* the original STX instruction will immediately
11778 * overwrite the same stack slot with appropriate value
11779 */
11780 *insn,
11781 };
11782
11783 cnt = ARRAY_SIZE(patch);
11784 new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
11785 if (!new_prog)
11786 return -ENOMEM;
11787
11788 delta += cnt - 1;
11789 env->prog = new_prog;
11790 insn = new_prog->insnsi + i + delta;
11791 continue;
11792 }
11793
c64b7983
JS
11794 switch (env->insn_aux_data[i + delta].ptr_type) {
11795 case PTR_TO_CTX:
11796 if (!ops->convert_ctx_access)
11797 continue;
11798 convert_ctx_access = ops->convert_ctx_access;
11799 break;
11800 case PTR_TO_SOCKET:
46f8bc92 11801 case PTR_TO_SOCK_COMMON:
c64b7983
JS
11802 convert_ctx_access = bpf_sock_convert_ctx_access;
11803 break;
655a51e5
MKL
11804 case PTR_TO_TCP_SOCK:
11805 convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
11806 break;
fada7fdc
JL
11807 case PTR_TO_XDP_SOCK:
11808 convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
11809 break;
2a02759e 11810 case PTR_TO_BTF_ID:
27ae7997
MKL
11811 if (type == BPF_READ) {
11812 insn->code = BPF_LDX | BPF_PROBE_MEM |
11813 BPF_SIZE((insn)->code);
11814 env->prog->aux->num_exentries++;
7e40781c 11815 } else if (resolve_prog_type(env->prog) != BPF_PROG_TYPE_STRUCT_OPS) {
2a02759e
AS
11816 verbose(env, "Writes through BTF pointers are not allowed\n");
11817 return -EINVAL;
11818 }
2a02759e 11819 continue;
c64b7983 11820 default:
9bac3d6d 11821 continue;
c64b7983 11822 }
9bac3d6d 11823
31fd8581 11824 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
f96da094 11825 size = BPF_LDST_BYTES(insn);
31fd8581
YS
11826
11827 /* If the read access is a narrower load of the field,
11828 * convert to a 4/8-byte load, to minimum program type specific
11829 * convert_ctx_access changes. If conversion is successful,
11830 * we will apply proper mask to the result.
11831 */
f96da094 11832 is_narrower_load = size < ctx_field_size;
46f53a65
AI
11833 size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
11834 off = insn->off;
31fd8581 11835 if (is_narrower_load) {
f96da094
DB
11836 u8 size_code;
11837
11838 if (type == BPF_WRITE) {
61bd5218 11839 verbose(env, "bpf verifier narrow ctx access misconfigured\n");
f96da094
DB
11840 return -EINVAL;
11841 }
31fd8581 11842
f96da094 11843 size_code = BPF_H;
31fd8581
YS
11844 if (ctx_field_size == 4)
11845 size_code = BPF_W;
11846 else if (ctx_field_size == 8)
11847 size_code = BPF_DW;
f96da094 11848
bc23105c 11849 insn->off = off & ~(size_default - 1);
31fd8581
YS
11850 insn->code = BPF_LDX | BPF_MEM | size_code;
11851 }
f96da094
DB
11852
11853 target_size = 0;
c64b7983
JS
11854 cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
11855 &target_size);
f96da094
DB
11856 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
11857 (ctx_field_size && !target_size)) {
61bd5218 11858 verbose(env, "bpf verifier is misconfigured\n");
9bac3d6d
AS
11859 return -EINVAL;
11860 }
f96da094
DB
11861
11862 if (is_narrower_load && size < target_size) {
d895a0f1
IL
11863 u8 shift = bpf_ctx_narrow_access_offset(
11864 off, size, size_default) * 8;
46f53a65
AI
11865 if (ctx_field_size <= 4) {
11866 if (shift)
11867 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
11868 insn->dst_reg,
11869 shift);
31fd8581 11870 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
f96da094 11871 (1 << size * 8) - 1);
46f53a65
AI
11872 } else {
11873 if (shift)
11874 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
11875 insn->dst_reg,
11876 shift);
31fd8581 11877 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
e2f7fc0a 11878 (1ULL << size * 8) - 1);
46f53a65 11879 }
31fd8581 11880 }
9bac3d6d 11881
8041902d 11882 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
9bac3d6d
AS
11883 if (!new_prog)
11884 return -ENOMEM;
11885
3df126f3 11886 delta += cnt - 1;
9bac3d6d
AS
11887
11888 /* keep walking new program and skip insns we just inserted */
11889 env->prog = new_prog;
3df126f3 11890 insn = new_prog->insnsi + i + delta;
9bac3d6d
AS
11891 }
11892
11893 return 0;
11894}
11895
1c2a088a
AS
11896static int jit_subprogs(struct bpf_verifier_env *env)
11897{
11898 struct bpf_prog *prog = env->prog, **func, *tmp;
11899 int i, j, subprog_start, subprog_end = 0, len, subprog;
a748c697 11900 struct bpf_map *map_ptr;
7105e828 11901 struct bpf_insn *insn;
1c2a088a 11902 void *old_bpf_func;
c4c0bdc0 11903 int err, num_exentries;
1c2a088a 11904
f910cefa 11905 if (env->subprog_cnt <= 1)
1c2a088a
AS
11906 return 0;
11907
7105e828 11908 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
69c087ba
YS
11909 if (bpf_pseudo_func(insn)) {
11910 env->insn_aux_data[i].call_imm = insn->imm;
11911 /* subprog is encoded in insn[1].imm */
11912 continue;
11913 }
11914
23a2d70c 11915 if (!bpf_pseudo_call(insn))
1c2a088a 11916 continue;
c7a89784
DB
11917 /* Upon error here we cannot fall back to interpreter but
11918 * need a hard reject of the program. Thus -EFAULT is
11919 * propagated in any case.
11920 */
1c2a088a
AS
11921 subprog = find_subprog(env, i + insn->imm + 1);
11922 if (subprog < 0) {
11923 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
11924 i + insn->imm + 1);
11925 return -EFAULT;
11926 }
11927 /* temporarily remember subprog id inside insn instead of
11928 * aux_data, since next loop will split up all insns into funcs
11929 */
f910cefa 11930 insn->off = subprog;
1c2a088a
AS
11931 /* remember original imm in case JIT fails and fallback
11932 * to interpreter will be needed
11933 */
11934 env->insn_aux_data[i].call_imm = insn->imm;
11935 /* point imm to __bpf_call_base+1 from JITs point of view */
11936 insn->imm = 1;
11937 }
11938
c454a46b
MKL
11939 err = bpf_prog_alloc_jited_linfo(prog);
11940 if (err)
11941 goto out_undo_insn;
11942
11943 err = -ENOMEM;
6396bb22 11944 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
1c2a088a 11945 if (!func)
c7a89784 11946 goto out_undo_insn;
1c2a088a 11947
f910cefa 11948 for (i = 0; i < env->subprog_cnt; i++) {
1c2a088a 11949 subprog_start = subprog_end;
4cb3d99c 11950 subprog_end = env->subprog_info[i + 1].start;
1c2a088a
AS
11951
11952 len = subprog_end - subprog_start;
492ecee8
AS
11953 /* BPF_PROG_RUN doesn't call subprogs directly,
11954 * hence main prog stats include the runtime of subprogs.
11955 * subprogs don't have IDs and not reachable via prog_get_next_id
700d4796 11956 * func[i]->stats will never be accessed and stays NULL
492ecee8
AS
11957 */
11958 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
1c2a088a
AS
11959 if (!func[i])
11960 goto out_free;
11961 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
11962 len * sizeof(struct bpf_insn));
4f74d809 11963 func[i]->type = prog->type;
1c2a088a 11964 func[i]->len = len;
4f74d809
DB
11965 if (bpf_prog_calc_tag(func[i]))
11966 goto out_free;
1c2a088a 11967 func[i]->is_func = 1;
ba64e7d8
YS
11968 func[i]->aux->func_idx = i;
11969 /* the btf and func_info will be freed only at prog->aux */
11970 func[i]->aux->btf = prog->aux->btf;
11971 func[i]->aux->func_info = prog->aux->func_info;
11972
a748c697
MF
11973 for (j = 0; j < prog->aux->size_poke_tab; j++) {
11974 u32 insn_idx = prog->aux->poke_tab[j].insn_idx;
11975 int ret;
11976
11977 if (!(insn_idx >= subprog_start &&
11978 insn_idx <= subprog_end))
11979 continue;
11980
11981 ret = bpf_jit_add_poke_descriptor(func[i],
11982 &prog->aux->poke_tab[j]);
11983 if (ret < 0) {
11984 verbose(env, "adding tail call poke descriptor failed\n");
11985 goto out_free;
11986 }
11987
11988 func[i]->insnsi[insn_idx - subprog_start].imm = ret + 1;
11989
11990 map_ptr = func[i]->aux->poke_tab[ret].tail_call.map;
11991 ret = map_ptr->ops->map_poke_track(map_ptr, func[i]->aux);
11992 if (ret < 0) {
11993 verbose(env, "tracking tail call prog failed\n");
11994 goto out_free;
11995 }
11996 }
11997
1c2a088a
AS
11998 /* Use bpf_prog_F_tag to indicate functions in stack traces.
11999 * Long term would need debug info to populate names
12000 */
12001 func[i]->aux->name[0] = 'F';
9c8105bd 12002 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
1c2a088a 12003 func[i]->jit_requested = 1;
e6ac2450 12004 func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
c454a46b
MKL
12005 func[i]->aux->linfo = prog->aux->linfo;
12006 func[i]->aux->nr_linfo = prog->aux->nr_linfo;
12007 func[i]->aux->jited_linfo = prog->aux->jited_linfo;
12008 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
c4c0bdc0
YS
12009 num_exentries = 0;
12010 insn = func[i]->insnsi;
12011 for (j = 0; j < func[i]->len; j++, insn++) {
12012 if (BPF_CLASS(insn->code) == BPF_LDX &&
12013 BPF_MODE(insn->code) == BPF_PROBE_MEM)
12014 num_exentries++;
12015 }
12016 func[i]->aux->num_exentries = num_exentries;
ebf7d1f5 12017 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
1c2a088a
AS
12018 func[i] = bpf_int_jit_compile(func[i]);
12019 if (!func[i]->jited) {
12020 err = -ENOTSUPP;
12021 goto out_free;
12022 }
12023 cond_resched();
12024 }
a748c697
MF
12025
12026 /* Untrack main program's aux structs so that during map_poke_run()
12027 * we will not stumble upon the unfilled poke descriptors; each
12028 * of the main program's poke descs got distributed across subprogs
12029 * and got tracked onto map, so we are sure that none of them will
12030 * be missed after the operation below
12031 */
12032 for (i = 0; i < prog->aux->size_poke_tab; i++) {
12033 map_ptr = prog->aux->poke_tab[i].tail_call.map;
12034
12035 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
12036 }
12037
1c2a088a
AS
12038 /* at this point all bpf functions were successfully JITed
12039 * now populate all bpf_calls with correct addresses and
12040 * run last pass of JIT
12041 */
f910cefa 12042 for (i = 0; i < env->subprog_cnt; i++) {
1c2a088a
AS
12043 insn = func[i]->insnsi;
12044 for (j = 0; j < func[i]->len; j++, insn++) {
69c087ba
YS
12045 if (bpf_pseudo_func(insn)) {
12046 subprog = insn[1].imm;
12047 insn[0].imm = (u32)(long)func[subprog]->bpf_func;
12048 insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
12049 continue;
12050 }
23a2d70c 12051 if (!bpf_pseudo_call(insn))
1c2a088a
AS
12052 continue;
12053 subprog = insn->off;
0d306c31
PB
12054 insn->imm = BPF_CAST_CALL(func[subprog]->bpf_func) -
12055 __bpf_call_base;
1c2a088a 12056 }
2162fed4
SD
12057
12058 /* we use the aux data to keep a list of the start addresses
12059 * of the JITed images for each function in the program
12060 *
12061 * for some architectures, such as powerpc64, the imm field
12062 * might not be large enough to hold the offset of the start
12063 * address of the callee's JITed image from __bpf_call_base
12064 *
12065 * in such cases, we can lookup the start address of a callee
12066 * by using its subprog id, available from the off field of
12067 * the call instruction, as an index for this list
12068 */
12069 func[i]->aux->func = func;
12070 func[i]->aux->func_cnt = env->subprog_cnt;
1c2a088a 12071 }
f910cefa 12072 for (i = 0; i < env->subprog_cnt; i++) {
1c2a088a
AS
12073 old_bpf_func = func[i]->bpf_func;
12074 tmp = bpf_int_jit_compile(func[i]);
12075 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
12076 verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
c7a89784 12077 err = -ENOTSUPP;
1c2a088a
AS
12078 goto out_free;
12079 }
12080 cond_resched();
12081 }
12082
12083 /* finally lock prog and jit images for all functions and
12084 * populate kallsysm
12085 */
f910cefa 12086 for (i = 0; i < env->subprog_cnt; i++) {
1c2a088a
AS
12087 bpf_prog_lock_ro(func[i]);
12088 bpf_prog_kallsyms_add(func[i]);
12089 }
7105e828
DB
12090
12091 /* Last step: make now unused interpreter insns from main
12092 * prog consistent for later dump requests, so they can
12093 * later look the same as if they were interpreted only.
12094 */
12095 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
69c087ba
YS
12096 if (bpf_pseudo_func(insn)) {
12097 insn[0].imm = env->insn_aux_data[i].call_imm;
12098 insn[1].imm = find_subprog(env, i + insn[0].imm + 1);
12099 continue;
12100 }
23a2d70c 12101 if (!bpf_pseudo_call(insn))
7105e828
DB
12102 continue;
12103 insn->off = env->insn_aux_data[i].call_imm;
12104 subprog = find_subprog(env, i + insn->off + 1);
dbecd738 12105 insn->imm = subprog;
7105e828
DB
12106 }
12107
1c2a088a
AS
12108 prog->jited = 1;
12109 prog->bpf_func = func[0]->bpf_func;
12110 prog->aux->func = func;
f910cefa 12111 prog->aux->func_cnt = env->subprog_cnt;
e16301fb 12112 bpf_prog_jit_attempt_done(prog);
1c2a088a
AS
12113 return 0;
12114out_free:
a748c697
MF
12115 for (i = 0; i < env->subprog_cnt; i++) {
12116 if (!func[i])
12117 continue;
12118
12119 for (j = 0; j < func[i]->aux->size_poke_tab; j++) {
12120 map_ptr = func[i]->aux->poke_tab[j].tail_call.map;
12121 map_ptr->ops->map_poke_untrack(map_ptr, func[i]->aux);
12122 }
12123 bpf_jit_free(func[i]);
12124 }
1c2a088a 12125 kfree(func);
c7a89784 12126out_undo_insn:
1c2a088a
AS
12127 /* cleanup main prog to be interpreted */
12128 prog->jit_requested = 0;
12129 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
23a2d70c 12130 if (!bpf_pseudo_call(insn))
1c2a088a
AS
12131 continue;
12132 insn->off = 0;
12133 insn->imm = env->insn_aux_data[i].call_imm;
12134 }
e16301fb 12135 bpf_prog_jit_attempt_done(prog);
1c2a088a
AS
12136 return err;
12137}
12138
1ea47e01
AS
12139static int fixup_call_args(struct bpf_verifier_env *env)
12140{
19d28fbd 12141#ifndef CONFIG_BPF_JIT_ALWAYS_ON
1ea47e01
AS
12142 struct bpf_prog *prog = env->prog;
12143 struct bpf_insn *insn = prog->insnsi;
e6ac2450 12144 bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
1ea47e01 12145 int i, depth;
19d28fbd 12146#endif
e4052d06 12147 int err = 0;
1ea47e01 12148
e4052d06
QM
12149 if (env->prog->jit_requested &&
12150 !bpf_prog_is_dev_bound(env->prog->aux)) {
19d28fbd
DM
12151 err = jit_subprogs(env);
12152 if (err == 0)
1c2a088a 12153 return 0;
c7a89784
DB
12154 if (err == -EFAULT)
12155 return err;
19d28fbd
DM
12156 }
12157#ifndef CONFIG_BPF_JIT_ALWAYS_ON
e6ac2450
MKL
12158 if (has_kfunc_call) {
12159 verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
12160 return -EINVAL;
12161 }
e411901c
MF
12162 if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
12163 /* When JIT fails the progs with bpf2bpf calls and tail_calls
12164 * have to be rejected, since interpreter doesn't support them yet.
12165 */
12166 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
12167 return -EINVAL;
12168 }
1ea47e01 12169 for (i = 0; i < prog->len; i++, insn++) {
69c087ba
YS
12170 if (bpf_pseudo_func(insn)) {
12171 /* When JIT fails the progs with callback calls
12172 * have to be rejected, since interpreter doesn't support them yet.
12173 */
12174 verbose(env, "callbacks are not allowed in non-JITed programs\n");
12175 return -EINVAL;
12176 }
12177
23a2d70c 12178 if (!bpf_pseudo_call(insn))
1ea47e01
AS
12179 continue;
12180 depth = get_callee_stack_depth(env, insn, i);
12181 if (depth < 0)
12182 return depth;
12183 bpf_patch_call_args(insn, depth);
12184 }
19d28fbd
DM
12185 err = 0;
12186#endif
12187 return err;
1ea47e01
AS
12188}
12189
e6ac2450
MKL
12190static int fixup_kfunc_call(struct bpf_verifier_env *env,
12191 struct bpf_insn *insn)
12192{
12193 const struct bpf_kfunc_desc *desc;
12194
12195 /* insn->imm has the btf func_id. Replace it with
12196 * an address (relative to __bpf_base_call).
12197 */
12198 desc = find_kfunc_desc(env->prog, insn->imm);
12199 if (!desc) {
12200 verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
12201 insn->imm);
12202 return -EFAULT;
12203 }
12204
12205 insn->imm = desc->imm;
12206
12207 return 0;
12208}
12209
e6ac5933
BJ
12210/* Do various post-verification rewrites in a single program pass.
12211 * These rewrites simplify JIT and interpreter implementations.
e245c5c6 12212 */
e6ac5933 12213static int do_misc_fixups(struct bpf_verifier_env *env)
e245c5c6 12214{
79741b3b 12215 struct bpf_prog *prog = env->prog;
d2e4c1e6 12216 bool expect_blinding = bpf_jit_blinding_enabled(prog);
79741b3b 12217 struct bpf_insn *insn = prog->insnsi;
e245c5c6 12218 const struct bpf_func_proto *fn;
79741b3b 12219 const int insn_cnt = prog->len;
09772d92 12220 const struct bpf_map_ops *ops;
c93552c4 12221 struct bpf_insn_aux_data *aux;
81ed18ab
AS
12222 struct bpf_insn insn_buf[16];
12223 struct bpf_prog *new_prog;
12224 struct bpf_map *map_ptr;
d2e4c1e6 12225 int i, ret, cnt, delta = 0;
e245c5c6 12226
79741b3b 12227 for (i = 0; i < insn_cnt; i++, insn++) {
e6ac5933 12228 /* Make divide-by-zero exceptions impossible. */
f6b1b3bf
DB
12229 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
12230 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
12231 insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
68fda450 12232 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
f6b1b3bf 12233 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
e88b2c6e
DB
12234 bool isdiv = BPF_OP(insn->code) == BPF_DIV;
12235 struct bpf_insn *patchlet;
12236 struct bpf_insn chk_and_div[] = {
9b00f1b7 12237 /* [R,W]x div 0 -> 0 */
e88b2c6e
DB
12238 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
12239 BPF_JNE | BPF_K, insn->src_reg,
12240 0, 2, 0),
f6b1b3bf
DB
12241 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
12242 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
12243 *insn,
12244 };
e88b2c6e 12245 struct bpf_insn chk_and_mod[] = {
9b00f1b7 12246 /* [R,W]x mod 0 -> [R,W]x */
e88b2c6e
DB
12247 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
12248 BPF_JEQ | BPF_K, insn->src_reg,
9b00f1b7 12249 0, 1 + (is64 ? 0 : 1), 0),
f6b1b3bf 12250 *insn,
9b00f1b7
DB
12251 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
12252 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
f6b1b3bf 12253 };
f6b1b3bf 12254
e88b2c6e
DB
12255 patchlet = isdiv ? chk_and_div : chk_and_mod;
12256 cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
9b00f1b7 12257 ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
f6b1b3bf
DB
12258
12259 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
68fda450
AS
12260 if (!new_prog)
12261 return -ENOMEM;
12262
12263 delta += cnt - 1;
12264 env->prog = prog = new_prog;
12265 insn = new_prog->insnsi + i + delta;
12266 continue;
12267 }
12268
e6ac5933 12269 /* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
e0cea7ce
DB
12270 if (BPF_CLASS(insn->code) == BPF_LD &&
12271 (BPF_MODE(insn->code) == BPF_ABS ||
12272 BPF_MODE(insn->code) == BPF_IND)) {
12273 cnt = env->ops->gen_ld_abs(insn, insn_buf);
12274 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
12275 verbose(env, "bpf verifier is misconfigured\n");
12276 return -EINVAL;
12277 }
12278
12279 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
12280 if (!new_prog)
12281 return -ENOMEM;
12282
12283 delta += cnt - 1;
12284 env->prog = prog = new_prog;
12285 insn = new_prog->insnsi + i + delta;
12286 continue;
12287 }
12288
e6ac5933 12289 /* Rewrite pointer arithmetic to mitigate speculation attacks. */
979d63d5
DB
12290 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
12291 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
12292 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
12293 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
979d63d5
DB
12294 struct bpf_insn *patch = &insn_buf[0];
12295 bool issrc, isneg;
12296 u32 off_reg;
12297
12298 aux = &env->insn_aux_data[i + delta];
3612af78
DB
12299 if (!aux->alu_state ||
12300 aux->alu_state == BPF_ALU_NON_POINTER)
979d63d5
DB
12301 continue;
12302
12303 isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
12304 issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
12305 BPF_ALU_SANITIZE_SRC;
12306
12307 off_reg = issrc ? insn->src_reg : insn->dst_reg;
12308 if (isneg)
12309 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
b5871dca 12310 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
979d63d5
DB
12311 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
12312 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
12313 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
12314 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
12315 if (issrc) {
12316 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX,
12317 off_reg);
12318 insn->src_reg = BPF_REG_AX;
12319 } else {
12320 *patch++ = BPF_ALU64_REG(BPF_AND, off_reg,
12321 BPF_REG_AX);
12322 }
12323 if (isneg)
12324 insn->code = insn->code == code_add ?
12325 code_sub : code_add;
12326 *patch++ = *insn;
12327 if (issrc && isneg)
12328 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
12329 cnt = patch - insn_buf;
12330
12331 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
12332 if (!new_prog)
12333 return -ENOMEM;
12334
12335 delta += cnt - 1;
12336 env->prog = prog = new_prog;
12337 insn = new_prog->insnsi + i + delta;
12338 continue;
12339 }
12340
79741b3b
AS
12341 if (insn->code != (BPF_JMP | BPF_CALL))
12342 continue;
cc8b0b92
AS
12343 if (insn->src_reg == BPF_PSEUDO_CALL)
12344 continue;
e6ac2450
MKL
12345 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
12346 ret = fixup_kfunc_call(env, insn);
12347 if (ret)
12348 return ret;
12349 continue;
12350 }
e245c5c6 12351
79741b3b
AS
12352 if (insn->imm == BPF_FUNC_get_route_realm)
12353 prog->dst_needed = 1;
12354 if (insn->imm == BPF_FUNC_get_prandom_u32)
12355 bpf_user_rnd_init_once();
9802d865
JB
12356 if (insn->imm == BPF_FUNC_override_return)
12357 prog->kprobe_override = 1;
79741b3b 12358 if (insn->imm == BPF_FUNC_tail_call) {
7b9f6da1
DM
12359 /* If we tail call into other programs, we
12360 * cannot make any assumptions since they can
12361 * be replaced dynamically during runtime in
12362 * the program array.
12363 */
12364 prog->cb_access = 1;
e411901c
MF
12365 if (!allow_tail_call_in_subprogs(env))
12366 prog->aux->stack_depth = MAX_BPF_STACK;
12367 prog->aux->max_pkt_offset = MAX_PACKET_OFF;
7b9f6da1 12368
79741b3b
AS
12369 /* mark bpf_tail_call as different opcode to avoid
12370 * conditional branch in the interpeter for every normal
12371 * call and to prevent accidental JITing by JIT compiler
12372 * that doesn't support bpf_tail_call yet
e245c5c6 12373 */
79741b3b 12374 insn->imm = 0;
71189fa9 12375 insn->code = BPF_JMP | BPF_TAIL_CALL;
b2157399 12376
c93552c4 12377 aux = &env->insn_aux_data[i + delta];
2c78ee89 12378 if (env->bpf_capable && !expect_blinding &&
cc52d914 12379 prog->jit_requested &&
d2e4c1e6
DB
12380 !bpf_map_key_poisoned(aux) &&
12381 !bpf_map_ptr_poisoned(aux) &&
12382 !bpf_map_ptr_unpriv(aux)) {
12383 struct bpf_jit_poke_descriptor desc = {
12384 .reason = BPF_POKE_REASON_TAIL_CALL,
12385 .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
12386 .tail_call.key = bpf_map_key_immediate(aux),
a748c697 12387 .insn_idx = i + delta,
d2e4c1e6
DB
12388 };
12389
12390 ret = bpf_jit_add_poke_descriptor(prog, &desc);
12391 if (ret < 0) {
12392 verbose(env, "adding tail call poke descriptor failed\n");
12393 return ret;
12394 }
12395
12396 insn->imm = ret + 1;
12397 continue;
12398 }
12399
c93552c4
DB
12400 if (!bpf_map_ptr_unpriv(aux))
12401 continue;
12402
b2157399
AS
12403 /* instead of changing every JIT dealing with tail_call
12404 * emit two extra insns:
12405 * if (index >= max_entries) goto out;
12406 * index &= array->index_mask;
12407 * to avoid out-of-bounds cpu speculation
12408 */
c93552c4 12409 if (bpf_map_ptr_poisoned(aux)) {
40950343 12410 verbose(env, "tail_call abusing map_ptr\n");
b2157399
AS
12411 return -EINVAL;
12412 }
c93552c4 12413
d2e4c1e6 12414 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
b2157399
AS
12415 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
12416 map_ptr->max_entries, 2);
12417 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
12418 container_of(map_ptr,
12419 struct bpf_array,
12420 map)->index_mask);
12421 insn_buf[2] = *insn;
12422 cnt = 3;
12423 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
12424 if (!new_prog)
12425 return -ENOMEM;
12426
12427 delta += cnt - 1;
12428 env->prog = prog = new_prog;
12429 insn = new_prog->insnsi + i + delta;
79741b3b
AS
12430 continue;
12431 }
e245c5c6 12432
89c63074 12433 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
09772d92
DB
12434 * and other inlining handlers are currently limited to 64 bit
12435 * only.
89c63074 12436 */
60b58afc 12437 if (prog->jit_requested && BITS_PER_LONG == 64 &&
09772d92
DB
12438 (insn->imm == BPF_FUNC_map_lookup_elem ||
12439 insn->imm == BPF_FUNC_map_update_elem ||
84430d42
DB
12440 insn->imm == BPF_FUNC_map_delete_elem ||
12441 insn->imm == BPF_FUNC_map_push_elem ||
12442 insn->imm == BPF_FUNC_map_pop_elem ||
e6a4750f
BT
12443 insn->imm == BPF_FUNC_map_peek_elem ||
12444 insn->imm == BPF_FUNC_redirect_map)) {
c93552c4
DB
12445 aux = &env->insn_aux_data[i + delta];
12446 if (bpf_map_ptr_poisoned(aux))
12447 goto patch_call_imm;
12448
d2e4c1e6 12449 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
09772d92
DB
12450 ops = map_ptr->ops;
12451 if (insn->imm == BPF_FUNC_map_lookup_elem &&
12452 ops->map_gen_lookup) {
12453 cnt = ops->map_gen_lookup(map_ptr, insn_buf);
4a8f87e6
DB
12454 if (cnt == -EOPNOTSUPP)
12455 goto patch_map_ops_generic;
12456 if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
09772d92
DB
12457 verbose(env, "bpf verifier is misconfigured\n");
12458 return -EINVAL;
12459 }
81ed18ab 12460
09772d92
DB
12461 new_prog = bpf_patch_insn_data(env, i + delta,
12462 insn_buf, cnt);
12463 if (!new_prog)
12464 return -ENOMEM;
81ed18ab 12465
09772d92
DB
12466 delta += cnt - 1;
12467 env->prog = prog = new_prog;
12468 insn = new_prog->insnsi + i + delta;
12469 continue;
12470 }
81ed18ab 12471
09772d92
DB
12472 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
12473 (void *(*)(struct bpf_map *map, void *key))NULL));
12474 BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
12475 (int (*)(struct bpf_map *map, void *key))NULL));
12476 BUILD_BUG_ON(!__same_type(ops->map_update_elem,
12477 (int (*)(struct bpf_map *map, void *key, void *value,
12478 u64 flags))NULL));
84430d42
DB
12479 BUILD_BUG_ON(!__same_type(ops->map_push_elem,
12480 (int (*)(struct bpf_map *map, void *value,
12481 u64 flags))NULL));
12482 BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
12483 (int (*)(struct bpf_map *map, void *value))NULL));
12484 BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
12485 (int (*)(struct bpf_map *map, void *value))NULL));
e6a4750f
BT
12486 BUILD_BUG_ON(!__same_type(ops->map_redirect,
12487 (int (*)(struct bpf_map *map, u32 ifindex, u64 flags))NULL));
12488
4a8f87e6 12489patch_map_ops_generic:
09772d92
DB
12490 switch (insn->imm) {
12491 case BPF_FUNC_map_lookup_elem:
12492 insn->imm = BPF_CAST_CALL(ops->map_lookup_elem) -
12493 __bpf_call_base;
12494 continue;
12495 case BPF_FUNC_map_update_elem:
12496 insn->imm = BPF_CAST_CALL(ops->map_update_elem) -
12497 __bpf_call_base;
12498 continue;
12499 case BPF_FUNC_map_delete_elem:
12500 insn->imm = BPF_CAST_CALL(ops->map_delete_elem) -
12501 __bpf_call_base;
12502 continue;
84430d42
DB
12503 case BPF_FUNC_map_push_elem:
12504 insn->imm = BPF_CAST_CALL(ops->map_push_elem) -
12505 __bpf_call_base;
12506 continue;
12507 case BPF_FUNC_map_pop_elem:
12508 insn->imm = BPF_CAST_CALL(ops->map_pop_elem) -
12509 __bpf_call_base;
12510 continue;
12511 case BPF_FUNC_map_peek_elem:
12512 insn->imm = BPF_CAST_CALL(ops->map_peek_elem) -
12513 __bpf_call_base;
12514 continue;
e6a4750f
BT
12515 case BPF_FUNC_redirect_map:
12516 insn->imm = BPF_CAST_CALL(ops->map_redirect) -
12517 __bpf_call_base;
12518 continue;
09772d92 12519 }
81ed18ab 12520
09772d92 12521 goto patch_call_imm;
81ed18ab
AS
12522 }
12523
e6ac5933 12524 /* Implement bpf_jiffies64 inline. */
5576b991
MKL
12525 if (prog->jit_requested && BITS_PER_LONG == 64 &&
12526 insn->imm == BPF_FUNC_jiffies64) {
12527 struct bpf_insn ld_jiffies_addr[2] = {
12528 BPF_LD_IMM64(BPF_REG_0,
12529 (unsigned long)&jiffies),
12530 };
12531
12532 insn_buf[0] = ld_jiffies_addr[0];
12533 insn_buf[1] = ld_jiffies_addr[1];
12534 insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
12535 BPF_REG_0, 0);
12536 cnt = 3;
12537
12538 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
12539 cnt);
12540 if (!new_prog)
12541 return -ENOMEM;
12542
12543 delta += cnt - 1;
12544 env->prog = prog = new_prog;
12545 insn = new_prog->insnsi + i + delta;
12546 continue;
12547 }
12548
81ed18ab 12549patch_call_imm:
5e43f899 12550 fn = env->ops->get_func_proto(insn->imm, env->prog);
79741b3b
AS
12551 /* all functions that have prototype and verifier allowed
12552 * programs to call them, must be real in-kernel functions
12553 */
12554 if (!fn->func) {
61bd5218
JK
12555 verbose(env,
12556 "kernel subsystem misconfigured func %s#%d\n",
79741b3b
AS
12557 func_id_name(insn->imm), insn->imm);
12558 return -EFAULT;
e245c5c6 12559 }
79741b3b 12560 insn->imm = fn->func - __bpf_call_base;
e245c5c6 12561 }
e245c5c6 12562
d2e4c1e6
DB
12563 /* Since poke tab is now finalized, publish aux to tracker. */
12564 for (i = 0; i < prog->aux->size_poke_tab; i++) {
12565 map_ptr = prog->aux->poke_tab[i].tail_call.map;
12566 if (!map_ptr->ops->map_poke_track ||
12567 !map_ptr->ops->map_poke_untrack ||
12568 !map_ptr->ops->map_poke_run) {
12569 verbose(env, "bpf verifier is misconfigured\n");
12570 return -EINVAL;
12571 }
12572
12573 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
12574 if (ret < 0) {
12575 verbose(env, "tracking tail call prog failed\n");
12576 return ret;
12577 }
12578 }
12579
e6ac2450
MKL
12580 sort_kfunc_descs_by_imm(env->prog);
12581
79741b3b
AS
12582 return 0;
12583}
e245c5c6 12584
58e2af8b 12585static void free_states(struct bpf_verifier_env *env)
f1bca824 12586{
58e2af8b 12587 struct bpf_verifier_state_list *sl, *sln;
f1bca824
AS
12588 int i;
12589
9f4686c4
AS
12590 sl = env->free_list;
12591 while (sl) {
12592 sln = sl->next;
12593 free_verifier_state(&sl->state, false);
12594 kfree(sl);
12595 sl = sln;
12596 }
51c39bb1 12597 env->free_list = NULL;
9f4686c4 12598
f1bca824
AS
12599 if (!env->explored_states)
12600 return;
12601
dc2a4ebc 12602 for (i = 0; i < state_htab_size(env); i++) {
f1bca824
AS
12603 sl = env->explored_states[i];
12604
a8f500af
AS
12605 while (sl) {
12606 sln = sl->next;
12607 free_verifier_state(&sl->state, false);
12608 kfree(sl);
12609 sl = sln;
12610 }
51c39bb1 12611 env->explored_states[i] = NULL;
f1bca824 12612 }
51c39bb1 12613}
f1bca824 12614
51c39bb1
AS
12615/* The verifier is using insn_aux_data[] to store temporary data during
12616 * verification and to store information for passes that run after the
12617 * verification like dead code sanitization. do_check_common() for subprogram N
12618 * may analyze many other subprograms. sanitize_insn_aux_data() clears all
12619 * temporary data after do_check_common() finds that subprogram N cannot be
12620 * verified independently. pass_cnt counts the number of times
12621 * do_check_common() was run and insn->aux->seen tells the pass number
12622 * insn_aux_data was touched. These variables are compared to clear temporary
12623 * data from failed pass. For testing and experiments do_check_common() can be
12624 * run multiple times even when prior attempt to verify is unsuccessful.
12625 */
12626static void sanitize_insn_aux_data(struct bpf_verifier_env *env)
12627{
12628 struct bpf_insn *insn = env->prog->insnsi;
12629 struct bpf_insn_aux_data *aux;
12630 int i, class;
12631
12632 for (i = 0; i < env->prog->len; i++) {
12633 class = BPF_CLASS(insn[i].code);
12634 if (class != BPF_LDX && class != BPF_STX)
12635 continue;
12636 aux = &env->insn_aux_data[i];
12637 if (aux->seen != env->pass_cnt)
12638 continue;
12639 memset(aux, 0, offsetof(typeof(*aux), orig_idx));
12640 }
f1bca824
AS
12641}
12642
51c39bb1
AS
12643static int do_check_common(struct bpf_verifier_env *env, int subprog)
12644{
6f8a57cc 12645 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
51c39bb1
AS
12646 struct bpf_verifier_state *state;
12647 struct bpf_reg_state *regs;
12648 int ret, i;
12649
12650 env->prev_linfo = NULL;
12651 env->pass_cnt++;
12652
12653 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
12654 if (!state)
12655 return -ENOMEM;
12656 state->curframe = 0;
12657 state->speculative = false;
12658 state->branches = 1;
12659 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
12660 if (!state->frame[0]) {
12661 kfree(state);
12662 return -ENOMEM;
12663 }
12664 env->cur_state = state;
12665 init_func_state(env, state->frame[0],
12666 BPF_MAIN_FUNC /* callsite */,
12667 0 /* frameno */,
12668 subprog);
12669
12670 regs = state->frame[state->curframe]->regs;
be8704ff 12671 if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
51c39bb1
AS
12672 ret = btf_prepare_func_args(env, subprog, regs);
12673 if (ret)
12674 goto out;
12675 for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
12676 if (regs[i].type == PTR_TO_CTX)
12677 mark_reg_known_zero(env, regs, i);
12678 else if (regs[i].type == SCALAR_VALUE)
12679 mark_reg_unknown(env, regs, i);
e5069b9c
DB
12680 else if (regs[i].type == PTR_TO_MEM_OR_NULL) {
12681 const u32 mem_size = regs[i].mem_size;
12682
12683 mark_reg_known_zero(env, regs, i);
12684 regs[i].mem_size = mem_size;
12685 regs[i].id = ++env->id_gen;
12686 }
51c39bb1
AS
12687 }
12688 } else {
12689 /* 1st arg to a function */
12690 regs[BPF_REG_1].type = PTR_TO_CTX;
12691 mark_reg_known_zero(env, regs, BPF_REG_1);
34747c41 12692 ret = btf_check_subprog_arg_match(env, subprog, regs);
51c39bb1
AS
12693 if (ret == -EFAULT)
12694 /* unlikely verifier bug. abort.
12695 * ret == 0 and ret < 0 are sadly acceptable for
12696 * main() function due to backward compatibility.
12697 * Like socket filter program may be written as:
12698 * int bpf_prog(struct pt_regs *ctx)
12699 * and never dereference that ctx in the program.
12700 * 'struct pt_regs' is a type mismatch for socket
12701 * filter that should be using 'struct __sk_buff'.
12702 */
12703 goto out;
12704 }
12705
12706 ret = do_check(env);
12707out:
f59bbfc2
AS
12708 /* check for NULL is necessary, since cur_state can be freed inside
12709 * do_check() under memory pressure.
12710 */
12711 if (env->cur_state) {
12712 free_verifier_state(env->cur_state, true);
12713 env->cur_state = NULL;
12714 }
6f8a57cc
AN
12715 while (!pop_stack(env, NULL, NULL, false));
12716 if (!ret && pop_log)
12717 bpf_vlog_reset(&env->log, 0);
51c39bb1
AS
12718 free_states(env);
12719 if (ret)
12720 /* clean aux data in case subprog was rejected */
12721 sanitize_insn_aux_data(env);
12722 return ret;
12723}
12724
12725/* Verify all global functions in a BPF program one by one based on their BTF.
12726 * All global functions must pass verification. Otherwise the whole program is rejected.
12727 * Consider:
12728 * int bar(int);
12729 * int foo(int f)
12730 * {
12731 * return bar(f);
12732 * }
12733 * int bar(int b)
12734 * {
12735 * ...
12736 * }
12737 * foo() will be verified first for R1=any_scalar_value. During verification it
12738 * will be assumed that bar() already verified successfully and call to bar()
12739 * from foo() will be checked for type match only. Later bar() will be verified
12740 * independently to check that it's safe for R1=any_scalar_value.
12741 */
12742static int do_check_subprogs(struct bpf_verifier_env *env)
12743{
12744 struct bpf_prog_aux *aux = env->prog->aux;
12745 int i, ret;
12746
12747 if (!aux->func_info)
12748 return 0;
12749
12750 for (i = 1; i < env->subprog_cnt; i++) {
12751 if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
12752 continue;
12753 env->insn_idx = env->subprog_info[i].start;
12754 WARN_ON_ONCE(env->insn_idx == 0);
12755 ret = do_check_common(env, i);
12756 if (ret) {
12757 return ret;
12758 } else if (env->log.level & BPF_LOG_LEVEL) {
12759 verbose(env,
12760 "Func#%d is safe for any args that match its prototype\n",
12761 i);
12762 }
12763 }
12764 return 0;
12765}
12766
12767static int do_check_main(struct bpf_verifier_env *env)
12768{
12769 int ret;
12770
12771 env->insn_idx = 0;
12772 ret = do_check_common(env, 0);
12773 if (!ret)
12774 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
12775 return ret;
12776}
12777
12778
06ee7115
AS
12779static void print_verification_stats(struct bpf_verifier_env *env)
12780{
12781 int i;
12782
12783 if (env->log.level & BPF_LOG_STATS) {
12784 verbose(env, "verification time %lld usec\n",
12785 div_u64(env->verification_time, 1000));
12786 verbose(env, "stack depth ");
12787 for (i = 0; i < env->subprog_cnt; i++) {
12788 u32 depth = env->subprog_info[i].stack_depth;
12789
12790 verbose(env, "%d", depth);
12791 if (i + 1 < env->subprog_cnt)
12792 verbose(env, "+");
12793 }
12794 verbose(env, "\n");
12795 }
12796 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
12797 "total_states %d peak_states %d mark_read %d\n",
12798 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
12799 env->max_states_per_insn, env->total_states,
12800 env->peak_states, env->longest_mark_read_walk);
f1bca824
AS
12801}
12802
27ae7997
MKL
12803static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
12804{
12805 const struct btf_type *t, *func_proto;
12806 const struct bpf_struct_ops *st_ops;
12807 const struct btf_member *member;
12808 struct bpf_prog *prog = env->prog;
12809 u32 btf_id, member_idx;
12810 const char *mname;
12811
12812 btf_id = prog->aux->attach_btf_id;
12813 st_ops = bpf_struct_ops_find(btf_id);
12814 if (!st_ops) {
12815 verbose(env, "attach_btf_id %u is not a supported struct\n",
12816 btf_id);
12817 return -ENOTSUPP;
12818 }
12819
12820 t = st_ops->type;
12821 member_idx = prog->expected_attach_type;
12822 if (member_idx >= btf_type_vlen(t)) {
12823 verbose(env, "attach to invalid member idx %u of struct %s\n",
12824 member_idx, st_ops->name);
12825 return -EINVAL;
12826 }
12827
12828 member = &btf_type_member(t)[member_idx];
12829 mname = btf_name_by_offset(btf_vmlinux, member->name_off);
12830 func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
12831 NULL);
12832 if (!func_proto) {
12833 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
12834 mname, member_idx, st_ops->name);
12835 return -EINVAL;
12836 }
12837
12838 if (st_ops->check_member) {
12839 int err = st_ops->check_member(t, member);
12840
12841 if (err) {
12842 verbose(env, "attach to unsupported member %s of struct %s\n",
12843 mname, st_ops->name);
12844 return err;
12845 }
12846 }
12847
12848 prog->aux->attach_func_proto = func_proto;
12849 prog->aux->attach_func_name = mname;
12850 env->ops = st_ops->verifier_ops;
12851
12852 return 0;
12853}
6ba43b76
KS
12854#define SECURITY_PREFIX "security_"
12855
f7b12b6f 12856static int check_attach_modify_return(unsigned long addr, const char *func_name)
6ba43b76 12857{
69191754 12858 if (within_error_injection_list(addr) ||
f7b12b6f 12859 !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
6ba43b76 12860 return 0;
6ba43b76 12861
6ba43b76
KS
12862 return -EINVAL;
12863}
27ae7997 12864
1e6c62a8
AS
12865/* list of non-sleepable functions that are otherwise on
12866 * ALLOW_ERROR_INJECTION list
12867 */
12868BTF_SET_START(btf_non_sleepable_error_inject)
12869/* Three functions below can be called from sleepable and non-sleepable context.
12870 * Assume non-sleepable from bpf safety point of view.
12871 */
12872BTF_ID(func, __add_to_page_cache_locked)
12873BTF_ID(func, should_fail_alloc_page)
12874BTF_ID(func, should_failslab)
12875BTF_SET_END(btf_non_sleepable_error_inject)
12876
12877static int check_non_sleepable_error_inject(u32 btf_id)
12878{
12879 return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
12880}
12881
f7b12b6f
THJ
12882int bpf_check_attach_target(struct bpf_verifier_log *log,
12883 const struct bpf_prog *prog,
12884 const struct bpf_prog *tgt_prog,
12885 u32 btf_id,
12886 struct bpf_attach_target_info *tgt_info)
38207291 12887{
be8704ff 12888 bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
f1b9509c 12889 const char prefix[] = "btf_trace_";
5b92a28a 12890 int ret = 0, subprog = -1, i;
38207291 12891 const struct btf_type *t;
5b92a28a 12892 bool conservative = true;
38207291 12893 const char *tname;
5b92a28a 12894 struct btf *btf;
f7b12b6f 12895 long addr = 0;
38207291 12896
f1b9509c 12897 if (!btf_id) {
efc68158 12898 bpf_log(log, "Tracing programs must provide btf_id\n");
f1b9509c
AS
12899 return -EINVAL;
12900 }
22dc4a0f 12901 btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
5b92a28a 12902 if (!btf) {
efc68158 12903 bpf_log(log,
5b92a28a
AS
12904 "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
12905 return -EINVAL;
12906 }
12907 t = btf_type_by_id(btf, btf_id);
f1b9509c 12908 if (!t) {
efc68158 12909 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
f1b9509c
AS
12910 return -EINVAL;
12911 }
5b92a28a 12912 tname = btf_name_by_offset(btf, t->name_off);
f1b9509c 12913 if (!tname) {
efc68158 12914 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
f1b9509c
AS
12915 return -EINVAL;
12916 }
5b92a28a
AS
12917 if (tgt_prog) {
12918 struct bpf_prog_aux *aux = tgt_prog->aux;
12919
12920 for (i = 0; i < aux->func_info_cnt; i++)
12921 if (aux->func_info[i].type_id == btf_id) {
12922 subprog = i;
12923 break;
12924 }
12925 if (subprog == -1) {
efc68158 12926 bpf_log(log, "Subprog %s doesn't exist\n", tname);
5b92a28a
AS
12927 return -EINVAL;
12928 }
12929 conservative = aux->func_info_aux[subprog].unreliable;
be8704ff
AS
12930 if (prog_extension) {
12931 if (conservative) {
efc68158 12932 bpf_log(log,
be8704ff
AS
12933 "Cannot replace static functions\n");
12934 return -EINVAL;
12935 }
12936 if (!prog->jit_requested) {
efc68158 12937 bpf_log(log,
be8704ff
AS
12938 "Extension programs should be JITed\n");
12939 return -EINVAL;
12940 }
be8704ff
AS
12941 }
12942 if (!tgt_prog->jited) {
efc68158 12943 bpf_log(log, "Can attach to only JITed progs\n");
be8704ff
AS
12944 return -EINVAL;
12945 }
12946 if (tgt_prog->type == prog->type) {
12947 /* Cannot fentry/fexit another fentry/fexit program.
12948 * Cannot attach program extension to another extension.
12949 * It's ok to attach fentry/fexit to extension program.
12950 */
efc68158 12951 bpf_log(log, "Cannot recursively attach\n");
be8704ff
AS
12952 return -EINVAL;
12953 }
12954 if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
12955 prog_extension &&
12956 (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
12957 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
12958 /* Program extensions can extend all program types
12959 * except fentry/fexit. The reason is the following.
12960 * The fentry/fexit programs are used for performance
12961 * analysis, stats and can be attached to any program
12962 * type except themselves. When extension program is
12963 * replacing XDP function it is necessary to allow
12964 * performance analysis of all functions. Both original
12965 * XDP program and its program extension. Hence
12966 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
12967 * allowed. If extending of fentry/fexit was allowed it
12968 * would be possible to create long call chain
12969 * fentry->extension->fentry->extension beyond
12970 * reasonable stack size. Hence extending fentry is not
12971 * allowed.
12972 */
efc68158 12973 bpf_log(log, "Cannot extend fentry/fexit\n");
be8704ff
AS
12974 return -EINVAL;
12975 }
5b92a28a 12976 } else {
be8704ff 12977 if (prog_extension) {
efc68158 12978 bpf_log(log, "Cannot replace kernel functions\n");
be8704ff
AS
12979 return -EINVAL;
12980 }
5b92a28a 12981 }
f1b9509c
AS
12982
12983 switch (prog->expected_attach_type) {
12984 case BPF_TRACE_RAW_TP:
5b92a28a 12985 if (tgt_prog) {
efc68158 12986 bpf_log(log,
5b92a28a
AS
12987 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
12988 return -EINVAL;
12989 }
38207291 12990 if (!btf_type_is_typedef(t)) {
efc68158 12991 bpf_log(log, "attach_btf_id %u is not a typedef\n",
38207291
MKL
12992 btf_id);
12993 return -EINVAL;
12994 }
f1b9509c 12995 if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
efc68158 12996 bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
38207291
MKL
12997 btf_id, tname);
12998 return -EINVAL;
12999 }
13000 tname += sizeof(prefix) - 1;
5b92a28a 13001 t = btf_type_by_id(btf, t->type);
38207291
MKL
13002 if (!btf_type_is_ptr(t))
13003 /* should never happen in valid vmlinux build */
13004 return -EINVAL;
5b92a28a 13005 t = btf_type_by_id(btf, t->type);
38207291
MKL
13006 if (!btf_type_is_func_proto(t))
13007 /* should never happen in valid vmlinux build */
13008 return -EINVAL;
13009
f7b12b6f 13010 break;
15d83c4d
YS
13011 case BPF_TRACE_ITER:
13012 if (!btf_type_is_func(t)) {
efc68158 13013 bpf_log(log, "attach_btf_id %u is not a function\n",
15d83c4d
YS
13014 btf_id);
13015 return -EINVAL;
13016 }
13017 t = btf_type_by_id(btf, t->type);
13018 if (!btf_type_is_func_proto(t))
13019 return -EINVAL;
f7b12b6f
THJ
13020 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
13021 if (ret)
13022 return ret;
13023 break;
be8704ff
AS
13024 default:
13025 if (!prog_extension)
13026 return -EINVAL;
df561f66 13027 fallthrough;
ae240823 13028 case BPF_MODIFY_RETURN:
9e4e01df 13029 case BPF_LSM_MAC:
fec56f58
AS
13030 case BPF_TRACE_FENTRY:
13031 case BPF_TRACE_FEXIT:
13032 if (!btf_type_is_func(t)) {
efc68158 13033 bpf_log(log, "attach_btf_id %u is not a function\n",
fec56f58
AS
13034 btf_id);
13035 return -EINVAL;
13036 }
be8704ff 13037 if (prog_extension &&
efc68158 13038 btf_check_type_match(log, prog, btf, t))
be8704ff 13039 return -EINVAL;
5b92a28a 13040 t = btf_type_by_id(btf, t->type);
fec56f58
AS
13041 if (!btf_type_is_func_proto(t))
13042 return -EINVAL;
f7b12b6f 13043
4a1e7c0c
THJ
13044 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
13045 (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
13046 prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
13047 return -EINVAL;
13048
f7b12b6f 13049 if (tgt_prog && conservative)
5b92a28a 13050 t = NULL;
f7b12b6f
THJ
13051
13052 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
fec56f58 13053 if (ret < 0)
f7b12b6f
THJ
13054 return ret;
13055
5b92a28a 13056 if (tgt_prog) {
e9eeec58
YS
13057 if (subprog == 0)
13058 addr = (long) tgt_prog->bpf_func;
13059 else
13060 addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
5b92a28a
AS
13061 } else {
13062 addr = kallsyms_lookup_name(tname);
13063 if (!addr) {
efc68158 13064 bpf_log(log,
5b92a28a
AS
13065 "The address of function %s cannot be found\n",
13066 tname);
f7b12b6f 13067 return -ENOENT;
5b92a28a 13068 }
fec56f58 13069 }
18644cec 13070
1e6c62a8
AS
13071 if (prog->aux->sleepable) {
13072 ret = -EINVAL;
13073 switch (prog->type) {
13074 case BPF_PROG_TYPE_TRACING:
13075 /* fentry/fexit/fmod_ret progs can be sleepable only if they are
13076 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
13077 */
13078 if (!check_non_sleepable_error_inject(btf_id) &&
13079 within_error_injection_list(addr))
13080 ret = 0;
13081 break;
13082 case BPF_PROG_TYPE_LSM:
13083 /* LSM progs check that they are attached to bpf_lsm_*() funcs.
13084 * Only some of them are sleepable.
13085 */
423f1610 13086 if (bpf_lsm_is_sleepable_hook(btf_id))
1e6c62a8
AS
13087 ret = 0;
13088 break;
13089 default:
13090 break;
13091 }
f7b12b6f
THJ
13092 if (ret) {
13093 bpf_log(log, "%s is not sleepable\n", tname);
13094 return ret;
13095 }
1e6c62a8 13096 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
1af9270e 13097 if (tgt_prog) {
efc68158 13098 bpf_log(log, "can't modify return codes of BPF programs\n");
f7b12b6f
THJ
13099 return -EINVAL;
13100 }
13101 ret = check_attach_modify_return(addr, tname);
13102 if (ret) {
13103 bpf_log(log, "%s() is not modifiable\n", tname);
13104 return ret;
1af9270e 13105 }
18644cec 13106 }
f7b12b6f
THJ
13107
13108 break;
13109 }
13110 tgt_info->tgt_addr = addr;
13111 tgt_info->tgt_name = tname;
13112 tgt_info->tgt_type = t;
13113 return 0;
13114}
13115
13116static int check_attach_btf_id(struct bpf_verifier_env *env)
13117{
13118 struct bpf_prog *prog = env->prog;
3aac1ead 13119 struct bpf_prog *tgt_prog = prog->aux->dst_prog;
f7b12b6f
THJ
13120 struct bpf_attach_target_info tgt_info = {};
13121 u32 btf_id = prog->aux->attach_btf_id;
13122 struct bpf_trampoline *tr;
13123 int ret;
13124 u64 key;
13125
13126 if (prog->aux->sleepable && prog->type != BPF_PROG_TYPE_TRACING &&
13127 prog->type != BPF_PROG_TYPE_LSM) {
13128 verbose(env, "Only fentry/fexit/fmod_ret and lsm programs can be sleepable\n");
13129 return -EINVAL;
13130 }
13131
13132 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
13133 return check_struct_ops_btf_id(env);
13134
13135 if (prog->type != BPF_PROG_TYPE_TRACING &&
13136 prog->type != BPF_PROG_TYPE_LSM &&
13137 prog->type != BPF_PROG_TYPE_EXT)
13138 return 0;
13139
13140 ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
13141 if (ret)
fec56f58 13142 return ret;
f7b12b6f
THJ
13143
13144 if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
3aac1ead
THJ
13145 /* to make freplace equivalent to their targets, they need to
13146 * inherit env->ops and expected_attach_type for the rest of the
13147 * verification
13148 */
f7b12b6f
THJ
13149 env->ops = bpf_verifier_ops[tgt_prog->type];
13150 prog->expected_attach_type = tgt_prog->expected_attach_type;
13151 }
13152
13153 /* store info about the attachment target that will be used later */
13154 prog->aux->attach_func_proto = tgt_info.tgt_type;
13155 prog->aux->attach_func_name = tgt_info.tgt_name;
13156
4a1e7c0c
THJ
13157 if (tgt_prog) {
13158 prog->aux->saved_dst_prog_type = tgt_prog->type;
13159 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
13160 }
13161
f7b12b6f
THJ
13162 if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
13163 prog->aux->attach_btf_trace = true;
13164 return 0;
13165 } else if (prog->expected_attach_type == BPF_TRACE_ITER) {
13166 if (!bpf_iter_prog_supported(prog))
13167 return -EINVAL;
13168 return 0;
13169 }
13170
13171 if (prog->type == BPF_PROG_TYPE_LSM) {
13172 ret = bpf_lsm_verify_prog(&env->log, prog);
13173 if (ret < 0)
13174 return ret;
38207291 13175 }
f7b12b6f 13176
22dc4a0f 13177 key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
f7b12b6f
THJ
13178 tr = bpf_trampoline_get(key, &tgt_info);
13179 if (!tr)
13180 return -ENOMEM;
13181
3aac1ead 13182 prog->aux->dst_trampoline = tr;
f7b12b6f 13183 return 0;
38207291
MKL
13184}
13185
76654e67
AM
13186struct btf *bpf_get_btf_vmlinux(void)
13187{
13188 if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
13189 mutex_lock(&bpf_verifier_lock);
13190 if (!btf_vmlinux)
13191 btf_vmlinux = btf_parse_vmlinux();
13192 mutex_unlock(&bpf_verifier_lock);
13193 }
13194 return btf_vmlinux;
13195}
13196
838e9690
YS
13197int bpf_check(struct bpf_prog **prog, union bpf_attr *attr,
13198 union bpf_attr __user *uattr)
51580e79 13199{
06ee7115 13200 u64 start_time = ktime_get_ns();
58e2af8b 13201 struct bpf_verifier_env *env;
b9193c1b 13202 struct bpf_verifier_log *log;
9e4c24e7 13203 int i, len, ret = -EINVAL;
e2ae4ca2 13204 bool is_priv;
51580e79 13205
eba0c929
AB
13206 /* no program is valid */
13207 if (ARRAY_SIZE(bpf_verifier_ops) == 0)
13208 return -EINVAL;
13209
58e2af8b 13210 /* 'struct bpf_verifier_env' can be global, but since it's not small,
cbd35700
AS
13211 * allocate/free it every time bpf_check() is called
13212 */
58e2af8b 13213 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
cbd35700
AS
13214 if (!env)
13215 return -ENOMEM;
61bd5218 13216 log = &env->log;
cbd35700 13217
9e4c24e7 13218 len = (*prog)->len;
fad953ce 13219 env->insn_aux_data =
9e4c24e7 13220 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
3df126f3
JK
13221 ret = -ENOMEM;
13222 if (!env->insn_aux_data)
13223 goto err_free_env;
9e4c24e7
JK
13224 for (i = 0; i < len; i++)
13225 env->insn_aux_data[i].orig_idx = i;
9bac3d6d 13226 env->prog = *prog;
00176a34 13227 env->ops = bpf_verifier_ops[env->prog->type];
2c78ee89 13228 is_priv = bpf_capable();
0246e64d 13229
76654e67 13230 bpf_get_btf_vmlinux();
8580ac94 13231
cbd35700 13232 /* grab the mutex to protect few globals used by verifier */
45a73c17
AS
13233 if (!is_priv)
13234 mutex_lock(&bpf_verifier_lock);
cbd35700
AS
13235
13236 if (attr->log_level || attr->log_buf || attr->log_size) {
13237 /* user requested verbose verifier output
13238 * and supplied buffer to store the verification trace
13239 */
e7bf8249
JK
13240 log->level = attr->log_level;
13241 log->ubuf = (char __user *) (unsigned long) attr->log_buf;
13242 log->len_total = attr->log_size;
cbd35700
AS
13243
13244 ret = -EINVAL;
e7bf8249 13245 /* log attributes have to be sane */
7a9f5c65 13246 if (log->len_total < 128 || log->len_total > UINT_MAX >> 2 ||
06ee7115 13247 !log->level || !log->ubuf || log->level & ~BPF_LOG_MASK)
3df126f3 13248 goto err_unlock;
cbd35700 13249 }
1ad2f583 13250
8580ac94
AS
13251 if (IS_ERR(btf_vmlinux)) {
13252 /* Either gcc or pahole or kernel are broken. */
13253 verbose(env, "in-kernel BTF is malformed\n");
13254 ret = PTR_ERR(btf_vmlinux);
38207291 13255 goto skip_full_check;
8580ac94
AS
13256 }
13257
1ad2f583
DB
13258 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
13259 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
e07b98d9 13260 env->strict_alignment = true;
e9ee9efc
DM
13261 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
13262 env->strict_alignment = false;
cbd35700 13263
2c78ee89 13264 env->allow_ptr_leaks = bpf_allow_ptr_leaks();
01f810ac 13265 env->allow_uninit_stack = bpf_allow_uninit_stack();
41c48f3a 13266 env->allow_ptr_to_map_access = bpf_allow_ptr_to_map_access();
2c78ee89
AS
13267 env->bypass_spec_v1 = bpf_bypass_spec_v1();
13268 env->bypass_spec_v4 = bpf_bypass_spec_v4();
13269 env->bpf_capable = bpf_capable();
e2ae4ca2 13270
10d274e8
AS
13271 if (is_priv)
13272 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
13273
cae1927c 13274 if (bpf_prog_is_dev_bound(env->prog->aux)) {
a40a2632 13275 ret = bpf_prog_offload_verifier_prep(env->prog);
ab3f0063 13276 if (ret)
f4e3ec0d 13277 goto skip_full_check;
ab3f0063
JK
13278 }
13279
dc2a4ebc 13280 env->explored_states = kvcalloc(state_htab_size(env),
58e2af8b 13281 sizeof(struct bpf_verifier_state_list *),
f1bca824
AS
13282 GFP_USER);
13283 ret = -ENOMEM;
13284 if (!env->explored_states)
13285 goto skip_full_check;
13286
e6ac2450
MKL
13287 ret = add_subprog_and_kfunc(env);
13288 if (ret < 0)
13289 goto skip_full_check;
13290
d9762e84 13291 ret = check_subprogs(env);
475fb78f
AS
13292 if (ret < 0)
13293 goto skip_full_check;
13294
c454a46b 13295 ret = check_btf_info(env, attr, uattr);
838e9690
YS
13296 if (ret < 0)
13297 goto skip_full_check;
13298
be8704ff
AS
13299 ret = check_attach_btf_id(env);
13300 if (ret)
13301 goto skip_full_check;
13302
4976b718
HL
13303 ret = resolve_pseudo_ldimm64(env);
13304 if (ret < 0)
13305 goto skip_full_check;
13306
d9762e84
MKL
13307 ret = check_cfg(env);
13308 if (ret < 0)
13309 goto skip_full_check;
13310
51c39bb1
AS
13311 ret = do_check_subprogs(env);
13312 ret = ret ?: do_check_main(env);
cbd35700 13313
c941ce9c
QM
13314 if (ret == 0 && bpf_prog_is_dev_bound(env->prog->aux))
13315 ret = bpf_prog_offload_finalize(env);
13316
0246e64d 13317skip_full_check:
51c39bb1 13318 kvfree(env->explored_states);
0246e64d 13319
c131187d 13320 if (ret == 0)
9b38c405 13321 ret = check_max_stack_depth(env);
c131187d 13322
9b38c405 13323 /* instruction rewrites happen after this point */
e2ae4ca2
JK
13324 if (is_priv) {
13325 if (ret == 0)
13326 opt_hard_wire_dead_code_branches(env);
52875a04
JK
13327 if (ret == 0)
13328 ret = opt_remove_dead_code(env);
a1b14abc
JK
13329 if (ret == 0)
13330 ret = opt_remove_nops(env);
52875a04
JK
13331 } else {
13332 if (ret == 0)
13333 sanitize_dead_code(env);
e2ae4ca2
JK
13334 }
13335
9bac3d6d
AS
13336 if (ret == 0)
13337 /* program is valid, convert *(u32*)(ctx + off) accesses */
13338 ret = convert_ctx_accesses(env);
13339
e245c5c6 13340 if (ret == 0)
e6ac5933 13341 ret = do_misc_fixups(env);
e245c5c6 13342
a4b1d3c1
JW
13343 /* do 32-bit optimization after insn patching has done so those patched
13344 * insns could be handled correctly.
13345 */
d6c2308c
JW
13346 if (ret == 0 && !bpf_prog_is_dev_bound(env->prog->aux)) {
13347 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
13348 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
13349 : false;
a4b1d3c1
JW
13350 }
13351
1ea47e01
AS
13352 if (ret == 0)
13353 ret = fixup_call_args(env);
13354
06ee7115
AS
13355 env->verification_time = ktime_get_ns() - start_time;
13356 print_verification_stats(env);
13357
a2a7d570 13358 if (log->level && bpf_verifier_log_full(log))
cbd35700 13359 ret = -ENOSPC;
a2a7d570 13360 if (log->level && !log->ubuf) {
cbd35700 13361 ret = -EFAULT;
a2a7d570 13362 goto err_release_maps;
cbd35700
AS
13363 }
13364
541c3bad
AN
13365 if (ret)
13366 goto err_release_maps;
13367
13368 if (env->used_map_cnt) {
0246e64d 13369 /* if program passed verifier, update used_maps in bpf_prog_info */
9bac3d6d
AS
13370 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
13371 sizeof(env->used_maps[0]),
13372 GFP_KERNEL);
0246e64d 13373
9bac3d6d 13374 if (!env->prog->aux->used_maps) {
0246e64d 13375 ret = -ENOMEM;
a2a7d570 13376 goto err_release_maps;
0246e64d
AS
13377 }
13378
9bac3d6d 13379 memcpy(env->prog->aux->used_maps, env->used_maps,
0246e64d 13380 sizeof(env->used_maps[0]) * env->used_map_cnt);
9bac3d6d 13381 env->prog->aux->used_map_cnt = env->used_map_cnt;
541c3bad
AN
13382 }
13383 if (env->used_btf_cnt) {
13384 /* if program passed verifier, update used_btfs in bpf_prog_aux */
13385 env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
13386 sizeof(env->used_btfs[0]),
13387 GFP_KERNEL);
13388 if (!env->prog->aux->used_btfs) {
13389 ret = -ENOMEM;
13390 goto err_release_maps;
13391 }
0246e64d 13392
541c3bad
AN
13393 memcpy(env->prog->aux->used_btfs, env->used_btfs,
13394 sizeof(env->used_btfs[0]) * env->used_btf_cnt);
13395 env->prog->aux->used_btf_cnt = env->used_btf_cnt;
13396 }
13397 if (env->used_map_cnt || env->used_btf_cnt) {
0246e64d
AS
13398 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
13399 * bpf_ld_imm64 instructions
13400 */
13401 convert_pseudo_ld_imm64(env);
13402 }
cbd35700 13403
541c3bad 13404 adjust_btf_func(env);
ba64e7d8 13405
a2a7d570 13406err_release_maps:
9bac3d6d 13407 if (!env->prog->aux->used_maps)
0246e64d 13408 /* if we didn't copy map pointers into bpf_prog_info, release
ab7f5bf0 13409 * them now. Otherwise free_used_maps() will release them.
0246e64d
AS
13410 */
13411 release_maps(env);
541c3bad
AN
13412 if (!env->prog->aux->used_btfs)
13413 release_btfs(env);
03f87c0b
THJ
13414
13415 /* extension progs temporarily inherit the attach_type of their targets
13416 for verification purposes, so set it back to zero before returning
13417 */
13418 if (env->prog->type == BPF_PROG_TYPE_EXT)
13419 env->prog->expected_attach_type = 0;
13420
9bac3d6d 13421 *prog = env->prog;
3df126f3 13422err_unlock:
45a73c17
AS
13423 if (!is_priv)
13424 mutex_unlock(&bpf_verifier_lock);
3df126f3
JK
13425 vfree(env->insn_aux_data);
13426err_free_env:
13427 kfree(env);
51580e79
AS
13428 return ret;
13429}